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) 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; 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 && !src_reg->id && 4442 !tnum_is_const(src_reg->var_off)) 4443 /* Ensure that src_reg has a valid ID that will be copied to 4444 * dst_reg and then will be used by find_equal_scalars() to 4445 * propagate min/max range. 4446 */ 4447 src_reg->id = ++env->id_gen; 4448 } 4449 4450 /* Copy src state preserving dst->parent and dst->live fields */ 4451 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 4452 { 4453 struct bpf_reg_state *parent = dst->parent; 4454 enum bpf_reg_liveness live = dst->live; 4455 4456 *dst = *src; 4457 dst->parent = parent; 4458 dst->live = live; 4459 } 4460 4461 static void save_register_state(struct bpf_verifier_env *env, 4462 struct bpf_func_state *state, 4463 int spi, struct bpf_reg_state *reg, 4464 int size) 4465 { 4466 int i; 4467 4468 copy_register_state(&state->stack[spi].spilled_ptr, reg); 4469 if (size == BPF_REG_SIZE) 4470 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4471 4472 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 4473 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 4474 4475 /* size < 8 bytes spill */ 4476 for (; i; i--) 4477 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]); 4478 } 4479 4480 static bool is_bpf_st_mem(struct bpf_insn *insn) 4481 { 4482 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 4483 } 4484 4485 static int get_reg_width(struct bpf_reg_state *reg) 4486 { 4487 return fls64(reg->umax_value); 4488 } 4489 4490 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 4491 * stack boundary and alignment are checked in check_mem_access() 4492 */ 4493 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 4494 /* stack frame we're writing to */ 4495 struct bpf_func_state *state, 4496 int off, int size, int value_regno, 4497 int insn_idx) 4498 { 4499 struct bpf_func_state *cur; /* state of the current function */ 4500 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 4501 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4502 struct bpf_reg_state *reg = NULL; 4503 int insn_flags = insn_stack_access_flags(state->frameno, spi); 4504 4505 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 4506 * so it's aligned access and [off, off + size) are within stack limits 4507 */ 4508 if (!env->allow_ptr_leaks && 4509 is_spilled_reg(&state->stack[spi]) && 4510 size != BPF_REG_SIZE) { 4511 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 4512 return -EACCES; 4513 } 4514 4515 cur = env->cur_state->frame[env->cur_state->curframe]; 4516 if (value_regno >= 0) 4517 reg = &cur->regs[value_regno]; 4518 if (!env->bypass_spec_v4) { 4519 bool sanitize = reg && is_spillable_regtype(reg->type); 4520 4521 for (i = 0; i < size; i++) { 4522 u8 type = state->stack[spi].slot_type[i]; 4523 4524 if (type != STACK_MISC && type != STACK_ZERO) { 4525 sanitize = true; 4526 break; 4527 } 4528 } 4529 4530 if (sanitize) 4531 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 4532 } 4533 4534 err = destroy_if_dynptr_stack_slot(env, state, spi); 4535 if (err) 4536 return err; 4537 4538 mark_stack_slot_scratched(env, spi); 4539 if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) { 4540 bool reg_value_fits; 4541 4542 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size; 4543 /* Make sure that reg had an ID to build a relation on spill. */ 4544 if (reg_value_fits) 4545 assign_scalar_id_before_mov(env, reg); 4546 save_register_state(env, state, spi, reg, size); 4547 /* Break the relation on a narrowing spill. */ 4548 if (!reg_value_fits) 4549 state->stack[spi].spilled_ptr.id = 0; 4550 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 4551 env->bpf_capable) { 4552 struct bpf_reg_state fake_reg = {}; 4553 4554 __mark_reg_known(&fake_reg, insn->imm); 4555 fake_reg.type = SCALAR_VALUE; 4556 save_register_state(env, state, spi, &fake_reg, size); 4557 } else if (reg && is_spillable_regtype(reg->type)) { 4558 /* register containing pointer is being spilled into stack */ 4559 if (size != BPF_REG_SIZE) { 4560 verbose_linfo(env, insn_idx, "; "); 4561 verbose(env, "invalid size of register spill\n"); 4562 return -EACCES; 4563 } 4564 if (state != cur && reg->type == PTR_TO_STACK) { 4565 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4566 return -EINVAL; 4567 } 4568 save_register_state(env, state, spi, reg, size); 4569 } else { 4570 u8 type = STACK_MISC; 4571 4572 /* regular write of data into stack destroys any spilled ptr */ 4573 state->stack[spi].spilled_ptr.type = NOT_INIT; 4574 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 4575 if (is_stack_slot_special(&state->stack[spi])) 4576 for (i = 0; i < BPF_REG_SIZE; i++) 4577 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 4578 4579 /* only mark the slot as written if all 8 bytes were written 4580 * otherwise read propagation may incorrectly stop too soon 4581 * when stack slots are partially written. 4582 * This heuristic means that read propagation will be 4583 * conservative, since it will add reg_live_read marks 4584 * to stack slots all the way to first state when programs 4585 * writes+reads less than 8 bytes 4586 */ 4587 if (size == BPF_REG_SIZE) 4588 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4589 4590 /* when we zero initialize stack slots mark them as such */ 4591 if ((reg && register_is_null(reg)) || 4592 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4593 /* STACK_ZERO case happened because register spill 4594 * wasn't properly aligned at the stack slot boundary, 4595 * so it's not a register spill anymore; force 4596 * originating register to be precise to make 4597 * STACK_ZERO correct for subsequent states 4598 */ 4599 err = mark_chain_precision(env, value_regno); 4600 if (err) 4601 return err; 4602 type = STACK_ZERO; 4603 } 4604 4605 /* Mark slots affected by this stack write. */ 4606 for (i = 0; i < size; i++) 4607 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 4608 insn_flags = 0; /* not a register spill */ 4609 } 4610 4611 if (insn_flags) 4612 return push_jmp_history(env, env->cur_state, insn_flags); 4613 return 0; 4614 } 4615 4616 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 4617 * known to contain a variable offset. 4618 * This function checks whether the write is permitted and conservatively 4619 * tracks the effects of the write, considering that each stack slot in the 4620 * dynamic range is potentially written to. 4621 * 4622 * 'off' includes 'regno->off'. 4623 * 'value_regno' can be -1, meaning that an unknown value is being written to 4624 * the stack. 4625 * 4626 * Spilled pointers in range are not marked as written because we don't know 4627 * what's going to be actually written. This means that read propagation for 4628 * future reads cannot be terminated by this write. 4629 * 4630 * For privileged programs, uninitialized stack slots are considered 4631 * initialized by this write (even though we don't know exactly what offsets 4632 * are going to be written to). The idea is that we don't want the verifier to 4633 * reject future reads that access slots written to through variable offsets. 4634 */ 4635 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4636 /* func where register points to */ 4637 struct bpf_func_state *state, 4638 int ptr_regno, int off, int size, 4639 int value_regno, int insn_idx) 4640 { 4641 struct bpf_func_state *cur; /* state of the current function */ 4642 int min_off, max_off; 4643 int i, err; 4644 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 4645 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4646 bool writing_zero = false; 4647 /* set if the fact that we're writing a zero is used to let any 4648 * stack slots remain STACK_ZERO 4649 */ 4650 bool zero_used = false; 4651 4652 cur = env->cur_state->frame[env->cur_state->curframe]; 4653 ptr_reg = &cur->regs[ptr_regno]; 4654 min_off = ptr_reg->smin_value + off; 4655 max_off = ptr_reg->smax_value + off + size; 4656 if (value_regno >= 0) 4657 value_reg = &cur->regs[value_regno]; 4658 if ((value_reg && register_is_null(value_reg)) || 4659 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4660 writing_zero = true; 4661 4662 for (i = min_off; i < max_off; i++) { 4663 int spi; 4664 4665 spi = __get_spi(i); 4666 err = destroy_if_dynptr_stack_slot(env, state, spi); 4667 if (err) 4668 return err; 4669 } 4670 4671 /* Variable offset writes destroy any spilled pointers in range. */ 4672 for (i = min_off; i < max_off; i++) { 4673 u8 new_type, *stype; 4674 int slot, spi; 4675 4676 slot = -i - 1; 4677 spi = slot / BPF_REG_SIZE; 4678 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4679 mark_stack_slot_scratched(env, spi); 4680 4681 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4682 /* Reject the write if range we may write to has not 4683 * been initialized beforehand. If we didn't reject 4684 * here, the ptr status would be erased below (even 4685 * though not all slots are actually overwritten), 4686 * possibly opening the door to leaks. 4687 * 4688 * We do however catch STACK_INVALID case below, and 4689 * only allow reading possibly uninitialized memory 4690 * later for CAP_PERFMON, as the write may not happen to 4691 * that slot. 4692 */ 4693 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4694 insn_idx, i); 4695 return -EINVAL; 4696 } 4697 4698 /* If writing_zero and the spi slot contains a spill of value 0, 4699 * maintain the spill type. 4700 */ 4701 if (writing_zero && *stype == STACK_SPILL && 4702 is_spilled_scalar_reg(&state->stack[spi])) { 4703 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr; 4704 4705 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) { 4706 zero_used = true; 4707 continue; 4708 } 4709 } 4710 4711 /* Erase all other spilled pointers. */ 4712 state->stack[spi].spilled_ptr.type = NOT_INIT; 4713 4714 /* Update the slot type. */ 4715 new_type = STACK_MISC; 4716 if (writing_zero && *stype == STACK_ZERO) { 4717 new_type = STACK_ZERO; 4718 zero_used = true; 4719 } 4720 /* If the slot is STACK_INVALID, we check whether it's OK to 4721 * pretend that it will be initialized by this write. The slot 4722 * might not actually be written to, and so if we mark it as 4723 * initialized future reads might leak uninitialized memory. 4724 * For privileged programs, we will accept such reads to slots 4725 * that may or may not be written because, if we're reject 4726 * them, the error would be too confusing. 4727 */ 4728 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4729 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4730 insn_idx, i); 4731 return -EINVAL; 4732 } 4733 *stype = new_type; 4734 } 4735 if (zero_used) { 4736 /* backtracking doesn't work for STACK_ZERO yet. */ 4737 err = mark_chain_precision(env, value_regno); 4738 if (err) 4739 return err; 4740 } 4741 return 0; 4742 } 4743 4744 /* When register 'dst_regno' is assigned some values from stack[min_off, 4745 * max_off), we set the register's type according to the types of the 4746 * respective stack slots. If all the stack values are known to be zeros, then 4747 * so is the destination reg. Otherwise, the register is considered to be 4748 * SCALAR. This function does not deal with register filling; the caller must 4749 * ensure that all spilled registers in the stack range have been marked as 4750 * read. 4751 */ 4752 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4753 /* func where src register points to */ 4754 struct bpf_func_state *ptr_state, 4755 int min_off, int max_off, int dst_regno) 4756 { 4757 struct bpf_verifier_state *vstate = env->cur_state; 4758 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4759 int i, slot, spi; 4760 u8 *stype; 4761 int zeros = 0; 4762 4763 for (i = min_off; i < max_off; i++) { 4764 slot = -i - 1; 4765 spi = slot / BPF_REG_SIZE; 4766 mark_stack_slot_scratched(env, spi); 4767 stype = ptr_state->stack[spi].slot_type; 4768 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4769 break; 4770 zeros++; 4771 } 4772 if (zeros == max_off - min_off) { 4773 /* Any access_size read into register is zero extended, 4774 * so the whole register == const_zero. 4775 */ 4776 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4777 } else { 4778 /* have read misc data from the stack */ 4779 mark_reg_unknown(env, state->regs, dst_regno); 4780 } 4781 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4782 } 4783 4784 /* Read the stack at 'off' and put the results into the register indicated by 4785 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4786 * spilled reg. 4787 * 4788 * 'dst_regno' can be -1, meaning that the read value is not going to a 4789 * register. 4790 * 4791 * The access is assumed to be within the current stack bounds. 4792 */ 4793 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4794 /* func where src register points to */ 4795 struct bpf_func_state *reg_state, 4796 int off, int size, int dst_regno) 4797 { 4798 struct bpf_verifier_state *vstate = env->cur_state; 4799 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4800 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4801 struct bpf_reg_state *reg; 4802 u8 *stype, type; 4803 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi); 4804 4805 stype = reg_state->stack[spi].slot_type; 4806 reg = ®_state->stack[spi].spilled_ptr; 4807 4808 mark_stack_slot_scratched(env, spi); 4809 4810 if (is_spilled_reg(®_state->stack[spi])) { 4811 u8 spill_size = 1; 4812 4813 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4814 spill_size++; 4815 4816 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4817 if (reg->type != SCALAR_VALUE) { 4818 verbose_linfo(env, env->insn_idx, "; "); 4819 verbose(env, "invalid size of register fill\n"); 4820 return -EACCES; 4821 } 4822 4823 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4824 if (dst_regno < 0) 4825 return 0; 4826 4827 if (size <= spill_size && 4828 bpf_stack_narrow_access_ok(off, size, spill_size)) { 4829 /* The earlier check_reg_arg() has decided the 4830 * subreg_def for this insn. Save it first. 4831 */ 4832 s32 subreg_def = state->regs[dst_regno].subreg_def; 4833 4834 copy_register_state(&state->regs[dst_regno], reg); 4835 state->regs[dst_regno].subreg_def = subreg_def; 4836 4837 /* Break the relation on a narrowing fill. 4838 * coerce_reg_to_size will adjust the boundaries. 4839 */ 4840 if (get_reg_width(reg) > size * BITS_PER_BYTE) 4841 state->regs[dst_regno].id = 0; 4842 } else { 4843 int spill_cnt = 0, zero_cnt = 0; 4844 4845 for (i = 0; i < size; i++) { 4846 type = stype[(slot - i) % BPF_REG_SIZE]; 4847 if (type == STACK_SPILL) { 4848 spill_cnt++; 4849 continue; 4850 } 4851 if (type == STACK_MISC) 4852 continue; 4853 if (type == STACK_ZERO) { 4854 zero_cnt++; 4855 continue; 4856 } 4857 if (type == STACK_INVALID && env->allow_uninit_stack) 4858 continue; 4859 verbose(env, "invalid read from stack off %d+%d size %d\n", 4860 off, i, size); 4861 return -EACCES; 4862 } 4863 4864 if (spill_cnt == size && 4865 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 4866 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4867 /* this IS register fill, so keep insn_flags */ 4868 } else if (zero_cnt == size) { 4869 /* similarly to mark_reg_stack_read(), preserve zeroes */ 4870 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4871 insn_flags = 0; /* not restoring original register state */ 4872 } else { 4873 mark_reg_unknown(env, state->regs, dst_regno); 4874 insn_flags = 0; /* not restoring original register state */ 4875 } 4876 } 4877 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4878 } else if (dst_regno >= 0) { 4879 /* restore register state from stack */ 4880 copy_register_state(&state->regs[dst_regno], reg); 4881 /* mark reg as written since spilled pointer state likely 4882 * has its liveness marks cleared by is_state_visited() 4883 * which resets stack/reg liveness for state transitions 4884 */ 4885 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4886 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 4887 /* If dst_regno==-1, the caller is asking us whether 4888 * it is acceptable to use this value as a SCALAR_VALUE 4889 * (e.g. for XADD). 4890 * We must not allow unprivileged callers to do that 4891 * with spilled pointers. 4892 */ 4893 verbose(env, "leaking pointer from stack off %d\n", 4894 off); 4895 return -EACCES; 4896 } 4897 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4898 } else { 4899 for (i = 0; i < size; i++) { 4900 type = stype[(slot - i) % BPF_REG_SIZE]; 4901 if (type == STACK_MISC) 4902 continue; 4903 if (type == STACK_ZERO) 4904 continue; 4905 if (type == STACK_INVALID && env->allow_uninit_stack) 4906 continue; 4907 verbose(env, "invalid read from stack off %d+%d size %d\n", 4908 off, i, size); 4909 return -EACCES; 4910 } 4911 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4912 if (dst_regno >= 0) 4913 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 4914 insn_flags = 0; /* we are not restoring spilled register */ 4915 } 4916 if (insn_flags) 4917 return push_jmp_history(env, env->cur_state, insn_flags); 4918 return 0; 4919 } 4920 4921 enum bpf_access_src { 4922 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 4923 ACCESS_HELPER = 2, /* the access is performed by a helper */ 4924 }; 4925 4926 static int check_stack_range_initialized(struct bpf_verifier_env *env, 4927 int regno, int off, int access_size, 4928 bool zero_size_allowed, 4929 enum bpf_access_src type, 4930 struct bpf_call_arg_meta *meta); 4931 4932 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 4933 { 4934 return cur_regs(env) + regno; 4935 } 4936 4937 /* Read the stack at 'ptr_regno + off' and put the result into the register 4938 * 'dst_regno'. 4939 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 4940 * but not its variable offset. 4941 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 4942 * 4943 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 4944 * filling registers (i.e. reads of spilled register cannot be detected when 4945 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 4946 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 4947 * offset; for a fixed offset check_stack_read_fixed_off should be used 4948 * instead. 4949 */ 4950 static int check_stack_read_var_off(struct bpf_verifier_env *env, 4951 int ptr_regno, int off, int size, int dst_regno) 4952 { 4953 /* The state of the source register. */ 4954 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4955 struct bpf_func_state *ptr_state = func(env, reg); 4956 int err; 4957 int min_off, max_off; 4958 4959 /* Note that we pass a NULL meta, so raw access will not be permitted. 4960 */ 4961 err = check_stack_range_initialized(env, ptr_regno, off, size, 4962 false, ACCESS_DIRECT, NULL); 4963 if (err) 4964 return err; 4965 4966 min_off = reg->smin_value + off; 4967 max_off = reg->smax_value + off; 4968 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 4969 return 0; 4970 } 4971 4972 /* check_stack_read dispatches to check_stack_read_fixed_off or 4973 * check_stack_read_var_off. 4974 * 4975 * The caller must ensure that the offset falls within the allocated stack 4976 * bounds. 4977 * 4978 * 'dst_regno' is a register which will receive the value from the stack. It 4979 * can be -1, meaning that the read value is not going to a register. 4980 */ 4981 static int check_stack_read(struct bpf_verifier_env *env, 4982 int ptr_regno, int off, int size, 4983 int dst_regno) 4984 { 4985 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4986 struct bpf_func_state *state = func(env, reg); 4987 int err; 4988 /* Some accesses are only permitted with a static offset. */ 4989 bool var_off = !tnum_is_const(reg->var_off); 4990 4991 /* The offset is required to be static when reads don't go to a 4992 * register, in order to not leak pointers (see 4993 * check_stack_read_fixed_off). 4994 */ 4995 if (dst_regno < 0 && var_off) { 4996 char tn_buf[48]; 4997 4998 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4999 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 5000 tn_buf, off, size); 5001 return -EACCES; 5002 } 5003 /* Variable offset is prohibited for unprivileged mode for simplicity 5004 * since it requires corresponding support in Spectre masking for stack 5005 * ALU. See also retrieve_ptr_limit(). The check in 5006 * check_stack_access_for_ptr_arithmetic() called by 5007 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 5008 * with variable offsets, therefore no check is required here. Further, 5009 * just checking it here would be insufficient as speculative stack 5010 * writes could still lead to unsafe speculative behaviour. 5011 */ 5012 if (!var_off) { 5013 off += reg->var_off.value; 5014 err = check_stack_read_fixed_off(env, state, off, size, 5015 dst_regno); 5016 } else { 5017 /* Variable offset stack reads need more conservative handling 5018 * than fixed offset ones. Note that dst_regno >= 0 on this 5019 * branch. 5020 */ 5021 err = check_stack_read_var_off(env, ptr_regno, off, size, 5022 dst_regno); 5023 } 5024 return err; 5025 } 5026 5027 5028 /* check_stack_write dispatches to check_stack_write_fixed_off or 5029 * check_stack_write_var_off. 5030 * 5031 * 'ptr_regno' is the register used as a pointer into the stack. 5032 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 5033 * 'value_regno' is the register whose value we're writing to the stack. It can 5034 * be -1, meaning that we're not writing from a register. 5035 * 5036 * The caller must ensure that the offset falls within the maximum stack size. 5037 */ 5038 static int check_stack_write(struct bpf_verifier_env *env, 5039 int ptr_regno, int off, int size, 5040 int value_regno, int insn_idx) 5041 { 5042 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5043 struct bpf_func_state *state = func(env, reg); 5044 int err; 5045 5046 if (tnum_is_const(reg->var_off)) { 5047 off += reg->var_off.value; 5048 err = check_stack_write_fixed_off(env, state, off, size, 5049 value_regno, insn_idx); 5050 } else { 5051 /* Variable offset stack reads need more conservative handling 5052 * than fixed offset ones. 5053 */ 5054 err = check_stack_write_var_off(env, state, 5055 ptr_regno, off, size, 5056 value_regno, insn_idx); 5057 } 5058 return err; 5059 } 5060 5061 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 5062 int off, int size, enum bpf_access_type type) 5063 { 5064 struct bpf_reg_state *regs = cur_regs(env); 5065 struct bpf_map *map = regs[regno].map_ptr; 5066 u32 cap = bpf_map_flags_to_cap(map); 5067 5068 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 5069 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 5070 map->value_size, off, size); 5071 return -EACCES; 5072 } 5073 5074 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 5075 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 5076 map->value_size, off, size); 5077 return -EACCES; 5078 } 5079 5080 return 0; 5081 } 5082 5083 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 5084 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 5085 int off, int size, u32 mem_size, 5086 bool zero_size_allowed) 5087 { 5088 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 5089 struct bpf_reg_state *reg; 5090 5091 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 5092 return 0; 5093 5094 reg = &cur_regs(env)[regno]; 5095 switch (reg->type) { 5096 case PTR_TO_MAP_KEY: 5097 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 5098 mem_size, off, size); 5099 break; 5100 case PTR_TO_MAP_VALUE: 5101 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 5102 mem_size, off, size); 5103 break; 5104 case PTR_TO_PACKET: 5105 case PTR_TO_PACKET_META: 5106 case PTR_TO_PACKET_END: 5107 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 5108 off, size, regno, reg->id, off, mem_size); 5109 break; 5110 case PTR_TO_MEM: 5111 default: 5112 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 5113 mem_size, off, size); 5114 } 5115 5116 return -EACCES; 5117 } 5118 5119 /* check read/write into a memory region with possible variable offset */ 5120 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 5121 int off, int size, u32 mem_size, 5122 bool zero_size_allowed) 5123 { 5124 struct bpf_verifier_state *vstate = env->cur_state; 5125 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5126 struct bpf_reg_state *reg = &state->regs[regno]; 5127 int err; 5128 5129 /* We may have adjusted the register pointing to memory region, so we 5130 * need to try adding each of min_value and max_value to off 5131 * to make sure our theoretical access will be safe. 5132 * 5133 * The minimum value is only important with signed 5134 * comparisons where we can't assume the floor of a 5135 * value is 0. If we are using signed variables for our 5136 * index'es we need to make sure that whatever we use 5137 * will have a set floor within our range. 5138 */ 5139 if (reg->smin_value < 0 && 5140 (reg->smin_value == S64_MIN || 5141 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5142 reg->smin_value + off < 0)) { 5143 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5144 regno); 5145 return -EACCES; 5146 } 5147 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5148 mem_size, zero_size_allowed); 5149 if (err) { 5150 verbose(env, "R%d min value is outside of the allowed memory range\n", 5151 regno); 5152 return err; 5153 } 5154 5155 /* If we haven't set a max value then we need to bail since we can't be 5156 * sure we won't do bad things. 5157 * If reg->umax_value + off could overflow, treat that as unbounded too. 5158 */ 5159 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5160 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5161 regno); 5162 return -EACCES; 5163 } 5164 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5165 mem_size, zero_size_allowed); 5166 if (err) { 5167 verbose(env, "R%d max value is outside of the allowed memory range\n", 5168 regno); 5169 return err; 5170 } 5171 5172 return 0; 5173 } 5174 5175 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5176 const struct bpf_reg_state *reg, int regno, 5177 bool fixed_off_ok) 5178 { 5179 /* Access to this pointer-typed register or passing it to a helper 5180 * is only allowed in its original, unmodified form. 5181 */ 5182 5183 if (reg->off < 0) { 5184 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5185 reg_type_str(env, reg->type), regno, reg->off); 5186 return -EACCES; 5187 } 5188 5189 if (!fixed_off_ok && reg->off) { 5190 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5191 reg_type_str(env, reg->type), regno, reg->off); 5192 return -EACCES; 5193 } 5194 5195 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5196 char tn_buf[48]; 5197 5198 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5199 verbose(env, "variable %s access var_off=%s disallowed\n", 5200 reg_type_str(env, reg->type), tn_buf); 5201 return -EACCES; 5202 } 5203 5204 return 0; 5205 } 5206 5207 static int check_ptr_off_reg(struct bpf_verifier_env *env, 5208 const struct bpf_reg_state *reg, int regno) 5209 { 5210 return __check_ptr_off_reg(env, reg, regno, false); 5211 } 5212 5213 static int map_kptr_match_type(struct bpf_verifier_env *env, 5214 struct btf_field *kptr_field, 5215 struct bpf_reg_state *reg, u32 regno) 5216 { 5217 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5218 int perm_flags; 5219 const char *reg_name = ""; 5220 5221 if (btf_is_kernel(reg->btf)) { 5222 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5223 5224 /* Only unreferenced case accepts untrusted pointers */ 5225 if (kptr_field->type == BPF_KPTR_UNREF) 5226 perm_flags |= PTR_UNTRUSTED; 5227 } else { 5228 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5229 if (kptr_field->type == BPF_KPTR_PERCPU) 5230 perm_flags |= MEM_PERCPU; 5231 } 5232 5233 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5234 goto bad_type; 5235 5236 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5237 reg_name = btf_type_name(reg->btf, reg->btf_id); 5238 5239 /* For ref_ptr case, release function check should ensure we get one 5240 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5241 * normal store of unreferenced kptr, we must ensure var_off is zero. 5242 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5243 * reg->off and reg->ref_obj_id are not needed here. 5244 */ 5245 if (__check_ptr_off_reg(env, reg, regno, true)) 5246 return -EACCES; 5247 5248 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5249 * we also need to take into account the reg->off. 5250 * 5251 * We want to support cases like: 5252 * 5253 * struct foo { 5254 * struct bar br; 5255 * struct baz bz; 5256 * }; 5257 * 5258 * struct foo *v; 5259 * v = func(); // PTR_TO_BTF_ID 5260 * val->foo = v; // reg->off is zero, btf and btf_id match type 5261 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5262 * // first member type of struct after comparison fails 5263 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5264 * // to match type 5265 * 5266 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5267 * is zero. We must also ensure that btf_struct_ids_match does not walk 5268 * the struct to match type against first member of struct, i.e. reject 5269 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5270 * strict mode to true for type match. 5271 */ 5272 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5273 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5274 kptr_field->type != BPF_KPTR_UNREF)) 5275 goto bad_type; 5276 return 0; 5277 bad_type: 5278 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5279 reg_type_str(env, reg->type), reg_name); 5280 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5281 if (kptr_field->type == BPF_KPTR_UNREF) 5282 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5283 targ_name); 5284 else 5285 verbose(env, "\n"); 5286 return -EINVAL; 5287 } 5288 5289 static bool in_sleepable(struct bpf_verifier_env *env) 5290 { 5291 return env->prog->sleepable || 5292 (env->cur_state && env->cur_state->in_sleepable); 5293 } 5294 5295 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5296 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5297 */ 5298 static bool in_rcu_cs(struct bpf_verifier_env *env) 5299 { 5300 return env->cur_state->active_rcu_lock || 5301 env->cur_state->active_lock.ptr || 5302 !in_sleepable(env); 5303 } 5304 5305 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5306 BTF_SET_START(rcu_protected_types) 5307 BTF_ID(struct, prog_test_ref_kfunc) 5308 #ifdef CONFIG_CGROUPS 5309 BTF_ID(struct, cgroup) 5310 #endif 5311 #ifdef CONFIG_BPF_JIT 5312 BTF_ID(struct, bpf_cpumask) 5313 #endif 5314 BTF_ID(struct, task_struct) 5315 BTF_ID(struct, bpf_crypto_ctx) 5316 BTF_SET_END(rcu_protected_types) 5317 5318 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5319 { 5320 if (!btf_is_kernel(btf)) 5321 return true; 5322 return btf_id_set_contains(&rcu_protected_types, btf_id); 5323 } 5324 5325 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 5326 { 5327 struct btf_struct_meta *meta; 5328 5329 if (btf_is_kernel(kptr_field->kptr.btf)) 5330 return NULL; 5331 5332 meta = btf_find_struct_meta(kptr_field->kptr.btf, 5333 kptr_field->kptr.btf_id); 5334 5335 return meta ? meta->record : NULL; 5336 } 5337 5338 static bool rcu_safe_kptr(const struct btf_field *field) 5339 { 5340 const struct btf_field_kptr *kptr = &field->kptr; 5341 5342 return field->type == BPF_KPTR_PERCPU || 5343 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 5344 } 5345 5346 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 5347 { 5348 struct btf_record *rec; 5349 u32 ret; 5350 5351 ret = PTR_MAYBE_NULL; 5352 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 5353 ret |= MEM_RCU; 5354 if (kptr_field->type == BPF_KPTR_PERCPU) 5355 ret |= MEM_PERCPU; 5356 else if (!btf_is_kernel(kptr_field->kptr.btf)) 5357 ret |= MEM_ALLOC; 5358 5359 rec = kptr_pointee_btf_record(kptr_field); 5360 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 5361 ret |= NON_OWN_REF; 5362 } else { 5363 ret |= PTR_UNTRUSTED; 5364 } 5365 5366 return ret; 5367 } 5368 5369 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5370 int value_regno, int insn_idx, 5371 struct btf_field *kptr_field) 5372 { 5373 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5374 int class = BPF_CLASS(insn->code); 5375 struct bpf_reg_state *val_reg; 5376 5377 /* Things we already checked for in check_map_access and caller: 5378 * - Reject cases where variable offset may touch kptr 5379 * - size of access (must be BPF_DW) 5380 * - tnum_is_const(reg->var_off) 5381 * - kptr_field->offset == off + reg->var_off.value 5382 */ 5383 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5384 if (BPF_MODE(insn->code) != BPF_MEM) { 5385 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5386 return -EACCES; 5387 } 5388 5389 /* We only allow loading referenced kptr, since it will be marked as 5390 * untrusted, similar to unreferenced kptr. 5391 */ 5392 if (class != BPF_LDX && 5393 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 5394 verbose(env, "store to referenced kptr disallowed\n"); 5395 return -EACCES; 5396 } 5397 5398 if (class == BPF_LDX) { 5399 val_reg = reg_state(env, value_regno); 5400 /* We can simply mark the value_regno receiving the pointer 5401 * value from map as PTR_TO_BTF_ID, with the correct type. 5402 */ 5403 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5404 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field)); 5405 } else if (class == BPF_STX) { 5406 val_reg = reg_state(env, value_regno); 5407 if (!register_is_null(val_reg) && 5408 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5409 return -EACCES; 5410 } else if (class == BPF_ST) { 5411 if (insn->imm) { 5412 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5413 kptr_field->offset); 5414 return -EACCES; 5415 } 5416 } else { 5417 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5418 return -EACCES; 5419 } 5420 return 0; 5421 } 5422 5423 /* check read/write into a map element with possible variable offset */ 5424 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5425 int off, int size, bool zero_size_allowed, 5426 enum bpf_access_src src) 5427 { 5428 struct bpf_verifier_state *vstate = env->cur_state; 5429 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5430 struct bpf_reg_state *reg = &state->regs[regno]; 5431 struct bpf_map *map = reg->map_ptr; 5432 struct btf_record *rec; 5433 int err, i; 5434 5435 err = check_mem_region_access(env, regno, off, size, map->value_size, 5436 zero_size_allowed); 5437 if (err) 5438 return err; 5439 5440 if (IS_ERR_OR_NULL(map->record)) 5441 return 0; 5442 rec = map->record; 5443 for (i = 0; i < rec->cnt; i++) { 5444 struct btf_field *field = &rec->fields[i]; 5445 u32 p = field->offset; 5446 5447 /* If any part of a field can be touched by load/store, reject 5448 * this program. To check that [x1, x2) overlaps with [y1, y2), 5449 * it is sufficient to check x1 < y2 && y1 < x2. 5450 */ 5451 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 5452 p < reg->umax_value + off + size) { 5453 switch (field->type) { 5454 case BPF_KPTR_UNREF: 5455 case BPF_KPTR_REF: 5456 case BPF_KPTR_PERCPU: 5457 if (src != ACCESS_DIRECT) { 5458 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 5459 return -EACCES; 5460 } 5461 if (!tnum_is_const(reg->var_off)) { 5462 verbose(env, "kptr access cannot have variable offset\n"); 5463 return -EACCES; 5464 } 5465 if (p != off + reg->var_off.value) { 5466 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 5467 p, off + reg->var_off.value); 5468 return -EACCES; 5469 } 5470 if (size != bpf_size_to_bytes(BPF_DW)) { 5471 verbose(env, "kptr access size must be BPF_DW\n"); 5472 return -EACCES; 5473 } 5474 break; 5475 default: 5476 verbose(env, "%s cannot be accessed directly by load/store\n", 5477 btf_field_type_name(field->type)); 5478 return -EACCES; 5479 } 5480 } 5481 } 5482 return 0; 5483 } 5484 5485 #define MAX_PACKET_OFF 0xffff 5486 5487 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5488 const struct bpf_call_arg_meta *meta, 5489 enum bpf_access_type t) 5490 { 5491 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5492 5493 switch (prog_type) { 5494 /* Program types only with direct read access go here! */ 5495 case BPF_PROG_TYPE_LWT_IN: 5496 case BPF_PROG_TYPE_LWT_OUT: 5497 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5498 case BPF_PROG_TYPE_SK_REUSEPORT: 5499 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5500 case BPF_PROG_TYPE_CGROUP_SKB: 5501 if (t == BPF_WRITE) 5502 return false; 5503 fallthrough; 5504 5505 /* Program types with direct read + write access go here! */ 5506 case BPF_PROG_TYPE_SCHED_CLS: 5507 case BPF_PROG_TYPE_SCHED_ACT: 5508 case BPF_PROG_TYPE_XDP: 5509 case BPF_PROG_TYPE_LWT_XMIT: 5510 case BPF_PROG_TYPE_SK_SKB: 5511 case BPF_PROG_TYPE_SK_MSG: 5512 if (meta) 5513 return meta->pkt_access; 5514 5515 env->seen_direct_write = true; 5516 return true; 5517 5518 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5519 if (t == BPF_WRITE) 5520 env->seen_direct_write = true; 5521 5522 return true; 5523 5524 default: 5525 return false; 5526 } 5527 } 5528 5529 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5530 int size, bool zero_size_allowed) 5531 { 5532 struct bpf_reg_state *regs = cur_regs(env); 5533 struct bpf_reg_state *reg = ®s[regno]; 5534 int err; 5535 5536 /* We may have added a variable offset to the packet pointer; but any 5537 * reg->range we have comes after that. We are only checking the fixed 5538 * offset. 5539 */ 5540 5541 /* We don't allow negative numbers, because we aren't tracking enough 5542 * detail to prove they're safe. 5543 */ 5544 if (reg->smin_value < 0) { 5545 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5546 regno); 5547 return -EACCES; 5548 } 5549 5550 err = reg->range < 0 ? -EINVAL : 5551 __check_mem_access(env, regno, off, size, reg->range, 5552 zero_size_allowed); 5553 if (err) { 5554 verbose(env, "R%d offset is outside of the packet\n", regno); 5555 return err; 5556 } 5557 5558 /* __check_mem_access has made sure "off + size - 1" is within u16. 5559 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5560 * otherwise find_good_pkt_pointers would have refused to set range info 5561 * that __check_mem_access would have rejected this pkt access. 5562 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5563 */ 5564 env->prog->aux->max_pkt_offset = 5565 max_t(u32, env->prog->aux->max_pkt_offset, 5566 off + reg->umax_value + size - 1); 5567 5568 return err; 5569 } 5570 5571 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5572 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5573 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5574 struct btf **btf, u32 *btf_id) 5575 { 5576 struct bpf_insn_access_aux info = { 5577 .reg_type = *reg_type, 5578 .log = &env->log, 5579 }; 5580 5581 if (env->ops->is_valid_access && 5582 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5583 /* A non zero info.ctx_field_size indicates that this field is a 5584 * candidate for later verifier transformation to load the whole 5585 * field and then apply a mask when accessed with a narrower 5586 * access than actual ctx access size. A zero info.ctx_field_size 5587 * will only allow for whole field access and rejects any other 5588 * type of narrower access. 5589 */ 5590 *reg_type = info.reg_type; 5591 5592 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5593 *btf = info.btf; 5594 *btf_id = info.btf_id; 5595 } else { 5596 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5597 } 5598 /* remember the offset of last byte accessed in ctx */ 5599 if (env->prog->aux->max_ctx_offset < off + size) 5600 env->prog->aux->max_ctx_offset = off + size; 5601 return 0; 5602 } 5603 5604 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5605 return -EACCES; 5606 } 5607 5608 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5609 int size) 5610 { 5611 if (size < 0 || off < 0 || 5612 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5613 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5614 off, size); 5615 return -EACCES; 5616 } 5617 return 0; 5618 } 5619 5620 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5621 u32 regno, int off, int size, 5622 enum bpf_access_type t) 5623 { 5624 struct bpf_reg_state *regs = cur_regs(env); 5625 struct bpf_reg_state *reg = ®s[regno]; 5626 struct bpf_insn_access_aux info = {}; 5627 bool valid; 5628 5629 if (reg->smin_value < 0) { 5630 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5631 regno); 5632 return -EACCES; 5633 } 5634 5635 switch (reg->type) { 5636 case PTR_TO_SOCK_COMMON: 5637 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5638 break; 5639 case PTR_TO_SOCKET: 5640 valid = bpf_sock_is_valid_access(off, size, t, &info); 5641 break; 5642 case PTR_TO_TCP_SOCK: 5643 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5644 break; 5645 case PTR_TO_XDP_SOCK: 5646 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5647 break; 5648 default: 5649 valid = false; 5650 } 5651 5652 5653 if (valid) { 5654 env->insn_aux_data[insn_idx].ctx_field_size = 5655 info.ctx_field_size; 5656 return 0; 5657 } 5658 5659 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5660 regno, reg_type_str(env, reg->type), off, size); 5661 5662 return -EACCES; 5663 } 5664 5665 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5666 { 5667 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5668 } 5669 5670 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5671 { 5672 const struct bpf_reg_state *reg = reg_state(env, regno); 5673 5674 return reg->type == PTR_TO_CTX; 5675 } 5676 5677 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5678 { 5679 const struct bpf_reg_state *reg = reg_state(env, regno); 5680 5681 return type_is_sk_pointer(reg->type); 5682 } 5683 5684 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5685 { 5686 const struct bpf_reg_state *reg = reg_state(env, regno); 5687 5688 return type_is_pkt_pointer(reg->type); 5689 } 5690 5691 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5692 { 5693 const struct bpf_reg_state *reg = reg_state(env, regno); 5694 5695 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5696 return reg->type == PTR_TO_FLOW_KEYS; 5697 } 5698 5699 static bool is_arena_reg(struct bpf_verifier_env *env, int regno) 5700 { 5701 const struct bpf_reg_state *reg = reg_state(env, regno); 5702 5703 return reg->type == PTR_TO_ARENA; 5704 } 5705 5706 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5707 #ifdef CONFIG_NET 5708 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5709 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5710 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5711 #endif 5712 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5713 }; 5714 5715 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5716 { 5717 /* A referenced register is always trusted. */ 5718 if (reg->ref_obj_id) 5719 return true; 5720 5721 /* Types listed in the reg2btf_ids are always trusted */ 5722 if (reg2btf_ids[base_type(reg->type)] && 5723 !bpf_type_has_unsafe_modifiers(reg->type)) 5724 return true; 5725 5726 /* If a register is not referenced, it is trusted if it has the 5727 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5728 * other type modifiers may be safe, but we elect to take an opt-in 5729 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5730 * not. 5731 * 5732 * Eventually, we should make PTR_TRUSTED the single source of truth 5733 * for whether a register is trusted. 5734 */ 5735 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5736 !bpf_type_has_unsafe_modifiers(reg->type); 5737 } 5738 5739 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5740 { 5741 return reg->type & MEM_RCU; 5742 } 5743 5744 static void clear_trusted_flags(enum bpf_type_flag *flag) 5745 { 5746 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5747 } 5748 5749 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5750 const struct bpf_reg_state *reg, 5751 int off, int size, bool strict) 5752 { 5753 struct tnum reg_off; 5754 int ip_align; 5755 5756 /* Byte size accesses are always allowed. */ 5757 if (!strict || size == 1) 5758 return 0; 5759 5760 /* For platforms that do not have a Kconfig enabling 5761 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5762 * NET_IP_ALIGN is universally set to '2'. And on platforms 5763 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5764 * to this code only in strict mode where we want to emulate 5765 * the NET_IP_ALIGN==2 checking. Therefore use an 5766 * unconditional IP align value of '2'. 5767 */ 5768 ip_align = 2; 5769 5770 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5771 if (!tnum_is_aligned(reg_off, size)) { 5772 char tn_buf[48]; 5773 5774 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5775 verbose(env, 5776 "misaligned packet access off %d+%s+%d+%d size %d\n", 5777 ip_align, tn_buf, reg->off, off, size); 5778 return -EACCES; 5779 } 5780 5781 return 0; 5782 } 5783 5784 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5785 const struct bpf_reg_state *reg, 5786 const char *pointer_desc, 5787 int off, int size, bool strict) 5788 { 5789 struct tnum reg_off; 5790 5791 /* Byte size accesses are always allowed. */ 5792 if (!strict || size == 1) 5793 return 0; 5794 5795 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5796 if (!tnum_is_aligned(reg_off, size)) { 5797 char tn_buf[48]; 5798 5799 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5800 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5801 pointer_desc, tn_buf, reg->off, off, size); 5802 return -EACCES; 5803 } 5804 5805 return 0; 5806 } 5807 5808 static int check_ptr_alignment(struct bpf_verifier_env *env, 5809 const struct bpf_reg_state *reg, int off, 5810 int size, bool strict_alignment_once) 5811 { 5812 bool strict = env->strict_alignment || strict_alignment_once; 5813 const char *pointer_desc = ""; 5814 5815 switch (reg->type) { 5816 case PTR_TO_PACKET: 5817 case PTR_TO_PACKET_META: 5818 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5819 * right in front, treat it the very same way. 5820 */ 5821 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5822 case PTR_TO_FLOW_KEYS: 5823 pointer_desc = "flow keys "; 5824 break; 5825 case PTR_TO_MAP_KEY: 5826 pointer_desc = "key "; 5827 break; 5828 case PTR_TO_MAP_VALUE: 5829 pointer_desc = "value "; 5830 break; 5831 case PTR_TO_CTX: 5832 pointer_desc = "context "; 5833 break; 5834 case PTR_TO_STACK: 5835 pointer_desc = "stack "; 5836 /* The stack spill tracking logic in check_stack_write_fixed_off() 5837 * and check_stack_read_fixed_off() relies on stack accesses being 5838 * aligned. 5839 */ 5840 strict = true; 5841 break; 5842 case PTR_TO_SOCKET: 5843 pointer_desc = "sock "; 5844 break; 5845 case PTR_TO_SOCK_COMMON: 5846 pointer_desc = "sock_common "; 5847 break; 5848 case PTR_TO_TCP_SOCK: 5849 pointer_desc = "tcp_sock "; 5850 break; 5851 case PTR_TO_XDP_SOCK: 5852 pointer_desc = "xdp_sock "; 5853 break; 5854 case PTR_TO_ARENA: 5855 return 0; 5856 default: 5857 break; 5858 } 5859 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5860 strict); 5861 } 5862 5863 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth) 5864 { 5865 if (env->prog->jit_requested) 5866 return round_up(stack_depth, 16); 5867 5868 /* round up to 32-bytes, since this is granularity 5869 * of interpreter stack size 5870 */ 5871 return round_up(max_t(u32, stack_depth, 1), 32); 5872 } 5873 5874 /* starting from main bpf function walk all instructions of the function 5875 * and recursively walk all callees that given function can call. 5876 * Ignore jump and exit insns. 5877 * Since recursion is prevented by check_cfg() this algorithm 5878 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 5879 */ 5880 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx) 5881 { 5882 struct bpf_subprog_info *subprog = env->subprog_info; 5883 struct bpf_insn *insn = env->prog->insnsi; 5884 int depth = 0, frame = 0, i, subprog_end; 5885 bool tail_call_reachable = false; 5886 int ret_insn[MAX_CALL_FRAMES]; 5887 int ret_prog[MAX_CALL_FRAMES]; 5888 int j; 5889 5890 i = subprog[idx].start; 5891 process_func: 5892 /* protect against potential stack overflow that might happen when 5893 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5894 * depth for such case down to 256 so that the worst case scenario 5895 * would result in 8k stack size (32 which is tailcall limit * 256 = 5896 * 8k). 5897 * 5898 * To get the idea what might happen, see an example: 5899 * func1 -> sub rsp, 128 5900 * subfunc1 -> sub rsp, 256 5901 * tailcall1 -> add rsp, 256 5902 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5903 * subfunc2 -> sub rsp, 64 5904 * subfunc22 -> sub rsp, 128 5905 * tailcall2 -> add rsp, 128 5906 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5907 * 5908 * tailcall will unwind the current stack frame but it will not get rid 5909 * of caller's stack as shown on the example above. 5910 */ 5911 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5912 verbose(env, 5913 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5914 depth); 5915 return -EACCES; 5916 } 5917 depth += round_up_stack_depth(env, subprog[idx].stack_depth); 5918 if (depth > MAX_BPF_STACK) { 5919 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5920 frame + 1, depth); 5921 return -EACCES; 5922 } 5923 continue_func: 5924 subprog_end = subprog[idx + 1].start; 5925 for (; i < subprog_end; i++) { 5926 int next_insn, sidx; 5927 5928 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 5929 bool err = false; 5930 5931 if (!is_bpf_throw_kfunc(insn + i)) 5932 continue; 5933 if (subprog[idx].is_cb) 5934 err = true; 5935 for (int c = 0; c < frame && !err; c++) { 5936 if (subprog[ret_prog[c]].is_cb) { 5937 err = true; 5938 break; 5939 } 5940 } 5941 if (!err) 5942 continue; 5943 verbose(env, 5944 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 5945 i, idx); 5946 return -EINVAL; 5947 } 5948 5949 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5950 continue; 5951 /* remember insn and function to return to */ 5952 ret_insn[frame] = i + 1; 5953 ret_prog[frame] = idx; 5954 5955 /* find the callee */ 5956 next_insn = i + insn[i].imm + 1; 5957 sidx = find_subprog(env, next_insn); 5958 if (sidx < 0) { 5959 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5960 next_insn); 5961 return -EFAULT; 5962 } 5963 if (subprog[sidx].is_async_cb) { 5964 if (subprog[sidx].has_tail_call) { 5965 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 5966 return -EFAULT; 5967 } 5968 /* async callbacks don't increase bpf prog stack size unless called directly */ 5969 if (!bpf_pseudo_call(insn + i)) 5970 continue; 5971 if (subprog[sidx].is_exception_cb) { 5972 verbose(env, "insn %d cannot call exception cb directly\n", i); 5973 return -EINVAL; 5974 } 5975 } 5976 i = next_insn; 5977 idx = sidx; 5978 5979 if (subprog[idx].has_tail_call) 5980 tail_call_reachable = true; 5981 5982 frame++; 5983 if (frame >= MAX_CALL_FRAMES) { 5984 verbose(env, "the call stack of %d frames is too deep !\n", 5985 frame); 5986 return -E2BIG; 5987 } 5988 goto process_func; 5989 } 5990 /* if tail call got detected across bpf2bpf calls then mark each of the 5991 * currently present subprog frames as tail call reachable subprogs; 5992 * this info will be utilized by JIT so that we will be preserving the 5993 * tail call counter throughout bpf2bpf calls combined with tailcalls 5994 */ 5995 if (tail_call_reachable) 5996 for (j = 0; j < frame; j++) { 5997 if (subprog[ret_prog[j]].is_exception_cb) { 5998 verbose(env, "cannot tail call within exception cb\n"); 5999 return -EINVAL; 6000 } 6001 subprog[ret_prog[j]].tail_call_reachable = true; 6002 } 6003 if (subprog[0].tail_call_reachable) 6004 env->prog->aux->tail_call_reachable = true; 6005 6006 /* end of for() loop means the last insn of the 'subprog' 6007 * was reached. Doesn't matter whether it was JA or EXIT 6008 */ 6009 if (frame == 0) 6010 return 0; 6011 depth -= round_up_stack_depth(env, subprog[idx].stack_depth); 6012 frame--; 6013 i = ret_insn[frame]; 6014 idx = ret_prog[frame]; 6015 goto continue_func; 6016 } 6017 6018 static int check_max_stack_depth(struct bpf_verifier_env *env) 6019 { 6020 struct bpf_subprog_info *si = env->subprog_info; 6021 int ret; 6022 6023 for (int i = 0; i < env->subprog_cnt; i++) { 6024 if (!i || si[i].is_async_cb) { 6025 ret = check_max_stack_depth_subprog(env, i); 6026 if (ret < 0) 6027 return ret; 6028 } 6029 continue; 6030 } 6031 return 0; 6032 } 6033 6034 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 6035 static int get_callee_stack_depth(struct bpf_verifier_env *env, 6036 const struct bpf_insn *insn, int idx) 6037 { 6038 int start = idx + insn->imm + 1, subprog; 6039 6040 subprog = find_subprog(env, start); 6041 if (subprog < 0) { 6042 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 6043 start); 6044 return -EFAULT; 6045 } 6046 return env->subprog_info[subprog].stack_depth; 6047 } 6048 #endif 6049 6050 static int __check_buffer_access(struct bpf_verifier_env *env, 6051 const char *buf_info, 6052 const struct bpf_reg_state *reg, 6053 int regno, int off, int size) 6054 { 6055 if (off < 0) { 6056 verbose(env, 6057 "R%d invalid %s buffer access: off=%d, size=%d\n", 6058 regno, buf_info, off, size); 6059 return -EACCES; 6060 } 6061 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6062 char tn_buf[48]; 6063 6064 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6065 verbose(env, 6066 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 6067 regno, off, tn_buf); 6068 return -EACCES; 6069 } 6070 6071 return 0; 6072 } 6073 6074 static int check_tp_buffer_access(struct bpf_verifier_env *env, 6075 const struct bpf_reg_state *reg, 6076 int regno, int off, int size) 6077 { 6078 int err; 6079 6080 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 6081 if (err) 6082 return err; 6083 6084 if (off + size > env->prog->aux->max_tp_access) 6085 env->prog->aux->max_tp_access = off + size; 6086 6087 return 0; 6088 } 6089 6090 static int check_buffer_access(struct bpf_verifier_env *env, 6091 const struct bpf_reg_state *reg, 6092 int regno, int off, int size, 6093 bool zero_size_allowed, 6094 u32 *max_access) 6095 { 6096 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 6097 int err; 6098 6099 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 6100 if (err) 6101 return err; 6102 6103 if (off + size > *max_access) 6104 *max_access = off + size; 6105 6106 return 0; 6107 } 6108 6109 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 6110 static void zext_32_to_64(struct bpf_reg_state *reg) 6111 { 6112 reg->var_off = tnum_subreg(reg->var_off); 6113 __reg_assign_32_into_64(reg); 6114 } 6115 6116 /* truncate register to smaller size (in bytes) 6117 * must be called with size < BPF_REG_SIZE 6118 */ 6119 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 6120 { 6121 u64 mask; 6122 6123 /* clear high bits in bit representation */ 6124 reg->var_off = tnum_cast(reg->var_off, size); 6125 6126 /* fix arithmetic bounds */ 6127 mask = ((u64)1 << (size * 8)) - 1; 6128 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 6129 reg->umin_value &= mask; 6130 reg->umax_value &= mask; 6131 } else { 6132 reg->umin_value = 0; 6133 reg->umax_value = mask; 6134 } 6135 reg->smin_value = reg->umin_value; 6136 reg->smax_value = reg->umax_value; 6137 6138 /* If size is smaller than 32bit register the 32bit register 6139 * values are also truncated so we push 64-bit bounds into 6140 * 32-bit bounds. Above were truncated < 32-bits already. 6141 */ 6142 if (size < 4) 6143 __mark_reg32_unbounded(reg); 6144 6145 reg_bounds_sync(reg); 6146 } 6147 6148 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 6149 { 6150 if (size == 1) { 6151 reg->smin_value = reg->s32_min_value = S8_MIN; 6152 reg->smax_value = reg->s32_max_value = S8_MAX; 6153 } else if (size == 2) { 6154 reg->smin_value = reg->s32_min_value = S16_MIN; 6155 reg->smax_value = reg->s32_max_value = S16_MAX; 6156 } else { 6157 /* size == 4 */ 6158 reg->smin_value = reg->s32_min_value = S32_MIN; 6159 reg->smax_value = reg->s32_max_value = S32_MAX; 6160 } 6161 reg->umin_value = reg->u32_min_value = 0; 6162 reg->umax_value = U64_MAX; 6163 reg->u32_max_value = U32_MAX; 6164 reg->var_off = tnum_unknown; 6165 } 6166 6167 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6168 { 6169 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6170 u64 top_smax_value, top_smin_value; 6171 u64 num_bits = size * 8; 6172 6173 if (tnum_is_const(reg->var_off)) { 6174 u64_cval = reg->var_off.value; 6175 if (size == 1) 6176 reg->var_off = tnum_const((s8)u64_cval); 6177 else if (size == 2) 6178 reg->var_off = tnum_const((s16)u64_cval); 6179 else 6180 /* size == 4 */ 6181 reg->var_off = tnum_const((s32)u64_cval); 6182 6183 u64_cval = reg->var_off.value; 6184 reg->smax_value = reg->smin_value = u64_cval; 6185 reg->umax_value = reg->umin_value = u64_cval; 6186 reg->s32_max_value = reg->s32_min_value = u64_cval; 6187 reg->u32_max_value = reg->u32_min_value = u64_cval; 6188 return; 6189 } 6190 6191 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6192 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6193 6194 if (top_smax_value != top_smin_value) 6195 goto out; 6196 6197 /* find the s64_min and s64_min after sign extension */ 6198 if (size == 1) { 6199 init_s64_max = (s8)reg->smax_value; 6200 init_s64_min = (s8)reg->smin_value; 6201 } else if (size == 2) { 6202 init_s64_max = (s16)reg->smax_value; 6203 init_s64_min = (s16)reg->smin_value; 6204 } else { 6205 init_s64_max = (s32)reg->smax_value; 6206 init_s64_min = (s32)reg->smin_value; 6207 } 6208 6209 s64_max = max(init_s64_max, init_s64_min); 6210 s64_min = min(init_s64_max, init_s64_min); 6211 6212 /* both of s64_max/s64_min positive or negative */ 6213 if ((s64_max >= 0) == (s64_min >= 0)) { 6214 reg->smin_value = reg->s32_min_value = s64_min; 6215 reg->smax_value = reg->s32_max_value = s64_max; 6216 reg->umin_value = reg->u32_min_value = s64_min; 6217 reg->umax_value = reg->u32_max_value = s64_max; 6218 reg->var_off = tnum_range(s64_min, s64_max); 6219 return; 6220 } 6221 6222 out: 6223 set_sext64_default_val(reg, size); 6224 } 6225 6226 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6227 { 6228 if (size == 1) { 6229 reg->s32_min_value = S8_MIN; 6230 reg->s32_max_value = S8_MAX; 6231 } else { 6232 /* size == 2 */ 6233 reg->s32_min_value = S16_MIN; 6234 reg->s32_max_value = S16_MAX; 6235 } 6236 reg->u32_min_value = 0; 6237 reg->u32_max_value = U32_MAX; 6238 } 6239 6240 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6241 { 6242 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6243 u32 top_smax_value, top_smin_value; 6244 u32 num_bits = size * 8; 6245 6246 if (tnum_is_const(reg->var_off)) { 6247 u32_val = reg->var_off.value; 6248 if (size == 1) 6249 reg->var_off = tnum_const((s8)u32_val); 6250 else 6251 reg->var_off = tnum_const((s16)u32_val); 6252 6253 u32_val = reg->var_off.value; 6254 reg->s32_min_value = reg->s32_max_value = u32_val; 6255 reg->u32_min_value = reg->u32_max_value = u32_val; 6256 return; 6257 } 6258 6259 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 6260 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 6261 6262 if (top_smax_value != top_smin_value) 6263 goto out; 6264 6265 /* find the s32_min and s32_min after sign extension */ 6266 if (size == 1) { 6267 init_s32_max = (s8)reg->s32_max_value; 6268 init_s32_min = (s8)reg->s32_min_value; 6269 } else { 6270 /* size == 2 */ 6271 init_s32_max = (s16)reg->s32_max_value; 6272 init_s32_min = (s16)reg->s32_min_value; 6273 } 6274 s32_max = max(init_s32_max, init_s32_min); 6275 s32_min = min(init_s32_max, init_s32_min); 6276 6277 if ((s32_min >= 0) == (s32_max >= 0)) { 6278 reg->s32_min_value = s32_min; 6279 reg->s32_max_value = s32_max; 6280 reg->u32_min_value = (u32)s32_min; 6281 reg->u32_max_value = (u32)s32_max; 6282 return; 6283 } 6284 6285 out: 6286 set_sext32_default_val(reg, size); 6287 } 6288 6289 static bool bpf_map_is_rdonly(const struct bpf_map *map) 6290 { 6291 /* A map is considered read-only if the following condition are true: 6292 * 6293 * 1) BPF program side cannot change any of the map content. The 6294 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6295 * and was set at map creation time. 6296 * 2) The map value(s) have been initialized from user space by a 6297 * loader and then "frozen", such that no new map update/delete 6298 * operations from syscall side are possible for the rest of 6299 * the map's lifetime from that point onwards. 6300 * 3) Any parallel/pending map update/delete operations from syscall 6301 * side have been completed. Only after that point, it's safe to 6302 * assume that map value(s) are immutable. 6303 */ 6304 return (map->map_flags & BPF_F_RDONLY_PROG) && 6305 READ_ONCE(map->frozen) && 6306 !bpf_map_write_active(map); 6307 } 6308 6309 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6310 bool is_ldsx) 6311 { 6312 void *ptr; 6313 u64 addr; 6314 int err; 6315 6316 err = map->ops->map_direct_value_addr(map, &addr, off); 6317 if (err) 6318 return err; 6319 ptr = (void *)(long)addr + off; 6320 6321 switch (size) { 6322 case sizeof(u8): 6323 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6324 break; 6325 case sizeof(u16): 6326 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6327 break; 6328 case sizeof(u32): 6329 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6330 break; 6331 case sizeof(u64): 6332 *val = *(u64 *)ptr; 6333 break; 6334 default: 6335 return -EINVAL; 6336 } 6337 return 0; 6338 } 6339 6340 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6341 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6342 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6343 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null) 6344 6345 /* 6346 * Allow list few fields as RCU trusted or full trusted. 6347 * This logic doesn't allow mix tagging and will be removed once GCC supports 6348 * btf_type_tag. 6349 */ 6350 6351 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6352 BTF_TYPE_SAFE_RCU(struct task_struct) { 6353 const cpumask_t *cpus_ptr; 6354 struct css_set __rcu *cgroups; 6355 struct task_struct __rcu *real_parent; 6356 struct task_struct *group_leader; 6357 }; 6358 6359 BTF_TYPE_SAFE_RCU(struct cgroup) { 6360 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6361 struct kernfs_node *kn; 6362 }; 6363 6364 BTF_TYPE_SAFE_RCU(struct css_set) { 6365 struct cgroup *dfl_cgrp; 6366 }; 6367 6368 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6369 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6370 struct file __rcu *exe_file; 6371 }; 6372 6373 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6374 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6375 */ 6376 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6377 struct sock *sk; 6378 }; 6379 6380 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6381 struct sock *sk; 6382 }; 6383 6384 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6385 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6386 struct seq_file *seq; 6387 }; 6388 6389 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6390 struct bpf_iter_meta *meta; 6391 struct task_struct *task; 6392 }; 6393 6394 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6395 struct file *file; 6396 }; 6397 6398 BTF_TYPE_SAFE_TRUSTED(struct file) { 6399 struct inode *f_inode; 6400 }; 6401 6402 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 6403 /* no negative dentry-s in places where bpf can see it */ 6404 struct inode *d_inode; 6405 }; 6406 6407 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) { 6408 struct sock *sk; 6409 }; 6410 6411 static bool type_is_rcu(struct bpf_verifier_env *env, 6412 struct bpf_reg_state *reg, 6413 const char *field_name, u32 btf_id) 6414 { 6415 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6416 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6417 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6418 6419 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6420 } 6421 6422 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6423 struct bpf_reg_state *reg, 6424 const char *field_name, u32 btf_id) 6425 { 6426 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6427 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6428 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6429 6430 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6431 } 6432 6433 static bool type_is_trusted(struct bpf_verifier_env *env, 6434 struct bpf_reg_state *reg, 6435 const char *field_name, u32 btf_id) 6436 { 6437 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 6438 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6439 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6440 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6441 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 6442 6443 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6444 } 6445 6446 static bool type_is_trusted_or_null(struct bpf_verifier_env *env, 6447 struct bpf_reg_state *reg, 6448 const char *field_name, u32 btf_id) 6449 { 6450 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)); 6451 6452 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, 6453 "__safe_trusted_or_null"); 6454 } 6455 6456 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6457 struct bpf_reg_state *regs, 6458 int regno, int off, int size, 6459 enum bpf_access_type atype, 6460 int value_regno) 6461 { 6462 struct bpf_reg_state *reg = regs + regno; 6463 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6464 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6465 const char *field_name = NULL; 6466 enum bpf_type_flag flag = 0; 6467 u32 btf_id = 0; 6468 int ret; 6469 6470 if (!env->allow_ptr_leaks) { 6471 verbose(env, 6472 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6473 tname); 6474 return -EPERM; 6475 } 6476 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6477 verbose(env, 6478 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6479 tname); 6480 return -EINVAL; 6481 } 6482 if (off < 0) { 6483 verbose(env, 6484 "R%d is ptr_%s invalid negative access: off=%d\n", 6485 regno, tname, off); 6486 return -EACCES; 6487 } 6488 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6489 char tn_buf[48]; 6490 6491 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6492 verbose(env, 6493 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6494 regno, tname, off, tn_buf); 6495 return -EACCES; 6496 } 6497 6498 if (reg->type & MEM_USER) { 6499 verbose(env, 6500 "R%d is ptr_%s access user memory: off=%d\n", 6501 regno, tname, off); 6502 return -EACCES; 6503 } 6504 6505 if (reg->type & MEM_PERCPU) { 6506 verbose(env, 6507 "R%d is ptr_%s access percpu memory: off=%d\n", 6508 regno, tname, off); 6509 return -EACCES; 6510 } 6511 6512 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6513 if (!btf_is_kernel(reg->btf)) { 6514 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 6515 return -EFAULT; 6516 } 6517 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6518 } else { 6519 /* Writes are permitted with default btf_struct_access for 6520 * program allocated objects (which always have ref_obj_id > 0), 6521 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6522 */ 6523 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6524 verbose(env, "only read is supported\n"); 6525 return -EACCES; 6526 } 6527 6528 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6529 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 6530 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 6531 return -EFAULT; 6532 } 6533 6534 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6535 } 6536 6537 if (ret < 0) 6538 return ret; 6539 6540 if (ret != PTR_TO_BTF_ID) { 6541 /* just mark; */ 6542 6543 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6544 /* If this is an untrusted pointer, all pointers formed by walking it 6545 * also inherit the untrusted flag. 6546 */ 6547 flag = PTR_UNTRUSTED; 6548 6549 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6550 /* By default any pointer obtained from walking a trusted pointer is no 6551 * longer trusted, unless the field being accessed has explicitly been 6552 * marked as inheriting its parent's state of trust (either full or RCU). 6553 * For example: 6554 * 'cgroups' pointer is untrusted if task->cgroups dereference 6555 * happened in a sleepable program outside of bpf_rcu_read_lock() 6556 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6557 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6558 * 6559 * A regular RCU-protected pointer with __rcu tag can also be deemed 6560 * trusted if we are in an RCU CS. Such pointer can be NULL. 6561 */ 6562 if (type_is_trusted(env, reg, field_name, btf_id)) { 6563 flag |= PTR_TRUSTED; 6564 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) { 6565 flag |= PTR_TRUSTED | PTR_MAYBE_NULL; 6566 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6567 if (type_is_rcu(env, reg, field_name, btf_id)) { 6568 /* ignore __rcu tag and mark it MEM_RCU */ 6569 flag |= MEM_RCU; 6570 } else if (flag & MEM_RCU || 6571 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6572 /* __rcu tagged pointers can be NULL */ 6573 flag |= MEM_RCU | PTR_MAYBE_NULL; 6574 6575 /* We always trust them */ 6576 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6577 flag & PTR_UNTRUSTED) 6578 flag &= ~PTR_UNTRUSTED; 6579 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6580 /* keep as-is */ 6581 } else { 6582 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6583 clear_trusted_flags(&flag); 6584 } 6585 } else { 6586 /* 6587 * If not in RCU CS or MEM_RCU pointer can be NULL then 6588 * aggressively mark as untrusted otherwise such 6589 * pointers will be plain PTR_TO_BTF_ID without flags 6590 * and will be allowed to be passed into helpers for 6591 * compat reasons. 6592 */ 6593 flag = PTR_UNTRUSTED; 6594 } 6595 } else { 6596 /* Old compat. Deprecated */ 6597 clear_trusted_flags(&flag); 6598 } 6599 6600 if (atype == BPF_READ && value_regno >= 0) 6601 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6602 6603 return 0; 6604 } 6605 6606 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6607 struct bpf_reg_state *regs, 6608 int regno, int off, int size, 6609 enum bpf_access_type atype, 6610 int value_regno) 6611 { 6612 struct bpf_reg_state *reg = regs + regno; 6613 struct bpf_map *map = reg->map_ptr; 6614 struct bpf_reg_state map_reg; 6615 enum bpf_type_flag flag = 0; 6616 const struct btf_type *t; 6617 const char *tname; 6618 u32 btf_id; 6619 int ret; 6620 6621 if (!btf_vmlinux) { 6622 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6623 return -ENOTSUPP; 6624 } 6625 6626 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6627 verbose(env, "map_ptr access not supported for map type %d\n", 6628 map->map_type); 6629 return -ENOTSUPP; 6630 } 6631 6632 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6633 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6634 6635 if (!env->allow_ptr_leaks) { 6636 verbose(env, 6637 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6638 tname); 6639 return -EPERM; 6640 } 6641 6642 if (off < 0) { 6643 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6644 regno, tname, off); 6645 return -EACCES; 6646 } 6647 6648 if (atype != BPF_READ) { 6649 verbose(env, "only read from %s is supported\n", tname); 6650 return -EACCES; 6651 } 6652 6653 /* Simulate access to a PTR_TO_BTF_ID */ 6654 memset(&map_reg, 0, sizeof(map_reg)); 6655 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6656 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6657 if (ret < 0) 6658 return ret; 6659 6660 if (value_regno >= 0) 6661 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6662 6663 return 0; 6664 } 6665 6666 /* Check that the stack access at the given offset is within bounds. The 6667 * maximum valid offset is -1. 6668 * 6669 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6670 * -state->allocated_stack for reads. 6671 */ 6672 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 6673 s64 off, 6674 struct bpf_func_state *state, 6675 enum bpf_access_type t) 6676 { 6677 int min_valid_off; 6678 6679 if (t == BPF_WRITE || env->allow_uninit_stack) 6680 min_valid_off = -MAX_BPF_STACK; 6681 else 6682 min_valid_off = -state->allocated_stack; 6683 6684 if (off < min_valid_off || off > -1) 6685 return -EACCES; 6686 return 0; 6687 } 6688 6689 /* Check that the stack access at 'regno + off' falls within the maximum stack 6690 * bounds. 6691 * 6692 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6693 */ 6694 static int check_stack_access_within_bounds( 6695 struct bpf_verifier_env *env, 6696 int regno, int off, int access_size, 6697 enum bpf_access_src src, enum bpf_access_type type) 6698 { 6699 struct bpf_reg_state *regs = cur_regs(env); 6700 struct bpf_reg_state *reg = regs + regno; 6701 struct bpf_func_state *state = func(env, reg); 6702 s64 min_off, max_off; 6703 int err; 6704 char *err_extra; 6705 6706 if (src == ACCESS_HELPER) 6707 /* We don't know if helpers are reading or writing (or both). */ 6708 err_extra = " indirect access to"; 6709 else if (type == BPF_READ) 6710 err_extra = " read from"; 6711 else 6712 err_extra = " write to"; 6713 6714 if (tnum_is_const(reg->var_off)) { 6715 min_off = (s64)reg->var_off.value + off; 6716 max_off = min_off + access_size; 6717 } else { 6718 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6719 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6720 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6721 err_extra, regno); 6722 return -EACCES; 6723 } 6724 min_off = reg->smin_value + off; 6725 max_off = reg->smax_value + off + access_size; 6726 } 6727 6728 err = check_stack_slot_within_bounds(env, min_off, state, type); 6729 if (!err && max_off > 0) 6730 err = -EINVAL; /* out of stack access into non-negative offsets */ 6731 if (!err && access_size < 0) 6732 /* access_size should not be negative (or overflow an int); others checks 6733 * along the way should have prevented such an access. 6734 */ 6735 err = -EFAULT; /* invalid negative access size; integer overflow? */ 6736 6737 if (err) { 6738 if (tnum_is_const(reg->var_off)) { 6739 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 6740 err_extra, regno, off, access_size); 6741 } else { 6742 char tn_buf[48]; 6743 6744 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6745 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n", 6746 err_extra, regno, tn_buf, off, access_size); 6747 } 6748 return err; 6749 } 6750 6751 /* Note that there is no stack access with offset zero, so the needed stack 6752 * size is -min_off, not -min_off+1. 6753 */ 6754 return grow_stack_state(env, state, -min_off /* size */); 6755 } 6756 6757 /* check whether memory at (regno + off) is accessible for t = (read | write) 6758 * if t==write, value_regno is a register which value is stored into memory 6759 * if t==read, value_regno is a register which will receive the value from memory 6760 * if t==write && value_regno==-1, some unknown value is stored into memory 6761 * if t==read && value_regno==-1, don't care what we read from memory 6762 */ 6763 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6764 int off, int bpf_size, enum bpf_access_type t, 6765 int value_regno, bool strict_alignment_once, bool is_ldsx) 6766 { 6767 struct bpf_reg_state *regs = cur_regs(env); 6768 struct bpf_reg_state *reg = regs + regno; 6769 int size, err = 0; 6770 6771 size = bpf_size_to_bytes(bpf_size); 6772 if (size < 0) 6773 return size; 6774 6775 /* alignment checks will add in reg->off themselves */ 6776 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6777 if (err) 6778 return err; 6779 6780 /* for access checks, reg->off is just part of off */ 6781 off += reg->off; 6782 6783 if (reg->type == PTR_TO_MAP_KEY) { 6784 if (t == BPF_WRITE) { 6785 verbose(env, "write to change key R%d not allowed\n", regno); 6786 return -EACCES; 6787 } 6788 6789 err = check_mem_region_access(env, regno, off, size, 6790 reg->map_ptr->key_size, false); 6791 if (err) 6792 return err; 6793 if (value_regno >= 0) 6794 mark_reg_unknown(env, regs, value_regno); 6795 } else if (reg->type == PTR_TO_MAP_VALUE) { 6796 struct btf_field *kptr_field = NULL; 6797 6798 if (t == BPF_WRITE && value_regno >= 0 && 6799 is_pointer_value(env, value_regno)) { 6800 verbose(env, "R%d leaks addr into map\n", value_regno); 6801 return -EACCES; 6802 } 6803 err = check_map_access_type(env, regno, off, size, t); 6804 if (err) 6805 return err; 6806 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6807 if (err) 6808 return err; 6809 if (tnum_is_const(reg->var_off)) 6810 kptr_field = btf_record_find(reg->map_ptr->record, 6811 off + reg->var_off.value, BPF_KPTR); 6812 if (kptr_field) { 6813 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6814 } else if (t == BPF_READ && value_regno >= 0) { 6815 struct bpf_map *map = reg->map_ptr; 6816 6817 /* if map is read-only, track its contents as scalars */ 6818 if (tnum_is_const(reg->var_off) && 6819 bpf_map_is_rdonly(map) && 6820 map->ops->map_direct_value_addr) { 6821 int map_off = off + reg->var_off.value; 6822 u64 val = 0; 6823 6824 err = bpf_map_direct_read(map, map_off, size, 6825 &val, is_ldsx); 6826 if (err) 6827 return err; 6828 6829 regs[value_regno].type = SCALAR_VALUE; 6830 __mark_reg_known(®s[value_regno], val); 6831 } else { 6832 mark_reg_unknown(env, regs, value_regno); 6833 } 6834 } 6835 } else if (base_type(reg->type) == PTR_TO_MEM) { 6836 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6837 6838 if (type_may_be_null(reg->type)) { 6839 verbose(env, "R%d invalid mem access '%s'\n", regno, 6840 reg_type_str(env, reg->type)); 6841 return -EACCES; 6842 } 6843 6844 if (t == BPF_WRITE && rdonly_mem) { 6845 verbose(env, "R%d cannot write into %s\n", 6846 regno, reg_type_str(env, reg->type)); 6847 return -EACCES; 6848 } 6849 6850 if (t == BPF_WRITE && value_regno >= 0 && 6851 is_pointer_value(env, value_regno)) { 6852 verbose(env, "R%d leaks addr into mem\n", value_regno); 6853 return -EACCES; 6854 } 6855 6856 err = check_mem_region_access(env, regno, off, size, 6857 reg->mem_size, false); 6858 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6859 mark_reg_unknown(env, regs, value_regno); 6860 } else if (reg->type == PTR_TO_CTX) { 6861 enum bpf_reg_type reg_type = SCALAR_VALUE; 6862 struct btf *btf = NULL; 6863 u32 btf_id = 0; 6864 6865 if (t == BPF_WRITE && value_regno >= 0 && 6866 is_pointer_value(env, value_regno)) { 6867 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6868 return -EACCES; 6869 } 6870 6871 err = check_ptr_off_reg(env, reg, regno); 6872 if (err < 0) 6873 return err; 6874 6875 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 6876 &btf_id); 6877 if (err) 6878 verbose_linfo(env, insn_idx, "; "); 6879 if (!err && t == BPF_READ && value_regno >= 0) { 6880 /* ctx access returns either a scalar, or a 6881 * PTR_TO_PACKET[_META,_END]. In the latter 6882 * case, we know the offset is zero. 6883 */ 6884 if (reg_type == SCALAR_VALUE) { 6885 mark_reg_unknown(env, regs, value_regno); 6886 } else { 6887 mark_reg_known_zero(env, regs, 6888 value_regno); 6889 if (type_may_be_null(reg_type)) 6890 regs[value_regno].id = ++env->id_gen; 6891 /* A load of ctx field could have different 6892 * actual load size with the one encoded in the 6893 * insn. When the dst is PTR, it is for sure not 6894 * a sub-register. 6895 */ 6896 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6897 if (base_type(reg_type) == PTR_TO_BTF_ID) { 6898 regs[value_regno].btf = btf; 6899 regs[value_regno].btf_id = btf_id; 6900 } 6901 } 6902 regs[value_regno].type = reg_type; 6903 } 6904 6905 } else if (reg->type == PTR_TO_STACK) { 6906 /* Basic bounds checks. */ 6907 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 6908 if (err) 6909 return err; 6910 6911 if (t == BPF_READ) 6912 err = check_stack_read(env, regno, off, size, 6913 value_regno); 6914 else 6915 err = check_stack_write(env, regno, off, size, 6916 value_regno, insn_idx); 6917 } else if (reg_is_pkt_pointer(reg)) { 6918 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6919 verbose(env, "cannot write into packet\n"); 6920 return -EACCES; 6921 } 6922 if (t == BPF_WRITE && value_regno >= 0 && 6923 is_pointer_value(env, value_regno)) { 6924 verbose(env, "R%d leaks addr into packet\n", 6925 value_regno); 6926 return -EACCES; 6927 } 6928 err = check_packet_access(env, regno, off, size, false); 6929 if (!err && t == BPF_READ && value_regno >= 0) 6930 mark_reg_unknown(env, regs, value_regno); 6931 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6932 if (t == BPF_WRITE && value_regno >= 0 && 6933 is_pointer_value(env, value_regno)) { 6934 verbose(env, "R%d leaks addr into flow keys\n", 6935 value_regno); 6936 return -EACCES; 6937 } 6938 6939 err = check_flow_keys_access(env, off, size); 6940 if (!err && t == BPF_READ && value_regno >= 0) 6941 mark_reg_unknown(env, regs, value_regno); 6942 } else if (type_is_sk_pointer(reg->type)) { 6943 if (t == BPF_WRITE) { 6944 verbose(env, "R%d cannot write into %s\n", 6945 regno, reg_type_str(env, reg->type)); 6946 return -EACCES; 6947 } 6948 err = check_sock_access(env, insn_idx, regno, off, size, t); 6949 if (!err && value_regno >= 0) 6950 mark_reg_unknown(env, regs, value_regno); 6951 } else if (reg->type == PTR_TO_TP_BUFFER) { 6952 err = check_tp_buffer_access(env, reg, regno, off, size); 6953 if (!err && t == BPF_READ && value_regno >= 0) 6954 mark_reg_unknown(env, regs, value_regno); 6955 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6956 !type_may_be_null(reg->type)) { 6957 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 6958 value_regno); 6959 } else if (reg->type == CONST_PTR_TO_MAP) { 6960 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 6961 value_regno); 6962 } else if (base_type(reg->type) == PTR_TO_BUF) { 6963 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6964 u32 *max_access; 6965 6966 if (rdonly_mem) { 6967 if (t == BPF_WRITE) { 6968 verbose(env, "R%d cannot write into %s\n", 6969 regno, reg_type_str(env, reg->type)); 6970 return -EACCES; 6971 } 6972 max_access = &env->prog->aux->max_rdonly_access; 6973 } else { 6974 max_access = &env->prog->aux->max_rdwr_access; 6975 } 6976 6977 err = check_buffer_access(env, reg, regno, off, size, false, 6978 max_access); 6979 6980 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6981 mark_reg_unknown(env, regs, value_regno); 6982 } else if (reg->type == PTR_TO_ARENA) { 6983 if (t == BPF_READ && value_regno >= 0) 6984 mark_reg_unknown(env, regs, value_regno); 6985 } else { 6986 verbose(env, "R%d invalid mem access '%s'\n", regno, 6987 reg_type_str(env, reg->type)); 6988 return -EACCES; 6989 } 6990 6991 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6992 regs[value_regno].type == SCALAR_VALUE) { 6993 if (!is_ldsx) 6994 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6995 coerce_reg_to_size(®s[value_regno], size); 6996 else 6997 coerce_reg_to_size_sx(®s[value_regno], size); 6998 } 6999 return err; 7000 } 7001 7002 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 7003 bool allow_trust_mismatch); 7004 7005 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 7006 { 7007 int load_reg; 7008 int err; 7009 7010 switch (insn->imm) { 7011 case BPF_ADD: 7012 case BPF_ADD | BPF_FETCH: 7013 case BPF_AND: 7014 case BPF_AND | BPF_FETCH: 7015 case BPF_OR: 7016 case BPF_OR | BPF_FETCH: 7017 case BPF_XOR: 7018 case BPF_XOR | BPF_FETCH: 7019 case BPF_XCHG: 7020 case BPF_CMPXCHG: 7021 break; 7022 default: 7023 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 7024 return -EINVAL; 7025 } 7026 7027 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 7028 verbose(env, "invalid atomic operand size\n"); 7029 return -EINVAL; 7030 } 7031 7032 /* check src1 operand */ 7033 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7034 if (err) 7035 return err; 7036 7037 /* check src2 operand */ 7038 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 7039 if (err) 7040 return err; 7041 7042 if (insn->imm == BPF_CMPXCHG) { 7043 /* Check comparison of R0 with memory location */ 7044 const u32 aux_reg = BPF_REG_0; 7045 7046 err = check_reg_arg(env, aux_reg, SRC_OP); 7047 if (err) 7048 return err; 7049 7050 if (is_pointer_value(env, aux_reg)) { 7051 verbose(env, "R%d leaks addr into mem\n", aux_reg); 7052 return -EACCES; 7053 } 7054 } 7055 7056 if (is_pointer_value(env, insn->src_reg)) { 7057 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 7058 return -EACCES; 7059 } 7060 7061 if (is_ctx_reg(env, insn->dst_reg) || 7062 is_pkt_reg(env, insn->dst_reg) || 7063 is_flow_key_reg(env, insn->dst_reg) || 7064 is_sk_reg(env, insn->dst_reg) || 7065 (is_arena_reg(env, insn->dst_reg) && !bpf_jit_supports_insn(insn, true))) { 7066 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 7067 insn->dst_reg, 7068 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 7069 return -EACCES; 7070 } 7071 7072 if (insn->imm & BPF_FETCH) { 7073 if (insn->imm == BPF_CMPXCHG) 7074 load_reg = BPF_REG_0; 7075 else 7076 load_reg = insn->src_reg; 7077 7078 /* check and record load of old value */ 7079 err = check_reg_arg(env, load_reg, DST_OP); 7080 if (err) 7081 return err; 7082 } else { 7083 /* This instruction accesses a memory location but doesn't 7084 * actually load it into a register. 7085 */ 7086 load_reg = -1; 7087 } 7088 7089 /* Check whether we can read the memory, with second call for fetch 7090 * case to simulate the register fill. 7091 */ 7092 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7093 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 7094 if (!err && load_reg >= 0) 7095 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7096 BPF_SIZE(insn->code), BPF_READ, load_reg, 7097 true, false); 7098 if (err) 7099 return err; 7100 7101 if (is_arena_reg(env, insn->dst_reg)) { 7102 err = save_aux_ptr_type(env, PTR_TO_ARENA, false); 7103 if (err) 7104 return err; 7105 } 7106 /* Check whether we can write into the same memory. */ 7107 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7108 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 7109 if (err) 7110 return err; 7111 return 0; 7112 } 7113 7114 /* When register 'regno' is used to read the stack (either directly or through 7115 * a helper function) make sure that it's within stack boundary and, depending 7116 * on the access type and privileges, that all elements of the stack are 7117 * initialized. 7118 * 7119 * 'off' includes 'regno->off', but not its dynamic part (if any). 7120 * 7121 * All registers that have been spilled on the stack in the slots within the 7122 * read offsets are marked as read. 7123 */ 7124 static int check_stack_range_initialized( 7125 struct bpf_verifier_env *env, int regno, int off, 7126 int access_size, bool zero_size_allowed, 7127 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 7128 { 7129 struct bpf_reg_state *reg = reg_state(env, regno); 7130 struct bpf_func_state *state = func(env, reg); 7131 int err, min_off, max_off, i, j, slot, spi; 7132 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 7133 enum bpf_access_type bounds_check_type; 7134 /* Some accesses can write anything into the stack, others are 7135 * read-only. 7136 */ 7137 bool clobber = false; 7138 7139 if (access_size == 0 && !zero_size_allowed) { 7140 verbose(env, "invalid zero-sized read\n"); 7141 return -EACCES; 7142 } 7143 7144 if (type == ACCESS_HELPER) { 7145 /* The bounds checks for writes are more permissive than for 7146 * reads. However, if raw_mode is not set, we'll do extra 7147 * checks below. 7148 */ 7149 bounds_check_type = BPF_WRITE; 7150 clobber = true; 7151 } else { 7152 bounds_check_type = BPF_READ; 7153 } 7154 err = check_stack_access_within_bounds(env, regno, off, access_size, 7155 type, bounds_check_type); 7156 if (err) 7157 return err; 7158 7159 7160 if (tnum_is_const(reg->var_off)) { 7161 min_off = max_off = reg->var_off.value + off; 7162 } else { 7163 /* Variable offset is prohibited for unprivileged mode for 7164 * simplicity since it requires corresponding support in 7165 * Spectre masking for stack ALU. 7166 * See also retrieve_ptr_limit(). 7167 */ 7168 if (!env->bypass_spec_v1) { 7169 char tn_buf[48]; 7170 7171 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7172 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 7173 regno, err_extra, tn_buf); 7174 return -EACCES; 7175 } 7176 /* Only initialized buffer on stack is allowed to be accessed 7177 * with variable offset. With uninitialized buffer it's hard to 7178 * guarantee that whole memory is marked as initialized on 7179 * helper return since specific bounds are unknown what may 7180 * cause uninitialized stack leaking. 7181 */ 7182 if (meta && meta->raw_mode) 7183 meta = NULL; 7184 7185 min_off = reg->smin_value + off; 7186 max_off = reg->smax_value + off; 7187 } 7188 7189 if (meta && meta->raw_mode) { 7190 /* Ensure we won't be overwriting dynptrs when simulating byte 7191 * by byte access in check_helper_call using meta.access_size. 7192 * This would be a problem if we have a helper in the future 7193 * which takes: 7194 * 7195 * helper(uninit_mem, len, dynptr) 7196 * 7197 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 7198 * may end up writing to dynptr itself when touching memory from 7199 * arg 1. This can be relaxed on a case by case basis for known 7200 * safe cases, but reject due to the possibilitiy of aliasing by 7201 * default. 7202 */ 7203 for (i = min_off; i < max_off + access_size; i++) { 7204 int stack_off = -i - 1; 7205 7206 spi = __get_spi(i); 7207 /* raw_mode may write past allocated_stack */ 7208 if (state->allocated_stack <= stack_off) 7209 continue; 7210 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 7211 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 7212 return -EACCES; 7213 } 7214 } 7215 meta->access_size = access_size; 7216 meta->regno = regno; 7217 return 0; 7218 } 7219 7220 for (i = min_off; i < max_off + access_size; i++) { 7221 u8 *stype; 7222 7223 slot = -i - 1; 7224 spi = slot / BPF_REG_SIZE; 7225 if (state->allocated_stack <= slot) { 7226 verbose(env, "verifier bug: allocated_stack too small"); 7227 return -EFAULT; 7228 } 7229 7230 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 7231 if (*stype == STACK_MISC) 7232 goto mark; 7233 if ((*stype == STACK_ZERO) || 7234 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 7235 if (clobber) { 7236 /* helper can write anything into the stack */ 7237 *stype = STACK_MISC; 7238 } 7239 goto mark; 7240 } 7241 7242 if (is_spilled_reg(&state->stack[spi]) && 7243 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 7244 env->allow_ptr_leaks)) { 7245 if (clobber) { 7246 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 7247 for (j = 0; j < BPF_REG_SIZE; j++) 7248 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 7249 } 7250 goto mark; 7251 } 7252 7253 if (tnum_is_const(reg->var_off)) { 7254 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 7255 err_extra, regno, min_off, i - min_off, access_size); 7256 } else { 7257 char tn_buf[48]; 7258 7259 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7260 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 7261 err_extra, regno, tn_buf, i - min_off, access_size); 7262 } 7263 return -EACCES; 7264 mark: 7265 /* reading any byte out of 8-byte 'spill_slot' will cause 7266 * the whole slot to be marked as 'read' 7267 */ 7268 mark_reg_read(env, &state->stack[spi].spilled_ptr, 7269 state->stack[spi].spilled_ptr.parent, 7270 REG_LIVE_READ64); 7271 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 7272 * be sure that whether stack slot is written to or not. Hence, 7273 * we must still conservatively propagate reads upwards even if 7274 * helper may write to the entire memory range. 7275 */ 7276 } 7277 return 0; 7278 } 7279 7280 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 7281 int access_size, bool zero_size_allowed, 7282 struct bpf_call_arg_meta *meta) 7283 { 7284 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7285 u32 *max_access; 7286 7287 switch (base_type(reg->type)) { 7288 case PTR_TO_PACKET: 7289 case PTR_TO_PACKET_META: 7290 return check_packet_access(env, regno, reg->off, access_size, 7291 zero_size_allowed); 7292 case PTR_TO_MAP_KEY: 7293 if (meta && meta->raw_mode) { 7294 verbose(env, "R%d cannot write into %s\n", regno, 7295 reg_type_str(env, reg->type)); 7296 return -EACCES; 7297 } 7298 return check_mem_region_access(env, regno, reg->off, access_size, 7299 reg->map_ptr->key_size, false); 7300 case PTR_TO_MAP_VALUE: 7301 if (check_map_access_type(env, regno, reg->off, access_size, 7302 meta && meta->raw_mode ? BPF_WRITE : 7303 BPF_READ)) 7304 return -EACCES; 7305 return check_map_access(env, regno, reg->off, access_size, 7306 zero_size_allowed, ACCESS_HELPER); 7307 case PTR_TO_MEM: 7308 if (type_is_rdonly_mem(reg->type)) { 7309 if (meta && meta->raw_mode) { 7310 verbose(env, "R%d cannot write into %s\n", regno, 7311 reg_type_str(env, reg->type)); 7312 return -EACCES; 7313 } 7314 } 7315 return check_mem_region_access(env, regno, reg->off, 7316 access_size, reg->mem_size, 7317 zero_size_allowed); 7318 case PTR_TO_BUF: 7319 if (type_is_rdonly_mem(reg->type)) { 7320 if (meta && meta->raw_mode) { 7321 verbose(env, "R%d cannot write into %s\n", regno, 7322 reg_type_str(env, reg->type)); 7323 return -EACCES; 7324 } 7325 7326 max_access = &env->prog->aux->max_rdonly_access; 7327 } else { 7328 max_access = &env->prog->aux->max_rdwr_access; 7329 } 7330 return check_buffer_access(env, reg, regno, reg->off, 7331 access_size, zero_size_allowed, 7332 max_access); 7333 case PTR_TO_STACK: 7334 return check_stack_range_initialized( 7335 env, 7336 regno, reg->off, access_size, 7337 zero_size_allowed, ACCESS_HELPER, meta); 7338 case PTR_TO_BTF_ID: 7339 return check_ptr_to_btf_access(env, regs, regno, reg->off, 7340 access_size, BPF_READ, -1); 7341 case PTR_TO_CTX: 7342 /* in case the function doesn't know how to access the context, 7343 * (because we are in a program of type SYSCALL for example), we 7344 * can not statically check its size. 7345 * Dynamically check it now. 7346 */ 7347 if (!env->ops->convert_ctx_access) { 7348 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 7349 int offset = access_size - 1; 7350 7351 /* Allow zero-byte read from PTR_TO_CTX */ 7352 if (access_size == 0) 7353 return zero_size_allowed ? 0 : -EACCES; 7354 7355 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 7356 atype, -1, false, false); 7357 } 7358 7359 fallthrough; 7360 default: /* scalar_value or invalid ptr */ 7361 /* Allow zero-byte read from NULL, regardless of pointer type */ 7362 if (zero_size_allowed && access_size == 0 && 7363 register_is_null(reg)) 7364 return 0; 7365 7366 verbose(env, "R%d type=%s ", regno, 7367 reg_type_str(env, reg->type)); 7368 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7369 return -EACCES; 7370 } 7371 } 7372 7373 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 7374 * size. 7375 * 7376 * @regno is the register containing the access size. regno-1 is the register 7377 * containing the pointer. 7378 */ 7379 static int check_mem_size_reg(struct bpf_verifier_env *env, 7380 struct bpf_reg_state *reg, u32 regno, 7381 bool zero_size_allowed, 7382 struct bpf_call_arg_meta *meta) 7383 { 7384 int err; 7385 7386 /* This is used to refine r0 return value bounds for helpers 7387 * that enforce this value as an upper bound on return values. 7388 * See do_refine_retval_range() for helpers that can refine 7389 * the return value. C type of helper is u32 so we pull register 7390 * bound from umax_value however, if negative verifier errors 7391 * out. Only upper bounds can be learned because retval is an 7392 * int type and negative retvals are allowed. 7393 */ 7394 meta->msize_max_value = reg->umax_value; 7395 7396 /* The register is SCALAR_VALUE; the access check 7397 * happens using its boundaries. 7398 */ 7399 if (!tnum_is_const(reg->var_off)) 7400 /* For unprivileged variable accesses, disable raw 7401 * mode so that the program is required to 7402 * initialize all the memory that the helper could 7403 * just partially fill up. 7404 */ 7405 meta = NULL; 7406 7407 if (reg->smin_value < 0) { 7408 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7409 regno); 7410 return -EACCES; 7411 } 7412 7413 if (reg->umin_value == 0 && !zero_size_allowed) { 7414 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n", 7415 regno, reg->umin_value, reg->umax_value); 7416 return -EACCES; 7417 } 7418 7419 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7420 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7421 regno); 7422 return -EACCES; 7423 } 7424 err = check_helper_mem_access(env, regno - 1, 7425 reg->umax_value, 7426 zero_size_allowed, meta); 7427 if (!err) 7428 err = mark_chain_precision(env, regno); 7429 return err; 7430 } 7431 7432 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7433 u32 regno, u32 mem_size) 7434 { 7435 bool may_be_null = type_may_be_null(reg->type); 7436 struct bpf_reg_state saved_reg; 7437 struct bpf_call_arg_meta meta; 7438 int err; 7439 7440 if (register_is_null(reg)) 7441 return 0; 7442 7443 memset(&meta, 0, sizeof(meta)); 7444 /* Assuming that the register contains a value check if the memory 7445 * access is safe. Temporarily save and restore the register's state as 7446 * the conversion shouldn't be visible to a caller. 7447 */ 7448 if (may_be_null) { 7449 saved_reg = *reg; 7450 mark_ptr_not_null_reg(reg); 7451 } 7452 7453 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 7454 /* Check access for BPF_WRITE */ 7455 meta.raw_mode = true; 7456 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 7457 7458 if (may_be_null) 7459 *reg = saved_reg; 7460 7461 return err; 7462 } 7463 7464 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7465 u32 regno) 7466 { 7467 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7468 bool may_be_null = type_may_be_null(mem_reg->type); 7469 struct bpf_reg_state saved_reg; 7470 struct bpf_call_arg_meta meta; 7471 int err; 7472 7473 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7474 7475 memset(&meta, 0, sizeof(meta)); 7476 7477 if (may_be_null) { 7478 saved_reg = *mem_reg; 7479 mark_ptr_not_null_reg(mem_reg); 7480 } 7481 7482 err = check_mem_size_reg(env, reg, regno, true, &meta); 7483 /* Check access for BPF_WRITE */ 7484 meta.raw_mode = true; 7485 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 7486 7487 if (may_be_null) 7488 *mem_reg = saved_reg; 7489 return err; 7490 } 7491 7492 /* Implementation details: 7493 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7494 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7495 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7496 * Two separate bpf_obj_new will also have different reg->id. 7497 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7498 * clears reg->id after value_or_null->value transition, since the verifier only 7499 * cares about the range of access to valid map value pointer and doesn't care 7500 * about actual address of the map element. 7501 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7502 * reg->id > 0 after value_or_null->value transition. By doing so 7503 * two bpf_map_lookups will be considered two different pointers that 7504 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7505 * returned from bpf_obj_new. 7506 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7507 * dead-locks. 7508 * Since only one bpf_spin_lock is allowed the checks are simpler than 7509 * reg_is_refcounted() logic. The verifier needs to remember only 7510 * one spin_lock instead of array of acquired_refs. 7511 * cur_state->active_lock remembers which map value element or allocated 7512 * object got locked and clears it after bpf_spin_unlock. 7513 */ 7514 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 7515 bool is_lock) 7516 { 7517 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7518 struct bpf_verifier_state *cur = env->cur_state; 7519 bool is_const = tnum_is_const(reg->var_off); 7520 u64 val = reg->var_off.value; 7521 struct bpf_map *map = NULL; 7522 struct btf *btf = NULL; 7523 struct btf_record *rec; 7524 7525 if (!is_const) { 7526 verbose(env, 7527 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 7528 regno); 7529 return -EINVAL; 7530 } 7531 if (reg->type == PTR_TO_MAP_VALUE) { 7532 map = reg->map_ptr; 7533 if (!map->btf) { 7534 verbose(env, 7535 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 7536 map->name); 7537 return -EINVAL; 7538 } 7539 } else { 7540 btf = reg->btf; 7541 } 7542 7543 rec = reg_btf_record(reg); 7544 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 7545 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 7546 map ? map->name : "kptr"); 7547 return -EINVAL; 7548 } 7549 if (rec->spin_lock_off != val + reg->off) { 7550 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 7551 val + reg->off, rec->spin_lock_off); 7552 return -EINVAL; 7553 } 7554 if (is_lock) { 7555 if (cur->active_lock.ptr) { 7556 verbose(env, 7557 "Locking two bpf_spin_locks are not allowed\n"); 7558 return -EINVAL; 7559 } 7560 if (map) 7561 cur->active_lock.ptr = map; 7562 else 7563 cur->active_lock.ptr = btf; 7564 cur->active_lock.id = reg->id; 7565 } else { 7566 void *ptr; 7567 7568 if (map) 7569 ptr = map; 7570 else 7571 ptr = btf; 7572 7573 if (!cur->active_lock.ptr) { 7574 verbose(env, "bpf_spin_unlock without taking a lock\n"); 7575 return -EINVAL; 7576 } 7577 if (cur->active_lock.ptr != ptr || 7578 cur->active_lock.id != reg->id) { 7579 verbose(env, "bpf_spin_unlock of different lock\n"); 7580 return -EINVAL; 7581 } 7582 7583 invalidate_non_owning_refs(env); 7584 7585 cur->active_lock.ptr = NULL; 7586 cur->active_lock.id = 0; 7587 } 7588 return 0; 7589 } 7590 7591 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7592 struct bpf_call_arg_meta *meta) 7593 { 7594 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7595 bool is_const = tnum_is_const(reg->var_off); 7596 struct bpf_map *map = reg->map_ptr; 7597 u64 val = reg->var_off.value; 7598 7599 if (!is_const) { 7600 verbose(env, 7601 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 7602 regno); 7603 return -EINVAL; 7604 } 7605 if (!map->btf) { 7606 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 7607 map->name); 7608 return -EINVAL; 7609 } 7610 if (!btf_record_has_field(map->record, BPF_TIMER)) { 7611 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 7612 return -EINVAL; 7613 } 7614 if (map->record->timer_off != val + reg->off) { 7615 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 7616 val + reg->off, map->record->timer_off); 7617 return -EINVAL; 7618 } 7619 if (meta->map_ptr) { 7620 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 7621 return -EFAULT; 7622 } 7623 meta->map_uid = reg->map_uid; 7624 meta->map_ptr = map; 7625 return 0; 7626 } 7627 7628 static int process_wq_func(struct bpf_verifier_env *env, int regno, 7629 struct bpf_kfunc_call_arg_meta *meta) 7630 { 7631 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7632 struct bpf_map *map = reg->map_ptr; 7633 u64 val = reg->var_off.value; 7634 7635 if (map->record->wq_off != val + reg->off) { 7636 verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n", 7637 val + reg->off, map->record->wq_off); 7638 return -EINVAL; 7639 } 7640 meta->map.uid = reg->map_uid; 7641 meta->map.ptr = map; 7642 return 0; 7643 } 7644 7645 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7646 struct bpf_call_arg_meta *meta) 7647 { 7648 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7649 struct bpf_map *map_ptr = reg->map_ptr; 7650 struct btf_field *kptr_field; 7651 u32 kptr_off; 7652 7653 if (!tnum_is_const(reg->var_off)) { 7654 verbose(env, 7655 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7656 regno); 7657 return -EINVAL; 7658 } 7659 if (!map_ptr->btf) { 7660 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7661 map_ptr->name); 7662 return -EINVAL; 7663 } 7664 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 7665 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 7666 return -EINVAL; 7667 } 7668 7669 meta->map_ptr = map_ptr; 7670 kptr_off = reg->off + reg->var_off.value; 7671 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 7672 if (!kptr_field) { 7673 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7674 return -EACCES; 7675 } 7676 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7677 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7678 return -EACCES; 7679 } 7680 meta->kptr_field = kptr_field; 7681 return 0; 7682 } 7683 7684 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7685 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7686 * 7687 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7688 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7689 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7690 * 7691 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7692 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7693 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7694 * mutate the view of the dynptr and also possibly destroy it. In the latter 7695 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7696 * memory that dynptr points to. 7697 * 7698 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7699 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7700 * readonly dynptr view yet, hence only the first case is tracked and checked. 7701 * 7702 * This is consistent with how C applies the const modifier to a struct object, 7703 * where the pointer itself inside bpf_dynptr becomes const but not what it 7704 * points to. 7705 * 7706 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7707 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7708 */ 7709 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7710 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7711 { 7712 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7713 int err; 7714 7715 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7716 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7717 */ 7718 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7719 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 7720 return -EFAULT; 7721 } 7722 7723 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7724 * constructing a mutable bpf_dynptr object. 7725 * 7726 * Currently, this is only possible with PTR_TO_STACK 7727 * pointing to a region of at least 16 bytes which doesn't 7728 * contain an existing bpf_dynptr. 7729 * 7730 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7731 * mutated or destroyed. However, the memory it points to 7732 * may be mutated. 7733 * 7734 * None - Points to a initialized dynptr that can be mutated and 7735 * destroyed, including mutation of the memory it points 7736 * to. 7737 */ 7738 if (arg_type & MEM_UNINIT) { 7739 int i; 7740 7741 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7742 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7743 return -EINVAL; 7744 } 7745 7746 /* we write BPF_DW bits (8 bytes) at a time */ 7747 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7748 err = check_mem_access(env, insn_idx, regno, 7749 i, BPF_DW, BPF_WRITE, -1, false, false); 7750 if (err) 7751 return err; 7752 } 7753 7754 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7755 } else /* MEM_RDONLY and None case from above */ { 7756 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7757 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7758 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7759 return -EINVAL; 7760 } 7761 7762 if (!is_dynptr_reg_valid_init(env, reg)) { 7763 verbose(env, 7764 "Expected an initialized dynptr as arg #%d\n", 7765 regno); 7766 return -EINVAL; 7767 } 7768 7769 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7770 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7771 verbose(env, 7772 "Expected a dynptr of type %s as arg #%d\n", 7773 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 7774 return -EINVAL; 7775 } 7776 7777 err = mark_dynptr_read(env, reg); 7778 } 7779 return err; 7780 } 7781 7782 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7783 { 7784 struct bpf_func_state *state = func(env, reg); 7785 7786 return state->stack[spi].spilled_ptr.ref_obj_id; 7787 } 7788 7789 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7790 { 7791 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7792 } 7793 7794 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7795 { 7796 return meta->kfunc_flags & KF_ITER_NEW; 7797 } 7798 7799 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7800 { 7801 return meta->kfunc_flags & KF_ITER_NEXT; 7802 } 7803 7804 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7805 { 7806 return meta->kfunc_flags & KF_ITER_DESTROY; 7807 } 7808 7809 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg) 7810 { 7811 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7812 * kfunc is iter state pointer 7813 */ 7814 return arg == 0 && is_iter_kfunc(meta); 7815 } 7816 7817 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7818 struct bpf_kfunc_call_arg_meta *meta) 7819 { 7820 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7821 const struct btf_type *t; 7822 const struct btf_param *arg; 7823 int spi, err, i, nr_slots; 7824 u32 btf_id; 7825 7826 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */ 7827 arg = &btf_params(meta->func_proto)[0]; 7828 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */ 7829 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */ 7830 nr_slots = t->size / BPF_REG_SIZE; 7831 7832 if (is_iter_new_kfunc(meta)) { 7833 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7834 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7835 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 7836 iter_type_str(meta->btf, btf_id), regno); 7837 return -EINVAL; 7838 } 7839 7840 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7841 err = check_mem_access(env, insn_idx, regno, 7842 i, BPF_DW, BPF_WRITE, -1, false, false); 7843 if (err) 7844 return err; 7845 } 7846 7847 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 7848 if (err) 7849 return err; 7850 } else { 7851 /* iter_next() or iter_destroy() expect initialized iter state*/ 7852 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 7853 switch (err) { 7854 case 0: 7855 break; 7856 case -EINVAL: 7857 verbose(env, "expected an initialized iter_%s as arg #%d\n", 7858 iter_type_str(meta->btf, btf_id), regno); 7859 return err; 7860 case -EPROTO: 7861 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 7862 return err; 7863 default: 7864 return err; 7865 } 7866 7867 spi = iter_get_spi(env, reg, nr_slots); 7868 if (spi < 0) 7869 return spi; 7870 7871 err = mark_iter_read(env, reg, spi, nr_slots); 7872 if (err) 7873 return err; 7874 7875 /* remember meta->iter info for process_iter_next_call() */ 7876 meta->iter.spi = spi; 7877 meta->iter.frameno = reg->frameno; 7878 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 7879 7880 if (is_iter_destroy_kfunc(meta)) { 7881 err = unmark_stack_slots_iter(env, reg, nr_slots); 7882 if (err) 7883 return err; 7884 } 7885 } 7886 7887 return 0; 7888 } 7889 7890 /* Look for a previous loop entry at insn_idx: nearest parent state 7891 * stopped at insn_idx with callsites matching those in cur->frame. 7892 */ 7893 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 7894 struct bpf_verifier_state *cur, 7895 int insn_idx) 7896 { 7897 struct bpf_verifier_state_list *sl; 7898 struct bpf_verifier_state *st; 7899 7900 /* Explored states are pushed in stack order, most recent states come first */ 7901 sl = *explored_state(env, insn_idx); 7902 for (; sl; sl = sl->next) { 7903 /* If st->branches != 0 state is a part of current DFS verification path, 7904 * hence cur & st for a loop. 7905 */ 7906 st = &sl->state; 7907 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 7908 st->dfs_depth < cur->dfs_depth) 7909 return st; 7910 } 7911 7912 return NULL; 7913 } 7914 7915 static void reset_idmap_scratch(struct bpf_verifier_env *env); 7916 static bool regs_exact(const struct bpf_reg_state *rold, 7917 const struct bpf_reg_state *rcur, 7918 struct bpf_idmap *idmap); 7919 7920 static void maybe_widen_reg(struct bpf_verifier_env *env, 7921 struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 7922 struct bpf_idmap *idmap) 7923 { 7924 if (rold->type != SCALAR_VALUE) 7925 return; 7926 if (rold->type != rcur->type) 7927 return; 7928 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap)) 7929 return; 7930 __mark_reg_unknown(env, rcur); 7931 } 7932 7933 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 7934 struct bpf_verifier_state *old, 7935 struct bpf_verifier_state *cur) 7936 { 7937 struct bpf_func_state *fold, *fcur; 7938 int i, fr; 7939 7940 reset_idmap_scratch(env); 7941 for (fr = old->curframe; fr >= 0; fr--) { 7942 fold = old->frame[fr]; 7943 fcur = cur->frame[fr]; 7944 7945 for (i = 0; i < MAX_BPF_REG; i++) 7946 maybe_widen_reg(env, 7947 &fold->regs[i], 7948 &fcur->regs[i], 7949 &env->idmap_scratch); 7950 7951 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) { 7952 if (!is_spilled_reg(&fold->stack[i]) || 7953 !is_spilled_reg(&fcur->stack[i])) 7954 continue; 7955 7956 maybe_widen_reg(env, 7957 &fold->stack[i].spilled_ptr, 7958 &fcur->stack[i].spilled_ptr, 7959 &env->idmap_scratch); 7960 } 7961 } 7962 return 0; 7963 } 7964 7965 /* process_iter_next_call() is called when verifier gets to iterator's next 7966 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7967 * to it as just "iter_next()" in comments below. 7968 * 7969 * BPF verifier relies on a crucial contract for any iter_next() 7970 * implementation: it should *eventually* return NULL, and once that happens 7971 * it should keep returning NULL. That is, once iterator exhausts elements to 7972 * iterate, it should never reset or spuriously return new elements. 7973 * 7974 * With the assumption of such contract, process_iter_next_call() simulates 7975 * a fork in the verifier state to validate loop logic correctness and safety 7976 * without having to simulate infinite amount of iterations. 7977 * 7978 * In current state, we first assume that iter_next() returned NULL and 7979 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7980 * conditions we should not form an infinite loop and should eventually reach 7981 * exit. 7982 * 7983 * Besides that, we also fork current state and enqueue it for later 7984 * verification. In a forked state we keep iterator state as ACTIVE 7985 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7986 * also bump iteration depth to prevent erroneous infinite loop detection 7987 * later on (see iter_active_depths_differ() comment for details). In this 7988 * state we assume that we'll eventually loop back to another iter_next() 7989 * calls (it could be in exactly same location or in some other instruction, 7990 * it doesn't matter, we don't make any unnecessary assumptions about this, 7991 * everything revolves around iterator state in a stack slot, not which 7992 * instruction is calling iter_next()). When that happens, we either will come 7993 * to iter_next() with equivalent state and can conclude that next iteration 7994 * will proceed in exactly the same way as we just verified, so it's safe to 7995 * assume that loop converges. If not, we'll go on another iteration 7996 * simulation with a different input state, until all possible starting states 7997 * are validated or we reach maximum number of instructions limit. 7998 * 7999 * This way, we will either exhaustively discover all possible input states 8000 * that iterator loop can start with and eventually will converge, or we'll 8001 * effectively regress into bounded loop simulation logic and either reach 8002 * maximum number of instructions if loop is not provably convergent, or there 8003 * is some statically known limit on number of iterations (e.g., if there is 8004 * an explicit `if n > 100 then break;` statement somewhere in the loop). 8005 * 8006 * Iteration convergence logic in is_state_visited() relies on exact 8007 * states comparison, which ignores read and precision marks. 8008 * This is necessary because read and precision marks are not finalized 8009 * while in the loop. Exact comparison might preclude convergence for 8010 * simple programs like below: 8011 * 8012 * i = 0; 8013 * while(iter_next(&it)) 8014 * i++; 8015 * 8016 * At each iteration step i++ would produce a new distinct state and 8017 * eventually instruction processing limit would be reached. 8018 * 8019 * To avoid such behavior speculatively forget (widen) range for 8020 * imprecise scalar registers, if those registers were not precise at the 8021 * end of the previous iteration and do not match exactly. 8022 * 8023 * This is a conservative heuristic that allows to verify wide range of programs, 8024 * however it precludes verification of programs that conjure an 8025 * imprecise value on the first loop iteration and use it as precise on a second. 8026 * For example, the following safe program would fail to verify: 8027 * 8028 * struct bpf_num_iter it; 8029 * int arr[10]; 8030 * int i = 0, a = 0; 8031 * bpf_iter_num_new(&it, 0, 10); 8032 * while (bpf_iter_num_next(&it)) { 8033 * if (a == 0) { 8034 * a = 1; 8035 * i = 7; // Because i changed verifier would forget 8036 * // it's range on second loop entry. 8037 * } else { 8038 * arr[i] = 42; // This would fail to verify. 8039 * } 8040 * } 8041 * bpf_iter_num_destroy(&it); 8042 */ 8043 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 8044 struct bpf_kfunc_call_arg_meta *meta) 8045 { 8046 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 8047 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 8048 struct bpf_reg_state *cur_iter, *queued_iter; 8049 int iter_frameno = meta->iter.frameno; 8050 int iter_spi = meta->iter.spi; 8051 8052 BTF_TYPE_EMIT(struct bpf_iter); 8053 8054 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 8055 8056 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 8057 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 8058 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 8059 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 8060 return -EFAULT; 8061 } 8062 8063 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 8064 /* Because iter_next() call is a checkpoint is_state_visitied() 8065 * should guarantee parent state with same call sites and insn_idx. 8066 */ 8067 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 8068 !same_callsites(cur_st->parent, cur_st)) { 8069 verbose(env, "bug: bad parent state for iter next call"); 8070 return -EFAULT; 8071 } 8072 /* Note cur_st->parent in the call below, it is necessary to skip 8073 * checkpoint created for cur_st by is_state_visited() 8074 * right at this instruction. 8075 */ 8076 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 8077 /* branch out active iter state */ 8078 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 8079 if (!queued_st) 8080 return -ENOMEM; 8081 8082 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 8083 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 8084 queued_iter->iter.depth++; 8085 if (prev_st) 8086 widen_imprecise_scalars(env, prev_st, queued_st); 8087 8088 queued_fr = queued_st->frame[queued_st->curframe]; 8089 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 8090 } 8091 8092 /* switch to DRAINED state, but keep the depth unchanged */ 8093 /* mark current iter state as drained and assume returned NULL */ 8094 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 8095 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 8096 8097 return 0; 8098 } 8099 8100 static bool arg_type_is_mem_size(enum bpf_arg_type type) 8101 { 8102 return type == ARG_CONST_SIZE || 8103 type == ARG_CONST_SIZE_OR_ZERO; 8104 } 8105 8106 static bool arg_type_is_release(enum bpf_arg_type type) 8107 { 8108 return type & OBJ_RELEASE; 8109 } 8110 8111 static bool arg_type_is_dynptr(enum bpf_arg_type type) 8112 { 8113 return base_type(type) == ARG_PTR_TO_DYNPTR; 8114 } 8115 8116 static int int_ptr_type_to_size(enum bpf_arg_type type) 8117 { 8118 if (type == ARG_PTR_TO_INT) 8119 return sizeof(u32); 8120 else if (type == ARG_PTR_TO_LONG) 8121 return sizeof(u64); 8122 8123 return -EINVAL; 8124 } 8125 8126 static int resolve_map_arg_type(struct bpf_verifier_env *env, 8127 const struct bpf_call_arg_meta *meta, 8128 enum bpf_arg_type *arg_type) 8129 { 8130 if (!meta->map_ptr) { 8131 /* kernel subsystem misconfigured verifier */ 8132 verbose(env, "invalid map_ptr to access map->type\n"); 8133 return -EACCES; 8134 } 8135 8136 switch (meta->map_ptr->map_type) { 8137 case BPF_MAP_TYPE_SOCKMAP: 8138 case BPF_MAP_TYPE_SOCKHASH: 8139 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 8140 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 8141 } else { 8142 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 8143 return -EINVAL; 8144 } 8145 break; 8146 case BPF_MAP_TYPE_BLOOM_FILTER: 8147 if (meta->func_id == BPF_FUNC_map_peek_elem) 8148 *arg_type = ARG_PTR_TO_MAP_VALUE; 8149 break; 8150 default: 8151 break; 8152 } 8153 return 0; 8154 } 8155 8156 struct bpf_reg_types { 8157 const enum bpf_reg_type types[10]; 8158 u32 *btf_id; 8159 }; 8160 8161 static const struct bpf_reg_types sock_types = { 8162 .types = { 8163 PTR_TO_SOCK_COMMON, 8164 PTR_TO_SOCKET, 8165 PTR_TO_TCP_SOCK, 8166 PTR_TO_XDP_SOCK, 8167 }, 8168 }; 8169 8170 #ifdef CONFIG_NET 8171 static const struct bpf_reg_types btf_id_sock_common_types = { 8172 .types = { 8173 PTR_TO_SOCK_COMMON, 8174 PTR_TO_SOCKET, 8175 PTR_TO_TCP_SOCK, 8176 PTR_TO_XDP_SOCK, 8177 PTR_TO_BTF_ID, 8178 PTR_TO_BTF_ID | PTR_TRUSTED, 8179 }, 8180 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 8181 }; 8182 #endif 8183 8184 static const struct bpf_reg_types mem_types = { 8185 .types = { 8186 PTR_TO_STACK, 8187 PTR_TO_PACKET, 8188 PTR_TO_PACKET_META, 8189 PTR_TO_MAP_KEY, 8190 PTR_TO_MAP_VALUE, 8191 PTR_TO_MEM, 8192 PTR_TO_MEM | MEM_RINGBUF, 8193 PTR_TO_BUF, 8194 PTR_TO_BTF_ID | PTR_TRUSTED, 8195 }, 8196 }; 8197 8198 static const struct bpf_reg_types int_ptr_types = { 8199 .types = { 8200 PTR_TO_STACK, 8201 PTR_TO_PACKET, 8202 PTR_TO_PACKET_META, 8203 PTR_TO_MAP_KEY, 8204 PTR_TO_MAP_VALUE, 8205 }, 8206 }; 8207 8208 static const struct bpf_reg_types spin_lock_types = { 8209 .types = { 8210 PTR_TO_MAP_VALUE, 8211 PTR_TO_BTF_ID | MEM_ALLOC, 8212 } 8213 }; 8214 8215 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 8216 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 8217 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 8218 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 8219 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 8220 static const struct bpf_reg_types btf_ptr_types = { 8221 .types = { 8222 PTR_TO_BTF_ID, 8223 PTR_TO_BTF_ID | PTR_TRUSTED, 8224 PTR_TO_BTF_ID | MEM_RCU, 8225 }, 8226 }; 8227 static const struct bpf_reg_types percpu_btf_ptr_types = { 8228 .types = { 8229 PTR_TO_BTF_ID | MEM_PERCPU, 8230 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 8231 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 8232 } 8233 }; 8234 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 8235 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 8236 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8237 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 8238 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8239 static const struct bpf_reg_types dynptr_types = { 8240 .types = { 8241 PTR_TO_STACK, 8242 CONST_PTR_TO_DYNPTR, 8243 } 8244 }; 8245 8246 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 8247 [ARG_PTR_TO_MAP_KEY] = &mem_types, 8248 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 8249 [ARG_CONST_SIZE] = &scalar_types, 8250 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 8251 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 8252 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 8253 [ARG_PTR_TO_CTX] = &context_types, 8254 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 8255 #ifdef CONFIG_NET 8256 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 8257 #endif 8258 [ARG_PTR_TO_SOCKET] = &fullsock_types, 8259 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 8260 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 8261 [ARG_PTR_TO_MEM] = &mem_types, 8262 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 8263 [ARG_PTR_TO_INT] = &int_ptr_types, 8264 [ARG_PTR_TO_LONG] = &int_ptr_types, 8265 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 8266 [ARG_PTR_TO_FUNC] = &func_ptr_types, 8267 [ARG_PTR_TO_STACK] = &stack_ptr_types, 8268 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 8269 [ARG_PTR_TO_TIMER] = &timer_types, 8270 [ARG_PTR_TO_KPTR] = &kptr_types, 8271 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 8272 }; 8273 8274 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 8275 enum bpf_arg_type arg_type, 8276 const u32 *arg_btf_id, 8277 struct bpf_call_arg_meta *meta) 8278 { 8279 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8280 enum bpf_reg_type expected, type = reg->type; 8281 const struct bpf_reg_types *compatible; 8282 int i, j; 8283 8284 compatible = compatible_reg_types[base_type(arg_type)]; 8285 if (!compatible) { 8286 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 8287 return -EFAULT; 8288 } 8289 8290 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 8291 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 8292 * 8293 * Same for MAYBE_NULL: 8294 * 8295 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 8296 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 8297 * 8298 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 8299 * 8300 * Therefore we fold these flags depending on the arg_type before comparison. 8301 */ 8302 if (arg_type & MEM_RDONLY) 8303 type &= ~MEM_RDONLY; 8304 if (arg_type & PTR_MAYBE_NULL) 8305 type &= ~PTR_MAYBE_NULL; 8306 if (base_type(arg_type) == ARG_PTR_TO_MEM) 8307 type &= ~DYNPTR_TYPE_FLAG_MASK; 8308 8309 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) { 8310 type &= ~MEM_ALLOC; 8311 type &= ~MEM_PERCPU; 8312 } 8313 8314 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 8315 expected = compatible->types[i]; 8316 if (expected == NOT_INIT) 8317 break; 8318 8319 if (type == expected) 8320 goto found; 8321 } 8322 8323 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 8324 for (j = 0; j + 1 < i; j++) 8325 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 8326 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 8327 return -EACCES; 8328 8329 found: 8330 if (base_type(reg->type) != PTR_TO_BTF_ID) 8331 return 0; 8332 8333 if (compatible == &mem_types) { 8334 if (!(arg_type & MEM_RDONLY)) { 8335 verbose(env, 8336 "%s() may write into memory pointed by R%d type=%s\n", 8337 func_id_name(meta->func_id), 8338 regno, reg_type_str(env, reg->type)); 8339 return -EACCES; 8340 } 8341 return 0; 8342 } 8343 8344 switch ((int)reg->type) { 8345 case PTR_TO_BTF_ID: 8346 case PTR_TO_BTF_ID | PTR_TRUSTED: 8347 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL: 8348 case PTR_TO_BTF_ID | MEM_RCU: 8349 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 8350 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 8351 { 8352 /* For bpf_sk_release, it needs to match against first member 8353 * 'struct sock_common', hence make an exception for it. This 8354 * allows bpf_sk_release to work for multiple socket types. 8355 */ 8356 bool strict_type_match = arg_type_is_release(arg_type) && 8357 meta->func_id != BPF_FUNC_sk_release; 8358 8359 if (type_may_be_null(reg->type) && 8360 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 8361 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 8362 return -EACCES; 8363 } 8364 8365 if (!arg_btf_id) { 8366 if (!compatible->btf_id) { 8367 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 8368 return -EFAULT; 8369 } 8370 arg_btf_id = compatible->btf_id; 8371 } 8372 8373 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8374 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8375 return -EACCES; 8376 } else { 8377 if (arg_btf_id == BPF_PTR_POISON) { 8378 verbose(env, "verifier internal error:"); 8379 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 8380 regno); 8381 return -EACCES; 8382 } 8383 8384 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 8385 btf_vmlinux, *arg_btf_id, 8386 strict_type_match)) { 8387 verbose(env, "R%d is of type %s but %s is expected\n", 8388 regno, btf_type_name(reg->btf, reg->btf_id), 8389 btf_type_name(btf_vmlinux, *arg_btf_id)); 8390 return -EACCES; 8391 } 8392 } 8393 break; 8394 } 8395 case PTR_TO_BTF_ID | MEM_ALLOC: 8396 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 8397 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8398 meta->func_id != BPF_FUNC_kptr_xchg) { 8399 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 8400 return -EFAULT; 8401 } 8402 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8403 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8404 return -EACCES; 8405 } 8406 break; 8407 case PTR_TO_BTF_ID | MEM_PERCPU: 8408 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 8409 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8410 /* Handled by helper specific checks */ 8411 break; 8412 default: 8413 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 8414 return -EFAULT; 8415 } 8416 return 0; 8417 } 8418 8419 static struct btf_field * 8420 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8421 { 8422 struct btf_field *field; 8423 struct btf_record *rec; 8424 8425 rec = reg_btf_record(reg); 8426 if (!rec) 8427 return NULL; 8428 8429 field = btf_record_find(rec, off, fields); 8430 if (!field) 8431 return NULL; 8432 8433 return field; 8434 } 8435 8436 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 8437 const struct bpf_reg_state *reg, int regno, 8438 enum bpf_arg_type arg_type) 8439 { 8440 u32 type = reg->type; 8441 8442 /* When referenced register is passed to release function, its fixed 8443 * offset must be 0. 8444 * 8445 * We will check arg_type_is_release reg has ref_obj_id when storing 8446 * meta->release_regno. 8447 */ 8448 if (arg_type_is_release(arg_type)) { 8449 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8450 * may not directly point to the object being released, but to 8451 * dynptr pointing to such object, which might be at some offset 8452 * on the stack. In that case, we simply to fallback to the 8453 * default handling. 8454 */ 8455 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8456 return 0; 8457 8458 /* Doing check_ptr_off_reg check for the offset will catch this 8459 * because fixed_off_ok is false, but checking here allows us 8460 * to give the user a better error message. 8461 */ 8462 if (reg->off) { 8463 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 8464 regno); 8465 return -EINVAL; 8466 } 8467 return __check_ptr_off_reg(env, reg, regno, false); 8468 } 8469 8470 switch (type) { 8471 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8472 case PTR_TO_STACK: 8473 case PTR_TO_PACKET: 8474 case PTR_TO_PACKET_META: 8475 case PTR_TO_MAP_KEY: 8476 case PTR_TO_MAP_VALUE: 8477 case PTR_TO_MEM: 8478 case PTR_TO_MEM | MEM_RDONLY: 8479 case PTR_TO_MEM | MEM_RINGBUF: 8480 case PTR_TO_BUF: 8481 case PTR_TO_BUF | MEM_RDONLY: 8482 case PTR_TO_ARENA: 8483 case SCALAR_VALUE: 8484 return 0; 8485 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8486 * fixed offset. 8487 */ 8488 case PTR_TO_BTF_ID: 8489 case PTR_TO_BTF_ID | MEM_ALLOC: 8490 case PTR_TO_BTF_ID | PTR_TRUSTED: 8491 case PTR_TO_BTF_ID | MEM_RCU: 8492 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8493 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8494 /* When referenced PTR_TO_BTF_ID is passed to release function, 8495 * its fixed offset must be 0. In the other cases, fixed offset 8496 * can be non-zero. This was already checked above. So pass 8497 * fixed_off_ok as true to allow fixed offset for all other 8498 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8499 * still need to do checks instead of returning. 8500 */ 8501 return __check_ptr_off_reg(env, reg, regno, true); 8502 default: 8503 return __check_ptr_off_reg(env, reg, regno, false); 8504 } 8505 } 8506 8507 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8508 const struct bpf_func_proto *fn, 8509 struct bpf_reg_state *regs) 8510 { 8511 struct bpf_reg_state *state = NULL; 8512 int i; 8513 8514 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8515 if (arg_type_is_dynptr(fn->arg_type[i])) { 8516 if (state) { 8517 verbose(env, "verifier internal error: multiple dynptr args\n"); 8518 return NULL; 8519 } 8520 state = ®s[BPF_REG_1 + i]; 8521 } 8522 8523 if (!state) 8524 verbose(env, "verifier internal error: no dynptr arg found\n"); 8525 8526 return state; 8527 } 8528 8529 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8530 { 8531 struct bpf_func_state *state = func(env, reg); 8532 int spi; 8533 8534 if (reg->type == CONST_PTR_TO_DYNPTR) 8535 return reg->id; 8536 spi = dynptr_get_spi(env, reg); 8537 if (spi < 0) 8538 return spi; 8539 return state->stack[spi].spilled_ptr.id; 8540 } 8541 8542 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8543 { 8544 struct bpf_func_state *state = func(env, reg); 8545 int spi; 8546 8547 if (reg->type == CONST_PTR_TO_DYNPTR) 8548 return reg->ref_obj_id; 8549 spi = dynptr_get_spi(env, reg); 8550 if (spi < 0) 8551 return spi; 8552 return state->stack[spi].spilled_ptr.ref_obj_id; 8553 } 8554 8555 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8556 struct bpf_reg_state *reg) 8557 { 8558 struct bpf_func_state *state = func(env, reg); 8559 int spi; 8560 8561 if (reg->type == CONST_PTR_TO_DYNPTR) 8562 return reg->dynptr.type; 8563 8564 spi = __get_spi(reg->off); 8565 if (spi < 0) { 8566 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8567 return BPF_DYNPTR_TYPE_INVALID; 8568 } 8569 8570 return state->stack[spi].spilled_ptr.dynptr.type; 8571 } 8572 8573 static int check_reg_const_str(struct bpf_verifier_env *env, 8574 struct bpf_reg_state *reg, u32 regno) 8575 { 8576 struct bpf_map *map = reg->map_ptr; 8577 int err; 8578 int map_off; 8579 u64 map_addr; 8580 char *str_ptr; 8581 8582 if (reg->type != PTR_TO_MAP_VALUE) 8583 return -EINVAL; 8584 8585 if (!bpf_map_is_rdonly(map)) { 8586 verbose(env, "R%d does not point to a readonly map'\n", regno); 8587 return -EACCES; 8588 } 8589 8590 if (!tnum_is_const(reg->var_off)) { 8591 verbose(env, "R%d is not a constant address'\n", regno); 8592 return -EACCES; 8593 } 8594 8595 if (!map->ops->map_direct_value_addr) { 8596 verbose(env, "no direct value access support for this map type\n"); 8597 return -EACCES; 8598 } 8599 8600 err = check_map_access(env, regno, reg->off, 8601 map->value_size - reg->off, false, 8602 ACCESS_HELPER); 8603 if (err) 8604 return err; 8605 8606 map_off = reg->off + reg->var_off.value; 8607 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8608 if (err) { 8609 verbose(env, "direct value access on string failed\n"); 8610 return err; 8611 } 8612 8613 str_ptr = (char *)(long)(map_addr); 8614 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8615 verbose(env, "string is not zero-terminated\n"); 8616 return -EINVAL; 8617 } 8618 return 0; 8619 } 8620 8621 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8622 struct bpf_call_arg_meta *meta, 8623 const struct bpf_func_proto *fn, 8624 int insn_idx) 8625 { 8626 u32 regno = BPF_REG_1 + arg; 8627 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8628 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8629 enum bpf_reg_type type = reg->type; 8630 u32 *arg_btf_id = NULL; 8631 int err = 0; 8632 8633 if (arg_type == ARG_DONTCARE) 8634 return 0; 8635 8636 err = check_reg_arg(env, regno, SRC_OP); 8637 if (err) 8638 return err; 8639 8640 if (arg_type == ARG_ANYTHING) { 8641 if (is_pointer_value(env, regno)) { 8642 verbose(env, "R%d leaks addr into helper function\n", 8643 regno); 8644 return -EACCES; 8645 } 8646 return 0; 8647 } 8648 8649 if (type_is_pkt_pointer(type) && 8650 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8651 verbose(env, "helper access to the packet is not allowed\n"); 8652 return -EACCES; 8653 } 8654 8655 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8656 err = resolve_map_arg_type(env, meta, &arg_type); 8657 if (err) 8658 return err; 8659 } 8660 8661 if (register_is_null(reg) && type_may_be_null(arg_type)) 8662 /* A NULL register has a SCALAR_VALUE type, so skip 8663 * type checking. 8664 */ 8665 goto skip_type_check; 8666 8667 /* arg_btf_id and arg_size are in a union. */ 8668 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8669 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8670 arg_btf_id = fn->arg_btf_id[arg]; 8671 8672 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 8673 if (err) 8674 return err; 8675 8676 err = check_func_arg_reg_off(env, reg, regno, arg_type); 8677 if (err) 8678 return err; 8679 8680 skip_type_check: 8681 if (arg_type_is_release(arg_type)) { 8682 if (arg_type_is_dynptr(arg_type)) { 8683 struct bpf_func_state *state = func(env, reg); 8684 int spi; 8685 8686 /* Only dynptr created on stack can be released, thus 8687 * the get_spi and stack state checks for spilled_ptr 8688 * should only be done before process_dynptr_func for 8689 * PTR_TO_STACK. 8690 */ 8691 if (reg->type == PTR_TO_STACK) { 8692 spi = dynptr_get_spi(env, reg); 8693 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8694 verbose(env, "arg %d is an unacquired reference\n", regno); 8695 return -EINVAL; 8696 } 8697 } else { 8698 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8699 return -EINVAL; 8700 } 8701 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 8702 verbose(env, "R%d must be referenced when passed to release function\n", 8703 regno); 8704 return -EINVAL; 8705 } 8706 if (meta->release_regno) { 8707 verbose(env, "verifier internal error: more than one release argument\n"); 8708 return -EFAULT; 8709 } 8710 meta->release_regno = regno; 8711 } 8712 8713 if (reg->ref_obj_id) { 8714 if (meta->ref_obj_id) { 8715 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 8716 regno, reg->ref_obj_id, 8717 meta->ref_obj_id); 8718 return -EFAULT; 8719 } 8720 meta->ref_obj_id = reg->ref_obj_id; 8721 } 8722 8723 switch (base_type(arg_type)) { 8724 case ARG_CONST_MAP_PTR: 8725 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8726 if (meta->map_ptr) { 8727 /* Use map_uid (which is unique id of inner map) to reject: 8728 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8729 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8730 * if (inner_map1 && inner_map2) { 8731 * timer = bpf_map_lookup_elem(inner_map1); 8732 * if (timer) 8733 * // mismatch would have been allowed 8734 * bpf_timer_init(timer, inner_map2); 8735 * } 8736 * 8737 * Comparing map_ptr is enough to distinguish normal and outer maps. 8738 */ 8739 if (meta->map_ptr != reg->map_ptr || 8740 meta->map_uid != reg->map_uid) { 8741 verbose(env, 8742 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8743 meta->map_uid, reg->map_uid); 8744 return -EINVAL; 8745 } 8746 } 8747 meta->map_ptr = reg->map_ptr; 8748 meta->map_uid = reg->map_uid; 8749 break; 8750 case ARG_PTR_TO_MAP_KEY: 8751 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8752 * check that [key, key + map->key_size) are within 8753 * stack limits and initialized 8754 */ 8755 if (!meta->map_ptr) { 8756 /* in function declaration map_ptr must come before 8757 * map_key, so that it's verified and known before 8758 * we have to check map_key here. Otherwise it means 8759 * that kernel subsystem misconfigured verifier 8760 */ 8761 verbose(env, "invalid map_ptr to access map->key\n"); 8762 return -EACCES; 8763 } 8764 err = check_helper_mem_access(env, regno, 8765 meta->map_ptr->key_size, false, 8766 NULL); 8767 break; 8768 case ARG_PTR_TO_MAP_VALUE: 8769 if (type_may_be_null(arg_type) && register_is_null(reg)) 8770 return 0; 8771 8772 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8773 * check [value, value + map->value_size) validity 8774 */ 8775 if (!meta->map_ptr) { 8776 /* kernel subsystem misconfigured verifier */ 8777 verbose(env, "invalid map_ptr to access map->value\n"); 8778 return -EACCES; 8779 } 8780 meta->raw_mode = arg_type & MEM_UNINIT; 8781 err = check_helper_mem_access(env, regno, 8782 meta->map_ptr->value_size, false, 8783 meta); 8784 break; 8785 case ARG_PTR_TO_PERCPU_BTF_ID: 8786 if (!reg->btf_id) { 8787 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8788 return -EACCES; 8789 } 8790 meta->ret_btf = reg->btf; 8791 meta->ret_btf_id = reg->btf_id; 8792 break; 8793 case ARG_PTR_TO_SPIN_LOCK: 8794 if (in_rbtree_lock_required_cb(env)) { 8795 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8796 return -EACCES; 8797 } 8798 if (meta->func_id == BPF_FUNC_spin_lock) { 8799 err = process_spin_lock(env, regno, true); 8800 if (err) 8801 return err; 8802 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8803 err = process_spin_lock(env, regno, false); 8804 if (err) 8805 return err; 8806 } else { 8807 verbose(env, "verifier internal error\n"); 8808 return -EFAULT; 8809 } 8810 break; 8811 case ARG_PTR_TO_TIMER: 8812 err = process_timer_func(env, regno, meta); 8813 if (err) 8814 return err; 8815 break; 8816 case ARG_PTR_TO_FUNC: 8817 meta->subprogno = reg->subprogno; 8818 break; 8819 case ARG_PTR_TO_MEM: 8820 /* The access to this pointer is only checked when we hit the 8821 * next is_mem_size argument below. 8822 */ 8823 meta->raw_mode = arg_type & MEM_UNINIT; 8824 if (arg_type & MEM_FIXED_SIZE) { 8825 err = check_helper_mem_access(env, regno, 8826 fn->arg_size[arg], false, 8827 meta); 8828 } 8829 break; 8830 case ARG_CONST_SIZE: 8831 err = check_mem_size_reg(env, reg, regno, false, meta); 8832 break; 8833 case ARG_CONST_SIZE_OR_ZERO: 8834 err = check_mem_size_reg(env, reg, regno, true, meta); 8835 break; 8836 case ARG_PTR_TO_DYNPTR: 8837 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 8838 if (err) 8839 return err; 8840 break; 8841 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8842 if (!tnum_is_const(reg->var_off)) { 8843 verbose(env, "R%d is not a known constant'\n", 8844 regno); 8845 return -EACCES; 8846 } 8847 meta->mem_size = reg->var_off.value; 8848 err = mark_chain_precision(env, regno); 8849 if (err) 8850 return err; 8851 break; 8852 case ARG_PTR_TO_INT: 8853 case ARG_PTR_TO_LONG: 8854 { 8855 int size = int_ptr_type_to_size(arg_type); 8856 8857 err = check_helper_mem_access(env, regno, size, false, meta); 8858 if (err) 8859 return err; 8860 err = check_ptr_alignment(env, reg, 0, size, true); 8861 break; 8862 } 8863 case ARG_PTR_TO_CONST_STR: 8864 { 8865 err = check_reg_const_str(env, reg, regno); 8866 if (err) 8867 return err; 8868 break; 8869 } 8870 case ARG_PTR_TO_KPTR: 8871 err = process_kptr_func(env, regno, meta); 8872 if (err) 8873 return err; 8874 break; 8875 } 8876 8877 return err; 8878 } 8879 8880 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8881 { 8882 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8883 enum bpf_prog_type type = resolve_prog_type(env->prog); 8884 8885 if (func_id != BPF_FUNC_map_update_elem) 8886 return false; 8887 8888 /* It's not possible to get access to a locked struct sock in these 8889 * contexts, so updating is safe. 8890 */ 8891 switch (type) { 8892 case BPF_PROG_TYPE_TRACING: 8893 if (eatype == BPF_TRACE_ITER) 8894 return true; 8895 break; 8896 case BPF_PROG_TYPE_SOCKET_FILTER: 8897 case BPF_PROG_TYPE_SCHED_CLS: 8898 case BPF_PROG_TYPE_SCHED_ACT: 8899 case BPF_PROG_TYPE_XDP: 8900 case BPF_PROG_TYPE_SK_REUSEPORT: 8901 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8902 case BPF_PROG_TYPE_SK_LOOKUP: 8903 return true; 8904 default: 8905 break; 8906 } 8907 8908 verbose(env, "cannot update sockmap in this context\n"); 8909 return false; 8910 } 8911 8912 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8913 { 8914 return env->prog->jit_requested && 8915 bpf_jit_supports_subprog_tailcalls(); 8916 } 8917 8918 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8919 struct bpf_map *map, int func_id) 8920 { 8921 if (!map) 8922 return 0; 8923 8924 /* We need a two way check, first is from map perspective ... */ 8925 switch (map->map_type) { 8926 case BPF_MAP_TYPE_PROG_ARRAY: 8927 if (func_id != BPF_FUNC_tail_call) 8928 goto error; 8929 break; 8930 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8931 if (func_id != BPF_FUNC_perf_event_read && 8932 func_id != BPF_FUNC_perf_event_output && 8933 func_id != BPF_FUNC_skb_output && 8934 func_id != BPF_FUNC_perf_event_read_value && 8935 func_id != BPF_FUNC_xdp_output) 8936 goto error; 8937 break; 8938 case BPF_MAP_TYPE_RINGBUF: 8939 if (func_id != BPF_FUNC_ringbuf_output && 8940 func_id != BPF_FUNC_ringbuf_reserve && 8941 func_id != BPF_FUNC_ringbuf_query && 8942 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8943 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8944 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8945 goto error; 8946 break; 8947 case BPF_MAP_TYPE_USER_RINGBUF: 8948 if (func_id != BPF_FUNC_user_ringbuf_drain) 8949 goto error; 8950 break; 8951 case BPF_MAP_TYPE_STACK_TRACE: 8952 if (func_id != BPF_FUNC_get_stackid) 8953 goto error; 8954 break; 8955 case BPF_MAP_TYPE_CGROUP_ARRAY: 8956 if (func_id != BPF_FUNC_skb_under_cgroup && 8957 func_id != BPF_FUNC_current_task_under_cgroup) 8958 goto error; 8959 break; 8960 case BPF_MAP_TYPE_CGROUP_STORAGE: 8961 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8962 if (func_id != BPF_FUNC_get_local_storage) 8963 goto error; 8964 break; 8965 case BPF_MAP_TYPE_DEVMAP: 8966 case BPF_MAP_TYPE_DEVMAP_HASH: 8967 if (func_id != BPF_FUNC_redirect_map && 8968 func_id != BPF_FUNC_map_lookup_elem) 8969 goto error; 8970 break; 8971 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8972 * appear. 8973 */ 8974 case BPF_MAP_TYPE_CPUMAP: 8975 if (func_id != BPF_FUNC_redirect_map) 8976 goto error; 8977 break; 8978 case BPF_MAP_TYPE_XSKMAP: 8979 if (func_id != BPF_FUNC_redirect_map && 8980 func_id != BPF_FUNC_map_lookup_elem) 8981 goto error; 8982 break; 8983 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8984 case BPF_MAP_TYPE_HASH_OF_MAPS: 8985 if (func_id != BPF_FUNC_map_lookup_elem) 8986 goto error; 8987 break; 8988 case BPF_MAP_TYPE_SOCKMAP: 8989 if (func_id != BPF_FUNC_sk_redirect_map && 8990 func_id != BPF_FUNC_sock_map_update && 8991 func_id != BPF_FUNC_map_delete_elem && 8992 func_id != BPF_FUNC_msg_redirect_map && 8993 func_id != BPF_FUNC_sk_select_reuseport && 8994 func_id != BPF_FUNC_map_lookup_elem && 8995 !may_update_sockmap(env, func_id)) 8996 goto error; 8997 break; 8998 case BPF_MAP_TYPE_SOCKHASH: 8999 if (func_id != BPF_FUNC_sk_redirect_hash && 9000 func_id != BPF_FUNC_sock_hash_update && 9001 func_id != BPF_FUNC_map_delete_elem && 9002 func_id != BPF_FUNC_msg_redirect_hash && 9003 func_id != BPF_FUNC_sk_select_reuseport && 9004 func_id != BPF_FUNC_map_lookup_elem && 9005 !may_update_sockmap(env, func_id)) 9006 goto error; 9007 break; 9008 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 9009 if (func_id != BPF_FUNC_sk_select_reuseport) 9010 goto error; 9011 break; 9012 case BPF_MAP_TYPE_QUEUE: 9013 case BPF_MAP_TYPE_STACK: 9014 if (func_id != BPF_FUNC_map_peek_elem && 9015 func_id != BPF_FUNC_map_pop_elem && 9016 func_id != BPF_FUNC_map_push_elem) 9017 goto error; 9018 break; 9019 case BPF_MAP_TYPE_SK_STORAGE: 9020 if (func_id != BPF_FUNC_sk_storage_get && 9021 func_id != BPF_FUNC_sk_storage_delete && 9022 func_id != BPF_FUNC_kptr_xchg) 9023 goto error; 9024 break; 9025 case BPF_MAP_TYPE_INODE_STORAGE: 9026 if (func_id != BPF_FUNC_inode_storage_get && 9027 func_id != BPF_FUNC_inode_storage_delete && 9028 func_id != BPF_FUNC_kptr_xchg) 9029 goto error; 9030 break; 9031 case BPF_MAP_TYPE_TASK_STORAGE: 9032 if (func_id != BPF_FUNC_task_storage_get && 9033 func_id != BPF_FUNC_task_storage_delete && 9034 func_id != BPF_FUNC_kptr_xchg) 9035 goto error; 9036 break; 9037 case BPF_MAP_TYPE_CGRP_STORAGE: 9038 if (func_id != BPF_FUNC_cgrp_storage_get && 9039 func_id != BPF_FUNC_cgrp_storage_delete && 9040 func_id != BPF_FUNC_kptr_xchg) 9041 goto error; 9042 break; 9043 case BPF_MAP_TYPE_BLOOM_FILTER: 9044 if (func_id != BPF_FUNC_map_peek_elem && 9045 func_id != BPF_FUNC_map_push_elem) 9046 goto error; 9047 break; 9048 default: 9049 break; 9050 } 9051 9052 /* ... and second from the function itself. */ 9053 switch (func_id) { 9054 case BPF_FUNC_tail_call: 9055 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 9056 goto error; 9057 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 9058 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 9059 return -EINVAL; 9060 } 9061 break; 9062 case BPF_FUNC_perf_event_read: 9063 case BPF_FUNC_perf_event_output: 9064 case BPF_FUNC_perf_event_read_value: 9065 case BPF_FUNC_skb_output: 9066 case BPF_FUNC_xdp_output: 9067 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 9068 goto error; 9069 break; 9070 case BPF_FUNC_ringbuf_output: 9071 case BPF_FUNC_ringbuf_reserve: 9072 case BPF_FUNC_ringbuf_query: 9073 case BPF_FUNC_ringbuf_reserve_dynptr: 9074 case BPF_FUNC_ringbuf_submit_dynptr: 9075 case BPF_FUNC_ringbuf_discard_dynptr: 9076 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 9077 goto error; 9078 break; 9079 case BPF_FUNC_user_ringbuf_drain: 9080 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 9081 goto error; 9082 break; 9083 case BPF_FUNC_get_stackid: 9084 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 9085 goto error; 9086 break; 9087 case BPF_FUNC_current_task_under_cgroup: 9088 case BPF_FUNC_skb_under_cgroup: 9089 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 9090 goto error; 9091 break; 9092 case BPF_FUNC_redirect_map: 9093 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 9094 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 9095 map->map_type != BPF_MAP_TYPE_CPUMAP && 9096 map->map_type != BPF_MAP_TYPE_XSKMAP) 9097 goto error; 9098 break; 9099 case BPF_FUNC_sk_redirect_map: 9100 case BPF_FUNC_msg_redirect_map: 9101 case BPF_FUNC_sock_map_update: 9102 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 9103 goto error; 9104 break; 9105 case BPF_FUNC_sk_redirect_hash: 9106 case BPF_FUNC_msg_redirect_hash: 9107 case BPF_FUNC_sock_hash_update: 9108 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 9109 goto error; 9110 break; 9111 case BPF_FUNC_get_local_storage: 9112 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 9113 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 9114 goto error; 9115 break; 9116 case BPF_FUNC_sk_select_reuseport: 9117 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 9118 map->map_type != BPF_MAP_TYPE_SOCKMAP && 9119 map->map_type != BPF_MAP_TYPE_SOCKHASH) 9120 goto error; 9121 break; 9122 case BPF_FUNC_map_pop_elem: 9123 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9124 map->map_type != BPF_MAP_TYPE_STACK) 9125 goto error; 9126 break; 9127 case BPF_FUNC_map_peek_elem: 9128 case BPF_FUNC_map_push_elem: 9129 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9130 map->map_type != BPF_MAP_TYPE_STACK && 9131 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 9132 goto error; 9133 break; 9134 case BPF_FUNC_map_lookup_percpu_elem: 9135 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 9136 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 9137 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 9138 goto error; 9139 break; 9140 case BPF_FUNC_sk_storage_get: 9141 case BPF_FUNC_sk_storage_delete: 9142 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 9143 goto error; 9144 break; 9145 case BPF_FUNC_inode_storage_get: 9146 case BPF_FUNC_inode_storage_delete: 9147 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 9148 goto error; 9149 break; 9150 case BPF_FUNC_task_storage_get: 9151 case BPF_FUNC_task_storage_delete: 9152 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 9153 goto error; 9154 break; 9155 case BPF_FUNC_cgrp_storage_get: 9156 case BPF_FUNC_cgrp_storage_delete: 9157 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 9158 goto error; 9159 break; 9160 default: 9161 break; 9162 } 9163 9164 return 0; 9165 error: 9166 verbose(env, "cannot pass map_type %d into func %s#%d\n", 9167 map->map_type, func_id_name(func_id), func_id); 9168 return -EINVAL; 9169 } 9170 9171 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 9172 { 9173 int count = 0; 9174 9175 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 9176 count++; 9177 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 9178 count++; 9179 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 9180 count++; 9181 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 9182 count++; 9183 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 9184 count++; 9185 9186 /* We only support one arg being in raw mode at the moment, 9187 * which is sufficient for the helper functions we have 9188 * right now. 9189 */ 9190 return count <= 1; 9191 } 9192 9193 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 9194 { 9195 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 9196 bool has_size = fn->arg_size[arg] != 0; 9197 bool is_next_size = false; 9198 9199 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 9200 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 9201 9202 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 9203 return is_next_size; 9204 9205 return has_size == is_next_size || is_next_size == is_fixed; 9206 } 9207 9208 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 9209 { 9210 /* bpf_xxx(..., buf, len) call will access 'len' 9211 * bytes from memory 'buf'. Both arg types need 9212 * to be paired, so make sure there's no buggy 9213 * helper function specification. 9214 */ 9215 if (arg_type_is_mem_size(fn->arg1_type) || 9216 check_args_pair_invalid(fn, 0) || 9217 check_args_pair_invalid(fn, 1) || 9218 check_args_pair_invalid(fn, 2) || 9219 check_args_pair_invalid(fn, 3) || 9220 check_args_pair_invalid(fn, 4)) 9221 return false; 9222 9223 return true; 9224 } 9225 9226 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 9227 { 9228 int i; 9229 9230 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 9231 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 9232 return !!fn->arg_btf_id[i]; 9233 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 9234 return fn->arg_btf_id[i] == BPF_PTR_POISON; 9235 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 9236 /* arg_btf_id and arg_size are in a union. */ 9237 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 9238 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 9239 return false; 9240 } 9241 9242 return true; 9243 } 9244 9245 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 9246 { 9247 return check_raw_mode_ok(fn) && 9248 check_arg_pair_ok(fn) && 9249 check_btf_id_ok(fn) ? 0 : -EINVAL; 9250 } 9251 9252 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 9253 * are now invalid, so turn them into unknown SCALAR_VALUE. 9254 * 9255 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 9256 * since these slices point to packet data. 9257 */ 9258 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 9259 { 9260 struct bpf_func_state *state; 9261 struct bpf_reg_state *reg; 9262 9263 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9264 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 9265 mark_reg_invalid(env, reg); 9266 })); 9267 } 9268 9269 enum { 9270 AT_PKT_END = -1, 9271 BEYOND_PKT_END = -2, 9272 }; 9273 9274 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 9275 { 9276 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9277 struct bpf_reg_state *reg = &state->regs[regn]; 9278 9279 if (reg->type != PTR_TO_PACKET) 9280 /* PTR_TO_PACKET_META is not supported yet */ 9281 return; 9282 9283 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 9284 * How far beyond pkt_end it goes is unknown. 9285 * if (!range_open) it's the case of pkt >= pkt_end 9286 * if (range_open) it's the case of pkt > pkt_end 9287 * hence this pointer is at least 1 byte bigger than pkt_end 9288 */ 9289 if (range_open) 9290 reg->range = BEYOND_PKT_END; 9291 else 9292 reg->range = AT_PKT_END; 9293 } 9294 9295 /* The pointer with the specified id has released its reference to kernel 9296 * resources. Identify all copies of the same pointer and clear the reference. 9297 */ 9298 static int release_reference(struct bpf_verifier_env *env, 9299 int ref_obj_id) 9300 { 9301 struct bpf_func_state *state; 9302 struct bpf_reg_state *reg; 9303 int err; 9304 9305 err = release_reference_state(cur_func(env), ref_obj_id); 9306 if (err) 9307 return err; 9308 9309 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9310 if (reg->ref_obj_id == ref_obj_id) 9311 mark_reg_invalid(env, reg); 9312 })); 9313 9314 return 0; 9315 } 9316 9317 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9318 { 9319 struct bpf_func_state *unused; 9320 struct bpf_reg_state *reg; 9321 9322 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9323 if (type_is_non_owning_ref(reg->type)) 9324 mark_reg_invalid(env, reg); 9325 })); 9326 } 9327 9328 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9329 struct bpf_reg_state *regs) 9330 { 9331 int i; 9332 9333 /* after the call registers r0 - r5 were scratched */ 9334 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9335 mark_reg_not_init(env, regs, caller_saved[i]); 9336 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9337 } 9338 } 9339 9340 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9341 struct bpf_func_state *caller, 9342 struct bpf_func_state *callee, 9343 int insn_idx); 9344 9345 static int set_callee_state(struct bpf_verifier_env *env, 9346 struct bpf_func_state *caller, 9347 struct bpf_func_state *callee, int insn_idx); 9348 9349 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9350 set_callee_state_fn set_callee_state_cb, 9351 struct bpf_verifier_state *state) 9352 { 9353 struct bpf_func_state *caller, *callee; 9354 int err; 9355 9356 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9357 verbose(env, "the call stack of %d frames is too deep\n", 9358 state->curframe + 2); 9359 return -E2BIG; 9360 } 9361 9362 if (state->frame[state->curframe + 1]) { 9363 verbose(env, "verifier bug. Frame %d already allocated\n", 9364 state->curframe + 1); 9365 return -EFAULT; 9366 } 9367 9368 caller = state->frame[state->curframe]; 9369 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 9370 if (!callee) 9371 return -ENOMEM; 9372 state->frame[state->curframe + 1] = callee; 9373 9374 /* callee cannot access r0, r6 - r9 for reading and has to write 9375 * into its own stack before reading from it. 9376 * callee can read/write into caller's stack 9377 */ 9378 init_func_state(env, callee, 9379 /* remember the callsite, it will be used by bpf_exit */ 9380 callsite, 9381 state->curframe + 1 /* frameno within this callchain */, 9382 subprog /* subprog number within this prog */); 9383 /* Transfer references to the callee */ 9384 err = copy_reference_state(callee, caller); 9385 err = err ?: set_callee_state_cb(env, caller, callee, callsite); 9386 if (err) 9387 goto err_out; 9388 9389 /* only increment it after check_reg_arg() finished */ 9390 state->curframe++; 9391 9392 return 0; 9393 9394 err_out: 9395 free_func_state(callee); 9396 state->frame[state->curframe + 1] = NULL; 9397 return err; 9398 } 9399 9400 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, 9401 const struct btf *btf, 9402 struct bpf_reg_state *regs) 9403 { 9404 struct bpf_subprog_info *sub = subprog_info(env, subprog); 9405 struct bpf_verifier_log *log = &env->log; 9406 u32 i; 9407 int ret; 9408 9409 ret = btf_prepare_func_args(env, subprog); 9410 if (ret) 9411 return ret; 9412 9413 /* check that BTF function arguments match actual types that the 9414 * verifier sees. 9415 */ 9416 for (i = 0; i < sub->arg_cnt; i++) { 9417 u32 regno = i + 1; 9418 struct bpf_reg_state *reg = ®s[regno]; 9419 struct bpf_subprog_arg_info *arg = &sub->args[i]; 9420 9421 if (arg->arg_type == ARG_ANYTHING) { 9422 if (reg->type != SCALAR_VALUE) { 9423 bpf_log(log, "R%d is not a scalar\n", regno); 9424 return -EINVAL; 9425 } 9426 } else if (arg->arg_type == ARG_PTR_TO_CTX) { 9427 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9428 if (ret < 0) 9429 return ret; 9430 /* If function expects ctx type in BTF check that caller 9431 * is passing PTR_TO_CTX. 9432 */ 9433 if (reg->type != PTR_TO_CTX) { 9434 bpf_log(log, "arg#%d expects pointer to ctx\n", i); 9435 return -EINVAL; 9436 } 9437 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 9438 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9439 if (ret < 0) 9440 return ret; 9441 if (check_mem_reg(env, reg, regno, arg->mem_size)) 9442 return -EINVAL; 9443 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) { 9444 bpf_log(log, "arg#%d is expected to be non-NULL\n", i); 9445 return -EINVAL; 9446 } 9447 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 9448 /* 9449 * Can pass any value and the kernel won't crash, but 9450 * only PTR_TO_ARENA or SCALAR make sense. Everything 9451 * else is a bug in the bpf program. Point it out to 9452 * the user at the verification time instead of 9453 * run-time debug nightmare. 9454 */ 9455 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) { 9456 bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno); 9457 return -EINVAL; 9458 } 9459 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 9460 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0); 9461 if (ret) 9462 return ret; 9463 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 9464 struct bpf_call_arg_meta meta; 9465 int err; 9466 9467 if (register_is_null(reg) && type_may_be_null(arg->arg_type)) 9468 continue; 9469 9470 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */ 9471 err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta); 9472 err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type); 9473 if (err) 9474 return err; 9475 } else { 9476 bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n", 9477 i, arg->arg_type); 9478 return -EFAULT; 9479 } 9480 } 9481 9482 return 0; 9483 } 9484 9485 /* Compare BTF of a function call with given bpf_reg_state. 9486 * Returns: 9487 * EFAULT - there is a verifier bug. Abort verification. 9488 * EINVAL - there is a type mismatch or BTF is not available. 9489 * 0 - BTF matches with what bpf_reg_state expects. 9490 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized. 9491 */ 9492 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog, 9493 struct bpf_reg_state *regs) 9494 { 9495 struct bpf_prog *prog = env->prog; 9496 struct btf *btf = prog->aux->btf; 9497 u32 btf_id; 9498 int err; 9499 9500 if (!prog->aux->func_info) 9501 return -EINVAL; 9502 9503 btf_id = prog->aux->func_info[subprog].type_id; 9504 if (!btf_id) 9505 return -EFAULT; 9506 9507 if (prog->aux->func_info_aux[subprog].unreliable) 9508 return -EINVAL; 9509 9510 err = btf_check_func_arg_match(env, subprog, btf, regs); 9511 /* Compiler optimizations can remove arguments from static functions 9512 * or mismatched type can be passed into a global function. 9513 * In such cases mark the function as unreliable from BTF point of view. 9514 */ 9515 if (err) 9516 prog->aux->func_info_aux[subprog].unreliable = true; 9517 return err; 9518 } 9519 9520 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9521 int insn_idx, int subprog, 9522 set_callee_state_fn set_callee_state_cb) 9523 { 9524 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9525 struct bpf_func_state *caller, *callee; 9526 int err; 9527 9528 caller = state->frame[state->curframe]; 9529 err = btf_check_subprog_call(env, subprog, caller->regs); 9530 if (err == -EFAULT) 9531 return err; 9532 9533 /* set_callee_state is used for direct subprog calls, but we are 9534 * interested in validating only BPF helpers that can call subprogs as 9535 * callbacks 9536 */ 9537 env->subprog_info[subprog].is_cb = true; 9538 if (bpf_pseudo_kfunc_call(insn) && 9539 !is_callback_calling_kfunc(insn->imm)) { 9540 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 9541 func_id_name(insn->imm), insn->imm); 9542 return -EFAULT; 9543 } else if (!bpf_pseudo_kfunc_call(insn) && 9544 !is_callback_calling_function(insn->imm)) { /* helper */ 9545 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 9546 func_id_name(insn->imm), insn->imm); 9547 return -EFAULT; 9548 } 9549 9550 if (is_async_callback_calling_insn(insn)) { 9551 struct bpf_verifier_state *async_cb; 9552 9553 /* there is no real recursion here. timer and workqueue callbacks are async */ 9554 env->subprog_info[subprog].is_async_cb = true; 9555 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9556 insn_idx, subprog, 9557 is_bpf_wq_set_callback_impl_kfunc(insn->imm)); 9558 if (!async_cb) 9559 return -EFAULT; 9560 callee = async_cb->frame[0]; 9561 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9562 9563 /* Convert bpf_timer_set_callback() args into timer callback args */ 9564 err = set_callee_state_cb(env, caller, callee, insn_idx); 9565 if (err) 9566 return err; 9567 9568 return 0; 9569 } 9570 9571 /* for callback functions enqueue entry to callback and 9572 * proceed with next instruction within current frame. 9573 */ 9574 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9575 if (!callback_state) 9576 return -ENOMEM; 9577 9578 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9579 callback_state); 9580 if (err) 9581 return err; 9582 9583 callback_state->callback_unroll_depth++; 9584 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9585 caller->callback_depth = 0; 9586 return 0; 9587 } 9588 9589 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9590 int *insn_idx) 9591 { 9592 struct bpf_verifier_state *state = env->cur_state; 9593 struct bpf_func_state *caller; 9594 int err, subprog, target_insn; 9595 9596 target_insn = *insn_idx + insn->imm + 1; 9597 subprog = find_subprog(env, target_insn); 9598 if (subprog < 0) { 9599 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn); 9600 return -EFAULT; 9601 } 9602 9603 caller = state->frame[state->curframe]; 9604 err = btf_check_subprog_call(env, subprog, caller->regs); 9605 if (err == -EFAULT) 9606 return err; 9607 if (subprog_is_global(env, subprog)) { 9608 const char *sub_name = subprog_name(env, subprog); 9609 9610 /* Only global subprogs cannot be called with a lock held. */ 9611 if (env->cur_state->active_lock.ptr) { 9612 verbose(env, "global function calls are not allowed while holding a lock,\n" 9613 "use static function instead\n"); 9614 return -EINVAL; 9615 } 9616 9617 /* Only global subprogs cannot be called with preemption disabled. */ 9618 if (env->cur_state->active_preempt_lock) { 9619 verbose(env, "global function calls are not allowed with preemption disabled,\n" 9620 "use static function instead\n"); 9621 return -EINVAL; 9622 } 9623 9624 if (err) { 9625 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 9626 subprog, sub_name); 9627 return err; 9628 } 9629 9630 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 9631 subprog, sub_name); 9632 /* mark global subprog for verifying after main prog */ 9633 subprog_aux(env, subprog)->called = true; 9634 clear_caller_saved_regs(env, caller->regs); 9635 9636 /* All global functions return a 64-bit SCALAR_VALUE */ 9637 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9638 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9639 9640 /* continue with next insn after call */ 9641 return 0; 9642 } 9643 9644 /* for regular function entry setup new frame and continue 9645 * from that frame. 9646 */ 9647 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9648 if (err) 9649 return err; 9650 9651 clear_caller_saved_regs(env, caller->regs); 9652 9653 /* and go analyze first insn of the callee */ 9654 *insn_idx = env->subprog_info[subprog].start - 1; 9655 9656 if (env->log.level & BPF_LOG_LEVEL) { 9657 verbose(env, "caller:\n"); 9658 print_verifier_state(env, caller, true); 9659 verbose(env, "callee:\n"); 9660 print_verifier_state(env, state->frame[state->curframe], true); 9661 } 9662 9663 return 0; 9664 } 9665 9666 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9667 struct bpf_func_state *caller, 9668 struct bpf_func_state *callee) 9669 { 9670 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9671 * void *callback_ctx, u64 flags); 9672 * callback_fn(struct bpf_map *map, void *key, void *value, 9673 * void *callback_ctx); 9674 */ 9675 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9676 9677 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9678 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9679 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9680 9681 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9682 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9683 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9684 9685 /* pointer to stack or null */ 9686 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9687 9688 /* unused */ 9689 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9690 return 0; 9691 } 9692 9693 static int set_callee_state(struct bpf_verifier_env *env, 9694 struct bpf_func_state *caller, 9695 struct bpf_func_state *callee, int insn_idx) 9696 { 9697 int i; 9698 9699 /* copy r1 - r5 args that callee can access. The copy includes parent 9700 * pointers, which connects us up to the liveness chain 9701 */ 9702 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9703 callee->regs[i] = caller->regs[i]; 9704 return 0; 9705 } 9706 9707 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9708 struct bpf_func_state *caller, 9709 struct bpf_func_state *callee, 9710 int insn_idx) 9711 { 9712 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9713 struct bpf_map *map; 9714 int err; 9715 9716 /* valid map_ptr and poison value does not matter */ 9717 map = insn_aux->map_ptr_state.map_ptr; 9718 if (!map->ops->map_set_for_each_callback_args || 9719 !map->ops->map_for_each_callback) { 9720 verbose(env, "callback function not allowed for map\n"); 9721 return -ENOTSUPP; 9722 } 9723 9724 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9725 if (err) 9726 return err; 9727 9728 callee->in_callback_fn = true; 9729 callee->callback_ret_range = retval_range(0, 1); 9730 return 0; 9731 } 9732 9733 static int set_loop_callback_state(struct bpf_verifier_env *env, 9734 struct bpf_func_state *caller, 9735 struct bpf_func_state *callee, 9736 int insn_idx) 9737 { 9738 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9739 * u64 flags); 9740 * callback_fn(u32 index, void *callback_ctx); 9741 */ 9742 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9743 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9744 9745 /* unused */ 9746 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9747 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9748 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9749 9750 callee->in_callback_fn = true; 9751 callee->callback_ret_range = retval_range(0, 1); 9752 return 0; 9753 } 9754 9755 static int set_timer_callback_state(struct bpf_verifier_env *env, 9756 struct bpf_func_state *caller, 9757 struct bpf_func_state *callee, 9758 int insn_idx) 9759 { 9760 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9761 9762 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9763 * callback_fn(struct bpf_map *map, void *key, void *value); 9764 */ 9765 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9766 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9767 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9768 9769 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9770 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9771 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9772 9773 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9774 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9775 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9776 9777 /* unused */ 9778 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9779 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9780 callee->in_async_callback_fn = true; 9781 callee->callback_ret_range = retval_range(0, 1); 9782 return 0; 9783 } 9784 9785 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9786 struct bpf_func_state *caller, 9787 struct bpf_func_state *callee, 9788 int insn_idx) 9789 { 9790 /* bpf_find_vma(struct task_struct *task, u64 addr, 9791 * void *callback_fn, void *callback_ctx, u64 flags) 9792 * (callback_fn)(struct task_struct *task, 9793 * struct vm_area_struct *vma, void *callback_ctx); 9794 */ 9795 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9796 9797 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9798 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9799 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9800 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 9801 9802 /* pointer to stack or null */ 9803 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9804 9805 /* unused */ 9806 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9807 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9808 callee->in_callback_fn = true; 9809 callee->callback_ret_range = retval_range(0, 1); 9810 return 0; 9811 } 9812 9813 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9814 struct bpf_func_state *caller, 9815 struct bpf_func_state *callee, 9816 int insn_idx) 9817 { 9818 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9819 * callback_ctx, u64 flags); 9820 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9821 */ 9822 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9823 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9824 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9825 9826 /* unused */ 9827 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9828 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9829 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9830 9831 callee->in_callback_fn = true; 9832 callee->callback_ret_range = retval_range(0, 1); 9833 return 0; 9834 } 9835 9836 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9837 struct bpf_func_state *caller, 9838 struct bpf_func_state *callee, 9839 int insn_idx) 9840 { 9841 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9842 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9843 * 9844 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9845 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9846 * by this point, so look at 'root' 9847 */ 9848 struct btf_field *field; 9849 9850 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 9851 BPF_RB_ROOT); 9852 if (!field || !field->graph_root.value_btf_id) 9853 return -EFAULT; 9854 9855 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9856 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9857 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9858 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9859 9860 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9861 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9862 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9863 callee->in_callback_fn = true; 9864 callee->callback_ret_range = retval_range(0, 1); 9865 return 0; 9866 } 9867 9868 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9869 9870 /* Are we currently verifying the callback for a rbtree helper that must 9871 * be called with lock held? If so, no need to complain about unreleased 9872 * lock 9873 */ 9874 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9875 { 9876 struct bpf_verifier_state *state = env->cur_state; 9877 struct bpf_insn *insn = env->prog->insnsi; 9878 struct bpf_func_state *callee; 9879 int kfunc_btf_id; 9880 9881 if (!state->curframe) 9882 return false; 9883 9884 callee = state->frame[state->curframe]; 9885 9886 if (!callee->in_callback_fn) 9887 return false; 9888 9889 kfunc_btf_id = insn[callee->callsite].imm; 9890 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9891 } 9892 9893 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg) 9894 { 9895 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval; 9896 } 9897 9898 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9899 { 9900 struct bpf_verifier_state *state = env->cur_state, *prev_st; 9901 struct bpf_func_state *caller, *callee; 9902 struct bpf_reg_state *r0; 9903 bool in_callback_fn; 9904 int err; 9905 9906 callee = state->frame[state->curframe]; 9907 r0 = &callee->regs[BPF_REG_0]; 9908 if (r0->type == PTR_TO_STACK) { 9909 /* technically it's ok to return caller's stack pointer 9910 * (or caller's caller's pointer) back to the caller, 9911 * since these pointers are valid. Only current stack 9912 * pointer will be invalid as soon as function exits, 9913 * but let's be conservative 9914 */ 9915 verbose(env, "cannot return stack pointer to the caller\n"); 9916 return -EINVAL; 9917 } 9918 9919 caller = state->frame[state->curframe - 1]; 9920 if (callee->in_callback_fn) { 9921 if (r0->type != SCALAR_VALUE) { 9922 verbose(env, "R0 not a scalar value\n"); 9923 return -EACCES; 9924 } 9925 9926 /* we are going to rely on register's precise value */ 9927 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64); 9928 err = err ?: mark_chain_precision(env, BPF_REG_0); 9929 if (err) 9930 return err; 9931 9932 /* enforce R0 return value range */ 9933 if (!retval_range_within(callee->callback_ret_range, r0)) { 9934 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 9935 "At callback return", "R0"); 9936 return -EINVAL; 9937 } 9938 if (!calls_callback(env, callee->callsite)) { 9939 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n", 9940 *insn_idx, callee->callsite); 9941 return -EFAULT; 9942 } 9943 } else { 9944 /* return to the caller whatever r0 had in the callee */ 9945 caller->regs[BPF_REG_0] = *r0; 9946 } 9947 9948 /* callback_fn frame should have released its own additions to parent's 9949 * reference state at this point, or check_reference_leak would 9950 * complain, hence it must be the same as the caller. There is no need 9951 * to copy it back. 9952 */ 9953 if (!callee->in_callback_fn) { 9954 /* Transfer references to the caller */ 9955 err = copy_reference_state(caller, callee); 9956 if (err) 9957 return err; 9958 } 9959 9960 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 9961 * there function call logic would reschedule callback visit. If iteration 9962 * converges is_state_visited() would prune that visit eventually. 9963 */ 9964 in_callback_fn = callee->in_callback_fn; 9965 if (in_callback_fn) 9966 *insn_idx = callee->callsite; 9967 else 9968 *insn_idx = callee->callsite + 1; 9969 9970 if (env->log.level & BPF_LOG_LEVEL) { 9971 verbose(env, "returning from callee:\n"); 9972 print_verifier_state(env, callee, true); 9973 verbose(env, "to caller at %d:\n", *insn_idx); 9974 print_verifier_state(env, caller, true); 9975 } 9976 /* clear everything in the callee. In case of exceptional exits using 9977 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 9978 free_func_state(callee); 9979 state->frame[state->curframe--] = NULL; 9980 9981 /* for callbacks widen imprecise scalars to make programs like below verify: 9982 * 9983 * struct ctx { int i; } 9984 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 9985 * ... 9986 * struct ctx = { .i = 0; } 9987 * bpf_loop(100, cb, &ctx, 0); 9988 * 9989 * This is similar to what is done in process_iter_next_call() for open 9990 * coded iterators. 9991 */ 9992 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 9993 if (prev_st) { 9994 err = widen_imprecise_scalars(env, prev_st, state); 9995 if (err) 9996 return err; 9997 } 9998 return 0; 9999 } 10000 10001 static int do_refine_retval_range(struct bpf_verifier_env *env, 10002 struct bpf_reg_state *regs, int ret_type, 10003 int func_id, 10004 struct bpf_call_arg_meta *meta) 10005 { 10006 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 10007 10008 if (ret_type != RET_INTEGER) 10009 return 0; 10010 10011 switch (func_id) { 10012 case BPF_FUNC_get_stack: 10013 case BPF_FUNC_get_task_stack: 10014 case BPF_FUNC_probe_read_str: 10015 case BPF_FUNC_probe_read_kernel_str: 10016 case BPF_FUNC_probe_read_user_str: 10017 ret_reg->smax_value = meta->msize_max_value; 10018 ret_reg->s32_max_value = meta->msize_max_value; 10019 ret_reg->smin_value = -MAX_ERRNO; 10020 ret_reg->s32_min_value = -MAX_ERRNO; 10021 reg_bounds_sync(ret_reg); 10022 break; 10023 case BPF_FUNC_get_smp_processor_id: 10024 ret_reg->umax_value = nr_cpu_ids - 1; 10025 ret_reg->u32_max_value = nr_cpu_ids - 1; 10026 ret_reg->smax_value = nr_cpu_ids - 1; 10027 ret_reg->s32_max_value = nr_cpu_ids - 1; 10028 ret_reg->umin_value = 0; 10029 ret_reg->u32_min_value = 0; 10030 ret_reg->smin_value = 0; 10031 ret_reg->s32_min_value = 0; 10032 reg_bounds_sync(ret_reg); 10033 break; 10034 } 10035 10036 return reg_bounds_sanity_check(env, ret_reg, "retval"); 10037 } 10038 10039 static int 10040 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 10041 int func_id, int insn_idx) 10042 { 10043 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 10044 struct bpf_map *map = meta->map_ptr; 10045 10046 if (func_id != BPF_FUNC_tail_call && 10047 func_id != BPF_FUNC_map_lookup_elem && 10048 func_id != BPF_FUNC_map_update_elem && 10049 func_id != BPF_FUNC_map_delete_elem && 10050 func_id != BPF_FUNC_map_push_elem && 10051 func_id != BPF_FUNC_map_pop_elem && 10052 func_id != BPF_FUNC_map_peek_elem && 10053 func_id != BPF_FUNC_for_each_map_elem && 10054 func_id != BPF_FUNC_redirect_map && 10055 func_id != BPF_FUNC_map_lookup_percpu_elem) 10056 return 0; 10057 10058 if (map == NULL) { 10059 verbose(env, "kernel subsystem misconfigured verifier\n"); 10060 return -EINVAL; 10061 } 10062 10063 /* In case of read-only, some additional restrictions 10064 * need to be applied in order to prevent altering the 10065 * state of the map from program side. 10066 */ 10067 if ((map->map_flags & BPF_F_RDONLY_PROG) && 10068 (func_id == BPF_FUNC_map_delete_elem || 10069 func_id == BPF_FUNC_map_update_elem || 10070 func_id == BPF_FUNC_map_push_elem || 10071 func_id == BPF_FUNC_map_pop_elem)) { 10072 verbose(env, "write into map forbidden\n"); 10073 return -EACCES; 10074 } 10075 10076 if (!aux->map_ptr_state.map_ptr) 10077 bpf_map_ptr_store(aux, meta->map_ptr, 10078 !meta->map_ptr->bypass_spec_v1, false); 10079 else if (aux->map_ptr_state.map_ptr != meta->map_ptr) 10080 bpf_map_ptr_store(aux, meta->map_ptr, 10081 !meta->map_ptr->bypass_spec_v1, true); 10082 return 0; 10083 } 10084 10085 static int 10086 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 10087 int func_id, int insn_idx) 10088 { 10089 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 10090 struct bpf_reg_state *regs = cur_regs(env), *reg; 10091 struct bpf_map *map = meta->map_ptr; 10092 u64 val, max; 10093 int err; 10094 10095 if (func_id != BPF_FUNC_tail_call) 10096 return 0; 10097 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 10098 verbose(env, "kernel subsystem misconfigured verifier\n"); 10099 return -EINVAL; 10100 } 10101 10102 reg = ®s[BPF_REG_3]; 10103 val = reg->var_off.value; 10104 max = map->max_entries; 10105 10106 if (!(is_reg_const(reg, false) && val < max)) { 10107 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 10108 return 0; 10109 } 10110 10111 err = mark_chain_precision(env, BPF_REG_3); 10112 if (err) 10113 return err; 10114 if (bpf_map_key_unseen(aux)) 10115 bpf_map_key_store(aux, val); 10116 else if (!bpf_map_key_poisoned(aux) && 10117 bpf_map_key_immediate(aux) != val) 10118 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 10119 return 0; 10120 } 10121 10122 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 10123 { 10124 struct bpf_func_state *state = cur_func(env); 10125 bool refs_lingering = false; 10126 int i; 10127 10128 if (!exception_exit && state->frameno && !state->in_callback_fn) 10129 return 0; 10130 10131 for (i = 0; i < state->acquired_refs; i++) { 10132 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 10133 continue; 10134 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 10135 state->refs[i].id, state->refs[i].insn_idx); 10136 refs_lingering = true; 10137 } 10138 return refs_lingering ? -EINVAL : 0; 10139 } 10140 10141 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 10142 struct bpf_reg_state *regs) 10143 { 10144 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 10145 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 10146 struct bpf_map *fmt_map = fmt_reg->map_ptr; 10147 struct bpf_bprintf_data data = {}; 10148 int err, fmt_map_off, num_args; 10149 u64 fmt_addr; 10150 char *fmt; 10151 10152 /* data must be an array of u64 */ 10153 if (data_len_reg->var_off.value % 8) 10154 return -EINVAL; 10155 num_args = data_len_reg->var_off.value / 8; 10156 10157 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 10158 * and map_direct_value_addr is set. 10159 */ 10160 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 10161 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 10162 fmt_map_off); 10163 if (err) { 10164 verbose(env, "verifier bug\n"); 10165 return -EFAULT; 10166 } 10167 fmt = (char *)(long)fmt_addr + fmt_map_off; 10168 10169 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 10170 * can focus on validating the format specifiers. 10171 */ 10172 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 10173 if (err < 0) 10174 verbose(env, "Invalid format string\n"); 10175 10176 return err; 10177 } 10178 10179 static int check_get_func_ip(struct bpf_verifier_env *env) 10180 { 10181 enum bpf_prog_type type = resolve_prog_type(env->prog); 10182 int func_id = BPF_FUNC_get_func_ip; 10183 10184 if (type == BPF_PROG_TYPE_TRACING) { 10185 if (!bpf_prog_has_trampoline(env->prog)) { 10186 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 10187 func_id_name(func_id), func_id); 10188 return -ENOTSUPP; 10189 } 10190 return 0; 10191 } else if (type == BPF_PROG_TYPE_KPROBE) { 10192 return 0; 10193 } 10194 10195 verbose(env, "func %s#%d not supported for program type %d\n", 10196 func_id_name(func_id), func_id, type); 10197 return -ENOTSUPP; 10198 } 10199 10200 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 10201 { 10202 return &env->insn_aux_data[env->insn_idx]; 10203 } 10204 10205 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 10206 { 10207 struct bpf_reg_state *regs = cur_regs(env); 10208 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 10209 bool reg_is_null = register_is_null(reg); 10210 10211 if (reg_is_null) 10212 mark_chain_precision(env, BPF_REG_4); 10213 10214 return reg_is_null; 10215 } 10216 10217 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 10218 { 10219 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 10220 10221 if (!state->initialized) { 10222 state->initialized = 1; 10223 state->fit_for_inline = loop_flag_is_zero(env); 10224 state->callback_subprogno = subprogno; 10225 return; 10226 } 10227 10228 if (!state->fit_for_inline) 10229 return; 10230 10231 state->fit_for_inline = (loop_flag_is_zero(env) && 10232 state->callback_subprogno == subprogno); 10233 } 10234 10235 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10236 int *insn_idx_p) 10237 { 10238 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 10239 bool returns_cpu_specific_alloc_ptr = false; 10240 const struct bpf_func_proto *fn = NULL; 10241 enum bpf_return_type ret_type; 10242 enum bpf_type_flag ret_flag; 10243 struct bpf_reg_state *regs; 10244 struct bpf_call_arg_meta meta; 10245 int insn_idx = *insn_idx_p; 10246 bool changes_data; 10247 int i, err, func_id; 10248 10249 /* find function prototype */ 10250 func_id = insn->imm; 10251 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 10252 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 10253 func_id); 10254 return -EINVAL; 10255 } 10256 10257 if (env->ops->get_func_proto) 10258 fn = env->ops->get_func_proto(func_id, env->prog); 10259 if (!fn) { 10260 verbose(env, "program of this type cannot use helper %s#%d\n", 10261 func_id_name(func_id), func_id); 10262 return -EINVAL; 10263 } 10264 10265 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 10266 if (!env->prog->gpl_compatible && fn->gpl_only) { 10267 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10268 return -EINVAL; 10269 } 10270 10271 if (fn->allowed && !fn->allowed(env->prog)) { 10272 verbose(env, "helper call is not allowed in probe\n"); 10273 return -EINVAL; 10274 } 10275 10276 if (!in_sleepable(env) && fn->might_sleep) { 10277 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 10278 return -EINVAL; 10279 } 10280 10281 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10282 changes_data = bpf_helper_changes_pkt_data(fn->func); 10283 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10284 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 10285 func_id_name(func_id), func_id); 10286 return -EINVAL; 10287 } 10288 10289 memset(&meta, 0, sizeof(meta)); 10290 meta.pkt_access = fn->pkt_access; 10291 10292 err = check_func_proto(fn, func_id); 10293 if (err) { 10294 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 10295 func_id_name(func_id), func_id); 10296 return err; 10297 } 10298 10299 if (env->cur_state->active_rcu_lock) { 10300 if (fn->might_sleep) { 10301 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 10302 func_id_name(func_id), func_id); 10303 return -EINVAL; 10304 } 10305 10306 if (in_sleepable(env) && is_storage_get_function(func_id)) 10307 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10308 } 10309 10310 if (env->cur_state->active_preempt_lock) { 10311 if (fn->might_sleep) { 10312 verbose(env, "sleepable helper %s#%d in non-preemptible region\n", 10313 func_id_name(func_id), func_id); 10314 return -EINVAL; 10315 } 10316 10317 if (in_sleepable(env) && is_storage_get_function(func_id)) 10318 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10319 } 10320 10321 meta.func_id = func_id; 10322 /* check args */ 10323 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10324 err = check_func_arg(env, i, &meta, fn, insn_idx); 10325 if (err) 10326 return err; 10327 } 10328 10329 err = record_func_map(env, &meta, func_id, insn_idx); 10330 if (err) 10331 return err; 10332 10333 err = record_func_key(env, &meta, func_id, insn_idx); 10334 if (err) 10335 return err; 10336 10337 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10338 * is inferred from register state. 10339 */ 10340 for (i = 0; i < meta.access_size; i++) { 10341 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 10342 BPF_WRITE, -1, false, false); 10343 if (err) 10344 return err; 10345 } 10346 10347 regs = cur_regs(env); 10348 10349 if (meta.release_regno) { 10350 err = -EINVAL; 10351 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 10352 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 10353 * is safe to do directly. 10354 */ 10355 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 10356 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 10357 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 10358 return -EFAULT; 10359 } 10360 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 10361 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 10362 u32 ref_obj_id = meta.ref_obj_id; 10363 bool in_rcu = in_rcu_cs(env); 10364 struct bpf_func_state *state; 10365 struct bpf_reg_state *reg; 10366 10367 err = release_reference_state(cur_func(env), ref_obj_id); 10368 if (!err) { 10369 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10370 if (reg->ref_obj_id == ref_obj_id) { 10371 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 10372 reg->ref_obj_id = 0; 10373 reg->type &= ~MEM_ALLOC; 10374 reg->type |= MEM_RCU; 10375 } else { 10376 mark_reg_invalid(env, reg); 10377 } 10378 } 10379 })); 10380 } 10381 } else if (meta.ref_obj_id) { 10382 err = release_reference(env, meta.ref_obj_id); 10383 } else if (register_is_null(®s[meta.release_regno])) { 10384 /* meta.ref_obj_id can only be 0 if register that is meant to be 10385 * released is NULL, which must be > R0. 10386 */ 10387 err = 0; 10388 } 10389 if (err) { 10390 verbose(env, "func %s#%d reference has not been acquired before\n", 10391 func_id_name(func_id), func_id); 10392 return err; 10393 } 10394 } 10395 10396 switch (func_id) { 10397 case BPF_FUNC_tail_call: 10398 err = check_reference_leak(env, false); 10399 if (err) { 10400 verbose(env, "tail_call would lead to reference leak\n"); 10401 return err; 10402 } 10403 break; 10404 case BPF_FUNC_get_local_storage: 10405 /* check that flags argument in get_local_storage(map, flags) is 0, 10406 * this is required because get_local_storage() can't return an error. 10407 */ 10408 if (!register_is_null(®s[BPF_REG_2])) { 10409 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10410 return -EINVAL; 10411 } 10412 break; 10413 case BPF_FUNC_for_each_map_elem: 10414 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10415 set_map_elem_callback_state); 10416 break; 10417 case BPF_FUNC_timer_set_callback: 10418 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10419 set_timer_callback_state); 10420 break; 10421 case BPF_FUNC_find_vma: 10422 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10423 set_find_vma_callback_state); 10424 break; 10425 case BPF_FUNC_snprintf: 10426 err = check_bpf_snprintf_call(env, regs); 10427 break; 10428 case BPF_FUNC_loop: 10429 update_loop_inline_state(env, meta.subprogno); 10430 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10431 * is finished, thus mark it precise. 10432 */ 10433 err = mark_chain_precision(env, BPF_REG_1); 10434 if (err) 10435 return err; 10436 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) { 10437 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10438 set_loop_callback_state); 10439 } else { 10440 cur_func(env)->callback_depth = 0; 10441 if (env->log.level & BPF_LOG_LEVEL2) 10442 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10443 env->cur_state->curframe); 10444 } 10445 break; 10446 case BPF_FUNC_dynptr_from_mem: 10447 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10448 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10449 reg_type_str(env, regs[BPF_REG_1].type)); 10450 return -EACCES; 10451 } 10452 break; 10453 case BPF_FUNC_set_retval: 10454 if (prog_type == BPF_PROG_TYPE_LSM && 10455 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10456 if (!env->prog->aux->attach_func_proto->type) { 10457 /* Make sure programs that attach to void 10458 * hooks don't try to modify return value. 10459 */ 10460 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10461 return -EINVAL; 10462 } 10463 } 10464 break; 10465 case BPF_FUNC_dynptr_data: 10466 { 10467 struct bpf_reg_state *reg; 10468 int id, ref_obj_id; 10469 10470 reg = get_dynptr_arg_reg(env, fn, regs); 10471 if (!reg) 10472 return -EFAULT; 10473 10474 10475 if (meta.dynptr_id) { 10476 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 10477 return -EFAULT; 10478 } 10479 if (meta.ref_obj_id) { 10480 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 10481 return -EFAULT; 10482 } 10483 10484 id = dynptr_id(env, reg); 10485 if (id < 0) { 10486 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 10487 return id; 10488 } 10489 10490 ref_obj_id = dynptr_ref_obj_id(env, reg); 10491 if (ref_obj_id < 0) { 10492 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 10493 return ref_obj_id; 10494 } 10495 10496 meta.dynptr_id = id; 10497 meta.ref_obj_id = ref_obj_id; 10498 10499 break; 10500 } 10501 case BPF_FUNC_dynptr_write: 10502 { 10503 enum bpf_dynptr_type dynptr_type; 10504 struct bpf_reg_state *reg; 10505 10506 reg = get_dynptr_arg_reg(env, fn, regs); 10507 if (!reg) 10508 return -EFAULT; 10509 10510 dynptr_type = dynptr_get_type(env, reg); 10511 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10512 return -EFAULT; 10513 10514 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 10515 /* this will trigger clear_all_pkt_pointers(), which will 10516 * invalidate all dynptr slices associated with the skb 10517 */ 10518 changes_data = true; 10519 10520 break; 10521 } 10522 case BPF_FUNC_per_cpu_ptr: 10523 case BPF_FUNC_this_cpu_ptr: 10524 { 10525 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 10526 const struct btf_type *type; 10527 10528 if (reg->type & MEM_RCU) { 10529 type = btf_type_by_id(reg->btf, reg->btf_id); 10530 if (!type || !btf_type_is_struct(type)) { 10531 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 10532 return -EFAULT; 10533 } 10534 returns_cpu_specific_alloc_ptr = true; 10535 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 10536 } 10537 break; 10538 } 10539 case BPF_FUNC_user_ringbuf_drain: 10540 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10541 set_user_ringbuf_callback_state); 10542 break; 10543 } 10544 10545 if (err) 10546 return err; 10547 10548 /* reset caller saved regs */ 10549 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10550 mark_reg_not_init(env, regs, caller_saved[i]); 10551 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10552 } 10553 10554 /* helper call returns 64-bit value. */ 10555 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10556 10557 /* update return register (already marked as written above) */ 10558 ret_type = fn->ret_type; 10559 ret_flag = type_flag(ret_type); 10560 10561 switch (base_type(ret_type)) { 10562 case RET_INTEGER: 10563 /* sets type to SCALAR_VALUE */ 10564 mark_reg_unknown(env, regs, BPF_REG_0); 10565 break; 10566 case RET_VOID: 10567 regs[BPF_REG_0].type = NOT_INIT; 10568 break; 10569 case RET_PTR_TO_MAP_VALUE: 10570 /* There is no offset yet applied, variable or fixed */ 10571 mark_reg_known_zero(env, regs, BPF_REG_0); 10572 /* remember map_ptr, so that check_map_access() 10573 * can check 'value_size' boundary of memory access 10574 * to map element returned from bpf_map_lookup_elem() 10575 */ 10576 if (meta.map_ptr == NULL) { 10577 verbose(env, 10578 "kernel subsystem misconfigured verifier\n"); 10579 return -EINVAL; 10580 } 10581 regs[BPF_REG_0].map_ptr = meta.map_ptr; 10582 regs[BPF_REG_0].map_uid = meta.map_uid; 10583 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10584 if (!type_may_be_null(ret_type) && 10585 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 10586 regs[BPF_REG_0].id = ++env->id_gen; 10587 } 10588 break; 10589 case RET_PTR_TO_SOCKET: 10590 mark_reg_known_zero(env, regs, BPF_REG_0); 10591 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10592 break; 10593 case RET_PTR_TO_SOCK_COMMON: 10594 mark_reg_known_zero(env, regs, BPF_REG_0); 10595 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10596 break; 10597 case RET_PTR_TO_TCP_SOCK: 10598 mark_reg_known_zero(env, regs, BPF_REG_0); 10599 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10600 break; 10601 case RET_PTR_TO_MEM: 10602 mark_reg_known_zero(env, regs, BPF_REG_0); 10603 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10604 regs[BPF_REG_0].mem_size = meta.mem_size; 10605 break; 10606 case RET_PTR_TO_MEM_OR_BTF_ID: 10607 { 10608 const struct btf_type *t; 10609 10610 mark_reg_known_zero(env, regs, BPF_REG_0); 10611 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10612 if (!btf_type_is_struct(t)) { 10613 u32 tsize; 10614 const struct btf_type *ret; 10615 const char *tname; 10616 10617 /* resolve the type size of ksym. */ 10618 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10619 if (IS_ERR(ret)) { 10620 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10621 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10622 tname, PTR_ERR(ret)); 10623 return -EINVAL; 10624 } 10625 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10626 regs[BPF_REG_0].mem_size = tsize; 10627 } else { 10628 if (returns_cpu_specific_alloc_ptr) { 10629 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10630 } else { 10631 /* MEM_RDONLY may be carried from ret_flag, but it 10632 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10633 * it will confuse the check of PTR_TO_BTF_ID in 10634 * check_mem_access(). 10635 */ 10636 ret_flag &= ~MEM_RDONLY; 10637 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10638 } 10639 10640 regs[BPF_REG_0].btf = meta.ret_btf; 10641 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10642 } 10643 break; 10644 } 10645 case RET_PTR_TO_BTF_ID: 10646 { 10647 struct btf *ret_btf; 10648 int ret_btf_id; 10649 10650 mark_reg_known_zero(env, regs, BPF_REG_0); 10651 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10652 if (func_id == BPF_FUNC_kptr_xchg) { 10653 ret_btf = meta.kptr_field->kptr.btf; 10654 ret_btf_id = meta.kptr_field->kptr.btf_id; 10655 if (!btf_is_kernel(ret_btf)) { 10656 regs[BPF_REG_0].type |= MEM_ALLOC; 10657 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10658 regs[BPF_REG_0].type |= MEM_PERCPU; 10659 } 10660 } else { 10661 if (fn->ret_btf_id == BPF_PTR_POISON) { 10662 verbose(env, "verifier internal error:"); 10663 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 10664 func_id_name(func_id)); 10665 return -EINVAL; 10666 } 10667 ret_btf = btf_vmlinux; 10668 ret_btf_id = *fn->ret_btf_id; 10669 } 10670 if (ret_btf_id == 0) { 10671 verbose(env, "invalid return type %u of func %s#%d\n", 10672 base_type(ret_type), func_id_name(func_id), 10673 func_id); 10674 return -EINVAL; 10675 } 10676 regs[BPF_REG_0].btf = ret_btf; 10677 regs[BPF_REG_0].btf_id = ret_btf_id; 10678 break; 10679 } 10680 default: 10681 verbose(env, "unknown return type %u of func %s#%d\n", 10682 base_type(ret_type), func_id_name(func_id), func_id); 10683 return -EINVAL; 10684 } 10685 10686 if (type_may_be_null(regs[BPF_REG_0].type)) 10687 regs[BPF_REG_0].id = ++env->id_gen; 10688 10689 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 10690 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 10691 func_id_name(func_id), func_id); 10692 return -EFAULT; 10693 } 10694 10695 if (is_dynptr_ref_function(func_id)) 10696 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 10697 10698 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 10699 /* For release_reference() */ 10700 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10701 } else if (is_acquire_function(func_id, meta.map_ptr)) { 10702 int id = acquire_reference_state(env, insn_idx); 10703 10704 if (id < 0) 10705 return id; 10706 /* For mark_ptr_or_null_reg() */ 10707 regs[BPF_REG_0].id = id; 10708 /* For release_reference() */ 10709 regs[BPF_REG_0].ref_obj_id = id; 10710 } 10711 10712 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 10713 if (err) 10714 return err; 10715 10716 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 10717 if (err) 10718 return err; 10719 10720 if ((func_id == BPF_FUNC_get_stack || 10721 func_id == BPF_FUNC_get_task_stack) && 10722 !env->prog->has_callchain_buf) { 10723 const char *err_str; 10724 10725 #ifdef CONFIG_PERF_EVENTS 10726 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10727 err_str = "cannot get callchain buffer for func %s#%d\n"; 10728 #else 10729 err = -ENOTSUPP; 10730 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10731 #endif 10732 if (err) { 10733 verbose(env, err_str, func_id_name(func_id), func_id); 10734 return err; 10735 } 10736 10737 env->prog->has_callchain_buf = true; 10738 } 10739 10740 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10741 env->prog->call_get_stack = true; 10742 10743 if (func_id == BPF_FUNC_get_func_ip) { 10744 if (check_get_func_ip(env)) 10745 return -ENOTSUPP; 10746 env->prog->call_get_func_ip = true; 10747 } 10748 10749 if (changes_data) 10750 clear_all_pkt_pointers(env); 10751 return 0; 10752 } 10753 10754 /* mark_btf_func_reg_size() is used when the reg size is determined by 10755 * the BTF func_proto's return value size and argument. 10756 */ 10757 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10758 size_t reg_size) 10759 { 10760 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 10761 10762 if (regno == BPF_REG_0) { 10763 /* Function return value */ 10764 reg->live |= REG_LIVE_WRITTEN; 10765 reg->subreg_def = reg_size == sizeof(u64) ? 10766 DEF_NOT_SUBREG : env->insn_idx + 1; 10767 } else { 10768 /* Function argument */ 10769 if (reg_size == sizeof(u64)) { 10770 mark_insn_zext(env, reg); 10771 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 10772 } else { 10773 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 10774 } 10775 } 10776 } 10777 10778 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10779 { 10780 return meta->kfunc_flags & KF_ACQUIRE; 10781 } 10782 10783 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10784 { 10785 return meta->kfunc_flags & KF_RELEASE; 10786 } 10787 10788 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 10789 { 10790 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 10791 } 10792 10793 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 10794 { 10795 return meta->kfunc_flags & KF_SLEEPABLE; 10796 } 10797 10798 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10799 { 10800 return meta->kfunc_flags & KF_DESTRUCTIVE; 10801 } 10802 10803 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10804 { 10805 return meta->kfunc_flags & KF_RCU; 10806 } 10807 10808 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 10809 { 10810 return meta->kfunc_flags & KF_RCU_PROTECTED; 10811 } 10812 10813 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10814 const struct btf_param *arg, 10815 const struct bpf_reg_state *reg) 10816 { 10817 const struct btf_type *t; 10818 10819 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10820 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10821 return false; 10822 10823 return btf_param_match_suffix(btf, arg, "__sz"); 10824 } 10825 10826 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10827 const struct btf_param *arg, 10828 const struct bpf_reg_state *reg) 10829 { 10830 const struct btf_type *t; 10831 10832 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10833 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10834 return false; 10835 10836 return btf_param_match_suffix(btf, arg, "__szk"); 10837 } 10838 10839 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 10840 { 10841 return btf_param_match_suffix(btf, arg, "__opt"); 10842 } 10843 10844 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10845 { 10846 return btf_param_match_suffix(btf, arg, "__k"); 10847 } 10848 10849 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10850 { 10851 return btf_param_match_suffix(btf, arg, "__ign"); 10852 } 10853 10854 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg) 10855 { 10856 return btf_param_match_suffix(btf, arg, "__map"); 10857 } 10858 10859 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10860 { 10861 return btf_param_match_suffix(btf, arg, "__alloc"); 10862 } 10863 10864 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10865 { 10866 return btf_param_match_suffix(btf, arg, "__uninit"); 10867 } 10868 10869 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10870 { 10871 return btf_param_match_suffix(btf, arg, "__refcounted_kptr"); 10872 } 10873 10874 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 10875 { 10876 return btf_param_match_suffix(btf, arg, "__nullable"); 10877 } 10878 10879 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 10880 { 10881 return btf_param_match_suffix(btf, arg, "__str"); 10882 } 10883 10884 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10885 const struct btf_param *arg, 10886 const char *name) 10887 { 10888 int len, target_len = strlen(name); 10889 const char *param_name; 10890 10891 param_name = btf_name_by_offset(btf, arg->name_off); 10892 if (str_is_empty(param_name)) 10893 return false; 10894 len = strlen(param_name); 10895 if (len != target_len) 10896 return false; 10897 if (strcmp(param_name, name)) 10898 return false; 10899 10900 return true; 10901 } 10902 10903 enum { 10904 KF_ARG_DYNPTR_ID, 10905 KF_ARG_LIST_HEAD_ID, 10906 KF_ARG_LIST_NODE_ID, 10907 KF_ARG_RB_ROOT_ID, 10908 KF_ARG_RB_NODE_ID, 10909 KF_ARG_WORKQUEUE_ID, 10910 }; 10911 10912 BTF_ID_LIST(kf_arg_btf_ids) 10913 BTF_ID(struct, bpf_dynptr_kern) 10914 BTF_ID(struct, bpf_list_head) 10915 BTF_ID(struct, bpf_list_node) 10916 BTF_ID(struct, bpf_rb_root) 10917 BTF_ID(struct, bpf_rb_node) 10918 BTF_ID(struct, bpf_wq) 10919 10920 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10921 const struct btf_param *arg, int type) 10922 { 10923 const struct btf_type *t; 10924 u32 res_id; 10925 10926 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10927 if (!t) 10928 return false; 10929 if (!btf_type_is_ptr(t)) 10930 return false; 10931 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10932 if (!t) 10933 return false; 10934 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10935 } 10936 10937 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10938 { 10939 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10940 } 10941 10942 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10943 { 10944 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10945 } 10946 10947 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10948 { 10949 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10950 } 10951 10952 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10953 { 10954 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10955 } 10956 10957 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10958 { 10959 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10960 } 10961 10962 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg) 10963 { 10964 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID); 10965 } 10966 10967 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10968 const struct btf_param *arg) 10969 { 10970 const struct btf_type *t; 10971 10972 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10973 if (!t) 10974 return false; 10975 10976 return true; 10977 } 10978 10979 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10980 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10981 const struct btf *btf, 10982 const struct btf_type *t, int rec) 10983 { 10984 const struct btf_type *member_type; 10985 const struct btf_member *member; 10986 u32 i; 10987 10988 if (!btf_type_is_struct(t)) 10989 return false; 10990 10991 for_each_member(i, t, member) { 10992 const struct btf_array *array; 10993 10994 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 10995 if (btf_type_is_struct(member_type)) { 10996 if (rec >= 3) { 10997 verbose(env, "max struct nesting depth exceeded\n"); 10998 return false; 10999 } 11000 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 11001 return false; 11002 continue; 11003 } 11004 if (btf_type_is_array(member_type)) { 11005 array = btf_array(member_type); 11006 if (!array->nelems) 11007 return false; 11008 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 11009 if (!btf_type_is_scalar(member_type)) 11010 return false; 11011 continue; 11012 } 11013 if (!btf_type_is_scalar(member_type)) 11014 return false; 11015 } 11016 return true; 11017 } 11018 11019 enum kfunc_ptr_arg_type { 11020 KF_ARG_PTR_TO_CTX, 11021 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 11022 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 11023 KF_ARG_PTR_TO_DYNPTR, 11024 KF_ARG_PTR_TO_ITER, 11025 KF_ARG_PTR_TO_LIST_HEAD, 11026 KF_ARG_PTR_TO_LIST_NODE, 11027 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 11028 KF_ARG_PTR_TO_MEM, 11029 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 11030 KF_ARG_PTR_TO_CALLBACK, 11031 KF_ARG_PTR_TO_RB_ROOT, 11032 KF_ARG_PTR_TO_RB_NODE, 11033 KF_ARG_PTR_TO_NULL, 11034 KF_ARG_PTR_TO_CONST_STR, 11035 KF_ARG_PTR_TO_MAP, 11036 KF_ARG_PTR_TO_WORKQUEUE, 11037 }; 11038 11039 enum special_kfunc_type { 11040 KF_bpf_obj_new_impl, 11041 KF_bpf_obj_drop_impl, 11042 KF_bpf_refcount_acquire_impl, 11043 KF_bpf_list_push_front_impl, 11044 KF_bpf_list_push_back_impl, 11045 KF_bpf_list_pop_front, 11046 KF_bpf_list_pop_back, 11047 KF_bpf_cast_to_kern_ctx, 11048 KF_bpf_rdonly_cast, 11049 KF_bpf_rcu_read_lock, 11050 KF_bpf_rcu_read_unlock, 11051 KF_bpf_rbtree_remove, 11052 KF_bpf_rbtree_add_impl, 11053 KF_bpf_rbtree_first, 11054 KF_bpf_dynptr_from_skb, 11055 KF_bpf_dynptr_from_xdp, 11056 KF_bpf_dynptr_slice, 11057 KF_bpf_dynptr_slice_rdwr, 11058 KF_bpf_dynptr_clone, 11059 KF_bpf_percpu_obj_new_impl, 11060 KF_bpf_percpu_obj_drop_impl, 11061 KF_bpf_throw, 11062 KF_bpf_wq_set_callback_impl, 11063 KF_bpf_preempt_disable, 11064 KF_bpf_preempt_enable, 11065 KF_bpf_iter_css_task_new, 11066 KF_bpf_session_cookie, 11067 }; 11068 11069 BTF_SET_START(special_kfunc_set) 11070 BTF_ID(func, bpf_obj_new_impl) 11071 BTF_ID(func, bpf_obj_drop_impl) 11072 BTF_ID(func, bpf_refcount_acquire_impl) 11073 BTF_ID(func, bpf_list_push_front_impl) 11074 BTF_ID(func, bpf_list_push_back_impl) 11075 BTF_ID(func, bpf_list_pop_front) 11076 BTF_ID(func, bpf_list_pop_back) 11077 BTF_ID(func, bpf_cast_to_kern_ctx) 11078 BTF_ID(func, bpf_rdonly_cast) 11079 BTF_ID(func, bpf_rbtree_remove) 11080 BTF_ID(func, bpf_rbtree_add_impl) 11081 BTF_ID(func, bpf_rbtree_first) 11082 BTF_ID(func, bpf_dynptr_from_skb) 11083 BTF_ID(func, bpf_dynptr_from_xdp) 11084 BTF_ID(func, bpf_dynptr_slice) 11085 BTF_ID(func, bpf_dynptr_slice_rdwr) 11086 BTF_ID(func, bpf_dynptr_clone) 11087 BTF_ID(func, bpf_percpu_obj_new_impl) 11088 BTF_ID(func, bpf_percpu_obj_drop_impl) 11089 BTF_ID(func, bpf_throw) 11090 BTF_ID(func, bpf_wq_set_callback_impl) 11091 #ifdef CONFIG_CGROUPS 11092 BTF_ID(func, bpf_iter_css_task_new) 11093 #endif 11094 BTF_SET_END(special_kfunc_set) 11095 11096 BTF_ID_LIST(special_kfunc_list) 11097 BTF_ID(func, bpf_obj_new_impl) 11098 BTF_ID(func, bpf_obj_drop_impl) 11099 BTF_ID(func, bpf_refcount_acquire_impl) 11100 BTF_ID(func, bpf_list_push_front_impl) 11101 BTF_ID(func, bpf_list_push_back_impl) 11102 BTF_ID(func, bpf_list_pop_front) 11103 BTF_ID(func, bpf_list_pop_back) 11104 BTF_ID(func, bpf_cast_to_kern_ctx) 11105 BTF_ID(func, bpf_rdonly_cast) 11106 BTF_ID(func, bpf_rcu_read_lock) 11107 BTF_ID(func, bpf_rcu_read_unlock) 11108 BTF_ID(func, bpf_rbtree_remove) 11109 BTF_ID(func, bpf_rbtree_add_impl) 11110 BTF_ID(func, bpf_rbtree_first) 11111 BTF_ID(func, bpf_dynptr_from_skb) 11112 BTF_ID(func, bpf_dynptr_from_xdp) 11113 BTF_ID(func, bpf_dynptr_slice) 11114 BTF_ID(func, bpf_dynptr_slice_rdwr) 11115 BTF_ID(func, bpf_dynptr_clone) 11116 BTF_ID(func, bpf_percpu_obj_new_impl) 11117 BTF_ID(func, bpf_percpu_obj_drop_impl) 11118 BTF_ID(func, bpf_throw) 11119 BTF_ID(func, bpf_wq_set_callback_impl) 11120 BTF_ID(func, bpf_preempt_disable) 11121 BTF_ID(func, bpf_preempt_enable) 11122 #ifdef CONFIG_CGROUPS 11123 BTF_ID(func, bpf_iter_css_task_new) 11124 #else 11125 BTF_ID_UNUSED 11126 #endif 11127 BTF_ID(func, bpf_session_cookie) 11128 11129 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 11130 { 11131 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 11132 meta->arg_owning_ref) { 11133 return false; 11134 } 11135 11136 return meta->kfunc_flags & KF_RET_NULL; 11137 } 11138 11139 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 11140 { 11141 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 11142 } 11143 11144 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 11145 { 11146 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 11147 } 11148 11149 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta) 11150 { 11151 return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable]; 11152 } 11153 11154 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta) 11155 { 11156 return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable]; 11157 } 11158 11159 static enum kfunc_ptr_arg_type 11160 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 11161 struct bpf_kfunc_call_arg_meta *meta, 11162 const struct btf_type *t, const struct btf_type *ref_t, 11163 const char *ref_tname, const struct btf_param *args, 11164 int argno, int nargs) 11165 { 11166 u32 regno = argno + 1; 11167 struct bpf_reg_state *regs = cur_regs(env); 11168 struct bpf_reg_state *reg = ®s[regno]; 11169 bool arg_mem_size = false; 11170 11171 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 11172 return KF_ARG_PTR_TO_CTX; 11173 11174 /* In this function, we verify the kfunc's BTF as per the argument type, 11175 * leaving the rest of the verification with respect to the register 11176 * type to our caller. When a set of conditions hold in the BTF type of 11177 * arguments, we resolve it to a known kfunc_ptr_arg_type. 11178 */ 11179 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 11180 return KF_ARG_PTR_TO_CTX; 11181 11182 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 11183 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 11184 11185 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 11186 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 11187 11188 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 11189 return KF_ARG_PTR_TO_DYNPTR; 11190 11191 if (is_kfunc_arg_iter(meta, argno)) 11192 return KF_ARG_PTR_TO_ITER; 11193 11194 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 11195 return KF_ARG_PTR_TO_LIST_HEAD; 11196 11197 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 11198 return KF_ARG_PTR_TO_LIST_NODE; 11199 11200 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 11201 return KF_ARG_PTR_TO_RB_ROOT; 11202 11203 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 11204 return KF_ARG_PTR_TO_RB_NODE; 11205 11206 if (is_kfunc_arg_const_str(meta->btf, &args[argno])) 11207 return KF_ARG_PTR_TO_CONST_STR; 11208 11209 if (is_kfunc_arg_map(meta->btf, &args[argno])) 11210 return KF_ARG_PTR_TO_MAP; 11211 11212 if (is_kfunc_arg_wq(meta->btf, &args[argno])) 11213 return KF_ARG_PTR_TO_WORKQUEUE; 11214 11215 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 11216 if (!btf_type_is_struct(ref_t)) { 11217 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 11218 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 11219 return -EINVAL; 11220 } 11221 return KF_ARG_PTR_TO_BTF_ID; 11222 } 11223 11224 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 11225 return KF_ARG_PTR_TO_CALLBACK; 11226 11227 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg)) 11228 return KF_ARG_PTR_TO_NULL; 11229 11230 if (argno + 1 < nargs && 11231 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 11232 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 11233 arg_mem_size = true; 11234 11235 /* This is the catch all argument type of register types supported by 11236 * check_helper_mem_access. However, we only allow when argument type is 11237 * pointer to scalar, or struct composed (recursively) of scalars. When 11238 * arg_mem_size is true, the pointer can be void *. 11239 */ 11240 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 11241 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 11242 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 11243 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 11244 return -EINVAL; 11245 } 11246 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 11247 } 11248 11249 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 11250 struct bpf_reg_state *reg, 11251 const struct btf_type *ref_t, 11252 const char *ref_tname, u32 ref_id, 11253 struct bpf_kfunc_call_arg_meta *meta, 11254 int argno) 11255 { 11256 const struct btf_type *reg_ref_t; 11257 bool strict_type_match = false; 11258 const struct btf *reg_btf; 11259 const char *reg_ref_tname; 11260 u32 reg_ref_id; 11261 11262 if (base_type(reg->type) == PTR_TO_BTF_ID) { 11263 reg_btf = reg->btf; 11264 reg_ref_id = reg->btf_id; 11265 } else { 11266 reg_btf = btf_vmlinux; 11267 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 11268 } 11269 11270 /* Enforce strict type matching for calls to kfuncs that are acquiring 11271 * or releasing a reference, or are no-cast aliases. We do _not_ 11272 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 11273 * as we want to enable BPF programs to pass types that are bitwise 11274 * equivalent without forcing them to explicitly cast with something 11275 * like bpf_cast_to_kern_ctx(). 11276 * 11277 * For example, say we had a type like the following: 11278 * 11279 * struct bpf_cpumask { 11280 * cpumask_t cpumask; 11281 * refcount_t usage; 11282 * }; 11283 * 11284 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 11285 * to a struct cpumask, so it would be safe to pass a struct 11286 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 11287 * 11288 * The philosophy here is similar to how we allow scalars of different 11289 * types to be passed to kfuncs as long as the size is the same. The 11290 * only difference here is that we're simply allowing 11291 * btf_struct_ids_match() to walk the struct at the 0th offset, and 11292 * resolve types. 11293 */ 11294 if (is_kfunc_acquire(meta) || 11295 (is_kfunc_release(meta) && reg->ref_obj_id) || 11296 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 11297 strict_type_match = true; 11298 11299 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 11300 11301 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 11302 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 11303 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 11304 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 11305 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 11306 btf_type_str(reg_ref_t), reg_ref_tname); 11307 return -EINVAL; 11308 } 11309 return 0; 11310 } 11311 11312 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11313 { 11314 struct bpf_verifier_state *state = env->cur_state; 11315 struct btf_record *rec = reg_btf_record(reg); 11316 11317 if (!state->active_lock.ptr) { 11318 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 11319 return -EFAULT; 11320 } 11321 11322 if (type_flag(reg->type) & NON_OWN_REF) { 11323 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 11324 return -EFAULT; 11325 } 11326 11327 reg->type |= NON_OWN_REF; 11328 if (rec->refcount_off >= 0) 11329 reg->type |= MEM_RCU; 11330 11331 return 0; 11332 } 11333 11334 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 11335 { 11336 struct bpf_func_state *state, *unused; 11337 struct bpf_reg_state *reg; 11338 int i; 11339 11340 state = cur_func(env); 11341 11342 if (!ref_obj_id) { 11343 verbose(env, "verifier internal error: ref_obj_id is zero for " 11344 "owning -> non-owning conversion\n"); 11345 return -EFAULT; 11346 } 11347 11348 for (i = 0; i < state->acquired_refs; i++) { 11349 if (state->refs[i].id != ref_obj_id) 11350 continue; 11351 11352 /* Clear ref_obj_id here so release_reference doesn't clobber 11353 * the whole reg 11354 */ 11355 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11356 if (reg->ref_obj_id == ref_obj_id) { 11357 reg->ref_obj_id = 0; 11358 ref_set_non_owning(env, reg); 11359 } 11360 })); 11361 return 0; 11362 } 11363 11364 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 11365 return -EFAULT; 11366 } 11367 11368 /* Implementation details: 11369 * 11370 * Each register points to some region of memory, which we define as an 11371 * allocation. Each allocation may embed a bpf_spin_lock which protects any 11372 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 11373 * allocation. The lock and the data it protects are colocated in the same 11374 * memory region. 11375 * 11376 * Hence, everytime a register holds a pointer value pointing to such 11377 * allocation, the verifier preserves a unique reg->id for it. 11378 * 11379 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 11380 * bpf_spin_lock is called. 11381 * 11382 * To enable this, lock state in the verifier captures two values: 11383 * active_lock.ptr = Register's type specific pointer 11384 * active_lock.id = A unique ID for each register pointer value 11385 * 11386 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11387 * supported register types. 11388 * 11389 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11390 * allocated objects is the reg->btf pointer. 11391 * 11392 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11393 * can establish the provenance of the map value statically for each distinct 11394 * lookup into such maps. They always contain a single map value hence unique 11395 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11396 * 11397 * So, in case of global variables, they use array maps with max_entries = 1, 11398 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11399 * into the same map value as max_entries is 1, as described above). 11400 * 11401 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11402 * outer map pointer (in verifier context), but each lookup into an inner map 11403 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11404 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11405 * will get different reg->id assigned to each lookup, hence different 11406 * active_lock.id. 11407 * 11408 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11409 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11410 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11411 */ 11412 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11413 { 11414 void *ptr; 11415 u32 id; 11416 11417 switch ((int)reg->type) { 11418 case PTR_TO_MAP_VALUE: 11419 ptr = reg->map_ptr; 11420 break; 11421 case PTR_TO_BTF_ID | MEM_ALLOC: 11422 ptr = reg->btf; 11423 break; 11424 default: 11425 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 11426 return -EFAULT; 11427 } 11428 id = reg->id; 11429 11430 if (!env->cur_state->active_lock.ptr) 11431 return -EINVAL; 11432 if (env->cur_state->active_lock.ptr != ptr || 11433 env->cur_state->active_lock.id != id) { 11434 verbose(env, "held lock and object are not in the same allocation\n"); 11435 return -EINVAL; 11436 } 11437 return 0; 11438 } 11439 11440 static bool is_bpf_list_api_kfunc(u32 btf_id) 11441 { 11442 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11443 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11444 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11445 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 11446 } 11447 11448 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11449 { 11450 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 11451 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11452 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 11453 } 11454 11455 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11456 { 11457 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 11458 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11459 } 11460 11461 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11462 { 11463 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11464 } 11465 11466 static bool is_async_callback_calling_kfunc(u32 btf_id) 11467 { 11468 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl]; 11469 } 11470 11471 static bool is_bpf_throw_kfunc(struct bpf_insn *insn) 11472 { 11473 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 11474 insn->imm == special_kfunc_list[KF_bpf_throw]; 11475 } 11476 11477 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id) 11478 { 11479 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl]; 11480 } 11481 11482 static bool is_callback_calling_kfunc(u32 btf_id) 11483 { 11484 return is_sync_callback_calling_kfunc(btf_id) || 11485 is_async_callback_calling_kfunc(btf_id); 11486 } 11487 11488 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11489 { 11490 return is_bpf_rbtree_api_kfunc(btf_id); 11491 } 11492 11493 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11494 enum btf_field_type head_field_type, 11495 u32 kfunc_btf_id) 11496 { 11497 bool ret; 11498 11499 switch (head_field_type) { 11500 case BPF_LIST_HEAD: 11501 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11502 break; 11503 case BPF_RB_ROOT: 11504 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11505 break; 11506 default: 11507 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11508 btf_field_type_name(head_field_type)); 11509 return false; 11510 } 11511 11512 if (!ret) 11513 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11514 btf_field_type_name(head_field_type)); 11515 return ret; 11516 } 11517 11518 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11519 enum btf_field_type node_field_type, 11520 u32 kfunc_btf_id) 11521 { 11522 bool ret; 11523 11524 switch (node_field_type) { 11525 case BPF_LIST_NODE: 11526 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11527 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 11528 break; 11529 case BPF_RB_NODE: 11530 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11531 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 11532 break; 11533 default: 11534 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11535 btf_field_type_name(node_field_type)); 11536 return false; 11537 } 11538 11539 if (!ret) 11540 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11541 btf_field_type_name(node_field_type)); 11542 return ret; 11543 } 11544 11545 static int 11546 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11547 struct bpf_reg_state *reg, u32 regno, 11548 struct bpf_kfunc_call_arg_meta *meta, 11549 enum btf_field_type head_field_type, 11550 struct btf_field **head_field) 11551 { 11552 const char *head_type_name; 11553 struct btf_field *field; 11554 struct btf_record *rec; 11555 u32 head_off; 11556 11557 if (meta->btf != btf_vmlinux) { 11558 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11559 return -EFAULT; 11560 } 11561 11562 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11563 return -EFAULT; 11564 11565 head_type_name = btf_field_type_name(head_field_type); 11566 if (!tnum_is_const(reg->var_off)) { 11567 verbose(env, 11568 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11569 regno, head_type_name); 11570 return -EINVAL; 11571 } 11572 11573 rec = reg_btf_record(reg); 11574 head_off = reg->off + reg->var_off.value; 11575 field = btf_record_find(rec, head_off, head_field_type); 11576 if (!field) { 11577 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11578 return -EINVAL; 11579 } 11580 11581 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11582 if (check_reg_allocation_locked(env, reg)) { 11583 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11584 rec->spin_lock_off, head_type_name); 11585 return -EINVAL; 11586 } 11587 11588 if (*head_field) { 11589 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 11590 return -EFAULT; 11591 } 11592 *head_field = field; 11593 return 0; 11594 } 11595 11596 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11597 struct bpf_reg_state *reg, u32 regno, 11598 struct bpf_kfunc_call_arg_meta *meta) 11599 { 11600 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 11601 &meta->arg_list_head.field); 11602 } 11603 11604 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11605 struct bpf_reg_state *reg, u32 regno, 11606 struct bpf_kfunc_call_arg_meta *meta) 11607 { 11608 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 11609 &meta->arg_rbtree_root.field); 11610 } 11611 11612 static int 11613 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11614 struct bpf_reg_state *reg, u32 regno, 11615 struct bpf_kfunc_call_arg_meta *meta, 11616 enum btf_field_type head_field_type, 11617 enum btf_field_type node_field_type, 11618 struct btf_field **node_field) 11619 { 11620 const char *node_type_name; 11621 const struct btf_type *et, *t; 11622 struct btf_field *field; 11623 u32 node_off; 11624 11625 if (meta->btf != btf_vmlinux) { 11626 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11627 return -EFAULT; 11628 } 11629 11630 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11631 return -EFAULT; 11632 11633 node_type_name = btf_field_type_name(node_field_type); 11634 if (!tnum_is_const(reg->var_off)) { 11635 verbose(env, 11636 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11637 regno, node_type_name); 11638 return -EINVAL; 11639 } 11640 11641 node_off = reg->off + reg->var_off.value; 11642 field = reg_find_field_offset(reg, node_off, node_field_type); 11643 if (!field || field->offset != node_off) { 11644 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11645 return -EINVAL; 11646 } 11647 11648 field = *node_field; 11649 11650 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11651 t = btf_type_by_id(reg->btf, reg->btf_id); 11652 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11653 field->graph_root.value_btf_id, true)) { 11654 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11655 "in struct %s, but arg is at offset=%d in struct %s\n", 11656 btf_field_type_name(head_field_type), 11657 btf_field_type_name(node_field_type), 11658 field->graph_root.node_offset, 11659 btf_name_by_offset(field->graph_root.btf, et->name_off), 11660 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11661 return -EINVAL; 11662 } 11663 meta->arg_btf = reg->btf; 11664 meta->arg_btf_id = reg->btf_id; 11665 11666 if (node_off != field->graph_root.node_offset) { 11667 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11668 node_off, btf_field_type_name(node_field_type), 11669 field->graph_root.node_offset, 11670 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11671 return -EINVAL; 11672 } 11673 11674 return 0; 11675 } 11676 11677 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11678 struct bpf_reg_state *reg, u32 regno, 11679 struct bpf_kfunc_call_arg_meta *meta) 11680 { 11681 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11682 BPF_LIST_HEAD, BPF_LIST_NODE, 11683 &meta->arg_list_head.field); 11684 } 11685 11686 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11687 struct bpf_reg_state *reg, u32 regno, 11688 struct bpf_kfunc_call_arg_meta *meta) 11689 { 11690 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11691 BPF_RB_ROOT, BPF_RB_NODE, 11692 &meta->arg_rbtree_root.field); 11693 } 11694 11695 /* 11696 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 11697 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 11698 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 11699 * them can only be attached to some specific hook points. 11700 */ 11701 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 11702 { 11703 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11704 11705 switch (prog_type) { 11706 case BPF_PROG_TYPE_LSM: 11707 return true; 11708 case BPF_PROG_TYPE_TRACING: 11709 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 11710 return true; 11711 fallthrough; 11712 default: 11713 return in_sleepable(env); 11714 } 11715 } 11716 11717 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11718 int insn_idx) 11719 { 11720 const char *func_name = meta->func_name, *ref_tname; 11721 const struct btf *btf = meta->btf; 11722 const struct btf_param *args; 11723 struct btf_record *rec; 11724 u32 i, nargs; 11725 int ret; 11726 11727 args = (const struct btf_param *)(meta->func_proto + 1); 11728 nargs = btf_type_vlen(meta->func_proto); 11729 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 11730 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11731 MAX_BPF_FUNC_REG_ARGS); 11732 return -EINVAL; 11733 } 11734 11735 /* Check that BTF function arguments match actual types that the 11736 * verifier sees. 11737 */ 11738 for (i = 0; i < nargs; i++) { 11739 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 11740 const struct btf_type *t, *ref_t, *resolve_ret; 11741 enum bpf_arg_type arg_type = ARG_DONTCARE; 11742 u32 regno = i + 1, ref_id, type_size; 11743 bool is_ret_buf_sz = false; 11744 int kf_arg_type; 11745 11746 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11747 11748 if (is_kfunc_arg_ignore(btf, &args[i])) 11749 continue; 11750 11751 if (btf_type_is_scalar(t)) { 11752 if (reg->type != SCALAR_VALUE) { 11753 verbose(env, "R%d is not a scalar\n", regno); 11754 return -EINVAL; 11755 } 11756 11757 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11758 if (meta->arg_constant.found) { 11759 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11760 return -EFAULT; 11761 } 11762 if (!tnum_is_const(reg->var_off)) { 11763 verbose(env, "R%d must be a known constant\n", regno); 11764 return -EINVAL; 11765 } 11766 ret = mark_chain_precision(env, regno); 11767 if (ret < 0) 11768 return ret; 11769 meta->arg_constant.found = true; 11770 meta->arg_constant.value = reg->var_off.value; 11771 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 11772 meta->r0_rdonly = true; 11773 is_ret_buf_sz = true; 11774 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 11775 is_ret_buf_sz = true; 11776 } 11777 11778 if (is_ret_buf_sz) { 11779 if (meta->r0_size) { 11780 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 11781 return -EINVAL; 11782 } 11783 11784 if (!tnum_is_const(reg->var_off)) { 11785 verbose(env, "R%d is not a const\n", regno); 11786 return -EINVAL; 11787 } 11788 11789 meta->r0_size = reg->var_off.value; 11790 ret = mark_chain_precision(env, regno); 11791 if (ret) 11792 return ret; 11793 } 11794 continue; 11795 } 11796 11797 if (!btf_type_is_ptr(t)) { 11798 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 11799 return -EINVAL; 11800 } 11801 11802 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 11803 (register_is_null(reg) || type_may_be_null(reg->type)) && 11804 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 11805 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 11806 return -EACCES; 11807 } 11808 11809 if (reg->ref_obj_id) { 11810 if (is_kfunc_release(meta) && meta->ref_obj_id) { 11811 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 11812 regno, reg->ref_obj_id, 11813 meta->ref_obj_id); 11814 return -EFAULT; 11815 } 11816 meta->ref_obj_id = reg->ref_obj_id; 11817 if (is_kfunc_release(meta)) 11818 meta->release_regno = regno; 11819 } 11820 11821 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 11822 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 11823 11824 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 11825 if (kf_arg_type < 0) 11826 return kf_arg_type; 11827 11828 switch (kf_arg_type) { 11829 case KF_ARG_PTR_TO_NULL: 11830 continue; 11831 case KF_ARG_PTR_TO_MAP: 11832 if (!reg->map_ptr) { 11833 verbose(env, "pointer in R%d isn't map pointer\n", regno); 11834 return -EINVAL; 11835 } 11836 if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) { 11837 /* Use map_uid (which is unique id of inner map) to reject: 11838 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 11839 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 11840 * if (inner_map1 && inner_map2) { 11841 * wq = bpf_map_lookup_elem(inner_map1); 11842 * if (wq) 11843 * // mismatch would have been allowed 11844 * bpf_wq_init(wq, inner_map2); 11845 * } 11846 * 11847 * Comparing map_ptr is enough to distinguish normal and outer maps. 11848 */ 11849 if (meta->map.ptr != reg->map_ptr || 11850 meta->map.uid != reg->map_uid) { 11851 verbose(env, 11852 "workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 11853 meta->map.uid, reg->map_uid); 11854 return -EINVAL; 11855 } 11856 } 11857 meta->map.ptr = reg->map_ptr; 11858 meta->map.uid = reg->map_uid; 11859 fallthrough; 11860 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11861 case KF_ARG_PTR_TO_BTF_ID: 11862 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 11863 break; 11864 11865 if (!is_trusted_reg(reg)) { 11866 if (!is_kfunc_rcu(meta)) { 11867 verbose(env, "R%d must be referenced or trusted\n", regno); 11868 return -EINVAL; 11869 } 11870 if (!is_rcu_reg(reg)) { 11871 verbose(env, "R%d must be a rcu pointer\n", regno); 11872 return -EINVAL; 11873 } 11874 } 11875 11876 fallthrough; 11877 case KF_ARG_PTR_TO_CTX: 11878 /* Trusted arguments have the same offset checks as release arguments */ 11879 arg_type |= OBJ_RELEASE; 11880 break; 11881 case KF_ARG_PTR_TO_DYNPTR: 11882 case KF_ARG_PTR_TO_ITER: 11883 case KF_ARG_PTR_TO_LIST_HEAD: 11884 case KF_ARG_PTR_TO_LIST_NODE: 11885 case KF_ARG_PTR_TO_RB_ROOT: 11886 case KF_ARG_PTR_TO_RB_NODE: 11887 case KF_ARG_PTR_TO_MEM: 11888 case KF_ARG_PTR_TO_MEM_SIZE: 11889 case KF_ARG_PTR_TO_CALLBACK: 11890 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11891 case KF_ARG_PTR_TO_CONST_STR: 11892 case KF_ARG_PTR_TO_WORKQUEUE: 11893 /* Trusted by default */ 11894 break; 11895 default: 11896 WARN_ON_ONCE(1); 11897 return -EFAULT; 11898 } 11899 11900 if (is_kfunc_release(meta) && reg->ref_obj_id) 11901 arg_type |= OBJ_RELEASE; 11902 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 11903 if (ret < 0) 11904 return ret; 11905 11906 switch (kf_arg_type) { 11907 case KF_ARG_PTR_TO_CTX: 11908 if (reg->type != PTR_TO_CTX) { 11909 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 11910 return -EINVAL; 11911 } 11912 11913 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11914 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 11915 if (ret < 0) 11916 return -EINVAL; 11917 meta->ret_btf_id = ret; 11918 } 11919 break; 11920 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11921 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 11922 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) { 11923 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i); 11924 return -EINVAL; 11925 } 11926 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 11927 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 11928 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i); 11929 return -EINVAL; 11930 } 11931 } else { 11932 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11933 return -EINVAL; 11934 } 11935 if (!reg->ref_obj_id) { 11936 verbose(env, "allocated object must be referenced\n"); 11937 return -EINVAL; 11938 } 11939 if (meta->btf == btf_vmlinux) { 11940 meta->arg_btf = reg->btf; 11941 meta->arg_btf_id = reg->btf_id; 11942 } 11943 break; 11944 case KF_ARG_PTR_TO_DYNPTR: 11945 { 11946 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 11947 int clone_ref_obj_id = 0; 11948 11949 if (reg->type != PTR_TO_STACK && 11950 reg->type != CONST_PTR_TO_DYNPTR) { 11951 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 11952 return -EINVAL; 11953 } 11954 11955 if (reg->type == CONST_PTR_TO_DYNPTR) 11956 dynptr_arg_type |= MEM_RDONLY; 11957 11958 if (is_kfunc_arg_uninit(btf, &args[i])) 11959 dynptr_arg_type |= MEM_UNINIT; 11960 11961 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 11962 dynptr_arg_type |= DYNPTR_TYPE_SKB; 11963 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 11964 dynptr_arg_type |= DYNPTR_TYPE_XDP; 11965 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 11966 (dynptr_arg_type & MEM_UNINIT)) { 11967 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 11968 11969 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 11970 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 11971 return -EFAULT; 11972 } 11973 11974 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 11975 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 11976 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 11977 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 11978 return -EFAULT; 11979 } 11980 } 11981 11982 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 11983 if (ret < 0) 11984 return ret; 11985 11986 if (!(dynptr_arg_type & MEM_UNINIT)) { 11987 int id = dynptr_id(env, reg); 11988 11989 if (id < 0) { 11990 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 11991 return id; 11992 } 11993 meta->initialized_dynptr.id = id; 11994 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 11995 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 11996 } 11997 11998 break; 11999 } 12000 case KF_ARG_PTR_TO_ITER: 12001 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 12002 if (!check_css_task_iter_allowlist(env)) { 12003 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 12004 return -EINVAL; 12005 } 12006 } 12007 ret = process_iter_arg(env, regno, insn_idx, meta); 12008 if (ret < 0) 12009 return ret; 12010 break; 12011 case KF_ARG_PTR_TO_LIST_HEAD: 12012 if (reg->type != PTR_TO_MAP_VALUE && 12013 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12014 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 12015 return -EINVAL; 12016 } 12017 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 12018 verbose(env, "allocated object must be referenced\n"); 12019 return -EINVAL; 12020 } 12021 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 12022 if (ret < 0) 12023 return ret; 12024 break; 12025 case KF_ARG_PTR_TO_RB_ROOT: 12026 if (reg->type != PTR_TO_MAP_VALUE && 12027 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12028 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 12029 return -EINVAL; 12030 } 12031 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 12032 verbose(env, "allocated object must be referenced\n"); 12033 return -EINVAL; 12034 } 12035 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 12036 if (ret < 0) 12037 return ret; 12038 break; 12039 case KF_ARG_PTR_TO_LIST_NODE: 12040 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12041 verbose(env, "arg#%d expected pointer to allocated object\n", i); 12042 return -EINVAL; 12043 } 12044 if (!reg->ref_obj_id) { 12045 verbose(env, "allocated object must be referenced\n"); 12046 return -EINVAL; 12047 } 12048 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 12049 if (ret < 0) 12050 return ret; 12051 break; 12052 case KF_ARG_PTR_TO_RB_NODE: 12053 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 12054 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 12055 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 12056 return -EINVAL; 12057 } 12058 if (in_rbtree_lock_required_cb(env)) { 12059 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 12060 return -EINVAL; 12061 } 12062 } else { 12063 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12064 verbose(env, "arg#%d expected pointer to allocated object\n", i); 12065 return -EINVAL; 12066 } 12067 if (!reg->ref_obj_id) { 12068 verbose(env, "allocated object must be referenced\n"); 12069 return -EINVAL; 12070 } 12071 } 12072 12073 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 12074 if (ret < 0) 12075 return ret; 12076 break; 12077 case KF_ARG_PTR_TO_MAP: 12078 /* If argument has '__map' suffix expect 'struct bpf_map *' */ 12079 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP]; 12080 ref_t = btf_type_by_id(btf_vmlinux, ref_id); 12081 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12082 fallthrough; 12083 case KF_ARG_PTR_TO_BTF_ID: 12084 /* Only base_type is checked, further checks are done here */ 12085 if ((base_type(reg->type) != PTR_TO_BTF_ID || 12086 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 12087 !reg2btf_ids[base_type(reg->type)]) { 12088 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 12089 verbose(env, "expected %s or socket\n", 12090 reg_type_str(env, base_type(reg->type) | 12091 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 12092 return -EINVAL; 12093 } 12094 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 12095 if (ret < 0) 12096 return ret; 12097 break; 12098 case KF_ARG_PTR_TO_MEM: 12099 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 12100 if (IS_ERR(resolve_ret)) { 12101 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 12102 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 12103 return -EINVAL; 12104 } 12105 ret = check_mem_reg(env, reg, regno, type_size); 12106 if (ret < 0) 12107 return ret; 12108 break; 12109 case KF_ARG_PTR_TO_MEM_SIZE: 12110 { 12111 struct bpf_reg_state *buff_reg = ®s[regno]; 12112 const struct btf_param *buff_arg = &args[i]; 12113 struct bpf_reg_state *size_reg = ®s[regno + 1]; 12114 const struct btf_param *size_arg = &args[i + 1]; 12115 12116 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 12117 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 12118 if (ret < 0) { 12119 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 12120 return ret; 12121 } 12122 } 12123 12124 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 12125 if (meta->arg_constant.found) { 12126 verbose(env, "verifier internal error: only one constant argument permitted\n"); 12127 return -EFAULT; 12128 } 12129 if (!tnum_is_const(size_reg->var_off)) { 12130 verbose(env, "R%d must be a known constant\n", regno + 1); 12131 return -EINVAL; 12132 } 12133 meta->arg_constant.found = true; 12134 meta->arg_constant.value = size_reg->var_off.value; 12135 } 12136 12137 /* Skip next '__sz' or '__szk' argument */ 12138 i++; 12139 break; 12140 } 12141 case KF_ARG_PTR_TO_CALLBACK: 12142 if (reg->type != PTR_TO_FUNC) { 12143 verbose(env, "arg%d expected pointer to func\n", i); 12144 return -EINVAL; 12145 } 12146 meta->subprogno = reg->subprogno; 12147 break; 12148 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12149 if (!type_is_ptr_alloc_obj(reg->type)) { 12150 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 12151 return -EINVAL; 12152 } 12153 if (!type_is_non_owning_ref(reg->type)) 12154 meta->arg_owning_ref = true; 12155 12156 rec = reg_btf_record(reg); 12157 if (!rec) { 12158 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 12159 return -EFAULT; 12160 } 12161 12162 if (rec->refcount_off < 0) { 12163 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 12164 return -EINVAL; 12165 } 12166 12167 meta->arg_btf = reg->btf; 12168 meta->arg_btf_id = reg->btf_id; 12169 break; 12170 case KF_ARG_PTR_TO_CONST_STR: 12171 if (reg->type != PTR_TO_MAP_VALUE) { 12172 verbose(env, "arg#%d doesn't point to a const string\n", i); 12173 return -EINVAL; 12174 } 12175 ret = check_reg_const_str(env, reg, regno); 12176 if (ret) 12177 return ret; 12178 break; 12179 case KF_ARG_PTR_TO_WORKQUEUE: 12180 if (reg->type != PTR_TO_MAP_VALUE) { 12181 verbose(env, "arg#%d doesn't point to a map value\n", i); 12182 return -EINVAL; 12183 } 12184 ret = process_wq_func(env, regno, meta); 12185 if (ret < 0) 12186 return ret; 12187 break; 12188 } 12189 } 12190 12191 if (is_kfunc_release(meta) && !meta->release_regno) { 12192 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 12193 func_name); 12194 return -EINVAL; 12195 } 12196 12197 return 0; 12198 } 12199 12200 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 12201 struct bpf_insn *insn, 12202 struct bpf_kfunc_call_arg_meta *meta, 12203 const char **kfunc_name) 12204 { 12205 const struct btf_type *func, *func_proto; 12206 u32 func_id, *kfunc_flags; 12207 const char *func_name; 12208 struct btf *desc_btf; 12209 12210 if (kfunc_name) 12211 *kfunc_name = NULL; 12212 12213 if (!insn->imm) 12214 return -EINVAL; 12215 12216 desc_btf = find_kfunc_desc_btf(env, insn->off); 12217 if (IS_ERR(desc_btf)) 12218 return PTR_ERR(desc_btf); 12219 12220 func_id = insn->imm; 12221 func = btf_type_by_id(desc_btf, func_id); 12222 func_name = btf_name_by_offset(desc_btf, func->name_off); 12223 if (kfunc_name) 12224 *kfunc_name = func_name; 12225 func_proto = btf_type_by_id(desc_btf, func->type); 12226 12227 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 12228 if (!kfunc_flags) { 12229 return -EACCES; 12230 } 12231 12232 memset(meta, 0, sizeof(*meta)); 12233 meta->btf = desc_btf; 12234 meta->func_id = func_id; 12235 meta->kfunc_flags = *kfunc_flags; 12236 meta->func_proto = func_proto; 12237 meta->func_name = func_name; 12238 12239 return 0; 12240 } 12241 12242 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 12243 12244 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 12245 int *insn_idx_p) 12246 { 12247 bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable; 12248 u32 i, nargs, ptr_type_id, release_ref_obj_id; 12249 struct bpf_reg_state *regs = cur_regs(env); 12250 const char *func_name, *ptr_type_name; 12251 const struct btf_type *t, *ptr_type; 12252 struct bpf_kfunc_call_arg_meta meta; 12253 struct bpf_insn_aux_data *insn_aux; 12254 int err, insn_idx = *insn_idx_p; 12255 const struct btf_param *args; 12256 const struct btf_type *ret_t; 12257 struct btf *desc_btf; 12258 12259 /* skip for now, but return error when we find this in fixup_kfunc_call */ 12260 if (!insn->imm) 12261 return 0; 12262 12263 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 12264 if (err == -EACCES && func_name) 12265 verbose(env, "calling kernel function %s is not allowed\n", func_name); 12266 if (err) 12267 return err; 12268 desc_btf = meta.btf; 12269 insn_aux = &env->insn_aux_data[insn_idx]; 12270 12271 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 12272 12273 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 12274 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 12275 return -EACCES; 12276 } 12277 12278 sleepable = is_kfunc_sleepable(&meta); 12279 if (sleepable && !in_sleepable(env)) { 12280 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 12281 return -EACCES; 12282 } 12283 12284 /* Check the arguments */ 12285 err = check_kfunc_args(env, &meta, insn_idx); 12286 if (err < 0) 12287 return err; 12288 12289 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12290 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12291 set_rbtree_add_callback_state); 12292 if (err) { 12293 verbose(env, "kfunc %s#%d failed callback verification\n", 12294 func_name, meta.func_id); 12295 return err; 12296 } 12297 } 12298 12299 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) { 12300 meta.r0_size = sizeof(u64); 12301 meta.r0_rdonly = false; 12302 } 12303 12304 if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) { 12305 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12306 set_timer_callback_state); 12307 if (err) { 12308 verbose(env, "kfunc %s#%d failed callback verification\n", 12309 func_name, meta.func_id); 12310 return err; 12311 } 12312 } 12313 12314 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 12315 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 12316 12317 preempt_disable = is_kfunc_bpf_preempt_disable(&meta); 12318 preempt_enable = is_kfunc_bpf_preempt_enable(&meta); 12319 12320 if (env->cur_state->active_rcu_lock) { 12321 struct bpf_func_state *state; 12322 struct bpf_reg_state *reg; 12323 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 12324 12325 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 12326 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 12327 return -EACCES; 12328 } 12329 12330 if (rcu_lock) { 12331 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 12332 return -EINVAL; 12333 } else if (rcu_unlock) { 12334 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({ 12335 if (reg->type & MEM_RCU) { 12336 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 12337 reg->type |= PTR_UNTRUSTED; 12338 } 12339 })); 12340 env->cur_state->active_rcu_lock = false; 12341 } else if (sleepable) { 12342 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 12343 return -EACCES; 12344 } 12345 } else if (rcu_lock) { 12346 env->cur_state->active_rcu_lock = true; 12347 } else if (rcu_unlock) { 12348 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 12349 return -EINVAL; 12350 } 12351 12352 if (env->cur_state->active_preempt_lock) { 12353 if (preempt_disable) { 12354 env->cur_state->active_preempt_lock++; 12355 } else if (preempt_enable) { 12356 env->cur_state->active_preempt_lock--; 12357 } else if (sleepable) { 12358 verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name); 12359 return -EACCES; 12360 } 12361 } else if (preempt_disable) { 12362 env->cur_state->active_preempt_lock++; 12363 } else if (preempt_enable) { 12364 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name); 12365 return -EINVAL; 12366 } 12367 12368 /* In case of release function, we get register number of refcounted 12369 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 12370 */ 12371 if (meta.release_regno) { 12372 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 12373 if (err) { 12374 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12375 func_name, meta.func_id); 12376 return err; 12377 } 12378 } 12379 12380 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 12381 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 12382 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12383 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 12384 insn_aux->insert_off = regs[BPF_REG_2].off; 12385 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 12386 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 12387 if (err) { 12388 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 12389 func_name, meta.func_id); 12390 return err; 12391 } 12392 12393 err = release_reference(env, release_ref_obj_id); 12394 if (err) { 12395 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12396 func_name, meta.func_id); 12397 return err; 12398 } 12399 } 12400 12401 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 12402 if (!bpf_jit_supports_exceptions()) { 12403 verbose(env, "JIT does not support calling kfunc %s#%d\n", 12404 func_name, meta.func_id); 12405 return -ENOTSUPP; 12406 } 12407 env->seen_exception = true; 12408 12409 /* In the case of the default callback, the cookie value passed 12410 * to bpf_throw becomes the return value of the program. 12411 */ 12412 if (!env->exception_callback_subprog) { 12413 err = check_return_code(env, BPF_REG_1, "R1"); 12414 if (err < 0) 12415 return err; 12416 } 12417 } 12418 12419 for (i = 0; i < CALLER_SAVED_REGS; i++) 12420 mark_reg_not_init(env, regs, caller_saved[i]); 12421 12422 /* Check return type */ 12423 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 12424 12425 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 12426 /* Only exception is bpf_obj_new_impl */ 12427 if (meta.btf != btf_vmlinux || 12428 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 12429 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] && 12430 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 12431 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 12432 return -EINVAL; 12433 } 12434 } 12435 12436 if (btf_type_is_scalar(t)) { 12437 mark_reg_unknown(env, regs, BPF_REG_0); 12438 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 12439 } else if (btf_type_is_ptr(t)) { 12440 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 12441 12442 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12443 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 12444 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12445 struct btf_struct_meta *struct_meta; 12446 struct btf *ret_btf; 12447 u32 ret_btf_id; 12448 12449 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set) 12450 return -ENOMEM; 12451 12452 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 12453 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 12454 return -EINVAL; 12455 } 12456 12457 ret_btf = env->prog->aux->btf; 12458 ret_btf_id = meta.arg_constant.value; 12459 12460 /* This may be NULL due to user not supplying a BTF */ 12461 if (!ret_btf) { 12462 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 12463 return -EINVAL; 12464 } 12465 12466 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 12467 if (!ret_t || !__btf_type_is_struct(ret_t)) { 12468 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 12469 return -EINVAL; 12470 } 12471 12472 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12473 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 12474 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 12475 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 12476 return -EINVAL; 12477 } 12478 12479 if (!bpf_global_percpu_ma_set) { 12480 mutex_lock(&bpf_percpu_ma_lock); 12481 if (!bpf_global_percpu_ma_set) { 12482 /* Charge memory allocated with bpf_global_percpu_ma to 12483 * root memcg. The obj_cgroup for root memcg is NULL. 12484 */ 12485 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 12486 if (!err) 12487 bpf_global_percpu_ma_set = true; 12488 } 12489 mutex_unlock(&bpf_percpu_ma_lock); 12490 if (err) 12491 return err; 12492 } 12493 12494 mutex_lock(&bpf_percpu_ma_lock); 12495 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 12496 mutex_unlock(&bpf_percpu_ma_lock); 12497 if (err) 12498 return err; 12499 } 12500 12501 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 12502 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12503 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 12504 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 12505 return -EINVAL; 12506 } 12507 12508 if (struct_meta) { 12509 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 12510 return -EINVAL; 12511 } 12512 } 12513 12514 mark_reg_known_zero(env, regs, BPF_REG_0); 12515 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12516 regs[BPF_REG_0].btf = ret_btf; 12517 regs[BPF_REG_0].btf_id = ret_btf_id; 12518 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) 12519 regs[BPF_REG_0].type |= MEM_PERCPU; 12520 12521 insn_aux->obj_new_size = ret_t->size; 12522 insn_aux->kptr_struct_meta = struct_meta; 12523 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 12524 mark_reg_known_zero(env, regs, BPF_REG_0); 12525 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12526 regs[BPF_REG_0].btf = meta.arg_btf; 12527 regs[BPF_REG_0].btf_id = meta.arg_btf_id; 12528 12529 insn_aux->kptr_struct_meta = 12530 btf_find_struct_meta(meta.arg_btf, 12531 meta.arg_btf_id); 12532 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 12533 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 12534 struct btf_field *field = meta.arg_list_head.field; 12535 12536 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12537 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12538 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12539 struct btf_field *field = meta.arg_rbtree_root.field; 12540 12541 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12542 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12543 mark_reg_known_zero(env, regs, BPF_REG_0); 12544 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 12545 regs[BPF_REG_0].btf = desc_btf; 12546 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 12547 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 12548 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 12549 if (!ret_t || !btf_type_is_struct(ret_t)) { 12550 verbose(env, 12551 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 12552 return -EINVAL; 12553 } 12554 12555 mark_reg_known_zero(env, regs, BPF_REG_0); 12556 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 12557 regs[BPF_REG_0].btf = desc_btf; 12558 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 12559 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 12560 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 12561 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 12562 12563 mark_reg_known_zero(env, regs, BPF_REG_0); 12564 12565 if (!meta.arg_constant.found) { 12566 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 12567 return -EFAULT; 12568 } 12569 12570 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 12571 12572 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 12573 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 12574 12575 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 12576 regs[BPF_REG_0].type |= MEM_RDONLY; 12577 } else { 12578 /* this will set env->seen_direct_write to true */ 12579 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 12580 verbose(env, "the prog does not allow writes to packet data\n"); 12581 return -EINVAL; 12582 } 12583 } 12584 12585 if (!meta.initialized_dynptr.id) { 12586 verbose(env, "verifier internal error: no dynptr id\n"); 12587 return -EFAULT; 12588 } 12589 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 12590 12591 /* we don't need to set BPF_REG_0's ref obj id 12592 * because packet slices are not refcounted (see 12593 * dynptr_type_refcounted) 12594 */ 12595 } else { 12596 verbose(env, "kernel function %s unhandled dynamic return type\n", 12597 meta.func_name); 12598 return -EFAULT; 12599 } 12600 } else if (btf_type_is_void(ptr_type)) { 12601 /* kfunc returning 'void *' is equivalent to returning scalar */ 12602 mark_reg_unknown(env, regs, BPF_REG_0); 12603 } else if (!__btf_type_is_struct(ptr_type)) { 12604 if (!meta.r0_size) { 12605 __u32 sz; 12606 12607 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 12608 meta.r0_size = sz; 12609 meta.r0_rdonly = true; 12610 } 12611 } 12612 if (!meta.r0_size) { 12613 ptr_type_name = btf_name_by_offset(desc_btf, 12614 ptr_type->name_off); 12615 verbose(env, 12616 "kernel function %s returns pointer type %s %s is not supported\n", 12617 func_name, 12618 btf_type_str(ptr_type), 12619 ptr_type_name); 12620 return -EINVAL; 12621 } 12622 12623 mark_reg_known_zero(env, regs, BPF_REG_0); 12624 regs[BPF_REG_0].type = PTR_TO_MEM; 12625 regs[BPF_REG_0].mem_size = meta.r0_size; 12626 12627 if (meta.r0_rdonly) 12628 regs[BPF_REG_0].type |= MEM_RDONLY; 12629 12630 /* Ensures we don't access the memory after a release_reference() */ 12631 if (meta.ref_obj_id) 12632 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 12633 } else { 12634 mark_reg_known_zero(env, regs, BPF_REG_0); 12635 regs[BPF_REG_0].btf = desc_btf; 12636 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 12637 regs[BPF_REG_0].btf_id = ptr_type_id; 12638 } 12639 12640 if (is_kfunc_ret_null(&meta)) { 12641 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 12642 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 12643 regs[BPF_REG_0].id = ++env->id_gen; 12644 } 12645 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 12646 if (is_kfunc_acquire(&meta)) { 12647 int id = acquire_reference_state(env, insn_idx); 12648 12649 if (id < 0) 12650 return id; 12651 if (is_kfunc_ret_null(&meta)) 12652 regs[BPF_REG_0].id = id; 12653 regs[BPF_REG_0].ref_obj_id = id; 12654 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12655 ref_set_non_owning(env, ®s[BPF_REG_0]); 12656 } 12657 12658 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 12659 regs[BPF_REG_0].id = ++env->id_gen; 12660 } else if (btf_type_is_void(t)) { 12661 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12662 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 12663 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 12664 insn_aux->kptr_struct_meta = 12665 btf_find_struct_meta(meta.arg_btf, 12666 meta.arg_btf_id); 12667 } 12668 } 12669 } 12670 12671 nargs = btf_type_vlen(meta.func_proto); 12672 args = (const struct btf_param *)(meta.func_proto + 1); 12673 for (i = 0; i < nargs; i++) { 12674 u32 regno = i + 1; 12675 12676 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 12677 if (btf_type_is_ptr(t)) 12678 mark_btf_func_reg_size(env, regno, sizeof(void *)); 12679 else 12680 /* scalar. ensured by btf_check_kfunc_arg_match() */ 12681 mark_btf_func_reg_size(env, regno, t->size); 12682 } 12683 12684 if (is_iter_next_kfunc(&meta)) { 12685 err = process_iter_next_call(env, insn_idx, &meta); 12686 if (err) 12687 return err; 12688 } 12689 12690 return 0; 12691 } 12692 12693 static bool signed_add_overflows(s64 a, s64 b) 12694 { 12695 /* Do the add in u64, where overflow is well-defined */ 12696 s64 res = (s64)((u64)a + (u64)b); 12697 12698 if (b < 0) 12699 return res > a; 12700 return res < a; 12701 } 12702 12703 static bool signed_add32_overflows(s32 a, s32 b) 12704 { 12705 /* Do the add in u32, where overflow is well-defined */ 12706 s32 res = (s32)((u32)a + (u32)b); 12707 12708 if (b < 0) 12709 return res > a; 12710 return res < a; 12711 } 12712 12713 static bool signed_sub_overflows(s64 a, s64 b) 12714 { 12715 /* Do the sub in u64, where overflow is well-defined */ 12716 s64 res = (s64)((u64)a - (u64)b); 12717 12718 if (b < 0) 12719 return res < a; 12720 return res > a; 12721 } 12722 12723 static bool signed_sub32_overflows(s32 a, s32 b) 12724 { 12725 /* Do the sub in u32, where overflow is well-defined */ 12726 s32 res = (s32)((u32)a - (u32)b); 12727 12728 if (b < 0) 12729 return res < a; 12730 return res > a; 12731 } 12732 12733 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 12734 const struct bpf_reg_state *reg, 12735 enum bpf_reg_type type) 12736 { 12737 bool known = tnum_is_const(reg->var_off); 12738 s64 val = reg->var_off.value; 12739 s64 smin = reg->smin_value; 12740 12741 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 12742 verbose(env, "math between %s pointer and %lld is not allowed\n", 12743 reg_type_str(env, type), val); 12744 return false; 12745 } 12746 12747 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 12748 verbose(env, "%s pointer offset %d is not allowed\n", 12749 reg_type_str(env, type), reg->off); 12750 return false; 12751 } 12752 12753 if (smin == S64_MIN) { 12754 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 12755 reg_type_str(env, type)); 12756 return false; 12757 } 12758 12759 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 12760 verbose(env, "value %lld makes %s pointer be out of bounds\n", 12761 smin, reg_type_str(env, type)); 12762 return false; 12763 } 12764 12765 return true; 12766 } 12767 12768 enum { 12769 REASON_BOUNDS = -1, 12770 REASON_TYPE = -2, 12771 REASON_PATHS = -3, 12772 REASON_LIMIT = -4, 12773 REASON_STACK = -5, 12774 }; 12775 12776 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 12777 u32 *alu_limit, bool mask_to_left) 12778 { 12779 u32 max = 0, ptr_limit = 0; 12780 12781 switch (ptr_reg->type) { 12782 case PTR_TO_STACK: 12783 /* Offset 0 is out-of-bounds, but acceptable start for the 12784 * left direction, see BPF_REG_FP. Also, unknown scalar 12785 * offset where we would need to deal with min/max bounds is 12786 * currently prohibited for unprivileged. 12787 */ 12788 max = MAX_BPF_STACK + mask_to_left; 12789 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 12790 break; 12791 case PTR_TO_MAP_VALUE: 12792 max = ptr_reg->map_ptr->value_size; 12793 ptr_limit = (mask_to_left ? 12794 ptr_reg->smin_value : 12795 ptr_reg->umax_value) + ptr_reg->off; 12796 break; 12797 default: 12798 return REASON_TYPE; 12799 } 12800 12801 if (ptr_limit >= max) 12802 return REASON_LIMIT; 12803 *alu_limit = ptr_limit; 12804 return 0; 12805 } 12806 12807 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 12808 const struct bpf_insn *insn) 12809 { 12810 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 12811 } 12812 12813 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 12814 u32 alu_state, u32 alu_limit) 12815 { 12816 /* If we arrived here from different branches with different 12817 * state or limits to sanitize, then this won't work. 12818 */ 12819 if (aux->alu_state && 12820 (aux->alu_state != alu_state || 12821 aux->alu_limit != alu_limit)) 12822 return REASON_PATHS; 12823 12824 /* Corresponding fixup done in do_misc_fixups(). */ 12825 aux->alu_state = alu_state; 12826 aux->alu_limit = alu_limit; 12827 return 0; 12828 } 12829 12830 static int sanitize_val_alu(struct bpf_verifier_env *env, 12831 struct bpf_insn *insn) 12832 { 12833 struct bpf_insn_aux_data *aux = cur_aux(env); 12834 12835 if (can_skip_alu_sanitation(env, insn)) 12836 return 0; 12837 12838 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 12839 } 12840 12841 static bool sanitize_needed(u8 opcode) 12842 { 12843 return opcode == BPF_ADD || opcode == BPF_SUB; 12844 } 12845 12846 struct bpf_sanitize_info { 12847 struct bpf_insn_aux_data aux; 12848 bool mask_to_left; 12849 }; 12850 12851 static struct bpf_verifier_state * 12852 sanitize_speculative_path(struct bpf_verifier_env *env, 12853 const struct bpf_insn *insn, 12854 u32 next_idx, u32 curr_idx) 12855 { 12856 struct bpf_verifier_state *branch; 12857 struct bpf_reg_state *regs; 12858 12859 branch = push_stack(env, next_idx, curr_idx, true); 12860 if (branch && insn) { 12861 regs = branch->frame[branch->curframe]->regs; 12862 if (BPF_SRC(insn->code) == BPF_K) { 12863 mark_reg_unknown(env, regs, insn->dst_reg); 12864 } else if (BPF_SRC(insn->code) == BPF_X) { 12865 mark_reg_unknown(env, regs, insn->dst_reg); 12866 mark_reg_unknown(env, regs, insn->src_reg); 12867 } 12868 } 12869 return branch; 12870 } 12871 12872 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 12873 struct bpf_insn *insn, 12874 const struct bpf_reg_state *ptr_reg, 12875 const struct bpf_reg_state *off_reg, 12876 struct bpf_reg_state *dst_reg, 12877 struct bpf_sanitize_info *info, 12878 const bool commit_window) 12879 { 12880 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 12881 struct bpf_verifier_state *vstate = env->cur_state; 12882 bool off_is_imm = tnum_is_const(off_reg->var_off); 12883 bool off_is_neg = off_reg->smin_value < 0; 12884 bool ptr_is_dst_reg = ptr_reg == dst_reg; 12885 u8 opcode = BPF_OP(insn->code); 12886 u32 alu_state, alu_limit; 12887 struct bpf_reg_state tmp; 12888 bool ret; 12889 int err; 12890 12891 if (can_skip_alu_sanitation(env, insn)) 12892 return 0; 12893 12894 /* We already marked aux for masking from non-speculative 12895 * paths, thus we got here in the first place. We only care 12896 * to explore bad access from here. 12897 */ 12898 if (vstate->speculative) 12899 goto do_sim; 12900 12901 if (!commit_window) { 12902 if (!tnum_is_const(off_reg->var_off) && 12903 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 12904 return REASON_BOUNDS; 12905 12906 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 12907 (opcode == BPF_SUB && !off_is_neg); 12908 } 12909 12910 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 12911 if (err < 0) 12912 return err; 12913 12914 if (commit_window) { 12915 /* In commit phase we narrow the masking window based on 12916 * the observed pointer move after the simulated operation. 12917 */ 12918 alu_state = info->aux.alu_state; 12919 alu_limit = abs(info->aux.alu_limit - alu_limit); 12920 } else { 12921 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 12922 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 12923 alu_state |= ptr_is_dst_reg ? 12924 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 12925 12926 /* Limit pruning on unknown scalars to enable deep search for 12927 * potential masking differences from other program paths. 12928 */ 12929 if (!off_is_imm) 12930 env->explore_alu_limits = true; 12931 } 12932 12933 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 12934 if (err < 0) 12935 return err; 12936 do_sim: 12937 /* If we're in commit phase, we're done here given we already 12938 * pushed the truncated dst_reg into the speculative verification 12939 * stack. 12940 * 12941 * Also, when register is a known constant, we rewrite register-based 12942 * operation to immediate-based, and thus do not need masking (and as 12943 * a consequence, do not need to simulate the zero-truncation either). 12944 */ 12945 if (commit_window || off_is_imm) 12946 return 0; 12947 12948 /* Simulate and find potential out-of-bounds access under 12949 * speculative execution from truncation as a result of 12950 * masking when off was not within expected range. If off 12951 * sits in dst, then we temporarily need to move ptr there 12952 * to simulate dst (== 0) +/-= ptr. Needed, for example, 12953 * for cases where we use K-based arithmetic in one direction 12954 * and truncated reg-based in the other in order to explore 12955 * bad access. 12956 */ 12957 if (!ptr_is_dst_reg) { 12958 tmp = *dst_reg; 12959 copy_register_state(dst_reg, ptr_reg); 12960 } 12961 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 12962 env->insn_idx); 12963 if (!ptr_is_dst_reg && ret) 12964 *dst_reg = tmp; 12965 return !ret ? REASON_STACK : 0; 12966 } 12967 12968 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 12969 { 12970 struct bpf_verifier_state *vstate = env->cur_state; 12971 12972 /* If we simulate paths under speculation, we don't update the 12973 * insn as 'seen' such that when we verify unreachable paths in 12974 * the non-speculative domain, sanitize_dead_code() can still 12975 * rewrite/sanitize them. 12976 */ 12977 if (!vstate->speculative) 12978 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 12979 } 12980 12981 static int sanitize_err(struct bpf_verifier_env *env, 12982 const struct bpf_insn *insn, int reason, 12983 const struct bpf_reg_state *off_reg, 12984 const struct bpf_reg_state *dst_reg) 12985 { 12986 static const char *err = "pointer arithmetic with it prohibited for !root"; 12987 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 12988 u32 dst = insn->dst_reg, src = insn->src_reg; 12989 12990 switch (reason) { 12991 case REASON_BOUNDS: 12992 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 12993 off_reg == dst_reg ? dst : src, err); 12994 break; 12995 case REASON_TYPE: 12996 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 12997 off_reg == dst_reg ? src : dst, err); 12998 break; 12999 case REASON_PATHS: 13000 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 13001 dst, op, err); 13002 break; 13003 case REASON_LIMIT: 13004 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 13005 dst, op, err); 13006 break; 13007 case REASON_STACK: 13008 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 13009 dst, err); 13010 break; 13011 default: 13012 verbose(env, "verifier internal error: unknown reason (%d)\n", 13013 reason); 13014 break; 13015 } 13016 13017 return -EACCES; 13018 } 13019 13020 /* check that stack access falls within stack limits and that 'reg' doesn't 13021 * have a variable offset. 13022 * 13023 * Variable offset is prohibited for unprivileged mode for simplicity since it 13024 * requires corresponding support in Spectre masking for stack ALU. See also 13025 * retrieve_ptr_limit(). 13026 * 13027 * 13028 * 'off' includes 'reg->off'. 13029 */ 13030 static int check_stack_access_for_ptr_arithmetic( 13031 struct bpf_verifier_env *env, 13032 int regno, 13033 const struct bpf_reg_state *reg, 13034 int off) 13035 { 13036 if (!tnum_is_const(reg->var_off)) { 13037 char tn_buf[48]; 13038 13039 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 13040 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 13041 regno, tn_buf, off); 13042 return -EACCES; 13043 } 13044 13045 if (off >= 0 || off < -MAX_BPF_STACK) { 13046 verbose(env, "R%d stack pointer arithmetic goes out of range, " 13047 "prohibited for !root; off=%d\n", regno, off); 13048 return -EACCES; 13049 } 13050 13051 return 0; 13052 } 13053 13054 static int sanitize_check_bounds(struct bpf_verifier_env *env, 13055 const struct bpf_insn *insn, 13056 const struct bpf_reg_state *dst_reg) 13057 { 13058 u32 dst = insn->dst_reg; 13059 13060 /* For unprivileged we require that resulting offset must be in bounds 13061 * in order to be able to sanitize access later on. 13062 */ 13063 if (env->bypass_spec_v1) 13064 return 0; 13065 13066 switch (dst_reg->type) { 13067 case PTR_TO_STACK: 13068 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 13069 dst_reg->off + dst_reg->var_off.value)) 13070 return -EACCES; 13071 break; 13072 case PTR_TO_MAP_VALUE: 13073 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 13074 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 13075 "prohibited for !root\n", dst); 13076 return -EACCES; 13077 } 13078 break; 13079 default: 13080 break; 13081 } 13082 13083 return 0; 13084 } 13085 13086 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 13087 * Caller should also handle BPF_MOV case separately. 13088 * If we return -EACCES, caller may want to try again treating pointer as a 13089 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 13090 */ 13091 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 13092 struct bpf_insn *insn, 13093 const struct bpf_reg_state *ptr_reg, 13094 const struct bpf_reg_state *off_reg) 13095 { 13096 struct bpf_verifier_state *vstate = env->cur_state; 13097 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13098 struct bpf_reg_state *regs = state->regs, *dst_reg; 13099 bool known = tnum_is_const(off_reg->var_off); 13100 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 13101 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 13102 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 13103 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 13104 struct bpf_sanitize_info info = {}; 13105 u8 opcode = BPF_OP(insn->code); 13106 u32 dst = insn->dst_reg; 13107 int ret; 13108 13109 dst_reg = ®s[dst]; 13110 13111 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 13112 smin_val > smax_val || umin_val > umax_val) { 13113 /* Taint dst register if offset had invalid bounds derived from 13114 * e.g. dead branches. 13115 */ 13116 __mark_reg_unknown(env, dst_reg); 13117 return 0; 13118 } 13119 13120 if (BPF_CLASS(insn->code) != BPF_ALU64) { 13121 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 13122 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13123 __mark_reg_unknown(env, dst_reg); 13124 return 0; 13125 } 13126 13127 verbose(env, 13128 "R%d 32-bit pointer arithmetic prohibited\n", 13129 dst); 13130 return -EACCES; 13131 } 13132 13133 if (ptr_reg->type & PTR_MAYBE_NULL) { 13134 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 13135 dst, reg_type_str(env, ptr_reg->type)); 13136 return -EACCES; 13137 } 13138 13139 switch (base_type(ptr_reg->type)) { 13140 case PTR_TO_CTX: 13141 case PTR_TO_MAP_VALUE: 13142 case PTR_TO_MAP_KEY: 13143 case PTR_TO_STACK: 13144 case PTR_TO_PACKET_META: 13145 case PTR_TO_PACKET: 13146 case PTR_TO_TP_BUFFER: 13147 case PTR_TO_BTF_ID: 13148 case PTR_TO_MEM: 13149 case PTR_TO_BUF: 13150 case PTR_TO_FUNC: 13151 case CONST_PTR_TO_DYNPTR: 13152 break; 13153 case PTR_TO_FLOW_KEYS: 13154 if (known) 13155 break; 13156 fallthrough; 13157 case CONST_PTR_TO_MAP: 13158 /* smin_val represents the known value */ 13159 if (known && smin_val == 0 && opcode == BPF_ADD) 13160 break; 13161 fallthrough; 13162 default: 13163 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 13164 dst, reg_type_str(env, ptr_reg->type)); 13165 return -EACCES; 13166 } 13167 13168 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 13169 * The id may be overwritten later if we create a new variable offset. 13170 */ 13171 dst_reg->type = ptr_reg->type; 13172 dst_reg->id = ptr_reg->id; 13173 13174 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 13175 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 13176 return -EINVAL; 13177 13178 /* pointer types do not carry 32-bit bounds at the moment. */ 13179 __mark_reg32_unbounded(dst_reg); 13180 13181 if (sanitize_needed(opcode)) { 13182 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 13183 &info, false); 13184 if (ret < 0) 13185 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13186 } 13187 13188 switch (opcode) { 13189 case BPF_ADD: 13190 /* We can take a fixed offset as long as it doesn't overflow 13191 * the s32 'off' field 13192 */ 13193 if (known && (ptr_reg->off + smin_val == 13194 (s64)(s32)(ptr_reg->off + smin_val))) { 13195 /* pointer += K. Accumulate it into fixed offset */ 13196 dst_reg->smin_value = smin_ptr; 13197 dst_reg->smax_value = smax_ptr; 13198 dst_reg->umin_value = umin_ptr; 13199 dst_reg->umax_value = umax_ptr; 13200 dst_reg->var_off = ptr_reg->var_off; 13201 dst_reg->off = ptr_reg->off + smin_val; 13202 dst_reg->raw = ptr_reg->raw; 13203 break; 13204 } 13205 /* A new variable offset is created. Note that off_reg->off 13206 * == 0, since it's a scalar. 13207 * dst_reg gets the pointer type and since some positive 13208 * integer value was added to the pointer, give it a new 'id' 13209 * if it's a PTR_TO_PACKET. 13210 * this creates a new 'base' pointer, off_reg (variable) gets 13211 * added into the variable offset, and we copy the fixed offset 13212 * from ptr_reg. 13213 */ 13214 if (signed_add_overflows(smin_ptr, smin_val) || 13215 signed_add_overflows(smax_ptr, smax_val)) { 13216 dst_reg->smin_value = S64_MIN; 13217 dst_reg->smax_value = S64_MAX; 13218 } else { 13219 dst_reg->smin_value = smin_ptr + smin_val; 13220 dst_reg->smax_value = smax_ptr + smax_val; 13221 } 13222 if (umin_ptr + umin_val < umin_ptr || 13223 umax_ptr + umax_val < umax_ptr) { 13224 dst_reg->umin_value = 0; 13225 dst_reg->umax_value = U64_MAX; 13226 } else { 13227 dst_reg->umin_value = umin_ptr + umin_val; 13228 dst_reg->umax_value = umax_ptr + umax_val; 13229 } 13230 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 13231 dst_reg->off = ptr_reg->off; 13232 dst_reg->raw = ptr_reg->raw; 13233 if (reg_is_pkt_pointer(ptr_reg)) { 13234 dst_reg->id = ++env->id_gen; 13235 /* something was added to pkt_ptr, set range to zero */ 13236 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13237 } 13238 break; 13239 case BPF_SUB: 13240 if (dst_reg == off_reg) { 13241 /* scalar -= pointer. Creates an unknown scalar */ 13242 verbose(env, "R%d tried to subtract pointer from scalar\n", 13243 dst); 13244 return -EACCES; 13245 } 13246 /* We don't allow subtraction from FP, because (according to 13247 * test_verifier.c test "invalid fp arithmetic", JITs might not 13248 * be able to deal with it. 13249 */ 13250 if (ptr_reg->type == PTR_TO_STACK) { 13251 verbose(env, "R%d subtraction from stack pointer prohibited\n", 13252 dst); 13253 return -EACCES; 13254 } 13255 if (known && (ptr_reg->off - smin_val == 13256 (s64)(s32)(ptr_reg->off - smin_val))) { 13257 /* pointer -= K. Subtract it from fixed offset */ 13258 dst_reg->smin_value = smin_ptr; 13259 dst_reg->smax_value = smax_ptr; 13260 dst_reg->umin_value = umin_ptr; 13261 dst_reg->umax_value = umax_ptr; 13262 dst_reg->var_off = ptr_reg->var_off; 13263 dst_reg->id = ptr_reg->id; 13264 dst_reg->off = ptr_reg->off - smin_val; 13265 dst_reg->raw = ptr_reg->raw; 13266 break; 13267 } 13268 /* A new variable offset is created. If the subtrahend is known 13269 * nonnegative, then any reg->range we had before is still good. 13270 */ 13271 if (signed_sub_overflows(smin_ptr, smax_val) || 13272 signed_sub_overflows(smax_ptr, smin_val)) { 13273 /* Overflow possible, we know nothing */ 13274 dst_reg->smin_value = S64_MIN; 13275 dst_reg->smax_value = S64_MAX; 13276 } else { 13277 dst_reg->smin_value = smin_ptr - smax_val; 13278 dst_reg->smax_value = smax_ptr - smin_val; 13279 } 13280 if (umin_ptr < umax_val) { 13281 /* Overflow possible, we know nothing */ 13282 dst_reg->umin_value = 0; 13283 dst_reg->umax_value = U64_MAX; 13284 } else { 13285 /* Cannot overflow (as long as bounds are consistent) */ 13286 dst_reg->umin_value = umin_ptr - umax_val; 13287 dst_reg->umax_value = umax_ptr - umin_val; 13288 } 13289 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 13290 dst_reg->off = ptr_reg->off; 13291 dst_reg->raw = ptr_reg->raw; 13292 if (reg_is_pkt_pointer(ptr_reg)) { 13293 dst_reg->id = ++env->id_gen; 13294 /* something was added to pkt_ptr, set range to zero */ 13295 if (smin_val < 0) 13296 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13297 } 13298 break; 13299 case BPF_AND: 13300 case BPF_OR: 13301 case BPF_XOR: 13302 /* bitwise ops on pointers are troublesome, prohibit. */ 13303 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 13304 dst, bpf_alu_string[opcode >> 4]); 13305 return -EACCES; 13306 default: 13307 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 13308 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 13309 dst, bpf_alu_string[opcode >> 4]); 13310 return -EACCES; 13311 } 13312 13313 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 13314 return -EINVAL; 13315 reg_bounds_sync(dst_reg); 13316 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 13317 return -EACCES; 13318 if (sanitize_needed(opcode)) { 13319 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 13320 &info, true); 13321 if (ret < 0) 13322 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13323 } 13324 13325 return 0; 13326 } 13327 13328 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 13329 struct bpf_reg_state *src_reg) 13330 { 13331 s32 smin_val = src_reg->s32_min_value; 13332 s32 smax_val = src_reg->s32_max_value; 13333 u32 umin_val = src_reg->u32_min_value; 13334 u32 umax_val = src_reg->u32_max_value; 13335 13336 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 13337 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 13338 dst_reg->s32_min_value = S32_MIN; 13339 dst_reg->s32_max_value = S32_MAX; 13340 } else { 13341 dst_reg->s32_min_value += smin_val; 13342 dst_reg->s32_max_value += smax_val; 13343 } 13344 if (dst_reg->u32_min_value + umin_val < umin_val || 13345 dst_reg->u32_max_value + umax_val < umax_val) { 13346 dst_reg->u32_min_value = 0; 13347 dst_reg->u32_max_value = U32_MAX; 13348 } else { 13349 dst_reg->u32_min_value += umin_val; 13350 dst_reg->u32_max_value += umax_val; 13351 } 13352 } 13353 13354 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 13355 struct bpf_reg_state *src_reg) 13356 { 13357 s64 smin_val = src_reg->smin_value; 13358 s64 smax_val = src_reg->smax_value; 13359 u64 umin_val = src_reg->umin_value; 13360 u64 umax_val = src_reg->umax_value; 13361 13362 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 13363 signed_add_overflows(dst_reg->smax_value, smax_val)) { 13364 dst_reg->smin_value = S64_MIN; 13365 dst_reg->smax_value = S64_MAX; 13366 } else { 13367 dst_reg->smin_value += smin_val; 13368 dst_reg->smax_value += smax_val; 13369 } 13370 if (dst_reg->umin_value + umin_val < umin_val || 13371 dst_reg->umax_value + umax_val < umax_val) { 13372 dst_reg->umin_value = 0; 13373 dst_reg->umax_value = U64_MAX; 13374 } else { 13375 dst_reg->umin_value += umin_val; 13376 dst_reg->umax_value += umax_val; 13377 } 13378 } 13379 13380 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 13381 struct bpf_reg_state *src_reg) 13382 { 13383 s32 smin_val = src_reg->s32_min_value; 13384 s32 smax_val = src_reg->s32_max_value; 13385 u32 umin_val = src_reg->u32_min_value; 13386 u32 umax_val = src_reg->u32_max_value; 13387 13388 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 13389 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 13390 /* Overflow possible, we know nothing */ 13391 dst_reg->s32_min_value = S32_MIN; 13392 dst_reg->s32_max_value = S32_MAX; 13393 } else { 13394 dst_reg->s32_min_value -= smax_val; 13395 dst_reg->s32_max_value -= smin_val; 13396 } 13397 if (dst_reg->u32_min_value < umax_val) { 13398 /* Overflow possible, we know nothing */ 13399 dst_reg->u32_min_value = 0; 13400 dst_reg->u32_max_value = U32_MAX; 13401 } else { 13402 /* Cannot overflow (as long as bounds are consistent) */ 13403 dst_reg->u32_min_value -= umax_val; 13404 dst_reg->u32_max_value -= umin_val; 13405 } 13406 } 13407 13408 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 13409 struct bpf_reg_state *src_reg) 13410 { 13411 s64 smin_val = src_reg->smin_value; 13412 s64 smax_val = src_reg->smax_value; 13413 u64 umin_val = src_reg->umin_value; 13414 u64 umax_val = src_reg->umax_value; 13415 13416 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 13417 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 13418 /* Overflow possible, we know nothing */ 13419 dst_reg->smin_value = S64_MIN; 13420 dst_reg->smax_value = S64_MAX; 13421 } else { 13422 dst_reg->smin_value -= smax_val; 13423 dst_reg->smax_value -= smin_val; 13424 } 13425 if (dst_reg->umin_value < umax_val) { 13426 /* Overflow possible, we know nothing */ 13427 dst_reg->umin_value = 0; 13428 dst_reg->umax_value = U64_MAX; 13429 } else { 13430 /* Cannot overflow (as long as bounds are consistent) */ 13431 dst_reg->umin_value -= umax_val; 13432 dst_reg->umax_value -= umin_val; 13433 } 13434 } 13435 13436 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 13437 struct bpf_reg_state *src_reg) 13438 { 13439 s32 smin_val = src_reg->s32_min_value; 13440 u32 umin_val = src_reg->u32_min_value; 13441 u32 umax_val = src_reg->u32_max_value; 13442 13443 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 13444 /* Ain't nobody got time to multiply that sign */ 13445 __mark_reg32_unbounded(dst_reg); 13446 return; 13447 } 13448 /* Both values are positive, so we can work with unsigned and 13449 * copy the result to signed (unless it exceeds S32_MAX). 13450 */ 13451 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 13452 /* Potential overflow, we know nothing */ 13453 __mark_reg32_unbounded(dst_reg); 13454 return; 13455 } 13456 dst_reg->u32_min_value *= umin_val; 13457 dst_reg->u32_max_value *= umax_val; 13458 if (dst_reg->u32_max_value > S32_MAX) { 13459 /* Overflow possible, we know nothing */ 13460 dst_reg->s32_min_value = S32_MIN; 13461 dst_reg->s32_max_value = S32_MAX; 13462 } else { 13463 dst_reg->s32_min_value = dst_reg->u32_min_value; 13464 dst_reg->s32_max_value = dst_reg->u32_max_value; 13465 } 13466 } 13467 13468 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 13469 struct bpf_reg_state *src_reg) 13470 { 13471 s64 smin_val = src_reg->smin_value; 13472 u64 umin_val = src_reg->umin_value; 13473 u64 umax_val = src_reg->umax_value; 13474 13475 if (smin_val < 0 || dst_reg->smin_value < 0) { 13476 /* Ain't nobody got time to multiply that sign */ 13477 __mark_reg64_unbounded(dst_reg); 13478 return; 13479 } 13480 /* Both values are positive, so we can work with unsigned and 13481 * copy the result to signed (unless it exceeds S64_MAX). 13482 */ 13483 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 13484 /* Potential overflow, we know nothing */ 13485 __mark_reg64_unbounded(dst_reg); 13486 return; 13487 } 13488 dst_reg->umin_value *= umin_val; 13489 dst_reg->umax_value *= umax_val; 13490 if (dst_reg->umax_value > S64_MAX) { 13491 /* Overflow possible, we know nothing */ 13492 dst_reg->smin_value = S64_MIN; 13493 dst_reg->smax_value = S64_MAX; 13494 } else { 13495 dst_reg->smin_value = dst_reg->umin_value; 13496 dst_reg->smax_value = dst_reg->umax_value; 13497 } 13498 } 13499 13500 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 13501 struct bpf_reg_state *src_reg) 13502 { 13503 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13504 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13505 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13506 u32 umax_val = src_reg->u32_max_value; 13507 13508 if (src_known && dst_known) { 13509 __mark_reg32_known(dst_reg, var32_off.value); 13510 return; 13511 } 13512 13513 /* We get our minimum from the var_off, since that's inherently 13514 * bitwise. Our maximum is the minimum of the operands' maxima. 13515 */ 13516 dst_reg->u32_min_value = var32_off.value; 13517 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 13518 13519 /* Safe to set s32 bounds by casting u32 result into s32 when u32 13520 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 13521 */ 13522 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 13523 dst_reg->s32_min_value = dst_reg->u32_min_value; 13524 dst_reg->s32_max_value = dst_reg->u32_max_value; 13525 } else { 13526 dst_reg->s32_min_value = S32_MIN; 13527 dst_reg->s32_max_value = S32_MAX; 13528 } 13529 } 13530 13531 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 13532 struct bpf_reg_state *src_reg) 13533 { 13534 bool src_known = tnum_is_const(src_reg->var_off); 13535 bool dst_known = tnum_is_const(dst_reg->var_off); 13536 u64 umax_val = src_reg->umax_value; 13537 13538 if (src_known && dst_known) { 13539 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13540 return; 13541 } 13542 13543 /* We get our minimum from the var_off, since that's inherently 13544 * bitwise. Our maximum is the minimum of the operands' maxima. 13545 */ 13546 dst_reg->umin_value = dst_reg->var_off.value; 13547 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 13548 13549 /* Safe to set s64 bounds by casting u64 result into s64 when u64 13550 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 13551 */ 13552 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 13553 dst_reg->smin_value = dst_reg->umin_value; 13554 dst_reg->smax_value = dst_reg->umax_value; 13555 } else { 13556 dst_reg->smin_value = S64_MIN; 13557 dst_reg->smax_value = S64_MAX; 13558 } 13559 /* We may learn something more from the var_off */ 13560 __update_reg_bounds(dst_reg); 13561 } 13562 13563 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 13564 struct bpf_reg_state *src_reg) 13565 { 13566 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13567 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13568 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13569 u32 umin_val = src_reg->u32_min_value; 13570 13571 if (src_known && dst_known) { 13572 __mark_reg32_known(dst_reg, var32_off.value); 13573 return; 13574 } 13575 13576 /* We get our maximum from the var_off, and our minimum is the 13577 * maximum of the operands' minima 13578 */ 13579 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 13580 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13581 13582 /* Safe to set s32 bounds by casting u32 result into s32 when u32 13583 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 13584 */ 13585 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 13586 dst_reg->s32_min_value = dst_reg->u32_min_value; 13587 dst_reg->s32_max_value = dst_reg->u32_max_value; 13588 } else { 13589 dst_reg->s32_min_value = S32_MIN; 13590 dst_reg->s32_max_value = S32_MAX; 13591 } 13592 } 13593 13594 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 13595 struct bpf_reg_state *src_reg) 13596 { 13597 bool src_known = tnum_is_const(src_reg->var_off); 13598 bool dst_known = tnum_is_const(dst_reg->var_off); 13599 u64 umin_val = src_reg->umin_value; 13600 13601 if (src_known && dst_known) { 13602 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13603 return; 13604 } 13605 13606 /* We get our maximum from the var_off, and our minimum is the 13607 * maximum of the operands' minima 13608 */ 13609 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 13610 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13611 13612 /* Safe to set s64 bounds by casting u64 result into s64 when u64 13613 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 13614 */ 13615 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 13616 dst_reg->smin_value = dst_reg->umin_value; 13617 dst_reg->smax_value = dst_reg->umax_value; 13618 } else { 13619 dst_reg->smin_value = S64_MIN; 13620 dst_reg->smax_value = S64_MAX; 13621 } 13622 /* We may learn something more from the var_off */ 13623 __update_reg_bounds(dst_reg); 13624 } 13625 13626 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 13627 struct bpf_reg_state *src_reg) 13628 { 13629 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13630 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13631 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13632 13633 if (src_known && dst_known) { 13634 __mark_reg32_known(dst_reg, var32_off.value); 13635 return; 13636 } 13637 13638 /* We get both minimum and maximum from the var32_off. */ 13639 dst_reg->u32_min_value = var32_off.value; 13640 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13641 13642 /* Safe to set s32 bounds by casting u32 result into s32 when u32 13643 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 13644 */ 13645 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 13646 dst_reg->s32_min_value = dst_reg->u32_min_value; 13647 dst_reg->s32_max_value = dst_reg->u32_max_value; 13648 } else { 13649 dst_reg->s32_min_value = S32_MIN; 13650 dst_reg->s32_max_value = S32_MAX; 13651 } 13652 } 13653 13654 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 13655 struct bpf_reg_state *src_reg) 13656 { 13657 bool src_known = tnum_is_const(src_reg->var_off); 13658 bool dst_known = tnum_is_const(dst_reg->var_off); 13659 13660 if (src_known && dst_known) { 13661 /* dst_reg->var_off.value has been updated earlier */ 13662 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13663 return; 13664 } 13665 13666 /* We get both minimum and maximum from the var_off. */ 13667 dst_reg->umin_value = dst_reg->var_off.value; 13668 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13669 13670 /* Safe to set s64 bounds by casting u64 result into s64 when u64 13671 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 13672 */ 13673 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 13674 dst_reg->smin_value = dst_reg->umin_value; 13675 dst_reg->smax_value = dst_reg->umax_value; 13676 } else { 13677 dst_reg->smin_value = S64_MIN; 13678 dst_reg->smax_value = S64_MAX; 13679 } 13680 13681 __update_reg_bounds(dst_reg); 13682 } 13683 13684 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13685 u64 umin_val, u64 umax_val) 13686 { 13687 /* We lose all sign bit information (except what we can pick 13688 * up from var_off) 13689 */ 13690 dst_reg->s32_min_value = S32_MIN; 13691 dst_reg->s32_max_value = S32_MAX; 13692 /* If we might shift our top bit out, then we know nothing */ 13693 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 13694 dst_reg->u32_min_value = 0; 13695 dst_reg->u32_max_value = U32_MAX; 13696 } else { 13697 dst_reg->u32_min_value <<= umin_val; 13698 dst_reg->u32_max_value <<= umax_val; 13699 } 13700 } 13701 13702 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13703 struct bpf_reg_state *src_reg) 13704 { 13705 u32 umax_val = src_reg->u32_max_value; 13706 u32 umin_val = src_reg->u32_min_value; 13707 /* u32 alu operation will zext upper bits */ 13708 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13709 13710 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13711 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 13712 /* Not required but being careful mark reg64 bounds as unknown so 13713 * that we are forced to pick them up from tnum and zext later and 13714 * if some path skips this step we are still safe. 13715 */ 13716 __mark_reg64_unbounded(dst_reg); 13717 __update_reg32_bounds(dst_reg); 13718 } 13719 13720 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 13721 u64 umin_val, u64 umax_val) 13722 { 13723 /* Special case <<32 because it is a common compiler pattern to sign 13724 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 13725 * positive we know this shift will also be positive so we can track 13726 * bounds correctly. Otherwise we lose all sign bit information except 13727 * what we can pick up from var_off. Perhaps we can generalize this 13728 * later to shifts of any length. 13729 */ 13730 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 13731 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 13732 else 13733 dst_reg->smax_value = S64_MAX; 13734 13735 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 13736 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 13737 else 13738 dst_reg->smin_value = S64_MIN; 13739 13740 /* If we might shift our top bit out, then we know nothing */ 13741 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 13742 dst_reg->umin_value = 0; 13743 dst_reg->umax_value = U64_MAX; 13744 } else { 13745 dst_reg->umin_value <<= umin_val; 13746 dst_reg->umax_value <<= umax_val; 13747 } 13748 } 13749 13750 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 13751 struct bpf_reg_state *src_reg) 13752 { 13753 u64 umax_val = src_reg->umax_value; 13754 u64 umin_val = src_reg->umin_value; 13755 13756 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 13757 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 13758 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13759 13760 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 13761 /* We may learn something more from the var_off */ 13762 __update_reg_bounds(dst_reg); 13763 } 13764 13765 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 13766 struct bpf_reg_state *src_reg) 13767 { 13768 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13769 u32 umax_val = src_reg->u32_max_value; 13770 u32 umin_val = src_reg->u32_min_value; 13771 13772 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13773 * be negative, then either: 13774 * 1) src_reg might be zero, so the sign bit of the result is 13775 * unknown, so we lose our signed bounds 13776 * 2) it's known negative, thus the unsigned bounds capture the 13777 * signed bounds 13778 * 3) the signed bounds cross zero, so they tell us nothing 13779 * about the result 13780 * If the value in dst_reg is known nonnegative, then again the 13781 * unsigned bounds capture the signed bounds. 13782 * Thus, in all cases it suffices to blow away our signed bounds 13783 * and rely on inferring new ones from the unsigned bounds and 13784 * var_off of the result. 13785 */ 13786 dst_reg->s32_min_value = S32_MIN; 13787 dst_reg->s32_max_value = S32_MAX; 13788 13789 dst_reg->var_off = tnum_rshift(subreg, umin_val); 13790 dst_reg->u32_min_value >>= umax_val; 13791 dst_reg->u32_max_value >>= umin_val; 13792 13793 __mark_reg64_unbounded(dst_reg); 13794 __update_reg32_bounds(dst_reg); 13795 } 13796 13797 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 13798 struct bpf_reg_state *src_reg) 13799 { 13800 u64 umax_val = src_reg->umax_value; 13801 u64 umin_val = src_reg->umin_value; 13802 13803 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13804 * be negative, then either: 13805 * 1) src_reg might be zero, so the sign bit of the result is 13806 * unknown, so we lose our signed bounds 13807 * 2) it's known negative, thus the unsigned bounds capture the 13808 * signed bounds 13809 * 3) the signed bounds cross zero, so they tell us nothing 13810 * about the result 13811 * If the value in dst_reg is known nonnegative, then again the 13812 * unsigned bounds capture the signed bounds. 13813 * Thus, in all cases it suffices to blow away our signed bounds 13814 * and rely on inferring new ones from the unsigned bounds and 13815 * var_off of the result. 13816 */ 13817 dst_reg->smin_value = S64_MIN; 13818 dst_reg->smax_value = S64_MAX; 13819 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 13820 dst_reg->umin_value >>= umax_val; 13821 dst_reg->umax_value >>= umin_val; 13822 13823 /* Its not easy to operate on alu32 bounds here because it depends 13824 * on bits being shifted in. Take easy way out and mark unbounded 13825 * so we can recalculate later from tnum. 13826 */ 13827 __mark_reg32_unbounded(dst_reg); 13828 __update_reg_bounds(dst_reg); 13829 } 13830 13831 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 13832 struct bpf_reg_state *src_reg) 13833 { 13834 u64 umin_val = src_reg->u32_min_value; 13835 13836 /* Upon reaching here, src_known is true and 13837 * umax_val is equal to umin_val. 13838 */ 13839 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 13840 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 13841 13842 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 13843 13844 /* blow away the dst_reg umin_value/umax_value and rely on 13845 * dst_reg var_off to refine the result. 13846 */ 13847 dst_reg->u32_min_value = 0; 13848 dst_reg->u32_max_value = U32_MAX; 13849 13850 __mark_reg64_unbounded(dst_reg); 13851 __update_reg32_bounds(dst_reg); 13852 } 13853 13854 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 13855 struct bpf_reg_state *src_reg) 13856 { 13857 u64 umin_val = src_reg->umin_value; 13858 13859 /* Upon reaching here, src_known is true and umax_val is equal 13860 * to umin_val. 13861 */ 13862 dst_reg->smin_value >>= umin_val; 13863 dst_reg->smax_value >>= umin_val; 13864 13865 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 13866 13867 /* blow away the dst_reg umin_value/umax_value and rely on 13868 * dst_reg var_off to refine the result. 13869 */ 13870 dst_reg->umin_value = 0; 13871 dst_reg->umax_value = U64_MAX; 13872 13873 /* Its not easy to operate on alu32 bounds here because it depends 13874 * on bits being shifted in from upper 32-bits. Take easy way out 13875 * and mark unbounded so we can recalculate later from tnum. 13876 */ 13877 __mark_reg32_unbounded(dst_reg); 13878 __update_reg_bounds(dst_reg); 13879 } 13880 13881 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn, 13882 const struct bpf_reg_state *src_reg) 13883 { 13884 bool src_is_const = false; 13885 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 13886 13887 if (insn_bitness == 32) { 13888 if (tnum_subreg_is_const(src_reg->var_off) 13889 && src_reg->s32_min_value == src_reg->s32_max_value 13890 && src_reg->u32_min_value == src_reg->u32_max_value) 13891 src_is_const = true; 13892 } else { 13893 if (tnum_is_const(src_reg->var_off) 13894 && src_reg->smin_value == src_reg->smax_value 13895 && src_reg->umin_value == src_reg->umax_value) 13896 src_is_const = true; 13897 } 13898 13899 switch (BPF_OP(insn->code)) { 13900 case BPF_ADD: 13901 case BPF_SUB: 13902 case BPF_AND: 13903 case BPF_XOR: 13904 case BPF_OR: 13905 case BPF_MUL: 13906 return true; 13907 13908 /* Shift operators range is only computable if shift dimension operand 13909 * is a constant. Shifts greater than 31 or 63 are undefined. This 13910 * includes shifts by a negative number. 13911 */ 13912 case BPF_LSH: 13913 case BPF_RSH: 13914 case BPF_ARSH: 13915 return (src_is_const && src_reg->umax_value < insn_bitness); 13916 default: 13917 return false; 13918 } 13919 } 13920 13921 /* WARNING: This function does calculations on 64-bit values, but the actual 13922 * execution may occur on 32-bit values. Therefore, things like bitshifts 13923 * need extra checks in the 32-bit case. 13924 */ 13925 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 13926 struct bpf_insn *insn, 13927 struct bpf_reg_state *dst_reg, 13928 struct bpf_reg_state src_reg) 13929 { 13930 u8 opcode = BPF_OP(insn->code); 13931 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 13932 int ret; 13933 13934 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) { 13935 __mark_reg_unknown(env, dst_reg); 13936 return 0; 13937 } 13938 13939 if (sanitize_needed(opcode)) { 13940 ret = sanitize_val_alu(env, insn); 13941 if (ret < 0) 13942 return sanitize_err(env, insn, ret, NULL, NULL); 13943 } 13944 13945 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 13946 * There are two classes of instructions: The first class we track both 13947 * alu32 and alu64 sign/unsigned bounds independently this provides the 13948 * greatest amount of precision when alu operations are mixed with jmp32 13949 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 13950 * and BPF_OR. This is possible because these ops have fairly easy to 13951 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 13952 * See alu32 verifier tests for examples. The second class of 13953 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 13954 * with regards to tracking sign/unsigned bounds because the bits may 13955 * cross subreg boundaries in the alu64 case. When this happens we mark 13956 * the reg unbounded in the subreg bound space and use the resulting 13957 * tnum to calculate an approximation of the sign/unsigned bounds. 13958 */ 13959 switch (opcode) { 13960 case BPF_ADD: 13961 scalar32_min_max_add(dst_reg, &src_reg); 13962 scalar_min_max_add(dst_reg, &src_reg); 13963 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 13964 break; 13965 case BPF_SUB: 13966 scalar32_min_max_sub(dst_reg, &src_reg); 13967 scalar_min_max_sub(dst_reg, &src_reg); 13968 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 13969 break; 13970 case BPF_MUL: 13971 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 13972 scalar32_min_max_mul(dst_reg, &src_reg); 13973 scalar_min_max_mul(dst_reg, &src_reg); 13974 break; 13975 case BPF_AND: 13976 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 13977 scalar32_min_max_and(dst_reg, &src_reg); 13978 scalar_min_max_and(dst_reg, &src_reg); 13979 break; 13980 case BPF_OR: 13981 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 13982 scalar32_min_max_or(dst_reg, &src_reg); 13983 scalar_min_max_or(dst_reg, &src_reg); 13984 break; 13985 case BPF_XOR: 13986 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 13987 scalar32_min_max_xor(dst_reg, &src_reg); 13988 scalar_min_max_xor(dst_reg, &src_reg); 13989 break; 13990 case BPF_LSH: 13991 if (alu32) 13992 scalar32_min_max_lsh(dst_reg, &src_reg); 13993 else 13994 scalar_min_max_lsh(dst_reg, &src_reg); 13995 break; 13996 case BPF_RSH: 13997 if (alu32) 13998 scalar32_min_max_rsh(dst_reg, &src_reg); 13999 else 14000 scalar_min_max_rsh(dst_reg, &src_reg); 14001 break; 14002 case BPF_ARSH: 14003 if (alu32) 14004 scalar32_min_max_arsh(dst_reg, &src_reg); 14005 else 14006 scalar_min_max_arsh(dst_reg, &src_reg); 14007 break; 14008 default: 14009 break; 14010 } 14011 14012 /* ALU32 ops are zero extended into 64bit register */ 14013 if (alu32) 14014 zext_32_to_64(dst_reg); 14015 reg_bounds_sync(dst_reg); 14016 return 0; 14017 } 14018 14019 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 14020 * and var_off. 14021 */ 14022 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 14023 struct bpf_insn *insn) 14024 { 14025 struct bpf_verifier_state *vstate = env->cur_state; 14026 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14027 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 14028 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 14029 u8 opcode = BPF_OP(insn->code); 14030 int err; 14031 14032 dst_reg = ®s[insn->dst_reg]; 14033 src_reg = NULL; 14034 14035 if (dst_reg->type == PTR_TO_ARENA) { 14036 struct bpf_insn_aux_data *aux = cur_aux(env); 14037 14038 if (BPF_CLASS(insn->code) == BPF_ALU64) 14039 /* 14040 * 32-bit operations zero upper bits automatically. 14041 * 64-bit operations need to be converted to 32. 14042 */ 14043 aux->needs_zext = true; 14044 14045 /* Any arithmetic operations are allowed on arena pointers */ 14046 return 0; 14047 } 14048 14049 if (dst_reg->type != SCALAR_VALUE) 14050 ptr_reg = dst_reg; 14051 else 14052 /* Make sure ID is cleared otherwise dst_reg min/max could be 14053 * incorrectly propagated into other registers by find_equal_scalars() 14054 */ 14055 dst_reg->id = 0; 14056 if (BPF_SRC(insn->code) == BPF_X) { 14057 src_reg = ®s[insn->src_reg]; 14058 if (src_reg->type != SCALAR_VALUE) { 14059 if (dst_reg->type != SCALAR_VALUE) { 14060 /* Combining two pointers by any ALU op yields 14061 * an arbitrary scalar. Disallow all math except 14062 * pointer subtraction 14063 */ 14064 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 14065 mark_reg_unknown(env, regs, insn->dst_reg); 14066 return 0; 14067 } 14068 verbose(env, "R%d pointer %s pointer prohibited\n", 14069 insn->dst_reg, 14070 bpf_alu_string[opcode >> 4]); 14071 return -EACCES; 14072 } else { 14073 /* scalar += pointer 14074 * This is legal, but we have to reverse our 14075 * src/dest handling in computing the range 14076 */ 14077 err = mark_chain_precision(env, insn->dst_reg); 14078 if (err) 14079 return err; 14080 return adjust_ptr_min_max_vals(env, insn, 14081 src_reg, dst_reg); 14082 } 14083 } else if (ptr_reg) { 14084 /* pointer += scalar */ 14085 err = mark_chain_precision(env, insn->src_reg); 14086 if (err) 14087 return err; 14088 return adjust_ptr_min_max_vals(env, insn, 14089 dst_reg, src_reg); 14090 } else if (dst_reg->precise) { 14091 /* if dst_reg is precise, src_reg should be precise as well */ 14092 err = mark_chain_precision(env, insn->src_reg); 14093 if (err) 14094 return err; 14095 } 14096 } else { 14097 /* Pretend the src is a reg with a known value, since we only 14098 * need to be able to read from this state. 14099 */ 14100 off_reg.type = SCALAR_VALUE; 14101 __mark_reg_known(&off_reg, insn->imm); 14102 src_reg = &off_reg; 14103 if (ptr_reg) /* pointer += K */ 14104 return adjust_ptr_min_max_vals(env, insn, 14105 ptr_reg, src_reg); 14106 } 14107 14108 /* Got here implies adding two SCALAR_VALUEs */ 14109 if (WARN_ON_ONCE(ptr_reg)) { 14110 print_verifier_state(env, state, true); 14111 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 14112 return -EINVAL; 14113 } 14114 if (WARN_ON(!src_reg)) { 14115 print_verifier_state(env, state, true); 14116 verbose(env, "verifier internal error: no src_reg\n"); 14117 return -EINVAL; 14118 } 14119 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 14120 } 14121 14122 /* check validity of 32-bit and 64-bit arithmetic operations */ 14123 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 14124 { 14125 struct bpf_reg_state *regs = cur_regs(env); 14126 u8 opcode = BPF_OP(insn->code); 14127 int err; 14128 14129 if (opcode == BPF_END || opcode == BPF_NEG) { 14130 if (opcode == BPF_NEG) { 14131 if (BPF_SRC(insn->code) != BPF_K || 14132 insn->src_reg != BPF_REG_0 || 14133 insn->off != 0 || insn->imm != 0) { 14134 verbose(env, "BPF_NEG uses reserved fields\n"); 14135 return -EINVAL; 14136 } 14137 } else { 14138 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 14139 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 14140 (BPF_CLASS(insn->code) == BPF_ALU64 && 14141 BPF_SRC(insn->code) != BPF_TO_LE)) { 14142 verbose(env, "BPF_END uses reserved fields\n"); 14143 return -EINVAL; 14144 } 14145 } 14146 14147 /* check src operand */ 14148 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14149 if (err) 14150 return err; 14151 14152 if (is_pointer_value(env, insn->dst_reg)) { 14153 verbose(env, "R%d pointer arithmetic prohibited\n", 14154 insn->dst_reg); 14155 return -EACCES; 14156 } 14157 14158 /* check dest operand */ 14159 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14160 if (err) 14161 return err; 14162 14163 } else if (opcode == BPF_MOV) { 14164 14165 if (BPF_SRC(insn->code) == BPF_X) { 14166 if (BPF_CLASS(insn->code) == BPF_ALU) { 14167 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) || 14168 insn->imm) { 14169 verbose(env, "BPF_MOV uses reserved fields\n"); 14170 return -EINVAL; 14171 } 14172 } else if (insn->off == BPF_ADDR_SPACE_CAST) { 14173 if (insn->imm != 1 && insn->imm != 1u << 16) { 14174 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n"); 14175 return -EINVAL; 14176 } 14177 if (!env->prog->aux->arena) { 14178 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n"); 14179 return -EINVAL; 14180 } 14181 } else { 14182 if ((insn->off != 0 && insn->off != 8 && insn->off != 16 && 14183 insn->off != 32) || insn->imm) { 14184 verbose(env, "BPF_MOV uses reserved fields\n"); 14185 return -EINVAL; 14186 } 14187 } 14188 14189 /* check src operand */ 14190 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14191 if (err) 14192 return err; 14193 } else { 14194 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 14195 verbose(env, "BPF_MOV uses reserved fields\n"); 14196 return -EINVAL; 14197 } 14198 } 14199 14200 /* check dest operand, mark as required later */ 14201 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14202 if (err) 14203 return err; 14204 14205 if (BPF_SRC(insn->code) == BPF_X) { 14206 struct bpf_reg_state *src_reg = regs + insn->src_reg; 14207 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 14208 14209 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14210 if (insn->imm) { 14211 /* off == BPF_ADDR_SPACE_CAST */ 14212 mark_reg_unknown(env, regs, insn->dst_reg); 14213 if (insn->imm == 1) { /* cast from as(1) to as(0) */ 14214 dst_reg->type = PTR_TO_ARENA; 14215 /* PTR_TO_ARENA is 32-bit */ 14216 dst_reg->subreg_def = env->insn_idx + 1; 14217 } 14218 } else if (insn->off == 0) { 14219 /* case: R1 = R2 14220 * copy register state to dest reg 14221 */ 14222 assign_scalar_id_before_mov(env, src_reg); 14223 copy_register_state(dst_reg, src_reg); 14224 dst_reg->live |= REG_LIVE_WRITTEN; 14225 dst_reg->subreg_def = DEF_NOT_SUBREG; 14226 } else { 14227 /* case: R1 = (s8, s16 s32)R2 */ 14228 if (is_pointer_value(env, insn->src_reg)) { 14229 verbose(env, 14230 "R%d sign-extension part of pointer\n", 14231 insn->src_reg); 14232 return -EACCES; 14233 } else if (src_reg->type == SCALAR_VALUE) { 14234 bool no_sext; 14235 14236 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 14237 if (no_sext) 14238 assign_scalar_id_before_mov(env, src_reg); 14239 copy_register_state(dst_reg, src_reg); 14240 if (!no_sext) 14241 dst_reg->id = 0; 14242 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 14243 dst_reg->live |= REG_LIVE_WRITTEN; 14244 dst_reg->subreg_def = DEF_NOT_SUBREG; 14245 } else { 14246 mark_reg_unknown(env, regs, insn->dst_reg); 14247 } 14248 } 14249 } else { 14250 /* R1 = (u32) R2 */ 14251 if (is_pointer_value(env, insn->src_reg)) { 14252 verbose(env, 14253 "R%d partial copy of pointer\n", 14254 insn->src_reg); 14255 return -EACCES; 14256 } else if (src_reg->type == SCALAR_VALUE) { 14257 if (insn->off == 0) { 14258 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 14259 14260 if (is_src_reg_u32) 14261 assign_scalar_id_before_mov(env, src_reg); 14262 copy_register_state(dst_reg, src_reg); 14263 /* Make sure ID is cleared if src_reg is not in u32 14264 * range otherwise dst_reg min/max could be incorrectly 14265 * propagated into src_reg by find_equal_scalars() 14266 */ 14267 if (!is_src_reg_u32) 14268 dst_reg->id = 0; 14269 dst_reg->live |= REG_LIVE_WRITTEN; 14270 dst_reg->subreg_def = env->insn_idx + 1; 14271 } else { 14272 /* case: W1 = (s8, s16)W2 */ 14273 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 14274 14275 if (no_sext) 14276 assign_scalar_id_before_mov(env, src_reg); 14277 copy_register_state(dst_reg, src_reg); 14278 if (!no_sext) 14279 dst_reg->id = 0; 14280 dst_reg->live |= REG_LIVE_WRITTEN; 14281 dst_reg->subreg_def = env->insn_idx + 1; 14282 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 14283 } 14284 } else { 14285 mark_reg_unknown(env, regs, 14286 insn->dst_reg); 14287 } 14288 zext_32_to_64(dst_reg); 14289 reg_bounds_sync(dst_reg); 14290 } 14291 } else { 14292 /* case: R = imm 14293 * remember the value we stored into this reg 14294 */ 14295 /* clear any state __mark_reg_known doesn't set */ 14296 mark_reg_unknown(env, regs, insn->dst_reg); 14297 regs[insn->dst_reg].type = SCALAR_VALUE; 14298 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14299 __mark_reg_known(regs + insn->dst_reg, 14300 insn->imm); 14301 } else { 14302 __mark_reg_known(regs + insn->dst_reg, 14303 (u32)insn->imm); 14304 } 14305 } 14306 14307 } else if (opcode > BPF_END) { 14308 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 14309 return -EINVAL; 14310 14311 } else { /* all other ALU ops: and, sub, xor, add, ... */ 14312 14313 if (BPF_SRC(insn->code) == BPF_X) { 14314 if (insn->imm != 0 || insn->off > 1 || 14315 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14316 verbose(env, "BPF_ALU uses reserved fields\n"); 14317 return -EINVAL; 14318 } 14319 /* check src1 operand */ 14320 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14321 if (err) 14322 return err; 14323 } else { 14324 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 14325 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14326 verbose(env, "BPF_ALU uses reserved fields\n"); 14327 return -EINVAL; 14328 } 14329 } 14330 14331 /* check src2 operand */ 14332 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14333 if (err) 14334 return err; 14335 14336 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 14337 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 14338 verbose(env, "div by zero\n"); 14339 return -EINVAL; 14340 } 14341 14342 if ((opcode == BPF_LSH || opcode == BPF_RSH || 14343 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 14344 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 14345 14346 if (insn->imm < 0 || insn->imm >= size) { 14347 verbose(env, "invalid shift %d\n", insn->imm); 14348 return -EINVAL; 14349 } 14350 } 14351 14352 /* check dest operand */ 14353 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14354 err = err ?: adjust_reg_min_max_vals(env, insn); 14355 if (err) 14356 return err; 14357 } 14358 14359 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 14360 } 14361 14362 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 14363 struct bpf_reg_state *dst_reg, 14364 enum bpf_reg_type type, 14365 bool range_right_open) 14366 { 14367 struct bpf_func_state *state; 14368 struct bpf_reg_state *reg; 14369 int new_range; 14370 14371 if (dst_reg->off < 0 || 14372 (dst_reg->off == 0 && range_right_open)) 14373 /* This doesn't give us any range */ 14374 return; 14375 14376 if (dst_reg->umax_value > MAX_PACKET_OFF || 14377 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 14378 /* Risk of overflow. For instance, ptr + (1<<63) may be less 14379 * than pkt_end, but that's because it's also less than pkt. 14380 */ 14381 return; 14382 14383 new_range = dst_reg->off; 14384 if (range_right_open) 14385 new_range++; 14386 14387 /* Examples for register markings: 14388 * 14389 * pkt_data in dst register: 14390 * 14391 * r2 = r3; 14392 * r2 += 8; 14393 * if (r2 > pkt_end) goto <handle exception> 14394 * <access okay> 14395 * 14396 * r2 = r3; 14397 * r2 += 8; 14398 * if (r2 < pkt_end) goto <access okay> 14399 * <handle exception> 14400 * 14401 * Where: 14402 * r2 == dst_reg, pkt_end == src_reg 14403 * r2=pkt(id=n,off=8,r=0) 14404 * r3=pkt(id=n,off=0,r=0) 14405 * 14406 * pkt_data in src register: 14407 * 14408 * r2 = r3; 14409 * r2 += 8; 14410 * if (pkt_end >= r2) goto <access okay> 14411 * <handle exception> 14412 * 14413 * r2 = r3; 14414 * r2 += 8; 14415 * if (pkt_end <= r2) goto <handle exception> 14416 * <access okay> 14417 * 14418 * Where: 14419 * pkt_end == dst_reg, r2 == src_reg 14420 * r2=pkt(id=n,off=8,r=0) 14421 * r3=pkt(id=n,off=0,r=0) 14422 * 14423 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 14424 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 14425 * and [r3, r3 + 8-1) respectively is safe to access depending on 14426 * the check. 14427 */ 14428 14429 /* If our ids match, then we must have the same max_value. And we 14430 * don't care about the other reg's fixed offset, since if it's too big 14431 * the range won't allow anything. 14432 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 14433 */ 14434 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14435 if (reg->type == type && reg->id == dst_reg->id) 14436 /* keep the maximum range already checked */ 14437 reg->range = max(reg->range, new_range); 14438 })); 14439 } 14440 14441 /* 14442 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 14443 */ 14444 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14445 u8 opcode, bool is_jmp32) 14446 { 14447 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 14448 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 14449 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value; 14450 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value; 14451 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value; 14452 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value; 14453 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value; 14454 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value; 14455 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value; 14456 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value; 14457 14458 switch (opcode) { 14459 case BPF_JEQ: 14460 /* constants, umin/umax and smin/smax checks would be 14461 * redundant in this case because they all should match 14462 */ 14463 if (tnum_is_const(t1) && tnum_is_const(t2)) 14464 return t1.value == t2.value; 14465 /* non-overlapping ranges */ 14466 if (umin1 > umax2 || umax1 < umin2) 14467 return 0; 14468 if (smin1 > smax2 || smax1 < smin2) 14469 return 0; 14470 if (!is_jmp32) { 14471 /* if 64-bit ranges are inconclusive, see if we can 14472 * utilize 32-bit subrange knowledge to eliminate 14473 * branches that can't be taken a priori 14474 */ 14475 if (reg1->u32_min_value > reg2->u32_max_value || 14476 reg1->u32_max_value < reg2->u32_min_value) 14477 return 0; 14478 if (reg1->s32_min_value > reg2->s32_max_value || 14479 reg1->s32_max_value < reg2->s32_min_value) 14480 return 0; 14481 } 14482 break; 14483 case BPF_JNE: 14484 /* constants, umin/umax and smin/smax checks would be 14485 * redundant in this case because they all should match 14486 */ 14487 if (tnum_is_const(t1) && tnum_is_const(t2)) 14488 return t1.value != t2.value; 14489 /* non-overlapping ranges */ 14490 if (umin1 > umax2 || umax1 < umin2) 14491 return 1; 14492 if (smin1 > smax2 || smax1 < smin2) 14493 return 1; 14494 if (!is_jmp32) { 14495 /* if 64-bit ranges are inconclusive, see if we can 14496 * utilize 32-bit subrange knowledge to eliminate 14497 * branches that can't be taken a priori 14498 */ 14499 if (reg1->u32_min_value > reg2->u32_max_value || 14500 reg1->u32_max_value < reg2->u32_min_value) 14501 return 1; 14502 if (reg1->s32_min_value > reg2->s32_max_value || 14503 reg1->s32_max_value < reg2->s32_min_value) 14504 return 1; 14505 } 14506 break; 14507 case BPF_JSET: 14508 if (!is_reg_const(reg2, is_jmp32)) { 14509 swap(reg1, reg2); 14510 swap(t1, t2); 14511 } 14512 if (!is_reg_const(reg2, is_jmp32)) 14513 return -1; 14514 if ((~t1.mask & t1.value) & t2.value) 14515 return 1; 14516 if (!((t1.mask | t1.value) & t2.value)) 14517 return 0; 14518 break; 14519 case BPF_JGT: 14520 if (umin1 > umax2) 14521 return 1; 14522 else if (umax1 <= umin2) 14523 return 0; 14524 break; 14525 case BPF_JSGT: 14526 if (smin1 > smax2) 14527 return 1; 14528 else if (smax1 <= smin2) 14529 return 0; 14530 break; 14531 case BPF_JLT: 14532 if (umax1 < umin2) 14533 return 1; 14534 else if (umin1 >= umax2) 14535 return 0; 14536 break; 14537 case BPF_JSLT: 14538 if (smax1 < smin2) 14539 return 1; 14540 else if (smin1 >= smax2) 14541 return 0; 14542 break; 14543 case BPF_JGE: 14544 if (umin1 >= umax2) 14545 return 1; 14546 else if (umax1 < umin2) 14547 return 0; 14548 break; 14549 case BPF_JSGE: 14550 if (smin1 >= smax2) 14551 return 1; 14552 else if (smax1 < smin2) 14553 return 0; 14554 break; 14555 case BPF_JLE: 14556 if (umax1 <= umin2) 14557 return 1; 14558 else if (umin1 > umax2) 14559 return 0; 14560 break; 14561 case BPF_JSLE: 14562 if (smax1 <= smin2) 14563 return 1; 14564 else if (smin1 > smax2) 14565 return 0; 14566 break; 14567 } 14568 14569 return -1; 14570 } 14571 14572 static int flip_opcode(u32 opcode) 14573 { 14574 /* How can we transform "a <op> b" into "b <op> a"? */ 14575 static const u8 opcode_flip[16] = { 14576 /* these stay the same */ 14577 [BPF_JEQ >> 4] = BPF_JEQ, 14578 [BPF_JNE >> 4] = BPF_JNE, 14579 [BPF_JSET >> 4] = BPF_JSET, 14580 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 14581 [BPF_JGE >> 4] = BPF_JLE, 14582 [BPF_JGT >> 4] = BPF_JLT, 14583 [BPF_JLE >> 4] = BPF_JGE, 14584 [BPF_JLT >> 4] = BPF_JGT, 14585 [BPF_JSGE >> 4] = BPF_JSLE, 14586 [BPF_JSGT >> 4] = BPF_JSLT, 14587 [BPF_JSLE >> 4] = BPF_JSGE, 14588 [BPF_JSLT >> 4] = BPF_JSGT 14589 }; 14590 return opcode_flip[opcode >> 4]; 14591 } 14592 14593 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 14594 struct bpf_reg_state *src_reg, 14595 u8 opcode) 14596 { 14597 struct bpf_reg_state *pkt; 14598 14599 if (src_reg->type == PTR_TO_PACKET_END) { 14600 pkt = dst_reg; 14601 } else if (dst_reg->type == PTR_TO_PACKET_END) { 14602 pkt = src_reg; 14603 opcode = flip_opcode(opcode); 14604 } else { 14605 return -1; 14606 } 14607 14608 if (pkt->range >= 0) 14609 return -1; 14610 14611 switch (opcode) { 14612 case BPF_JLE: 14613 /* pkt <= pkt_end */ 14614 fallthrough; 14615 case BPF_JGT: 14616 /* pkt > pkt_end */ 14617 if (pkt->range == BEYOND_PKT_END) 14618 /* pkt has at last one extra byte beyond pkt_end */ 14619 return opcode == BPF_JGT; 14620 break; 14621 case BPF_JLT: 14622 /* pkt < pkt_end */ 14623 fallthrough; 14624 case BPF_JGE: 14625 /* pkt >= pkt_end */ 14626 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 14627 return opcode == BPF_JGE; 14628 break; 14629 } 14630 return -1; 14631 } 14632 14633 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 14634 * and return: 14635 * 1 - branch will be taken and "goto target" will be executed 14636 * 0 - branch will not be taken and fall-through to next insn 14637 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 14638 * range [0,10] 14639 */ 14640 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14641 u8 opcode, bool is_jmp32) 14642 { 14643 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 14644 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 14645 14646 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 14647 u64 val; 14648 14649 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 14650 if (!is_reg_const(reg2, is_jmp32)) { 14651 opcode = flip_opcode(opcode); 14652 swap(reg1, reg2); 14653 } 14654 /* and ensure that reg2 is a constant */ 14655 if (!is_reg_const(reg2, is_jmp32)) 14656 return -1; 14657 14658 if (!reg_not_null(reg1)) 14659 return -1; 14660 14661 /* If pointer is valid tests against zero will fail so we can 14662 * use this to direct branch taken. 14663 */ 14664 val = reg_const_value(reg2, is_jmp32); 14665 if (val != 0) 14666 return -1; 14667 14668 switch (opcode) { 14669 case BPF_JEQ: 14670 return 0; 14671 case BPF_JNE: 14672 return 1; 14673 default: 14674 return -1; 14675 } 14676 } 14677 14678 /* now deal with two scalars, but not necessarily constants */ 14679 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32); 14680 } 14681 14682 /* Opcode that corresponds to a *false* branch condition. 14683 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 14684 */ 14685 static u8 rev_opcode(u8 opcode) 14686 { 14687 switch (opcode) { 14688 case BPF_JEQ: return BPF_JNE; 14689 case BPF_JNE: return BPF_JEQ; 14690 /* JSET doesn't have it's reverse opcode in BPF, so add 14691 * BPF_X flag to denote the reverse of that operation 14692 */ 14693 case BPF_JSET: return BPF_JSET | BPF_X; 14694 case BPF_JSET | BPF_X: return BPF_JSET; 14695 case BPF_JGE: return BPF_JLT; 14696 case BPF_JGT: return BPF_JLE; 14697 case BPF_JLE: return BPF_JGT; 14698 case BPF_JLT: return BPF_JGE; 14699 case BPF_JSGE: return BPF_JSLT; 14700 case BPF_JSGT: return BPF_JSLE; 14701 case BPF_JSLE: return BPF_JSGT; 14702 case BPF_JSLT: return BPF_JSGE; 14703 default: return 0; 14704 } 14705 } 14706 14707 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 14708 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14709 u8 opcode, bool is_jmp32) 14710 { 14711 struct tnum t; 14712 u64 val; 14713 14714 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */ 14715 switch (opcode) { 14716 case BPF_JGE: 14717 case BPF_JGT: 14718 case BPF_JSGE: 14719 case BPF_JSGT: 14720 opcode = flip_opcode(opcode); 14721 swap(reg1, reg2); 14722 break; 14723 default: 14724 break; 14725 } 14726 14727 switch (opcode) { 14728 case BPF_JEQ: 14729 if (is_jmp32) { 14730 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14731 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14732 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14733 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14734 reg2->u32_min_value = reg1->u32_min_value; 14735 reg2->u32_max_value = reg1->u32_max_value; 14736 reg2->s32_min_value = reg1->s32_min_value; 14737 reg2->s32_max_value = reg1->s32_max_value; 14738 14739 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 14740 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14741 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 14742 } else { 14743 reg1->umin_value = max(reg1->umin_value, reg2->umin_value); 14744 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14745 reg1->smin_value = max(reg1->smin_value, reg2->smin_value); 14746 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14747 reg2->umin_value = reg1->umin_value; 14748 reg2->umax_value = reg1->umax_value; 14749 reg2->smin_value = reg1->smin_value; 14750 reg2->smax_value = reg1->smax_value; 14751 14752 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 14753 reg2->var_off = reg1->var_off; 14754 } 14755 break; 14756 case BPF_JNE: 14757 if (!is_reg_const(reg2, is_jmp32)) 14758 swap(reg1, reg2); 14759 if (!is_reg_const(reg2, is_jmp32)) 14760 break; 14761 14762 /* try to recompute the bound of reg1 if reg2 is a const and 14763 * is exactly the edge of reg1. 14764 */ 14765 val = reg_const_value(reg2, is_jmp32); 14766 if (is_jmp32) { 14767 /* u32_min_value is not equal to 0xffffffff at this point, 14768 * because otherwise u32_max_value is 0xffffffff as well, 14769 * in such a case both reg1 and reg2 would be constants, 14770 * jump would be predicted and reg_set_min_max() won't 14771 * be called. 14772 * 14773 * Same reasoning works for all {u,s}{min,max}{32,64} cases 14774 * below. 14775 */ 14776 if (reg1->u32_min_value == (u32)val) 14777 reg1->u32_min_value++; 14778 if (reg1->u32_max_value == (u32)val) 14779 reg1->u32_max_value--; 14780 if (reg1->s32_min_value == (s32)val) 14781 reg1->s32_min_value++; 14782 if (reg1->s32_max_value == (s32)val) 14783 reg1->s32_max_value--; 14784 } else { 14785 if (reg1->umin_value == (u64)val) 14786 reg1->umin_value++; 14787 if (reg1->umax_value == (u64)val) 14788 reg1->umax_value--; 14789 if (reg1->smin_value == (s64)val) 14790 reg1->smin_value++; 14791 if (reg1->smax_value == (s64)val) 14792 reg1->smax_value--; 14793 } 14794 break; 14795 case BPF_JSET: 14796 if (!is_reg_const(reg2, is_jmp32)) 14797 swap(reg1, reg2); 14798 if (!is_reg_const(reg2, is_jmp32)) 14799 break; 14800 val = reg_const_value(reg2, is_jmp32); 14801 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 14802 * requires single bit to learn something useful. E.g., if we 14803 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 14804 * are actually set? We can learn something definite only if 14805 * it's a single-bit value to begin with. 14806 * 14807 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 14808 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 14809 * bit 1 is set, which we can readily use in adjustments. 14810 */ 14811 if (!is_power_of_2(val)) 14812 break; 14813 if (is_jmp32) { 14814 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 14815 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14816 } else { 14817 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 14818 } 14819 break; 14820 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 14821 if (!is_reg_const(reg2, is_jmp32)) 14822 swap(reg1, reg2); 14823 if (!is_reg_const(reg2, is_jmp32)) 14824 break; 14825 val = reg_const_value(reg2, is_jmp32); 14826 if (is_jmp32) { 14827 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 14828 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14829 } else { 14830 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 14831 } 14832 break; 14833 case BPF_JLE: 14834 if (is_jmp32) { 14835 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14836 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14837 } else { 14838 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14839 reg2->umin_value = max(reg1->umin_value, reg2->umin_value); 14840 } 14841 break; 14842 case BPF_JLT: 14843 if (is_jmp32) { 14844 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1); 14845 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value); 14846 } else { 14847 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1); 14848 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value); 14849 } 14850 break; 14851 case BPF_JSLE: 14852 if (is_jmp32) { 14853 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14854 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14855 } else { 14856 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14857 reg2->smin_value = max(reg1->smin_value, reg2->smin_value); 14858 } 14859 break; 14860 case BPF_JSLT: 14861 if (is_jmp32) { 14862 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1); 14863 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value); 14864 } else { 14865 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1); 14866 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value); 14867 } 14868 break; 14869 default: 14870 return; 14871 } 14872 } 14873 14874 /* Adjusts the register min/max values in the case that the dst_reg and 14875 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K 14876 * check, in which case we have a fake SCALAR_VALUE representing insn->imm). 14877 * Technically we can do similar adjustments for pointers to the same object, 14878 * but we don't support that right now. 14879 */ 14880 static int reg_set_min_max(struct bpf_verifier_env *env, 14881 struct bpf_reg_state *true_reg1, 14882 struct bpf_reg_state *true_reg2, 14883 struct bpf_reg_state *false_reg1, 14884 struct bpf_reg_state *false_reg2, 14885 u8 opcode, bool is_jmp32) 14886 { 14887 int err; 14888 14889 /* If either register is a pointer, we can't learn anything about its 14890 * variable offset from the compare (unless they were a pointer into 14891 * the same object, but we don't bother with that). 14892 */ 14893 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE) 14894 return 0; 14895 14896 /* fallthrough (FALSE) branch */ 14897 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32); 14898 reg_bounds_sync(false_reg1); 14899 reg_bounds_sync(false_reg2); 14900 14901 /* jump (TRUE) branch */ 14902 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32); 14903 reg_bounds_sync(true_reg1); 14904 reg_bounds_sync(true_reg2); 14905 14906 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1"); 14907 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2"); 14908 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1"); 14909 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2"); 14910 return err; 14911 } 14912 14913 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 14914 struct bpf_reg_state *reg, u32 id, 14915 bool is_null) 14916 { 14917 if (type_may_be_null(reg->type) && reg->id == id && 14918 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 14919 /* Old offset (both fixed and variable parts) should have been 14920 * known-zero, because we don't allow pointer arithmetic on 14921 * pointers that might be NULL. If we see this happening, don't 14922 * convert the register. 14923 * 14924 * But in some cases, some helpers that return local kptrs 14925 * advance offset for the returned pointer. In those cases, it 14926 * is fine to expect to see reg->off. 14927 */ 14928 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 14929 return; 14930 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 14931 WARN_ON_ONCE(reg->off)) 14932 return; 14933 14934 if (is_null) { 14935 reg->type = SCALAR_VALUE; 14936 /* We don't need id and ref_obj_id from this point 14937 * onwards anymore, thus we should better reset it, 14938 * so that state pruning has chances to take effect. 14939 */ 14940 reg->id = 0; 14941 reg->ref_obj_id = 0; 14942 14943 return; 14944 } 14945 14946 mark_ptr_not_null_reg(reg); 14947 14948 if (!reg_may_point_to_spin_lock(reg)) { 14949 /* For not-NULL ptr, reg->ref_obj_id will be reset 14950 * in release_reference(). 14951 * 14952 * reg->id is still used by spin_lock ptr. Other 14953 * than spin_lock ptr type, reg->id can be reset. 14954 */ 14955 reg->id = 0; 14956 } 14957 } 14958 } 14959 14960 /* The logic is similar to find_good_pkt_pointers(), both could eventually 14961 * be folded together at some point. 14962 */ 14963 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 14964 bool is_null) 14965 { 14966 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14967 struct bpf_reg_state *regs = state->regs, *reg; 14968 u32 ref_obj_id = regs[regno].ref_obj_id; 14969 u32 id = regs[regno].id; 14970 14971 if (ref_obj_id && ref_obj_id == id && is_null) 14972 /* regs[regno] is in the " == NULL" branch. 14973 * No one could have freed the reference state before 14974 * doing the NULL check. 14975 */ 14976 WARN_ON_ONCE(release_reference_state(state, id)); 14977 14978 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14979 mark_ptr_or_null_reg(state, reg, id, is_null); 14980 })); 14981 } 14982 14983 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 14984 struct bpf_reg_state *dst_reg, 14985 struct bpf_reg_state *src_reg, 14986 struct bpf_verifier_state *this_branch, 14987 struct bpf_verifier_state *other_branch) 14988 { 14989 if (BPF_SRC(insn->code) != BPF_X) 14990 return false; 14991 14992 /* Pointers are always 64-bit. */ 14993 if (BPF_CLASS(insn->code) == BPF_JMP32) 14994 return false; 14995 14996 switch (BPF_OP(insn->code)) { 14997 case BPF_JGT: 14998 if ((dst_reg->type == PTR_TO_PACKET && 14999 src_reg->type == PTR_TO_PACKET_END) || 15000 (dst_reg->type == PTR_TO_PACKET_META && 15001 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15002 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 15003 find_good_pkt_pointers(this_branch, dst_reg, 15004 dst_reg->type, false); 15005 mark_pkt_end(other_branch, insn->dst_reg, true); 15006 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15007 src_reg->type == PTR_TO_PACKET) || 15008 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15009 src_reg->type == PTR_TO_PACKET_META)) { 15010 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 15011 find_good_pkt_pointers(other_branch, src_reg, 15012 src_reg->type, true); 15013 mark_pkt_end(this_branch, insn->src_reg, false); 15014 } else { 15015 return false; 15016 } 15017 break; 15018 case BPF_JLT: 15019 if ((dst_reg->type == PTR_TO_PACKET && 15020 src_reg->type == PTR_TO_PACKET_END) || 15021 (dst_reg->type == PTR_TO_PACKET_META && 15022 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15023 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 15024 find_good_pkt_pointers(other_branch, dst_reg, 15025 dst_reg->type, true); 15026 mark_pkt_end(this_branch, insn->dst_reg, false); 15027 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15028 src_reg->type == PTR_TO_PACKET) || 15029 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15030 src_reg->type == PTR_TO_PACKET_META)) { 15031 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 15032 find_good_pkt_pointers(this_branch, src_reg, 15033 src_reg->type, false); 15034 mark_pkt_end(other_branch, insn->src_reg, true); 15035 } else { 15036 return false; 15037 } 15038 break; 15039 case BPF_JGE: 15040 if ((dst_reg->type == PTR_TO_PACKET && 15041 src_reg->type == PTR_TO_PACKET_END) || 15042 (dst_reg->type == PTR_TO_PACKET_META && 15043 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15044 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 15045 find_good_pkt_pointers(this_branch, dst_reg, 15046 dst_reg->type, true); 15047 mark_pkt_end(other_branch, insn->dst_reg, false); 15048 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15049 src_reg->type == PTR_TO_PACKET) || 15050 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15051 src_reg->type == PTR_TO_PACKET_META)) { 15052 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 15053 find_good_pkt_pointers(other_branch, src_reg, 15054 src_reg->type, false); 15055 mark_pkt_end(this_branch, insn->src_reg, true); 15056 } else { 15057 return false; 15058 } 15059 break; 15060 case BPF_JLE: 15061 if ((dst_reg->type == PTR_TO_PACKET && 15062 src_reg->type == PTR_TO_PACKET_END) || 15063 (dst_reg->type == PTR_TO_PACKET_META && 15064 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15065 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 15066 find_good_pkt_pointers(other_branch, dst_reg, 15067 dst_reg->type, false); 15068 mark_pkt_end(this_branch, insn->dst_reg, true); 15069 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15070 src_reg->type == PTR_TO_PACKET) || 15071 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15072 src_reg->type == PTR_TO_PACKET_META)) { 15073 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 15074 find_good_pkt_pointers(this_branch, src_reg, 15075 src_reg->type, true); 15076 mark_pkt_end(other_branch, insn->src_reg, false); 15077 } else { 15078 return false; 15079 } 15080 break; 15081 default: 15082 return false; 15083 } 15084 15085 return true; 15086 } 15087 15088 static void find_equal_scalars(struct bpf_verifier_state *vstate, 15089 struct bpf_reg_state *known_reg) 15090 { 15091 struct bpf_func_state *state; 15092 struct bpf_reg_state *reg; 15093 15094 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15095 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 15096 copy_register_state(reg, known_reg); 15097 })); 15098 } 15099 15100 static int check_cond_jmp_op(struct bpf_verifier_env *env, 15101 struct bpf_insn *insn, int *insn_idx) 15102 { 15103 struct bpf_verifier_state *this_branch = env->cur_state; 15104 struct bpf_verifier_state *other_branch; 15105 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 15106 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 15107 struct bpf_reg_state *eq_branch_regs; 15108 struct bpf_reg_state fake_reg = {}; 15109 u8 opcode = BPF_OP(insn->code); 15110 bool is_jmp32; 15111 int pred = -1; 15112 int err; 15113 15114 /* Only conditional jumps are expected to reach here. */ 15115 if (opcode == BPF_JA || opcode > BPF_JCOND) { 15116 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 15117 return -EINVAL; 15118 } 15119 15120 if (opcode == BPF_JCOND) { 15121 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 15122 int idx = *insn_idx; 15123 15124 if (insn->code != (BPF_JMP | BPF_JCOND) || 15125 insn->src_reg != BPF_MAY_GOTO || 15126 insn->dst_reg || insn->imm || insn->off == 0) { 15127 verbose(env, "invalid may_goto off %d imm %d\n", 15128 insn->off, insn->imm); 15129 return -EINVAL; 15130 } 15131 prev_st = find_prev_entry(env, cur_st->parent, idx); 15132 15133 /* branch out 'fallthrough' insn as a new state to explore */ 15134 queued_st = push_stack(env, idx + 1, idx, false); 15135 if (!queued_st) 15136 return -ENOMEM; 15137 15138 queued_st->may_goto_depth++; 15139 if (prev_st) 15140 widen_imprecise_scalars(env, prev_st, queued_st); 15141 *insn_idx += insn->off; 15142 return 0; 15143 } 15144 15145 /* check src2 operand */ 15146 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15147 if (err) 15148 return err; 15149 15150 dst_reg = ®s[insn->dst_reg]; 15151 if (BPF_SRC(insn->code) == BPF_X) { 15152 if (insn->imm != 0) { 15153 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 15154 return -EINVAL; 15155 } 15156 15157 /* check src1 operand */ 15158 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15159 if (err) 15160 return err; 15161 15162 src_reg = ®s[insn->src_reg]; 15163 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 15164 is_pointer_value(env, insn->src_reg)) { 15165 verbose(env, "R%d pointer comparison prohibited\n", 15166 insn->src_reg); 15167 return -EACCES; 15168 } 15169 } else { 15170 if (insn->src_reg != BPF_REG_0) { 15171 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 15172 return -EINVAL; 15173 } 15174 src_reg = &fake_reg; 15175 src_reg->type = SCALAR_VALUE; 15176 __mark_reg_known(src_reg, insn->imm); 15177 } 15178 15179 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 15180 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32); 15181 if (pred >= 0) { 15182 /* If we get here with a dst_reg pointer type it is because 15183 * above is_branch_taken() special cased the 0 comparison. 15184 */ 15185 if (!__is_pointer_value(false, dst_reg)) 15186 err = mark_chain_precision(env, insn->dst_reg); 15187 if (BPF_SRC(insn->code) == BPF_X && !err && 15188 !__is_pointer_value(false, src_reg)) 15189 err = mark_chain_precision(env, insn->src_reg); 15190 if (err) 15191 return err; 15192 } 15193 15194 if (pred == 1) { 15195 /* Only follow the goto, ignore fall-through. If needed, push 15196 * the fall-through branch for simulation under speculative 15197 * execution. 15198 */ 15199 if (!env->bypass_spec_v1 && 15200 !sanitize_speculative_path(env, insn, *insn_idx + 1, 15201 *insn_idx)) 15202 return -EFAULT; 15203 if (env->log.level & BPF_LOG_LEVEL) 15204 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15205 *insn_idx += insn->off; 15206 return 0; 15207 } else if (pred == 0) { 15208 /* Only follow the fall-through branch, since that's where the 15209 * program will go. If needed, push the goto branch for 15210 * simulation under speculative execution. 15211 */ 15212 if (!env->bypass_spec_v1 && 15213 !sanitize_speculative_path(env, insn, 15214 *insn_idx + insn->off + 1, 15215 *insn_idx)) 15216 return -EFAULT; 15217 if (env->log.level & BPF_LOG_LEVEL) 15218 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15219 return 0; 15220 } 15221 15222 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 15223 false); 15224 if (!other_branch) 15225 return -EFAULT; 15226 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 15227 15228 if (BPF_SRC(insn->code) == BPF_X) { 15229 err = reg_set_min_max(env, 15230 &other_branch_regs[insn->dst_reg], 15231 &other_branch_regs[insn->src_reg], 15232 dst_reg, src_reg, opcode, is_jmp32); 15233 } else /* BPF_SRC(insn->code) == BPF_K */ { 15234 err = reg_set_min_max(env, 15235 &other_branch_regs[insn->dst_reg], 15236 src_reg /* fake one */, 15237 dst_reg, src_reg /* same fake one */, 15238 opcode, is_jmp32); 15239 } 15240 if (err) 15241 return err; 15242 15243 if (BPF_SRC(insn->code) == BPF_X && 15244 src_reg->type == SCALAR_VALUE && src_reg->id && 15245 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 15246 find_equal_scalars(this_branch, src_reg); 15247 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 15248 } 15249 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 15250 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 15251 find_equal_scalars(this_branch, dst_reg); 15252 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 15253 } 15254 15255 /* if one pointer register is compared to another pointer 15256 * register check if PTR_MAYBE_NULL could be lifted. 15257 * E.g. register A - maybe null 15258 * register B - not null 15259 * for JNE A, B, ... - A is not null in the false branch; 15260 * for JEQ A, B, ... - A is not null in the true branch. 15261 * 15262 * Since PTR_TO_BTF_ID points to a kernel struct that does 15263 * not need to be null checked by the BPF program, i.e., 15264 * could be null even without PTR_MAYBE_NULL marking, so 15265 * only propagate nullness when neither reg is that type. 15266 */ 15267 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 15268 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 15269 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 15270 base_type(src_reg->type) != PTR_TO_BTF_ID && 15271 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 15272 eq_branch_regs = NULL; 15273 switch (opcode) { 15274 case BPF_JEQ: 15275 eq_branch_regs = other_branch_regs; 15276 break; 15277 case BPF_JNE: 15278 eq_branch_regs = regs; 15279 break; 15280 default: 15281 /* do nothing */ 15282 break; 15283 } 15284 if (eq_branch_regs) { 15285 if (type_may_be_null(src_reg->type)) 15286 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 15287 else 15288 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 15289 } 15290 } 15291 15292 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 15293 * NOTE: these optimizations below are related with pointer comparison 15294 * which will never be JMP32. 15295 */ 15296 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 15297 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 15298 type_may_be_null(dst_reg->type)) { 15299 /* Mark all identical registers in each branch as either 15300 * safe or unknown depending R == 0 or R != 0 conditional. 15301 */ 15302 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 15303 opcode == BPF_JNE); 15304 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 15305 opcode == BPF_JEQ); 15306 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 15307 this_branch, other_branch) && 15308 is_pointer_value(env, insn->dst_reg)) { 15309 verbose(env, "R%d pointer comparison prohibited\n", 15310 insn->dst_reg); 15311 return -EACCES; 15312 } 15313 if (env->log.level & BPF_LOG_LEVEL) 15314 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15315 return 0; 15316 } 15317 15318 /* verify BPF_LD_IMM64 instruction */ 15319 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 15320 { 15321 struct bpf_insn_aux_data *aux = cur_aux(env); 15322 struct bpf_reg_state *regs = cur_regs(env); 15323 struct bpf_reg_state *dst_reg; 15324 struct bpf_map *map; 15325 int err; 15326 15327 if (BPF_SIZE(insn->code) != BPF_DW) { 15328 verbose(env, "invalid BPF_LD_IMM insn\n"); 15329 return -EINVAL; 15330 } 15331 if (insn->off != 0) { 15332 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 15333 return -EINVAL; 15334 } 15335 15336 err = check_reg_arg(env, insn->dst_reg, DST_OP); 15337 if (err) 15338 return err; 15339 15340 dst_reg = ®s[insn->dst_reg]; 15341 if (insn->src_reg == 0) { 15342 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 15343 15344 dst_reg->type = SCALAR_VALUE; 15345 __mark_reg_known(®s[insn->dst_reg], imm); 15346 return 0; 15347 } 15348 15349 /* All special src_reg cases are listed below. From this point onwards 15350 * we either succeed and assign a corresponding dst_reg->type after 15351 * zeroing the offset, or fail and reject the program. 15352 */ 15353 mark_reg_known_zero(env, regs, insn->dst_reg); 15354 15355 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 15356 dst_reg->type = aux->btf_var.reg_type; 15357 switch (base_type(dst_reg->type)) { 15358 case PTR_TO_MEM: 15359 dst_reg->mem_size = aux->btf_var.mem_size; 15360 break; 15361 case PTR_TO_BTF_ID: 15362 dst_reg->btf = aux->btf_var.btf; 15363 dst_reg->btf_id = aux->btf_var.btf_id; 15364 break; 15365 default: 15366 verbose(env, "bpf verifier is misconfigured\n"); 15367 return -EFAULT; 15368 } 15369 return 0; 15370 } 15371 15372 if (insn->src_reg == BPF_PSEUDO_FUNC) { 15373 struct bpf_prog_aux *aux = env->prog->aux; 15374 u32 subprogno = find_subprog(env, 15375 env->insn_idx + insn->imm + 1); 15376 15377 if (!aux->func_info) { 15378 verbose(env, "missing btf func_info\n"); 15379 return -EINVAL; 15380 } 15381 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 15382 verbose(env, "callback function not static\n"); 15383 return -EINVAL; 15384 } 15385 15386 dst_reg->type = PTR_TO_FUNC; 15387 dst_reg->subprogno = subprogno; 15388 return 0; 15389 } 15390 15391 map = env->used_maps[aux->map_index]; 15392 dst_reg->map_ptr = map; 15393 15394 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 15395 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 15396 if (map->map_type == BPF_MAP_TYPE_ARENA) { 15397 __mark_reg_unknown(env, dst_reg); 15398 return 0; 15399 } 15400 dst_reg->type = PTR_TO_MAP_VALUE; 15401 dst_reg->off = aux->map_off; 15402 WARN_ON_ONCE(map->max_entries != 1); 15403 /* We want reg->id to be same (0) as map_value is not distinct */ 15404 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 15405 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 15406 dst_reg->type = CONST_PTR_TO_MAP; 15407 } else { 15408 verbose(env, "bpf verifier is misconfigured\n"); 15409 return -EINVAL; 15410 } 15411 15412 return 0; 15413 } 15414 15415 static bool may_access_skb(enum bpf_prog_type type) 15416 { 15417 switch (type) { 15418 case BPF_PROG_TYPE_SOCKET_FILTER: 15419 case BPF_PROG_TYPE_SCHED_CLS: 15420 case BPF_PROG_TYPE_SCHED_ACT: 15421 return true; 15422 default: 15423 return false; 15424 } 15425 } 15426 15427 /* verify safety of LD_ABS|LD_IND instructions: 15428 * - they can only appear in the programs where ctx == skb 15429 * - since they are wrappers of function calls, they scratch R1-R5 registers, 15430 * preserve R6-R9, and store return value into R0 15431 * 15432 * Implicit input: 15433 * ctx == skb == R6 == CTX 15434 * 15435 * Explicit input: 15436 * SRC == any register 15437 * IMM == 32-bit immediate 15438 * 15439 * Output: 15440 * R0 - 8/16/32-bit skb data converted to cpu endianness 15441 */ 15442 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 15443 { 15444 struct bpf_reg_state *regs = cur_regs(env); 15445 static const int ctx_reg = BPF_REG_6; 15446 u8 mode = BPF_MODE(insn->code); 15447 int i, err; 15448 15449 if (!may_access_skb(resolve_prog_type(env->prog))) { 15450 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 15451 return -EINVAL; 15452 } 15453 15454 if (!env->ops->gen_ld_abs) { 15455 verbose(env, "bpf verifier is misconfigured\n"); 15456 return -EINVAL; 15457 } 15458 15459 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 15460 BPF_SIZE(insn->code) == BPF_DW || 15461 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 15462 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 15463 return -EINVAL; 15464 } 15465 15466 /* check whether implicit source operand (register R6) is readable */ 15467 err = check_reg_arg(env, ctx_reg, SRC_OP); 15468 if (err) 15469 return err; 15470 15471 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 15472 * gen_ld_abs() may terminate the program at runtime, leading to 15473 * reference leak. 15474 */ 15475 err = check_reference_leak(env, false); 15476 if (err) { 15477 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 15478 return err; 15479 } 15480 15481 if (env->cur_state->active_lock.ptr) { 15482 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 15483 return -EINVAL; 15484 } 15485 15486 if (env->cur_state->active_rcu_lock) { 15487 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 15488 return -EINVAL; 15489 } 15490 15491 if (env->cur_state->active_preempt_lock) { 15492 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_preempt_disable-ed region\n"); 15493 return -EINVAL; 15494 } 15495 15496 if (regs[ctx_reg].type != PTR_TO_CTX) { 15497 verbose(env, 15498 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 15499 return -EINVAL; 15500 } 15501 15502 if (mode == BPF_IND) { 15503 /* check explicit source operand */ 15504 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15505 if (err) 15506 return err; 15507 } 15508 15509 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 15510 if (err < 0) 15511 return err; 15512 15513 /* reset caller saved regs to unreadable */ 15514 for (i = 0; i < CALLER_SAVED_REGS; i++) { 15515 mark_reg_not_init(env, regs, caller_saved[i]); 15516 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 15517 } 15518 15519 /* mark destination R0 register as readable, since it contains 15520 * the value fetched from the packet. 15521 * Already marked as written above. 15522 */ 15523 mark_reg_unknown(env, regs, BPF_REG_0); 15524 /* ld_abs load up to 32-bit skb data. */ 15525 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 15526 return 0; 15527 } 15528 15529 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 15530 { 15531 const char *exit_ctx = "At program exit"; 15532 struct tnum enforce_attach_type_range = tnum_unknown; 15533 const struct bpf_prog *prog = env->prog; 15534 struct bpf_reg_state *reg; 15535 struct bpf_retval_range range = retval_range(0, 1); 15536 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 15537 int err; 15538 struct bpf_func_state *frame = env->cur_state->frame[0]; 15539 const bool is_subprog = frame->subprogno; 15540 15541 /* LSM and struct_ops func-ptr's return type could be "void" */ 15542 if (!is_subprog || frame->in_exception_callback_fn) { 15543 switch (prog_type) { 15544 case BPF_PROG_TYPE_LSM: 15545 if (prog->expected_attach_type == BPF_LSM_CGROUP) 15546 /* See below, can be 0 or 0-1 depending on hook. */ 15547 break; 15548 fallthrough; 15549 case BPF_PROG_TYPE_STRUCT_OPS: 15550 if (!prog->aux->attach_func_proto->type) 15551 return 0; 15552 break; 15553 default: 15554 break; 15555 } 15556 } 15557 15558 /* eBPF calling convention is such that R0 is used 15559 * to return the value from eBPF program. 15560 * Make sure that it's readable at this time 15561 * of bpf_exit, which means that program wrote 15562 * something into it earlier 15563 */ 15564 err = check_reg_arg(env, regno, SRC_OP); 15565 if (err) 15566 return err; 15567 15568 if (is_pointer_value(env, regno)) { 15569 verbose(env, "R%d leaks addr as return value\n", regno); 15570 return -EACCES; 15571 } 15572 15573 reg = cur_regs(env) + regno; 15574 15575 if (frame->in_async_callback_fn) { 15576 /* enforce return zero from async callbacks like timer */ 15577 exit_ctx = "At async callback return"; 15578 range = retval_range(0, 0); 15579 goto enforce_retval; 15580 } 15581 15582 if (is_subprog && !frame->in_exception_callback_fn) { 15583 if (reg->type != SCALAR_VALUE) { 15584 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 15585 regno, reg_type_str(env, reg->type)); 15586 return -EINVAL; 15587 } 15588 return 0; 15589 } 15590 15591 switch (prog_type) { 15592 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 15593 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 15594 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 15595 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG || 15596 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 15597 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 15598 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME || 15599 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 15600 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME || 15601 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME) 15602 range = retval_range(1, 1); 15603 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 15604 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 15605 range = retval_range(0, 3); 15606 break; 15607 case BPF_PROG_TYPE_CGROUP_SKB: 15608 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 15609 range = retval_range(0, 3); 15610 enforce_attach_type_range = tnum_range(2, 3); 15611 } 15612 break; 15613 case BPF_PROG_TYPE_CGROUP_SOCK: 15614 case BPF_PROG_TYPE_SOCK_OPS: 15615 case BPF_PROG_TYPE_CGROUP_DEVICE: 15616 case BPF_PROG_TYPE_CGROUP_SYSCTL: 15617 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 15618 break; 15619 case BPF_PROG_TYPE_RAW_TRACEPOINT: 15620 if (!env->prog->aux->attach_btf_id) 15621 return 0; 15622 range = retval_range(0, 0); 15623 break; 15624 case BPF_PROG_TYPE_TRACING: 15625 switch (env->prog->expected_attach_type) { 15626 case BPF_TRACE_FENTRY: 15627 case BPF_TRACE_FEXIT: 15628 range = retval_range(0, 0); 15629 break; 15630 case BPF_TRACE_RAW_TP: 15631 case BPF_MODIFY_RETURN: 15632 return 0; 15633 case BPF_TRACE_ITER: 15634 break; 15635 default: 15636 return -ENOTSUPP; 15637 } 15638 break; 15639 case BPF_PROG_TYPE_SK_LOOKUP: 15640 range = retval_range(SK_DROP, SK_PASS); 15641 break; 15642 15643 case BPF_PROG_TYPE_LSM: 15644 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 15645 /* Regular BPF_PROG_TYPE_LSM programs can return 15646 * any value. 15647 */ 15648 return 0; 15649 } 15650 if (!env->prog->aux->attach_func_proto->type) { 15651 /* Make sure programs that attach to void 15652 * hooks don't try to modify return value. 15653 */ 15654 range = retval_range(1, 1); 15655 } 15656 break; 15657 15658 case BPF_PROG_TYPE_NETFILTER: 15659 range = retval_range(NF_DROP, NF_ACCEPT); 15660 break; 15661 case BPF_PROG_TYPE_EXT: 15662 /* freplace program can return anything as its return value 15663 * depends on the to-be-replaced kernel func or bpf program. 15664 */ 15665 default: 15666 return 0; 15667 } 15668 15669 enforce_retval: 15670 if (reg->type != SCALAR_VALUE) { 15671 verbose(env, "%s the register R%d is not a known value (%s)\n", 15672 exit_ctx, regno, reg_type_str(env, reg->type)); 15673 return -EINVAL; 15674 } 15675 15676 err = mark_chain_precision(env, regno); 15677 if (err) 15678 return err; 15679 15680 if (!retval_range_within(range, reg)) { 15681 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 15682 if (!is_subprog && 15683 prog->expected_attach_type == BPF_LSM_CGROUP && 15684 prog_type == BPF_PROG_TYPE_LSM && 15685 !prog->aux->attach_func_proto->type) 15686 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 15687 return -EINVAL; 15688 } 15689 15690 if (!tnum_is_unknown(enforce_attach_type_range) && 15691 tnum_in(enforce_attach_type_range, reg->var_off)) 15692 env->prog->enforce_expected_attach_type = 1; 15693 return 0; 15694 } 15695 15696 /* non-recursive DFS pseudo code 15697 * 1 procedure DFS-iterative(G,v): 15698 * 2 label v as discovered 15699 * 3 let S be a stack 15700 * 4 S.push(v) 15701 * 5 while S is not empty 15702 * 6 t <- S.peek() 15703 * 7 if t is what we're looking for: 15704 * 8 return t 15705 * 9 for all edges e in G.adjacentEdges(t) do 15706 * 10 if edge e is already labelled 15707 * 11 continue with the next edge 15708 * 12 w <- G.adjacentVertex(t,e) 15709 * 13 if vertex w is not discovered and not explored 15710 * 14 label e as tree-edge 15711 * 15 label w as discovered 15712 * 16 S.push(w) 15713 * 17 continue at 5 15714 * 18 else if vertex w is discovered 15715 * 19 label e as back-edge 15716 * 20 else 15717 * 21 // vertex w is explored 15718 * 22 label e as forward- or cross-edge 15719 * 23 label t as explored 15720 * 24 S.pop() 15721 * 15722 * convention: 15723 * 0x10 - discovered 15724 * 0x11 - discovered and fall-through edge labelled 15725 * 0x12 - discovered and fall-through and branch edges labelled 15726 * 0x20 - explored 15727 */ 15728 15729 enum { 15730 DISCOVERED = 0x10, 15731 EXPLORED = 0x20, 15732 FALLTHROUGH = 1, 15733 BRANCH = 2, 15734 }; 15735 15736 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 15737 { 15738 env->insn_aux_data[idx].prune_point = true; 15739 } 15740 15741 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 15742 { 15743 return env->insn_aux_data[insn_idx].prune_point; 15744 } 15745 15746 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 15747 { 15748 env->insn_aux_data[idx].force_checkpoint = true; 15749 } 15750 15751 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 15752 { 15753 return env->insn_aux_data[insn_idx].force_checkpoint; 15754 } 15755 15756 static void mark_calls_callback(struct bpf_verifier_env *env, int idx) 15757 { 15758 env->insn_aux_data[idx].calls_callback = true; 15759 } 15760 15761 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx) 15762 { 15763 return env->insn_aux_data[insn_idx].calls_callback; 15764 } 15765 15766 enum { 15767 DONE_EXPLORING = 0, 15768 KEEP_EXPLORING = 1, 15769 }; 15770 15771 /* t, w, e - match pseudo-code above: 15772 * t - index of current instruction 15773 * w - next instruction 15774 * e - edge 15775 */ 15776 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 15777 { 15778 int *insn_stack = env->cfg.insn_stack; 15779 int *insn_state = env->cfg.insn_state; 15780 15781 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 15782 return DONE_EXPLORING; 15783 15784 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 15785 return DONE_EXPLORING; 15786 15787 if (w < 0 || w >= env->prog->len) { 15788 verbose_linfo(env, t, "%d: ", t); 15789 verbose(env, "jump out of range from insn %d to %d\n", t, w); 15790 return -EINVAL; 15791 } 15792 15793 if (e == BRANCH) { 15794 /* mark branch target for state pruning */ 15795 mark_prune_point(env, w); 15796 mark_jmp_point(env, w); 15797 } 15798 15799 if (insn_state[w] == 0) { 15800 /* tree-edge */ 15801 insn_state[t] = DISCOVERED | e; 15802 insn_state[w] = DISCOVERED; 15803 if (env->cfg.cur_stack >= env->prog->len) 15804 return -E2BIG; 15805 insn_stack[env->cfg.cur_stack++] = w; 15806 return KEEP_EXPLORING; 15807 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 15808 if (env->bpf_capable) 15809 return DONE_EXPLORING; 15810 verbose_linfo(env, t, "%d: ", t); 15811 verbose_linfo(env, w, "%d: ", w); 15812 verbose(env, "back-edge from insn %d to %d\n", t, w); 15813 return -EINVAL; 15814 } else if (insn_state[w] == EXPLORED) { 15815 /* forward- or cross-edge */ 15816 insn_state[t] = DISCOVERED | e; 15817 } else { 15818 verbose(env, "insn state internal bug\n"); 15819 return -EFAULT; 15820 } 15821 return DONE_EXPLORING; 15822 } 15823 15824 static int visit_func_call_insn(int t, struct bpf_insn *insns, 15825 struct bpf_verifier_env *env, 15826 bool visit_callee) 15827 { 15828 int ret, insn_sz; 15829 15830 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 15831 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 15832 if (ret) 15833 return ret; 15834 15835 mark_prune_point(env, t + insn_sz); 15836 /* when we exit from subprog, we need to record non-linear history */ 15837 mark_jmp_point(env, t + insn_sz); 15838 15839 if (visit_callee) { 15840 mark_prune_point(env, t); 15841 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env); 15842 } 15843 return ret; 15844 } 15845 15846 /* Visits the instruction at index t and returns one of the following: 15847 * < 0 - an error occurred 15848 * DONE_EXPLORING - the instruction was fully explored 15849 * KEEP_EXPLORING - there is still work to be done before it is fully explored 15850 */ 15851 static int visit_insn(int t, struct bpf_verifier_env *env) 15852 { 15853 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 15854 int ret, off, insn_sz; 15855 15856 if (bpf_pseudo_func(insn)) 15857 return visit_func_call_insn(t, insns, env, true); 15858 15859 /* All non-branch instructions have a single fall-through edge. */ 15860 if (BPF_CLASS(insn->code) != BPF_JMP && 15861 BPF_CLASS(insn->code) != BPF_JMP32) { 15862 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 15863 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 15864 } 15865 15866 switch (BPF_OP(insn->code)) { 15867 case BPF_EXIT: 15868 return DONE_EXPLORING; 15869 15870 case BPF_CALL: 15871 if (is_async_callback_calling_insn(insn)) 15872 /* Mark this call insn as a prune point to trigger 15873 * is_state_visited() check before call itself is 15874 * processed by __check_func_call(). Otherwise new 15875 * async state will be pushed for further exploration. 15876 */ 15877 mark_prune_point(env, t); 15878 /* For functions that invoke callbacks it is not known how many times 15879 * callback would be called. Verifier models callback calling functions 15880 * by repeatedly visiting callback bodies and returning to origin call 15881 * instruction. 15882 * In order to stop such iteration verifier needs to identify when a 15883 * state identical some state from a previous iteration is reached. 15884 * Check below forces creation of checkpoint before callback calling 15885 * instruction to allow search for such identical states. 15886 */ 15887 if (is_sync_callback_calling_insn(insn)) { 15888 mark_calls_callback(env, t); 15889 mark_force_checkpoint(env, t); 15890 mark_prune_point(env, t); 15891 mark_jmp_point(env, t); 15892 } 15893 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 15894 struct bpf_kfunc_call_arg_meta meta; 15895 15896 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 15897 if (ret == 0 && is_iter_next_kfunc(&meta)) { 15898 mark_prune_point(env, t); 15899 /* Checking and saving state checkpoints at iter_next() call 15900 * is crucial for fast convergence of open-coded iterator loop 15901 * logic, so we need to force it. If we don't do that, 15902 * is_state_visited() might skip saving a checkpoint, causing 15903 * unnecessarily long sequence of not checkpointed 15904 * instructions and jumps, leading to exhaustion of jump 15905 * history buffer, and potentially other undesired outcomes. 15906 * It is expected that with correct open-coded iterators 15907 * convergence will happen quickly, so we don't run a risk of 15908 * exhausting memory. 15909 */ 15910 mark_force_checkpoint(env, t); 15911 } 15912 } 15913 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 15914 15915 case BPF_JA: 15916 if (BPF_SRC(insn->code) != BPF_K) 15917 return -EINVAL; 15918 15919 if (BPF_CLASS(insn->code) == BPF_JMP) 15920 off = insn->off; 15921 else 15922 off = insn->imm; 15923 15924 /* unconditional jump with single edge */ 15925 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 15926 if (ret) 15927 return ret; 15928 15929 mark_prune_point(env, t + off + 1); 15930 mark_jmp_point(env, t + off + 1); 15931 15932 return ret; 15933 15934 default: 15935 /* conditional jump with two edges */ 15936 mark_prune_point(env, t); 15937 if (is_may_goto_insn(insn)) 15938 mark_force_checkpoint(env, t); 15939 15940 ret = push_insn(t, t + 1, FALLTHROUGH, env); 15941 if (ret) 15942 return ret; 15943 15944 return push_insn(t, t + insn->off + 1, BRANCH, env); 15945 } 15946 } 15947 15948 /* non-recursive depth-first-search to detect loops in BPF program 15949 * loop == back-edge in directed graph 15950 */ 15951 static int check_cfg(struct bpf_verifier_env *env) 15952 { 15953 int insn_cnt = env->prog->len; 15954 int *insn_stack, *insn_state; 15955 int ex_insn_beg, i, ret = 0; 15956 bool ex_done = false; 15957 15958 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15959 if (!insn_state) 15960 return -ENOMEM; 15961 15962 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15963 if (!insn_stack) { 15964 kvfree(insn_state); 15965 return -ENOMEM; 15966 } 15967 15968 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 15969 insn_stack[0] = 0; /* 0 is the first instruction */ 15970 env->cfg.cur_stack = 1; 15971 15972 walk_cfg: 15973 while (env->cfg.cur_stack > 0) { 15974 int t = insn_stack[env->cfg.cur_stack - 1]; 15975 15976 ret = visit_insn(t, env); 15977 switch (ret) { 15978 case DONE_EXPLORING: 15979 insn_state[t] = EXPLORED; 15980 env->cfg.cur_stack--; 15981 break; 15982 case KEEP_EXPLORING: 15983 break; 15984 default: 15985 if (ret > 0) { 15986 verbose(env, "visit_insn internal bug\n"); 15987 ret = -EFAULT; 15988 } 15989 goto err_free; 15990 } 15991 } 15992 15993 if (env->cfg.cur_stack < 0) { 15994 verbose(env, "pop stack internal bug\n"); 15995 ret = -EFAULT; 15996 goto err_free; 15997 } 15998 15999 if (env->exception_callback_subprog && !ex_done) { 16000 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start; 16001 16002 insn_state[ex_insn_beg] = DISCOVERED; 16003 insn_stack[0] = ex_insn_beg; 16004 env->cfg.cur_stack = 1; 16005 ex_done = true; 16006 goto walk_cfg; 16007 } 16008 16009 for (i = 0; i < insn_cnt; i++) { 16010 struct bpf_insn *insn = &env->prog->insnsi[i]; 16011 16012 if (insn_state[i] != EXPLORED) { 16013 verbose(env, "unreachable insn %d\n", i); 16014 ret = -EINVAL; 16015 goto err_free; 16016 } 16017 if (bpf_is_ldimm64(insn)) { 16018 if (insn_state[i + 1] != 0) { 16019 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 16020 ret = -EINVAL; 16021 goto err_free; 16022 } 16023 i++; /* skip second half of ldimm64 */ 16024 } 16025 } 16026 ret = 0; /* cfg looks good */ 16027 16028 err_free: 16029 kvfree(insn_state); 16030 kvfree(insn_stack); 16031 env->cfg.insn_state = env->cfg.insn_stack = NULL; 16032 return ret; 16033 } 16034 16035 static int check_abnormal_return(struct bpf_verifier_env *env) 16036 { 16037 int i; 16038 16039 for (i = 1; i < env->subprog_cnt; i++) { 16040 if (env->subprog_info[i].has_ld_abs) { 16041 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 16042 return -EINVAL; 16043 } 16044 if (env->subprog_info[i].has_tail_call) { 16045 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 16046 return -EINVAL; 16047 } 16048 } 16049 return 0; 16050 } 16051 16052 /* The minimum supported BTF func info size */ 16053 #define MIN_BPF_FUNCINFO_SIZE 8 16054 #define MAX_FUNCINFO_REC_SIZE 252 16055 16056 static int check_btf_func_early(struct bpf_verifier_env *env, 16057 const union bpf_attr *attr, 16058 bpfptr_t uattr) 16059 { 16060 u32 krec_size = sizeof(struct bpf_func_info); 16061 const struct btf_type *type, *func_proto; 16062 u32 i, nfuncs, urec_size, min_size; 16063 struct bpf_func_info *krecord; 16064 struct bpf_prog *prog; 16065 const struct btf *btf; 16066 u32 prev_offset = 0; 16067 bpfptr_t urecord; 16068 int ret = -ENOMEM; 16069 16070 nfuncs = attr->func_info_cnt; 16071 if (!nfuncs) { 16072 if (check_abnormal_return(env)) 16073 return -EINVAL; 16074 return 0; 16075 } 16076 16077 urec_size = attr->func_info_rec_size; 16078 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 16079 urec_size > MAX_FUNCINFO_REC_SIZE || 16080 urec_size % sizeof(u32)) { 16081 verbose(env, "invalid func info rec size %u\n", urec_size); 16082 return -EINVAL; 16083 } 16084 16085 prog = env->prog; 16086 btf = prog->aux->btf; 16087 16088 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 16089 min_size = min_t(u32, krec_size, urec_size); 16090 16091 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 16092 if (!krecord) 16093 return -ENOMEM; 16094 16095 for (i = 0; i < nfuncs; i++) { 16096 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 16097 if (ret) { 16098 if (ret == -E2BIG) { 16099 verbose(env, "nonzero tailing record in func info"); 16100 /* set the size kernel expects so loader can zero 16101 * out the rest of the record. 16102 */ 16103 if (copy_to_bpfptr_offset(uattr, 16104 offsetof(union bpf_attr, func_info_rec_size), 16105 &min_size, sizeof(min_size))) 16106 ret = -EFAULT; 16107 } 16108 goto err_free; 16109 } 16110 16111 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 16112 ret = -EFAULT; 16113 goto err_free; 16114 } 16115 16116 /* check insn_off */ 16117 ret = -EINVAL; 16118 if (i == 0) { 16119 if (krecord[i].insn_off) { 16120 verbose(env, 16121 "nonzero insn_off %u for the first func info record", 16122 krecord[i].insn_off); 16123 goto err_free; 16124 } 16125 } else if (krecord[i].insn_off <= prev_offset) { 16126 verbose(env, 16127 "same or smaller insn offset (%u) than previous func info record (%u)", 16128 krecord[i].insn_off, prev_offset); 16129 goto err_free; 16130 } 16131 16132 /* check type_id */ 16133 type = btf_type_by_id(btf, krecord[i].type_id); 16134 if (!type || !btf_type_is_func(type)) { 16135 verbose(env, "invalid type id %d in func info", 16136 krecord[i].type_id); 16137 goto err_free; 16138 } 16139 16140 func_proto = btf_type_by_id(btf, type->type); 16141 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 16142 /* btf_func_check() already verified it during BTF load */ 16143 goto err_free; 16144 16145 prev_offset = krecord[i].insn_off; 16146 bpfptr_add(&urecord, urec_size); 16147 } 16148 16149 prog->aux->func_info = krecord; 16150 prog->aux->func_info_cnt = nfuncs; 16151 return 0; 16152 16153 err_free: 16154 kvfree(krecord); 16155 return ret; 16156 } 16157 16158 static int check_btf_func(struct bpf_verifier_env *env, 16159 const union bpf_attr *attr, 16160 bpfptr_t uattr) 16161 { 16162 const struct btf_type *type, *func_proto, *ret_type; 16163 u32 i, nfuncs, urec_size; 16164 struct bpf_func_info *krecord; 16165 struct bpf_func_info_aux *info_aux = NULL; 16166 struct bpf_prog *prog; 16167 const struct btf *btf; 16168 bpfptr_t urecord; 16169 bool scalar_return; 16170 int ret = -ENOMEM; 16171 16172 nfuncs = attr->func_info_cnt; 16173 if (!nfuncs) { 16174 if (check_abnormal_return(env)) 16175 return -EINVAL; 16176 return 0; 16177 } 16178 if (nfuncs != env->subprog_cnt) { 16179 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 16180 return -EINVAL; 16181 } 16182 16183 urec_size = attr->func_info_rec_size; 16184 16185 prog = env->prog; 16186 btf = prog->aux->btf; 16187 16188 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 16189 16190 krecord = prog->aux->func_info; 16191 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 16192 if (!info_aux) 16193 return -ENOMEM; 16194 16195 for (i = 0; i < nfuncs; i++) { 16196 /* check insn_off */ 16197 ret = -EINVAL; 16198 16199 if (env->subprog_info[i].start != krecord[i].insn_off) { 16200 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 16201 goto err_free; 16202 } 16203 16204 /* Already checked type_id */ 16205 type = btf_type_by_id(btf, krecord[i].type_id); 16206 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 16207 /* Already checked func_proto */ 16208 func_proto = btf_type_by_id(btf, type->type); 16209 16210 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 16211 scalar_return = 16212 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 16213 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 16214 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 16215 goto err_free; 16216 } 16217 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 16218 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 16219 goto err_free; 16220 } 16221 16222 bpfptr_add(&urecord, urec_size); 16223 } 16224 16225 prog->aux->func_info_aux = info_aux; 16226 return 0; 16227 16228 err_free: 16229 kfree(info_aux); 16230 return ret; 16231 } 16232 16233 static void adjust_btf_func(struct bpf_verifier_env *env) 16234 { 16235 struct bpf_prog_aux *aux = env->prog->aux; 16236 int i; 16237 16238 if (!aux->func_info) 16239 return; 16240 16241 /* func_info is not available for hidden subprogs */ 16242 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 16243 aux->func_info[i].insn_off = env->subprog_info[i].start; 16244 } 16245 16246 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 16247 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 16248 16249 static int check_btf_line(struct bpf_verifier_env *env, 16250 const union bpf_attr *attr, 16251 bpfptr_t uattr) 16252 { 16253 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 16254 struct bpf_subprog_info *sub; 16255 struct bpf_line_info *linfo; 16256 struct bpf_prog *prog; 16257 const struct btf *btf; 16258 bpfptr_t ulinfo; 16259 int err; 16260 16261 nr_linfo = attr->line_info_cnt; 16262 if (!nr_linfo) 16263 return 0; 16264 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 16265 return -EINVAL; 16266 16267 rec_size = attr->line_info_rec_size; 16268 if (rec_size < MIN_BPF_LINEINFO_SIZE || 16269 rec_size > MAX_LINEINFO_REC_SIZE || 16270 rec_size & (sizeof(u32) - 1)) 16271 return -EINVAL; 16272 16273 /* Need to zero it in case the userspace may 16274 * pass in a smaller bpf_line_info object. 16275 */ 16276 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 16277 GFP_KERNEL | __GFP_NOWARN); 16278 if (!linfo) 16279 return -ENOMEM; 16280 16281 prog = env->prog; 16282 btf = prog->aux->btf; 16283 16284 s = 0; 16285 sub = env->subprog_info; 16286 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 16287 expected_size = sizeof(struct bpf_line_info); 16288 ncopy = min_t(u32, expected_size, rec_size); 16289 for (i = 0; i < nr_linfo; i++) { 16290 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 16291 if (err) { 16292 if (err == -E2BIG) { 16293 verbose(env, "nonzero tailing record in line_info"); 16294 if (copy_to_bpfptr_offset(uattr, 16295 offsetof(union bpf_attr, line_info_rec_size), 16296 &expected_size, sizeof(expected_size))) 16297 err = -EFAULT; 16298 } 16299 goto err_free; 16300 } 16301 16302 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 16303 err = -EFAULT; 16304 goto err_free; 16305 } 16306 16307 /* 16308 * Check insn_off to ensure 16309 * 1) strictly increasing AND 16310 * 2) bounded by prog->len 16311 * 16312 * The linfo[0].insn_off == 0 check logically falls into 16313 * the later "missing bpf_line_info for func..." case 16314 * because the first linfo[0].insn_off must be the 16315 * first sub also and the first sub must have 16316 * subprog_info[0].start == 0. 16317 */ 16318 if ((i && linfo[i].insn_off <= prev_offset) || 16319 linfo[i].insn_off >= prog->len) { 16320 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 16321 i, linfo[i].insn_off, prev_offset, 16322 prog->len); 16323 err = -EINVAL; 16324 goto err_free; 16325 } 16326 16327 if (!prog->insnsi[linfo[i].insn_off].code) { 16328 verbose(env, 16329 "Invalid insn code at line_info[%u].insn_off\n", 16330 i); 16331 err = -EINVAL; 16332 goto err_free; 16333 } 16334 16335 if (!btf_name_by_offset(btf, linfo[i].line_off) || 16336 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 16337 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 16338 err = -EINVAL; 16339 goto err_free; 16340 } 16341 16342 if (s != env->subprog_cnt) { 16343 if (linfo[i].insn_off == sub[s].start) { 16344 sub[s].linfo_idx = i; 16345 s++; 16346 } else if (sub[s].start < linfo[i].insn_off) { 16347 verbose(env, "missing bpf_line_info for func#%u\n", s); 16348 err = -EINVAL; 16349 goto err_free; 16350 } 16351 } 16352 16353 prev_offset = linfo[i].insn_off; 16354 bpfptr_add(&ulinfo, rec_size); 16355 } 16356 16357 if (s != env->subprog_cnt) { 16358 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 16359 env->subprog_cnt - s, s); 16360 err = -EINVAL; 16361 goto err_free; 16362 } 16363 16364 prog->aux->linfo = linfo; 16365 prog->aux->nr_linfo = nr_linfo; 16366 16367 return 0; 16368 16369 err_free: 16370 kvfree(linfo); 16371 return err; 16372 } 16373 16374 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 16375 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 16376 16377 static int check_core_relo(struct bpf_verifier_env *env, 16378 const union bpf_attr *attr, 16379 bpfptr_t uattr) 16380 { 16381 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 16382 struct bpf_core_relo core_relo = {}; 16383 struct bpf_prog *prog = env->prog; 16384 const struct btf *btf = prog->aux->btf; 16385 struct bpf_core_ctx ctx = { 16386 .log = &env->log, 16387 .btf = btf, 16388 }; 16389 bpfptr_t u_core_relo; 16390 int err; 16391 16392 nr_core_relo = attr->core_relo_cnt; 16393 if (!nr_core_relo) 16394 return 0; 16395 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 16396 return -EINVAL; 16397 16398 rec_size = attr->core_relo_rec_size; 16399 if (rec_size < MIN_CORE_RELO_SIZE || 16400 rec_size > MAX_CORE_RELO_SIZE || 16401 rec_size % sizeof(u32)) 16402 return -EINVAL; 16403 16404 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 16405 expected_size = sizeof(struct bpf_core_relo); 16406 ncopy = min_t(u32, expected_size, rec_size); 16407 16408 /* Unlike func_info and line_info, copy and apply each CO-RE 16409 * relocation record one at a time. 16410 */ 16411 for (i = 0; i < nr_core_relo; i++) { 16412 /* future proofing when sizeof(bpf_core_relo) changes */ 16413 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 16414 if (err) { 16415 if (err == -E2BIG) { 16416 verbose(env, "nonzero tailing record in core_relo"); 16417 if (copy_to_bpfptr_offset(uattr, 16418 offsetof(union bpf_attr, core_relo_rec_size), 16419 &expected_size, sizeof(expected_size))) 16420 err = -EFAULT; 16421 } 16422 break; 16423 } 16424 16425 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 16426 err = -EFAULT; 16427 break; 16428 } 16429 16430 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 16431 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 16432 i, core_relo.insn_off, prog->len); 16433 err = -EINVAL; 16434 break; 16435 } 16436 16437 err = bpf_core_apply(&ctx, &core_relo, i, 16438 &prog->insnsi[core_relo.insn_off / 8]); 16439 if (err) 16440 break; 16441 bpfptr_add(&u_core_relo, rec_size); 16442 } 16443 return err; 16444 } 16445 16446 static int check_btf_info_early(struct bpf_verifier_env *env, 16447 const union bpf_attr *attr, 16448 bpfptr_t uattr) 16449 { 16450 struct btf *btf; 16451 int err; 16452 16453 if (!attr->func_info_cnt && !attr->line_info_cnt) { 16454 if (check_abnormal_return(env)) 16455 return -EINVAL; 16456 return 0; 16457 } 16458 16459 btf = btf_get_by_fd(attr->prog_btf_fd); 16460 if (IS_ERR(btf)) 16461 return PTR_ERR(btf); 16462 if (btf_is_kernel(btf)) { 16463 btf_put(btf); 16464 return -EACCES; 16465 } 16466 env->prog->aux->btf = btf; 16467 16468 err = check_btf_func_early(env, attr, uattr); 16469 if (err) 16470 return err; 16471 return 0; 16472 } 16473 16474 static int check_btf_info(struct bpf_verifier_env *env, 16475 const union bpf_attr *attr, 16476 bpfptr_t uattr) 16477 { 16478 int err; 16479 16480 if (!attr->func_info_cnt && !attr->line_info_cnt) { 16481 if (check_abnormal_return(env)) 16482 return -EINVAL; 16483 return 0; 16484 } 16485 16486 err = check_btf_func(env, attr, uattr); 16487 if (err) 16488 return err; 16489 16490 err = check_btf_line(env, attr, uattr); 16491 if (err) 16492 return err; 16493 16494 err = check_core_relo(env, attr, uattr); 16495 if (err) 16496 return err; 16497 16498 return 0; 16499 } 16500 16501 /* check %cur's range satisfies %old's */ 16502 static bool range_within(const struct bpf_reg_state *old, 16503 const struct bpf_reg_state *cur) 16504 { 16505 return old->umin_value <= cur->umin_value && 16506 old->umax_value >= cur->umax_value && 16507 old->smin_value <= cur->smin_value && 16508 old->smax_value >= cur->smax_value && 16509 old->u32_min_value <= cur->u32_min_value && 16510 old->u32_max_value >= cur->u32_max_value && 16511 old->s32_min_value <= cur->s32_min_value && 16512 old->s32_max_value >= cur->s32_max_value; 16513 } 16514 16515 /* If in the old state two registers had the same id, then they need to have 16516 * the same id in the new state as well. But that id could be different from 16517 * the old state, so we need to track the mapping from old to new ids. 16518 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 16519 * regs with old id 5 must also have new id 9 for the new state to be safe. But 16520 * regs with a different old id could still have new id 9, we don't care about 16521 * that. 16522 * So we look through our idmap to see if this old id has been seen before. If 16523 * so, we require the new id to match; otherwise, we add the id pair to the map. 16524 */ 16525 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 16526 { 16527 struct bpf_id_pair *map = idmap->map; 16528 unsigned int i; 16529 16530 /* either both IDs should be set or both should be zero */ 16531 if (!!old_id != !!cur_id) 16532 return false; 16533 16534 if (old_id == 0) /* cur_id == 0 as well */ 16535 return true; 16536 16537 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 16538 if (!map[i].old) { 16539 /* Reached an empty slot; haven't seen this id before */ 16540 map[i].old = old_id; 16541 map[i].cur = cur_id; 16542 return true; 16543 } 16544 if (map[i].old == old_id) 16545 return map[i].cur == cur_id; 16546 if (map[i].cur == cur_id) 16547 return false; 16548 } 16549 /* We ran out of idmap slots, which should be impossible */ 16550 WARN_ON_ONCE(1); 16551 return false; 16552 } 16553 16554 /* Similar to check_ids(), but allocate a unique temporary ID 16555 * for 'old_id' or 'cur_id' of zero. 16556 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 16557 */ 16558 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 16559 { 16560 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 16561 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 16562 16563 return check_ids(old_id, cur_id, idmap); 16564 } 16565 16566 static void clean_func_state(struct bpf_verifier_env *env, 16567 struct bpf_func_state *st) 16568 { 16569 enum bpf_reg_liveness live; 16570 int i, j; 16571 16572 for (i = 0; i < BPF_REG_FP; i++) { 16573 live = st->regs[i].live; 16574 /* liveness must not touch this register anymore */ 16575 st->regs[i].live |= REG_LIVE_DONE; 16576 if (!(live & REG_LIVE_READ)) 16577 /* since the register is unused, clear its state 16578 * to make further comparison simpler 16579 */ 16580 __mark_reg_not_init(env, &st->regs[i]); 16581 } 16582 16583 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 16584 live = st->stack[i].spilled_ptr.live; 16585 /* liveness must not touch this stack slot anymore */ 16586 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 16587 if (!(live & REG_LIVE_READ)) { 16588 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 16589 for (j = 0; j < BPF_REG_SIZE; j++) 16590 st->stack[i].slot_type[j] = STACK_INVALID; 16591 } 16592 } 16593 } 16594 16595 static void clean_verifier_state(struct bpf_verifier_env *env, 16596 struct bpf_verifier_state *st) 16597 { 16598 int i; 16599 16600 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 16601 /* all regs in this state in all frames were already marked */ 16602 return; 16603 16604 for (i = 0; i <= st->curframe; i++) 16605 clean_func_state(env, st->frame[i]); 16606 } 16607 16608 /* the parentage chains form a tree. 16609 * the verifier states are added to state lists at given insn and 16610 * pushed into state stack for future exploration. 16611 * when the verifier reaches bpf_exit insn some of the verifer states 16612 * stored in the state lists have their final liveness state already, 16613 * but a lot of states will get revised from liveness point of view when 16614 * the verifier explores other branches. 16615 * Example: 16616 * 1: r0 = 1 16617 * 2: if r1 == 100 goto pc+1 16618 * 3: r0 = 2 16619 * 4: exit 16620 * when the verifier reaches exit insn the register r0 in the state list of 16621 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 16622 * of insn 2 and goes exploring further. At the insn 4 it will walk the 16623 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 16624 * 16625 * Since the verifier pushes the branch states as it sees them while exploring 16626 * the program the condition of walking the branch instruction for the second 16627 * time means that all states below this branch were already explored and 16628 * their final liveness marks are already propagated. 16629 * Hence when the verifier completes the search of state list in is_state_visited() 16630 * we can call this clean_live_states() function to mark all liveness states 16631 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 16632 * will not be used. 16633 * This function also clears the registers and stack for states that !READ 16634 * to simplify state merging. 16635 * 16636 * Important note here that walking the same branch instruction in the callee 16637 * doesn't meant that the states are DONE. The verifier has to compare 16638 * the callsites 16639 */ 16640 static void clean_live_states(struct bpf_verifier_env *env, int insn, 16641 struct bpf_verifier_state *cur) 16642 { 16643 struct bpf_verifier_state_list *sl; 16644 16645 sl = *explored_state(env, insn); 16646 while (sl) { 16647 if (sl->state.branches) 16648 goto next; 16649 if (sl->state.insn_idx != insn || 16650 !same_callsites(&sl->state, cur)) 16651 goto next; 16652 clean_verifier_state(env, &sl->state); 16653 next: 16654 sl = sl->next; 16655 } 16656 } 16657 16658 static bool regs_exact(const struct bpf_reg_state *rold, 16659 const struct bpf_reg_state *rcur, 16660 struct bpf_idmap *idmap) 16661 { 16662 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16663 check_ids(rold->id, rcur->id, idmap) && 16664 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16665 } 16666 16667 enum exact_level { 16668 NOT_EXACT, 16669 EXACT, 16670 RANGE_WITHIN 16671 }; 16672 16673 /* Returns true if (rold safe implies rcur safe) */ 16674 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 16675 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, 16676 enum exact_level exact) 16677 { 16678 if (exact == EXACT) 16679 return regs_exact(rold, rcur, idmap); 16680 16681 if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT) 16682 /* explored state didn't use this */ 16683 return true; 16684 if (rold->type == NOT_INIT) { 16685 if (exact == NOT_EXACT || rcur->type == NOT_INIT) 16686 /* explored state can't have used this */ 16687 return true; 16688 } 16689 16690 /* Enforce that register types have to match exactly, including their 16691 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 16692 * rule. 16693 * 16694 * One can make a point that using a pointer register as unbounded 16695 * SCALAR would be technically acceptable, but this could lead to 16696 * pointer leaks because scalars are allowed to leak while pointers 16697 * are not. We could make this safe in special cases if root is 16698 * calling us, but it's probably not worth the hassle. 16699 * 16700 * Also, register types that are *not* MAYBE_NULL could technically be 16701 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 16702 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 16703 * to the same map). 16704 * However, if the old MAYBE_NULL register then got NULL checked, 16705 * doing so could have affected others with the same id, and we can't 16706 * check for that because we lost the id when we converted to 16707 * a non-MAYBE_NULL variant. 16708 * So, as a general rule we don't allow mixing MAYBE_NULL and 16709 * non-MAYBE_NULL registers as well. 16710 */ 16711 if (rold->type != rcur->type) 16712 return false; 16713 16714 switch (base_type(rold->type)) { 16715 case SCALAR_VALUE: 16716 if (env->explore_alu_limits) { 16717 /* explore_alu_limits disables tnum_in() and range_within() 16718 * logic and requires everything to be strict 16719 */ 16720 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16721 check_scalar_ids(rold->id, rcur->id, idmap); 16722 } 16723 if (!rold->precise && exact == NOT_EXACT) 16724 return true; 16725 /* Why check_ids() for scalar registers? 16726 * 16727 * Consider the following BPF code: 16728 * 1: r6 = ... unbound scalar, ID=a ... 16729 * 2: r7 = ... unbound scalar, ID=b ... 16730 * 3: if (r6 > r7) goto +1 16731 * 4: r6 = r7 16732 * 5: if (r6 > X) goto ... 16733 * 6: ... memory operation using r7 ... 16734 * 16735 * First verification path is [1-6]: 16736 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 16737 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark 16738 * r7 <= X, because r6 and r7 share same id. 16739 * Next verification path is [1-4, 6]. 16740 * 16741 * Instruction (6) would be reached in two states: 16742 * I. r6{.id=b}, r7{.id=b} via path 1-6; 16743 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 16744 * 16745 * Use check_ids() to distinguish these states. 16746 * --- 16747 * Also verify that new value satisfies old value range knowledge. 16748 */ 16749 return range_within(rold, rcur) && 16750 tnum_in(rold->var_off, rcur->var_off) && 16751 check_scalar_ids(rold->id, rcur->id, idmap); 16752 case PTR_TO_MAP_KEY: 16753 case PTR_TO_MAP_VALUE: 16754 case PTR_TO_MEM: 16755 case PTR_TO_BUF: 16756 case PTR_TO_TP_BUFFER: 16757 /* If the new min/max/var_off satisfy the old ones and 16758 * everything else matches, we are OK. 16759 */ 16760 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 16761 range_within(rold, rcur) && 16762 tnum_in(rold->var_off, rcur->var_off) && 16763 check_ids(rold->id, rcur->id, idmap) && 16764 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16765 case PTR_TO_PACKET_META: 16766 case PTR_TO_PACKET: 16767 /* We must have at least as much range as the old ptr 16768 * did, so that any accesses which were safe before are 16769 * still safe. This is true even if old range < old off, 16770 * since someone could have accessed through (ptr - k), or 16771 * even done ptr -= k in a register, to get a safe access. 16772 */ 16773 if (rold->range > rcur->range) 16774 return false; 16775 /* If the offsets don't match, we can't trust our alignment; 16776 * nor can we be sure that we won't fall out of range. 16777 */ 16778 if (rold->off != rcur->off) 16779 return false; 16780 /* id relations must be preserved */ 16781 if (!check_ids(rold->id, rcur->id, idmap)) 16782 return false; 16783 /* new val must satisfy old val knowledge */ 16784 return range_within(rold, rcur) && 16785 tnum_in(rold->var_off, rcur->var_off); 16786 case PTR_TO_STACK: 16787 /* two stack pointers are equal only if they're pointing to 16788 * the same stack frame, since fp-8 in foo != fp-8 in bar 16789 */ 16790 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 16791 case PTR_TO_ARENA: 16792 return true; 16793 default: 16794 return regs_exact(rold, rcur, idmap); 16795 } 16796 } 16797 16798 static struct bpf_reg_state unbound_reg; 16799 16800 static __init int unbound_reg_init(void) 16801 { 16802 __mark_reg_unknown_imprecise(&unbound_reg); 16803 unbound_reg.live |= REG_LIVE_READ; 16804 return 0; 16805 } 16806 late_initcall(unbound_reg_init); 16807 16808 static bool is_stack_all_misc(struct bpf_verifier_env *env, 16809 struct bpf_stack_state *stack) 16810 { 16811 u32 i; 16812 16813 for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) { 16814 if ((stack->slot_type[i] == STACK_MISC) || 16815 (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack)) 16816 continue; 16817 return false; 16818 } 16819 16820 return true; 16821 } 16822 16823 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env, 16824 struct bpf_stack_state *stack) 16825 { 16826 if (is_spilled_scalar_reg64(stack)) 16827 return &stack->spilled_ptr; 16828 16829 if (is_stack_all_misc(env, stack)) 16830 return &unbound_reg; 16831 16832 return NULL; 16833 } 16834 16835 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 16836 struct bpf_func_state *cur, struct bpf_idmap *idmap, 16837 enum exact_level exact) 16838 { 16839 int i, spi; 16840 16841 /* walk slots of the explored stack and ignore any additional 16842 * slots in the current stack, since explored(safe) state 16843 * didn't use them 16844 */ 16845 for (i = 0; i < old->allocated_stack; i++) { 16846 struct bpf_reg_state *old_reg, *cur_reg; 16847 16848 spi = i / BPF_REG_SIZE; 16849 16850 if (exact != NOT_EXACT && 16851 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16852 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16853 return false; 16854 16855 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) 16856 && exact == NOT_EXACT) { 16857 i += BPF_REG_SIZE - 1; 16858 /* explored state didn't use this */ 16859 continue; 16860 } 16861 16862 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 16863 continue; 16864 16865 if (env->allow_uninit_stack && 16866 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 16867 continue; 16868 16869 /* explored stack has more populated slots than current stack 16870 * and these slots were used 16871 */ 16872 if (i >= cur->allocated_stack) 16873 return false; 16874 16875 /* 64-bit scalar spill vs all slots MISC and vice versa. 16876 * Load from all slots MISC produces unbound scalar. 16877 * Construct a fake register for such stack and call 16878 * regsafe() to ensure scalar ids are compared. 16879 */ 16880 old_reg = scalar_reg_for_stack(env, &old->stack[spi]); 16881 cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]); 16882 if (old_reg && cur_reg) { 16883 if (!regsafe(env, old_reg, cur_reg, idmap, exact)) 16884 return false; 16885 i += BPF_REG_SIZE - 1; 16886 continue; 16887 } 16888 16889 /* if old state was safe with misc data in the stack 16890 * it will be safe with zero-initialized stack. 16891 * The opposite is not true 16892 */ 16893 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 16894 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 16895 continue; 16896 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16897 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16898 /* Ex: old explored (safe) state has STACK_SPILL in 16899 * this stack slot, but current has STACK_MISC -> 16900 * this verifier states are not equivalent, 16901 * return false to continue verification of this path 16902 */ 16903 return false; 16904 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 16905 continue; 16906 /* Both old and cur are having same slot_type */ 16907 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 16908 case STACK_SPILL: 16909 /* when explored and current stack slot are both storing 16910 * spilled registers, check that stored pointers types 16911 * are the same as well. 16912 * Ex: explored safe path could have stored 16913 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 16914 * but current path has stored: 16915 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 16916 * such verifier states are not equivalent. 16917 * return false to continue verification of this path 16918 */ 16919 if (!regsafe(env, &old->stack[spi].spilled_ptr, 16920 &cur->stack[spi].spilled_ptr, idmap, exact)) 16921 return false; 16922 break; 16923 case STACK_DYNPTR: 16924 old_reg = &old->stack[spi].spilled_ptr; 16925 cur_reg = &cur->stack[spi].spilled_ptr; 16926 if (old_reg->dynptr.type != cur_reg->dynptr.type || 16927 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 16928 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16929 return false; 16930 break; 16931 case STACK_ITER: 16932 old_reg = &old->stack[spi].spilled_ptr; 16933 cur_reg = &cur->stack[spi].spilled_ptr; 16934 /* iter.depth is not compared between states as it 16935 * doesn't matter for correctness and would otherwise 16936 * prevent convergence; we maintain it only to prevent 16937 * infinite loop check triggering, see 16938 * iter_active_depths_differ() 16939 */ 16940 if (old_reg->iter.btf != cur_reg->iter.btf || 16941 old_reg->iter.btf_id != cur_reg->iter.btf_id || 16942 old_reg->iter.state != cur_reg->iter.state || 16943 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 16944 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16945 return false; 16946 break; 16947 case STACK_MISC: 16948 case STACK_ZERO: 16949 case STACK_INVALID: 16950 continue; 16951 /* Ensure that new unhandled slot types return false by default */ 16952 default: 16953 return false; 16954 } 16955 } 16956 return true; 16957 } 16958 16959 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 16960 struct bpf_idmap *idmap) 16961 { 16962 int i; 16963 16964 if (old->acquired_refs != cur->acquired_refs) 16965 return false; 16966 16967 for (i = 0; i < old->acquired_refs; i++) { 16968 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 16969 return false; 16970 } 16971 16972 return true; 16973 } 16974 16975 /* compare two verifier states 16976 * 16977 * all states stored in state_list are known to be valid, since 16978 * verifier reached 'bpf_exit' instruction through them 16979 * 16980 * this function is called when verifier exploring different branches of 16981 * execution popped from the state stack. If it sees an old state that has 16982 * more strict register state and more strict stack state then this execution 16983 * branch doesn't need to be explored further, since verifier already 16984 * concluded that more strict state leads to valid finish. 16985 * 16986 * Therefore two states are equivalent if register state is more conservative 16987 * and explored stack state is more conservative than the current one. 16988 * Example: 16989 * explored current 16990 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 16991 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 16992 * 16993 * In other words if current stack state (one being explored) has more 16994 * valid slots than old one that already passed validation, it means 16995 * the verifier can stop exploring and conclude that current state is valid too 16996 * 16997 * Similarly with registers. If explored state has register type as invalid 16998 * whereas register type in current state is meaningful, it means that 16999 * the current state will reach 'bpf_exit' instruction safely 17000 */ 17001 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 17002 struct bpf_func_state *cur, enum exact_level exact) 17003 { 17004 int i; 17005 17006 if (old->callback_depth > cur->callback_depth) 17007 return false; 17008 17009 for (i = 0; i < MAX_BPF_REG; i++) 17010 if (!regsafe(env, &old->regs[i], &cur->regs[i], 17011 &env->idmap_scratch, exact)) 17012 return false; 17013 17014 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 17015 return false; 17016 17017 if (!refsafe(old, cur, &env->idmap_scratch)) 17018 return false; 17019 17020 return true; 17021 } 17022 17023 static void reset_idmap_scratch(struct bpf_verifier_env *env) 17024 { 17025 env->idmap_scratch.tmp_id_gen = env->id_gen; 17026 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 17027 } 17028 17029 static bool states_equal(struct bpf_verifier_env *env, 17030 struct bpf_verifier_state *old, 17031 struct bpf_verifier_state *cur, 17032 enum exact_level exact) 17033 { 17034 int i; 17035 17036 if (old->curframe != cur->curframe) 17037 return false; 17038 17039 reset_idmap_scratch(env); 17040 17041 /* Verification state from speculative execution simulation 17042 * must never prune a non-speculative execution one. 17043 */ 17044 if (old->speculative && !cur->speculative) 17045 return false; 17046 17047 if (old->active_lock.ptr != cur->active_lock.ptr) 17048 return false; 17049 17050 /* Old and cur active_lock's have to be either both present 17051 * or both absent. 17052 */ 17053 if (!!old->active_lock.id != !!cur->active_lock.id) 17054 return false; 17055 17056 if (old->active_lock.id && 17057 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch)) 17058 return false; 17059 17060 if (old->active_rcu_lock != cur->active_rcu_lock) 17061 return false; 17062 17063 if (old->active_preempt_lock != cur->active_preempt_lock) 17064 return false; 17065 17066 if (old->in_sleepable != cur->in_sleepable) 17067 return false; 17068 17069 /* for states to be equal callsites have to be the same 17070 * and all frame states need to be equivalent 17071 */ 17072 for (i = 0; i <= old->curframe; i++) { 17073 if (old->frame[i]->callsite != cur->frame[i]->callsite) 17074 return false; 17075 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact)) 17076 return false; 17077 } 17078 return true; 17079 } 17080 17081 /* Return 0 if no propagation happened. Return negative error code if error 17082 * happened. Otherwise, return the propagated bit. 17083 */ 17084 static int propagate_liveness_reg(struct bpf_verifier_env *env, 17085 struct bpf_reg_state *reg, 17086 struct bpf_reg_state *parent_reg) 17087 { 17088 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 17089 u8 flag = reg->live & REG_LIVE_READ; 17090 int err; 17091 17092 /* When comes here, read flags of PARENT_REG or REG could be any of 17093 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 17094 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 17095 */ 17096 if (parent_flag == REG_LIVE_READ64 || 17097 /* Or if there is no read flag from REG. */ 17098 !flag || 17099 /* Or if the read flag from REG is the same as PARENT_REG. */ 17100 parent_flag == flag) 17101 return 0; 17102 17103 err = mark_reg_read(env, reg, parent_reg, flag); 17104 if (err) 17105 return err; 17106 17107 return flag; 17108 } 17109 17110 /* A write screens off any subsequent reads; but write marks come from the 17111 * straight-line code between a state and its parent. When we arrive at an 17112 * equivalent state (jump target or such) we didn't arrive by the straight-line 17113 * code, so read marks in the state must propagate to the parent regardless 17114 * of the state's write marks. That's what 'parent == state->parent' comparison 17115 * in mark_reg_read() is for. 17116 */ 17117 static int propagate_liveness(struct bpf_verifier_env *env, 17118 const struct bpf_verifier_state *vstate, 17119 struct bpf_verifier_state *vparent) 17120 { 17121 struct bpf_reg_state *state_reg, *parent_reg; 17122 struct bpf_func_state *state, *parent; 17123 int i, frame, err = 0; 17124 17125 if (vparent->curframe != vstate->curframe) { 17126 WARN(1, "propagate_live: parent frame %d current frame %d\n", 17127 vparent->curframe, vstate->curframe); 17128 return -EFAULT; 17129 } 17130 /* Propagate read liveness of registers... */ 17131 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 17132 for (frame = 0; frame <= vstate->curframe; frame++) { 17133 parent = vparent->frame[frame]; 17134 state = vstate->frame[frame]; 17135 parent_reg = parent->regs; 17136 state_reg = state->regs; 17137 /* We don't need to worry about FP liveness, it's read-only */ 17138 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 17139 err = propagate_liveness_reg(env, &state_reg[i], 17140 &parent_reg[i]); 17141 if (err < 0) 17142 return err; 17143 if (err == REG_LIVE_READ64) 17144 mark_insn_zext(env, &parent_reg[i]); 17145 } 17146 17147 /* Propagate stack slots. */ 17148 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 17149 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 17150 parent_reg = &parent->stack[i].spilled_ptr; 17151 state_reg = &state->stack[i].spilled_ptr; 17152 err = propagate_liveness_reg(env, state_reg, 17153 parent_reg); 17154 if (err < 0) 17155 return err; 17156 } 17157 } 17158 return 0; 17159 } 17160 17161 /* find precise scalars in the previous equivalent state and 17162 * propagate them into the current state 17163 */ 17164 static int propagate_precision(struct bpf_verifier_env *env, 17165 const struct bpf_verifier_state *old) 17166 { 17167 struct bpf_reg_state *state_reg; 17168 struct bpf_func_state *state; 17169 int i, err = 0, fr; 17170 bool first; 17171 17172 for (fr = old->curframe; fr >= 0; fr--) { 17173 state = old->frame[fr]; 17174 state_reg = state->regs; 17175 first = true; 17176 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 17177 if (state_reg->type != SCALAR_VALUE || 17178 !state_reg->precise || 17179 !(state_reg->live & REG_LIVE_READ)) 17180 continue; 17181 if (env->log.level & BPF_LOG_LEVEL2) { 17182 if (first) 17183 verbose(env, "frame %d: propagating r%d", fr, i); 17184 else 17185 verbose(env, ",r%d", i); 17186 } 17187 bt_set_frame_reg(&env->bt, fr, i); 17188 first = false; 17189 } 17190 17191 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 17192 if (!is_spilled_reg(&state->stack[i])) 17193 continue; 17194 state_reg = &state->stack[i].spilled_ptr; 17195 if (state_reg->type != SCALAR_VALUE || 17196 !state_reg->precise || 17197 !(state_reg->live & REG_LIVE_READ)) 17198 continue; 17199 if (env->log.level & BPF_LOG_LEVEL2) { 17200 if (first) 17201 verbose(env, "frame %d: propagating fp%d", 17202 fr, (-i - 1) * BPF_REG_SIZE); 17203 else 17204 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 17205 } 17206 bt_set_frame_slot(&env->bt, fr, i); 17207 first = false; 17208 } 17209 if (!first) 17210 verbose(env, "\n"); 17211 } 17212 17213 err = mark_chain_precision_batch(env); 17214 if (err < 0) 17215 return err; 17216 17217 return 0; 17218 } 17219 17220 static bool states_maybe_looping(struct bpf_verifier_state *old, 17221 struct bpf_verifier_state *cur) 17222 { 17223 struct bpf_func_state *fold, *fcur; 17224 int i, fr = cur->curframe; 17225 17226 if (old->curframe != fr) 17227 return false; 17228 17229 fold = old->frame[fr]; 17230 fcur = cur->frame[fr]; 17231 for (i = 0; i < MAX_BPF_REG; i++) 17232 if (memcmp(&fold->regs[i], &fcur->regs[i], 17233 offsetof(struct bpf_reg_state, parent))) 17234 return false; 17235 return true; 17236 } 17237 17238 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 17239 { 17240 return env->insn_aux_data[insn_idx].is_iter_next; 17241 } 17242 17243 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 17244 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 17245 * states to match, which otherwise would look like an infinite loop. So while 17246 * iter_next() calls are taken care of, we still need to be careful and 17247 * prevent erroneous and too eager declaration of "ininite loop", when 17248 * iterators are involved. 17249 * 17250 * Here's a situation in pseudo-BPF assembly form: 17251 * 17252 * 0: again: ; set up iter_next() call args 17253 * 1: r1 = &it ; <CHECKPOINT HERE> 17254 * 2: call bpf_iter_num_next ; this is iter_next() call 17255 * 3: if r0 == 0 goto done 17256 * 4: ... something useful here ... 17257 * 5: goto again ; another iteration 17258 * 6: done: 17259 * 7: r1 = &it 17260 * 8: call bpf_iter_num_destroy ; clean up iter state 17261 * 9: exit 17262 * 17263 * This is a typical loop. Let's assume that we have a prune point at 1:, 17264 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 17265 * again`, assuming other heuristics don't get in a way). 17266 * 17267 * When we first time come to 1:, let's say we have some state X. We proceed 17268 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 17269 * Now we come back to validate that forked ACTIVE state. We proceed through 17270 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 17271 * are converging. But the problem is that we don't know that yet, as this 17272 * convergence has to happen at iter_next() call site only. So if nothing is 17273 * done, at 1: verifier will use bounded loop logic and declare infinite 17274 * looping (and would be *technically* correct, if not for iterator's 17275 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 17276 * don't want that. So what we do in process_iter_next_call() when we go on 17277 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 17278 * a different iteration. So when we suspect an infinite loop, we additionally 17279 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 17280 * pretend we are not looping and wait for next iter_next() call. 17281 * 17282 * This only applies to ACTIVE state. In DRAINED state we don't expect to 17283 * loop, because that would actually mean infinite loop, as DRAINED state is 17284 * "sticky", and so we'll keep returning into the same instruction with the 17285 * same state (at least in one of possible code paths). 17286 * 17287 * This approach allows to keep infinite loop heuristic even in the face of 17288 * active iterator. E.g., C snippet below is and will be detected as 17289 * inifintely looping: 17290 * 17291 * struct bpf_iter_num it; 17292 * int *p, x; 17293 * 17294 * bpf_iter_num_new(&it, 0, 10); 17295 * while ((p = bpf_iter_num_next(&t))) { 17296 * x = p; 17297 * while (x--) {} // <<-- infinite loop here 17298 * } 17299 * 17300 */ 17301 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 17302 { 17303 struct bpf_reg_state *slot, *cur_slot; 17304 struct bpf_func_state *state; 17305 int i, fr; 17306 17307 for (fr = old->curframe; fr >= 0; fr--) { 17308 state = old->frame[fr]; 17309 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 17310 if (state->stack[i].slot_type[0] != STACK_ITER) 17311 continue; 17312 17313 slot = &state->stack[i].spilled_ptr; 17314 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 17315 continue; 17316 17317 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 17318 if (cur_slot->iter.depth != slot->iter.depth) 17319 return true; 17320 } 17321 } 17322 return false; 17323 } 17324 17325 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 17326 { 17327 struct bpf_verifier_state_list *new_sl; 17328 struct bpf_verifier_state_list *sl, **pprev; 17329 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry; 17330 int i, j, n, err, states_cnt = 0; 17331 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx); 17332 bool add_new_state = force_new_state; 17333 bool force_exact; 17334 17335 /* bpf progs typically have pruning point every 4 instructions 17336 * http://vger.kernel.org/bpfconf2019.html#session-1 17337 * Do not add new state for future pruning if the verifier hasn't seen 17338 * at least 2 jumps and at least 8 instructions. 17339 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 17340 * In tests that amounts to up to 50% reduction into total verifier 17341 * memory consumption and 20% verifier time speedup. 17342 */ 17343 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 17344 env->insn_processed - env->prev_insn_processed >= 8) 17345 add_new_state = true; 17346 17347 pprev = explored_state(env, insn_idx); 17348 sl = *pprev; 17349 17350 clean_live_states(env, insn_idx, cur); 17351 17352 while (sl) { 17353 states_cnt++; 17354 if (sl->state.insn_idx != insn_idx) 17355 goto next; 17356 17357 if (sl->state.branches) { 17358 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 17359 17360 if (frame->in_async_callback_fn && 17361 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 17362 /* Different async_entry_cnt means that the verifier is 17363 * processing another entry into async callback. 17364 * Seeing the same state is not an indication of infinite 17365 * loop or infinite recursion. 17366 * But finding the same state doesn't mean that it's safe 17367 * to stop processing the current state. The previous state 17368 * hasn't yet reached bpf_exit, since state.branches > 0. 17369 * Checking in_async_callback_fn alone is not enough either. 17370 * Since the verifier still needs to catch infinite loops 17371 * inside async callbacks. 17372 */ 17373 goto skip_inf_loop_check; 17374 } 17375 /* BPF open-coded iterators loop detection is special. 17376 * states_maybe_looping() logic is too simplistic in detecting 17377 * states that *might* be equivalent, because it doesn't know 17378 * about ID remapping, so don't even perform it. 17379 * See process_iter_next_call() and iter_active_depths_differ() 17380 * for overview of the logic. When current and one of parent 17381 * states are detected as equivalent, it's a good thing: we prove 17382 * convergence and can stop simulating further iterations. 17383 * It's safe to assume that iterator loop will finish, taking into 17384 * account iter_next() contract of eventually returning 17385 * sticky NULL result. 17386 * 17387 * Note, that states have to be compared exactly in this case because 17388 * read and precision marks might not be finalized inside the loop. 17389 * E.g. as in the program below: 17390 * 17391 * 1. r7 = -16 17392 * 2. r6 = bpf_get_prandom_u32() 17393 * 3. while (bpf_iter_num_next(&fp[-8])) { 17394 * 4. if (r6 != 42) { 17395 * 5. r7 = -32 17396 * 6. r6 = bpf_get_prandom_u32() 17397 * 7. continue 17398 * 8. } 17399 * 9. r0 = r10 17400 * 10. r0 += r7 17401 * 11. r8 = *(u64 *)(r0 + 0) 17402 * 12. r6 = bpf_get_prandom_u32() 17403 * 13. } 17404 * 17405 * Here verifier would first visit path 1-3, create a checkpoint at 3 17406 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 17407 * not have read or precision mark for r7 yet, thus inexact states 17408 * comparison would discard current state with r7=-32 17409 * => unsafe memory access at 11 would not be caught. 17410 */ 17411 if (is_iter_next_insn(env, insn_idx)) { 17412 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 17413 struct bpf_func_state *cur_frame; 17414 struct bpf_reg_state *iter_state, *iter_reg; 17415 int spi; 17416 17417 cur_frame = cur->frame[cur->curframe]; 17418 /* btf_check_iter_kfuncs() enforces that 17419 * iter state pointer is always the first arg 17420 */ 17421 iter_reg = &cur_frame->regs[BPF_REG_1]; 17422 /* current state is valid due to states_equal(), 17423 * so we can assume valid iter and reg state, 17424 * no need for extra (re-)validations 17425 */ 17426 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 17427 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 17428 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 17429 update_loop_entry(cur, &sl->state); 17430 goto hit; 17431 } 17432 } 17433 goto skip_inf_loop_check; 17434 } 17435 if (is_may_goto_insn_at(env, insn_idx)) { 17436 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 17437 update_loop_entry(cur, &sl->state); 17438 goto hit; 17439 } 17440 goto skip_inf_loop_check; 17441 } 17442 if (calls_callback(env, insn_idx)) { 17443 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) 17444 goto hit; 17445 goto skip_inf_loop_check; 17446 } 17447 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 17448 if (states_maybe_looping(&sl->state, cur) && 17449 states_equal(env, &sl->state, cur, EXACT) && 17450 !iter_active_depths_differ(&sl->state, cur) && 17451 sl->state.may_goto_depth == cur->may_goto_depth && 17452 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 17453 verbose_linfo(env, insn_idx, "; "); 17454 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 17455 verbose(env, "cur state:"); 17456 print_verifier_state(env, cur->frame[cur->curframe], true); 17457 verbose(env, "old state:"); 17458 print_verifier_state(env, sl->state.frame[cur->curframe], true); 17459 return -EINVAL; 17460 } 17461 /* if the verifier is processing a loop, avoid adding new state 17462 * too often, since different loop iterations have distinct 17463 * states and may not help future pruning. 17464 * This threshold shouldn't be too low to make sure that 17465 * a loop with large bound will be rejected quickly. 17466 * The most abusive loop will be: 17467 * r1 += 1 17468 * if r1 < 1000000 goto pc-2 17469 * 1M insn_procssed limit / 100 == 10k peak states. 17470 * This threshold shouldn't be too high either, since states 17471 * at the end of the loop are likely to be useful in pruning. 17472 */ 17473 skip_inf_loop_check: 17474 if (!force_new_state && 17475 env->jmps_processed - env->prev_jmps_processed < 20 && 17476 env->insn_processed - env->prev_insn_processed < 100) 17477 add_new_state = false; 17478 goto miss; 17479 } 17480 /* If sl->state is a part of a loop and this loop's entry is a part of 17481 * current verification path then states have to be compared exactly. 17482 * 'force_exact' is needed to catch the following case: 17483 * 17484 * initial Here state 'succ' was processed first, 17485 * | it was eventually tracked to produce a 17486 * V state identical to 'hdr'. 17487 * .---------> hdr All branches from 'succ' had been explored 17488 * | | and thus 'succ' has its .branches == 0. 17489 * | V 17490 * | .------... Suppose states 'cur' and 'succ' correspond 17491 * | | | to the same instruction + callsites. 17492 * | V V In such case it is necessary to check 17493 * | ... ... if 'succ' and 'cur' are states_equal(). 17494 * | | | If 'succ' and 'cur' are a part of the 17495 * | V V same loop exact flag has to be set. 17496 * | succ <- cur To check if that is the case, verify 17497 * | | if loop entry of 'succ' is in current 17498 * | V DFS path. 17499 * | ... 17500 * | | 17501 * '----' 17502 * 17503 * Additional details are in the comment before get_loop_entry(). 17504 */ 17505 loop_entry = get_loop_entry(&sl->state); 17506 force_exact = loop_entry && loop_entry->branches > 0; 17507 if (states_equal(env, &sl->state, cur, force_exact ? RANGE_WITHIN : NOT_EXACT)) { 17508 if (force_exact) 17509 update_loop_entry(cur, loop_entry); 17510 hit: 17511 sl->hit_cnt++; 17512 /* reached equivalent register/stack state, 17513 * prune the search. 17514 * Registers read by the continuation are read by us. 17515 * If we have any write marks in env->cur_state, they 17516 * will prevent corresponding reads in the continuation 17517 * from reaching our parent (an explored_state). Our 17518 * own state will get the read marks recorded, but 17519 * they'll be immediately forgotten as we're pruning 17520 * this state and will pop a new one. 17521 */ 17522 err = propagate_liveness(env, &sl->state, cur); 17523 17524 /* if previous state reached the exit with precision and 17525 * current state is equivalent to it (except precision marks) 17526 * the precision needs to be propagated back in 17527 * the current state. 17528 */ 17529 if (is_jmp_point(env, env->insn_idx)) 17530 err = err ? : push_jmp_history(env, cur, 0); 17531 err = err ? : propagate_precision(env, &sl->state); 17532 if (err) 17533 return err; 17534 return 1; 17535 } 17536 miss: 17537 /* when new state is not going to be added do not increase miss count. 17538 * Otherwise several loop iterations will remove the state 17539 * recorded earlier. The goal of these heuristics is to have 17540 * states from some iterations of the loop (some in the beginning 17541 * and some at the end) to help pruning. 17542 */ 17543 if (add_new_state) 17544 sl->miss_cnt++; 17545 /* heuristic to determine whether this state is beneficial 17546 * to keep checking from state equivalence point of view. 17547 * Higher numbers increase max_states_per_insn and verification time, 17548 * but do not meaningfully decrease insn_processed. 17549 * 'n' controls how many times state could miss before eviction. 17550 * Use bigger 'n' for checkpoints because evicting checkpoint states 17551 * too early would hinder iterator convergence. 17552 */ 17553 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 17554 if (sl->miss_cnt > sl->hit_cnt * n + n) { 17555 /* the state is unlikely to be useful. Remove it to 17556 * speed up verification 17557 */ 17558 *pprev = sl->next; 17559 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE && 17560 !sl->state.used_as_loop_entry) { 17561 u32 br = sl->state.branches; 17562 17563 WARN_ONCE(br, 17564 "BUG live_done but branches_to_explore %d\n", 17565 br); 17566 free_verifier_state(&sl->state, false); 17567 kfree(sl); 17568 env->peak_states--; 17569 } else { 17570 /* cannot free this state, since parentage chain may 17571 * walk it later. Add it for free_list instead to 17572 * be freed at the end of verification 17573 */ 17574 sl->next = env->free_list; 17575 env->free_list = sl; 17576 } 17577 sl = *pprev; 17578 continue; 17579 } 17580 next: 17581 pprev = &sl->next; 17582 sl = *pprev; 17583 } 17584 17585 if (env->max_states_per_insn < states_cnt) 17586 env->max_states_per_insn = states_cnt; 17587 17588 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 17589 return 0; 17590 17591 if (!add_new_state) 17592 return 0; 17593 17594 /* There were no equivalent states, remember the current one. 17595 * Technically the current state is not proven to be safe yet, 17596 * but it will either reach outer most bpf_exit (which means it's safe) 17597 * or it will be rejected. When there are no loops the verifier won't be 17598 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 17599 * again on the way to bpf_exit. 17600 * When looping the sl->state.branches will be > 0 and this state 17601 * will not be considered for equivalence until branches == 0. 17602 */ 17603 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 17604 if (!new_sl) 17605 return -ENOMEM; 17606 env->total_states++; 17607 env->peak_states++; 17608 env->prev_jmps_processed = env->jmps_processed; 17609 env->prev_insn_processed = env->insn_processed; 17610 17611 /* forget precise markings we inherited, see __mark_chain_precision */ 17612 if (env->bpf_capable) 17613 mark_all_scalars_imprecise(env, cur); 17614 17615 /* add new state to the head of linked list */ 17616 new = &new_sl->state; 17617 err = copy_verifier_state(new, cur); 17618 if (err) { 17619 free_verifier_state(new, false); 17620 kfree(new_sl); 17621 return err; 17622 } 17623 new->insn_idx = insn_idx; 17624 WARN_ONCE(new->branches != 1, 17625 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 17626 17627 cur->parent = new; 17628 cur->first_insn_idx = insn_idx; 17629 cur->dfs_depth = new->dfs_depth + 1; 17630 clear_jmp_history(cur); 17631 new_sl->next = *explored_state(env, insn_idx); 17632 *explored_state(env, insn_idx) = new_sl; 17633 /* connect new state to parentage chain. Current frame needs all 17634 * registers connected. Only r6 - r9 of the callers are alive (pushed 17635 * to the stack implicitly by JITs) so in callers' frames connect just 17636 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 17637 * the state of the call instruction (with WRITTEN set), and r0 comes 17638 * from callee with its full parentage chain, anyway. 17639 */ 17640 /* clear write marks in current state: the writes we did are not writes 17641 * our child did, so they don't screen off its reads from us. 17642 * (There are no read marks in current state, because reads always mark 17643 * their parent and current state never has children yet. Only 17644 * explored_states can get read marks.) 17645 */ 17646 for (j = 0; j <= cur->curframe; j++) { 17647 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 17648 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 17649 for (i = 0; i < BPF_REG_FP; i++) 17650 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 17651 } 17652 17653 /* all stack frames are accessible from callee, clear them all */ 17654 for (j = 0; j <= cur->curframe; j++) { 17655 struct bpf_func_state *frame = cur->frame[j]; 17656 struct bpf_func_state *newframe = new->frame[j]; 17657 17658 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 17659 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 17660 frame->stack[i].spilled_ptr.parent = 17661 &newframe->stack[i].spilled_ptr; 17662 } 17663 } 17664 return 0; 17665 } 17666 17667 /* Return true if it's OK to have the same insn return a different type. */ 17668 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 17669 { 17670 switch (base_type(type)) { 17671 case PTR_TO_CTX: 17672 case PTR_TO_SOCKET: 17673 case PTR_TO_SOCK_COMMON: 17674 case PTR_TO_TCP_SOCK: 17675 case PTR_TO_XDP_SOCK: 17676 case PTR_TO_BTF_ID: 17677 case PTR_TO_ARENA: 17678 return false; 17679 default: 17680 return true; 17681 } 17682 } 17683 17684 /* If an instruction was previously used with particular pointer types, then we 17685 * need to be careful to avoid cases such as the below, where it may be ok 17686 * for one branch accessing the pointer, but not ok for the other branch: 17687 * 17688 * R1 = sock_ptr 17689 * goto X; 17690 * ... 17691 * R1 = some_other_valid_ptr; 17692 * goto X; 17693 * ... 17694 * R2 = *(u32 *)(R1 + 0); 17695 */ 17696 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 17697 { 17698 return src != prev && (!reg_type_mismatch_ok(src) || 17699 !reg_type_mismatch_ok(prev)); 17700 } 17701 17702 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 17703 bool allow_trust_mismatch) 17704 { 17705 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 17706 17707 if (*prev_type == NOT_INIT) { 17708 /* Saw a valid insn 17709 * dst_reg = *(u32 *)(src_reg + off) 17710 * save type to validate intersecting paths 17711 */ 17712 *prev_type = type; 17713 } else if (reg_type_mismatch(type, *prev_type)) { 17714 /* Abuser program is trying to use the same insn 17715 * dst_reg = *(u32*) (src_reg + off) 17716 * with different pointer types: 17717 * src_reg == ctx in one branch and 17718 * src_reg == stack|map in some other branch. 17719 * Reject it. 17720 */ 17721 if (allow_trust_mismatch && 17722 base_type(type) == PTR_TO_BTF_ID && 17723 base_type(*prev_type) == PTR_TO_BTF_ID) { 17724 /* 17725 * Have to support a use case when one path through 17726 * the program yields TRUSTED pointer while another 17727 * is UNTRUSTED. Fallback to UNTRUSTED to generate 17728 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 17729 */ 17730 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 17731 } else { 17732 verbose(env, "same insn cannot be used with different pointers\n"); 17733 return -EINVAL; 17734 } 17735 } 17736 17737 return 0; 17738 } 17739 17740 static int do_check(struct bpf_verifier_env *env) 17741 { 17742 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17743 struct bpf_verifier_state *state = env->cur_state; 17744 struct bpf_insn *insns = env->prog->insnsi; 17745 struct bpf_reg_state *regs; 17746 int insn_cnt = env->prog->len; 17747 bool do_print_state = false; 17748 int prev_insn_idx = -1; 17749 17750 for (;;) { 17751 bool exception_exit = false; 17752 struct bpf_insn *insn; 17753 u8 class; 17754 int err; 17755 17756 /* reset current history entry on each new instruction */ 17757 env->cur_hist_ent = NULL; 17758 17759 env->prev_insn_idx = prev_insn_idx; 17760 if (env->insn_idx >= insn_cnt) { 17761 verbose(env, "invalid insn idx %d insn_cnt %d\n", 17762 env->insn_idx, insn_cnt); 17763 return -EFAULT; 17764 } 17765 17766 insn = &insns[env->insn_idx]; 17767 class = BPF_CLASS(insn->code); 17768 17769 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 17770 verbose(env, 17771 "BPF program is too large. Processed %d insn\n", 17772 env->insn_processed); 17773 return -E2BIG; 17774 } 17775 17776 state->last_insn_idx = env->prev_insn_idx; 17777 17778 if (is_prune_point(env, env->insn_idx)) { 17779 err = is_state_visited(env, env->insn_idx); 17780 if (err < 0) 17781 return err; 17782 if (err == 1) { 17783 /* found equivalent state, can prune the search */ 17784 if (env->log.level & BPF_LOG_LEVEL) { 17785 if (do_print_state) 17786 verbose(env, "\nfrom %d to %d%s: safe\n", 17787 env->prev_insn_idx, env->insn_idx, 17788 env->cur_state->speculative ? 17789 " (speculative execution)" : ""); 17790 else 17791 verbose(env, "%d: safe\n", env->insn_idx); 17792 } 17793 goto process_bpf_exit; 17794 } 17795 } 17796 17797 if (is_jmp_point(env, env->insn_idx)) { 17798 err = push_jmp_history(env, state, 0); 17799 if (err) 17800 return err; 17801 } 17802 17803 if (signal_pending(current)) 17804 return -EAGAIN; 17805 17806 if (need_resched()) 17807 cond_resched(); 17808 17809 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17810 verbose(env, "\nfrom %d to %d%s:", 17811 env->prev_insn_idx, env->insn_idx, 17812 env->cur_state->speculative ? 17813 " (speculative execution)" : ""); 17814 print_verifier_state(env, state->frame[state->curframe], true); 17815 do_print_state = false; 17816 } 17817 17818 if (env->log.level & BPF_LOG_LEVEL) { 17819 const struct bpf_insn_cbs cbs = { 17820 .cb_call = disasm_kfunc_name, 17821 .cb_print = verbose, 17822 .private_data = env, 17823 }; 17824 17825 if (verifier_state_scratched(env)) 17826 print_insn_state(env, state->frame[state->curframe]); 17827 17828 verbose_linfo(env, env->insn_idx, "; "); 17829 env->prev_log_pos = env->log.end_pos; 17830 verbose(env, "%d: ", env->insn_idx); 17831 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 17832 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17833 env->prev_log_pos = env->log.end_pos; 17834 } 17835 17836 if (bpf_prog_is_offloaded(env->prog->aux)) { 17837 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17838 env->prev_insn_idx); 17839 if (err) 17840 return err; 17841 } 17842 17843 regs = cur_regs(env); 17844 sanitize_mark_insn_seen(env); 17845 prev_insn_idx = env->insn_idx; 17846 17847 if (class == BPF_ALU || class == BPF_ALU64) { 17848 err = check_alu_op(env, insn); 17849 if (err) 17850 return err; 17851 17852 } else if (class == BPF_LDX) { 17853 enum bpf_reg_type src_reg_type; 17854 17855 /* check for reserved fields is already done */ 17856 17857 /* check src operand */ 17858 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17859 if (err) 17860 return err; 17861 17862 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 17863 if (err) 17864 return err; 17865 17866 src_reg_type = regs[insn->src_reg].type; 17867 17868 /* check that memory (src_reg + off) is readable, 17869 * the state of dst_reg will be updated by this func 17870 */ 17871 err = check_mem_access(env, env->insn_idx, insn->src_reg, 17872 insn->off, BPF_SIZE(insn->code), 17873 BPF_READ, insn->dst_reg, false, 17874 BPF_MODE(insn->code) == BPF_MEMSX); 17875 err = err ?: save_aux_ptr_type(env, src_reg_type, true); 17876 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], "ldx"); 17877 if (err) 17878 return err; 17879 } else if (class == BPF_STX) { 17880 enum bpf_reg_type dst_reg_type; 17881 17882 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 17883 err = check_atomic(env, env->insn_idx, insn); 17884 if (err) 17885 return err; 17886 env->insn_idx++; 17887 continue; 17888 } 17889 17890 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 17891 verbose(env, "BPF_STX uses reserved fields\n"); 17892 return -EINVAL; 17893 } 17894 17895 /* check src1 operand */ 17896 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17897 if (err) 17898 return err; 17899 /* check src2 operand */ 17900 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17901 if (err) 17902 return err; 17903 17904 dst_reg_type = regs[insn->dst_reg].type; 17905 17906 /* check that memory (dst_reg + off) is writeable */ 17907 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17908 insn->off, BPF_SIZE(insn->code), 17909 BPF_WRITE, insn->src_reg, false, false); 17910 if (err) 17911 return err; 17912 17913 err = save_aux_ptr_type(env, dst_reg_type, false); 17914 if (err) 17915 return err; 17916 } else if (class == BPF_ST) { 17917 enum bpf_reg_type dst_reg_type; 17918 17919 if (BPF_MODE(insn->code) != BPF_MEM || 17920 insn->src_reg != BPF_REG_0) { 17921 verbose(env, "BPF_ST uses reserved fields\n"); 17922 return -EINVAL; 17923 } 17924 /* check src operand */ 17925 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17926 if (err) 17927 return err; 17928 17929 dst_reg_type = regs[insn->dst_reg].type; 17930 17931 /* check that memory (dst_reg + off) is writeable */ 17932 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17933 insn->off, BPF_SIZE(insn->code), 17934 BPF_WRITE, -1, false, false); 17935 if (err) 17936 return err; 17937 17938 err = save_aux_ptr_type(env, dst_reg_type, false); 17939 if (err) 17940 return err; 17941 } else if (class == BPF_JMP || class == BPF_JMP32) { 17942 u8 opcode = BPF_OP(insn->code); 17943 17944 env->jmps_processed++; 17945 if (opcode == BPF_CALL) { 17946 if (BPF_SRC(insn->code) != BPF_K || 17947 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 17948 && insn->off != 0) || 17949 (insn->src_reg != BPF_REG_0 && 17950 insn->src_reg != BPF_PSEUDO_CALL && 17951 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 17952 insn->dst_reg != BPF_REG_0 || 17953 class == BPF_JMP32) { 17954 verbose(env, "BPF_CALL uses reserved fields\n"); 17955 return -EINVAL; 17956 } 17957 17958 if (env->cur_state->active_lock.ptr) { 17959 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 17960 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17961 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 17962 verbose(env, "function calls are not allowed while holding a lock\n"); 17963 return -EINVAL; 17964 } 17965 } 17966 if (insn->src_reg == BPF_PSEUDO_CALL) { 17967 err = check_func_call(env, insn, &env->insn_idx); 17968 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 17969 err = check_kfunc_call(env, insn, &env->insn_idx); 17970 if (!err && is_bpf_throw_kfunc(insn)) { 17971 exception_exit = true; 17972 goto process_bpf_exit_full; 17973 } 17974 } else { 17975 err = check_helper_call(env, insn, &env->insn_idx); 17976 } 17977 if (err) 17978 return err; 17979 17980 mark_reg_scratched(env, BPF_REG_0); 17981 } else if (opcode == BPF_JA) { 17982 if (BPF_SRC(insn->code) != BPF_K || 17983 insn->src_reg != BPF_REG_0 || 17984 insn->dst_reg != BPF_REG_0 || 17985 (class == BPF_JMP && insn->imm != 0) || 17986 (class == BPF_JMP32 && insn->off != 0)) { 17987 verbose(env, "BPF_JA uses reserved fields\n"); 17988 return -EINVAL; 17989 } 17990 17991 if (class == BPF_JMP) 17992 env->insn_idx += insn->off + 1; 17993 else 17994 env->insn_idx += insn->imm + 1; 17995 continue; 17996 17997 } else if (opcode == BPF_EXIT) { 17998 if (BPF_SRC(insn->code) != BPF_K || 17999 insn->imm != 0 || 18000 insn->src_reg != BPF_REG_0 || 18001 insn->dst_reg != BPF_REG_0 || 18002 class == BPF_JMP32) { 18003 verbose(env, "BPF_EXIT uses reserved fields\n"); 18004 return -EINVAL; 18005 } 18006 process_bpf_exit_full: 18007 if (env->cur_state->active_lock.ptr && !env->cur_state->curframe) { 18008 verbose(env, "bpf_spin_unlock is missing\n"); 18009 return -EINVAL; 18010 } 18011 18012 if (env->cur_state->active_rcu_lock && !env->cur_state->curframe) { 18013 verbose(env, "bpf_rcu_read_unlock is missing\n"); 18014 return -EINVAL; 18015 } 18016 18017 if (env->cur_state->active_preempt_lock && !env->cur_state->curframe) { 18018 verbose(env, "%d bpf_preempt_enable%s missing\n", 18019 env->cur_state->active_preempt_lock, 18020 env->cur_state->active_preempt_lock == 1 ? " is" : "(s) are"); 18021 return -EINVAL; 18022 } 18023 18024 /* We must do check_reference_leak here before 18025 * prepare_func_exit to handle the case when 18026 * state->curframe > 0, it may be a callback 18027 * function, for which reference_state must 18028 * match caller reference state when it exits. 18029 */ 18030 err = check_reference_leak(env, exception_exit); 18031 if (err) 18032 return err; 18033 18034 /* The side effect of the prepare_func_exit 18035 * which is being skipped is that it frees 18036 * bpf_func_state. Typically, process_bpf_exit 18037 * will only be hit with outermost exit. 18038 * copy_verifier_state in pop_stack will handle 18039 * freeing of any extra bpf_func_state left over 18040 * from not processing all nested function 18041 * exits. We also skip return code checks as 18042 * they are not needed for exceptional exits. 18043 */ 18044 if (exception_exit) 18045 goto process_bpf_exit; 18046 18047 if (state->curframe) { 18048 /* exit from nested function */ 18049 err = prepare_func_exit(env, &env->insn_idx); 18050 if (err) 18051 return err; 18052 do_print_state = true; 18053 continue; 18054 } 18055 18056 err = check_return_code(env, BPF_REG_0, "R0"); 18057 if (err) 18058 return err; 18059 process_bpf_exit: 18060 mark_verifier_state_scratched(env); 18061 update_branch_counts(env, env->cur_state); 18062 err = pop_stack(env, &prev_insn_idx, 18063 &env->insn_idx, pop_log); 18064 if (err < 0) { 18065 if (err != -ENOENT) 18066 return err; 18067 break; 18068 } else { 18069 do_print_state = true; 18070 continue; 18071 } 18072 } else { 18073 err = check_cond_jmp_op(env, insn, &env->insn_idx); 18074 if (err) 18075 return err; 18076 } 18077 } else if (class == BPF_LD) { 18078 u8 mode = BPF_MODE(insn->code); 18079 18080 if (mode == BPF_ABS || mode == BPF_IND) { 18081 err = check_ld_abs(env, insn); 18082 if (err) 18083 return err; 18084 18085 } else if (mode == BPF_IMM) { 18086 err = check_ld_imm(env, insn); 18087 if (err) 18088 return err; 18089 18090 env->insn_idx++; 18091 sanitize_mark_insn_seen(env); 18092 } else { 18093 verbose(env, "invalid BPF_LD mode\n"); 18094 return -EINVAL; 18095 } 18096 } else { 18097 verbose(env, "unknown insn class %d\n", class); 18098 return -EINVAL; 18099 } 18100 18101 env->insn_idx++; 18102 } 18103 18104 return 0; 18105 } 18106 18107 static int find_btf_percpu_datasec(struct btf *btf) 18108 { 18109 const struct btf_type *t; 18110 const char *tname; 18111 int i, n; 18112 18113 /* 18114 * Both vmlinux and module each have their own ".data..percpu" 18115 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 18116 * types to look at only module's own BTF types. 18117 */ 18118 n = btf_nr_types(btf); 18119 if (btf_is_module(btf)) 18120 i = btf_nr_types(btf_vmlinux); 18121 else 18122 i = 1; 18123 18124 for(; i < n; i++) { 18125 t = btf_type_by_id(btf, i); 18126 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 18127 continue; 18128 18129 tname = btf_name_by_offset(btf, t->name_off); 18130 if (!strcmp(tname, ".data..percpu")) 18131 return i; 18132 } 18133 18134 return -ENOENT; 18135 } 18136 18137 /* replace pseudo btf_id with kernel symbol address */ 18138 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 18139 struct bpf_insn *insn, 18140 struct bpf_insn_aux_data *aux) 18141 { 18142 const struct btf_var_secinfo *vsi; 18143 const struct btf_type *datasec; 18144 struct btf_mod_pair *btf_mod; 18145 const struct btf_type *t; 18146 const char *sym_name; 18147 bool percpu = false; 18148 u32 type, id = insn->imm; 18149 struct btf *btf; 18150 s32 datasec_id; 18151 u64 addr; 18152 int i, btf_fd, err; 18153 18154 btf_fd = insn[1].imm; 18155 if (btf_fd) { 18156 btf = btf_get_by_fd(btf_fd); 18157 if (IS_ERR(btf)) { 18158 verbose(env, "invalid module BTF object FD specified.\n"); 18159 return -EINVAL; 18160 } 18161 } else { 18162 if (!btf_vmlinux) { 18163 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 18164 return -EINVAL; 18165 } 18166 btf = btf_vmlinux; 18167 btf_get(btf); 18168 } 18169 18170 t = btf_type_by_id(btf, id); 18171 if (!t) { 18172 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 18173 err = -ENOENT; 18174 goto err_put; 18175 } 18176 18177 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 18178 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 18179 err = -EINVAL; 18180 goto err_put; 18181 } 18182 18183 sym_name = btf_name_by_offset(btf, t->name_off); 18184 addr = kallsyms_lookup_name(sym_name); 18185 if (!addr) { 18186 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 18187 sym_name); 18188 err = -ENOENT; 18189 goto err_put; 18190 } 18191 insn[0].imm = (u32)addr; 18192 insn[1].imm = addr >> 32; 18193 18194 if (btf_type_is_func(t)) { 18195 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 18196 aux->btf_var.mem_size = 0; 18197 goto check_btf; 18198 } 18199 18200 datasec_id = find_btf_percpu_datasec(btf); 18201 if (datasec_id > 0) { 18202 datasec = btf_type_by_id(btf, datasec_id); 18203 for_each_vsi(i, datasec, vsi) { 18204 if (vsi->type == id) { 18205 percpu = true; 18206 break; 18207 } 18208 } 18209 } 18210 18211 type = t->type; 18212 t = btf_type_skip_modifiers(btf, type, NULL); 18213 if (percpu) { 18214 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 18215 aux->btf_var.btf = btf; 18216 aux->btf_var.btf_id = type; 18217 } else if (!btf_type_is_struct(t)) { 18218 const struct btf_type *ret; 18219 const char *tname; 18220 u32 tsize; 18221 18222 /* resolve the type size of ksym. */ 18223 ret = btf_resolve_size(btf, t, &tsize); 18224 if (IS_ERR(ret)) { 18225 tname = btf_name_by_offset(btf, t->name_off); 18226 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 18227 tname, PTR_ERR(ret)); 18228 err = -EINVAL; 18229 goto err_put; 18230 } 18231 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 18232 aux->btf_var.mem_size = tsize; 18233 } else { 18234 aux->btf_var.reg_type = PTR_TO_BTF_ID; 18235 aux->btf_var.btf = btf; 18236 aux->btf_var.btf_id = type; 18237 } 18238 check_btf: 18239 /* check whether we recorded this BTF (and maybe module) already */ 18240 for (i = 0; i < env->used_btf_cnt; i++) { 18241 if (env->used_btfs[i].btf == btf) { 18242 btf_put(btf); 18243 return 0; 18244 } 18245 } 18246 18247 if (env->used_btf_cnt >= MAX_USED_BTFS) { 18248 err = -E2BIG; 18249 goto err_put; 18250 } 18251 18252 btf_mod = &env->used_btfs[env->used_btf_cnt]; 18253 btf_mod->btf = btf; 18254 btf_mod->module = NULL; 18255 18256 /* if we reference variables from kernel module, bump its refcount */ 18257 if (btf_is_module(btf)) { 18258 btf_mod->module = btf_try_get_module(btf); 18259 if (!btf_mod->module) { 18260 err = -ENXIO; 18261 goto err_put; 18262 } 18263 } 18264 18265 env->used_btf_cnt++; 18266 18267 return 0; 18268 err_put: 18269 btf_put(btf); 18270 return err; 18271 } 18272 18273 static bool is_tracing_prog_type(enum bpf_prog_type type) 18274 { 18275 switch (type) { 18276 case BPF_PROG_TYPE_KPROBE: 18277 case BPF_PROG_TYPE_TRACEPOINT: 18278 case BPF_PROG_TYPE_PERF_EVENT: 18279 case BPF_PROG_TYPE_RAW_TRACEPOINT: 18280 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 18281 return true; 18282 default: 18283 return false; 18284 } 18285 } 18286 18287 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 18288 struct bpf_map *map, 18289 struct bpf_prog *prog) 18290 18291 { 18292 enum bpf_prog_type prog_type = resolve_prog_type(prog); 18293 18294 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 18295 btf_record_has_field(map->record, BPF_RB_ROOT)) { 18296 if (is_tracing_prog_type(prog_type)) { 18297 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 18298 return -EINVAL; 18299 } 18300 } 18301 18302 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 18303 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 18304 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 18305 return -EINVAL; 18306 } 18307 18308 if (is_tracing_prog_type(prog_type)) { 18309 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 18310 return -EINVAL; 18311 } 18312 } 18313 18314 if (btf_record_has_field(map->record, BPF_TIMER)) { 18315 if (is_tracing_prog_type(prog_type)) { 18316 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 18317 return -EINVAL; 18318 } 18319 } 18320 18321 if (btf_record_has_field(map->record, BPF_WORKQUEUE)) { 18322 if (is_tracing_prog_type(prog_type)) { 18323 verbose(env, "tracing progs cannot use bpf_wq yet\n"); 18324 return -EINVAL; 18325 } 18326 } 18327 18328 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 18329 !bpf_offload_prog_map_match(prog, map)) { 18330 verbose(env, "offload device mismatch between prog and map\n"); 18331 return -EINVAL; 18332 } 18333 18334 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 18335 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 18336 return -EINVAL; 18337 } 18338 18339 if (prog->sleepable) 18340 switch (map->map_type) { 18341 case BPF_MAP_TYPE_HASH: 18342 case BPF_MAP_TYPE_LRU_HASH: 18343 case BPF_MAP_TYPE_ARRAY: 18344 case BPF_MAP_TYPE_PERCPU_HASH: 18345 case BPF_MAP_TYPE_PERCPU_ARRAY: 18346 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 18347 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 18348 case BPF_MAP_TYPE_HASH_OF_MAPS: 18349 case BPF_MAP_TYPE_RINGBUF: 18350 case BPF_MAP_TYPE_USER_RINGBUF: 18351 case BPF_MAP_TYPE_INODE_STORAGE: 18352 case BPF_MAP_TYPE_SK_STORAGE: 18353 case BPF_MAP_TYPE_TASK_STORAGE: 18354 case BPF_MAP_TYPE_CGRP_STORAGE: 18355 case BPF_MAP_TYPE_QUEUE: 18356 case BPF_MAP_TYPE_STACK: 18357 case BPF_MAP_TYPE_ARENA: 18358 break; 18359 default: 18360 verbose(env, 18361 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 18362 return -EINVAL; 18363 } 18364 18365 return 0; 18366 } 18367 18368 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 18369 { 18370 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 18371 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 18372 } 18373 18374 /* find and rewrite pseudo imm in ld_imm64 instructions: 18375 * 18376 * 1. if it accesses map FD, replace it with actual map pointer. 18377 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 18378 * 18379 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 18380 */ 18381 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 18382 { 18383 struct bpf_insn *insn = env->prog->insnsi; 18384 int insn_cnt = env->prog->len; 18385 int i, j, err; 18386 18387 err = bpf_prog_calc_tag(env->prog); 18388 if (err) 18389 return err; 18390 18391 for (i = 0; i < insn_cnt; i++, insn++) { 18392 if (BPF_CLASS(insn->code) == BPF_LDX && 18393 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 18394 insn->imm != 0)) { 18395 verbose(env, "BPF_LDX uses reserved fields\n"); 18396 return -EINVAL; 18397 } 18398 18399 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 18400 struct bpf_insn_aux_data *aux; 18401 struct bpf_map *map; 18402 struct fd f; 18403 u64 addr; 18404 u32 fd; 18405 18406 if (i == insn_cnt - 1 || insn[1].code != 0 || 18407 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 18408 insn[1].off != 0) { 18409 verbose(env, "invalid bpf_ld_imm64 insn\n"); 18410 return -EINVAL; 18411 } 18412 18413 if (insn[0].src_reg == 0) 18414 /* valid generic load 64-bit imm */ 18415 goto next_insn; 18416 18417 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 18418 aux = &env->insn_aux_data[i]; 18419 err = check_pseudo_btf_id(env, insn, aux); 18420 if (err) 18421 return err; 18422 goto next_insn; 18423 } 18424 18425 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 18426 aux = &env->insn_aux_data[i]; 18427 aux->ptr_type = PTR_TO_FUNC; 18428 goto next_insn; 18429 } 18430 18431 /* In final convert_pseudo_ld_imm64() step, this is 18432 * converted into regular 64-bit imm load insn. 18433 */ 18434 switch (insn[0].src_reg) { 18435 case BPF_PSEUDO_MAP_VALUE: 18436 case BPF_PSEUDO_MAP_IDX_VALUE: 18437 break; 18438 case BPF_PSEUDO_MAP_FD: 18439 case BPF_PSEUDO_MAP_IDX: 18440 if (insn[1].imm == 0) 18441 break; 18442 fallthrough; 18443 default: 18444 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 18445 return -EINVAL; 18446 } 18447 18448 switch (insn[0].src_reg) { 18449 case BPF_PSEUDO_MAP_IDX_VALUE: 18450 case BPF_PSEUDO_MAP_IDX: 18451 if (bpfptr_is_null(env->fd_array)) { 18452 verbose(env, "fd_idx without fd_array is invalid\n"); 18453 return -EPROTO; 18454 } 18455 if (copy_from_bpfptr_offset(&fd, env->fd_array, 18456 insn[0].imm * sizeof(fd), 18457 sizeof(fd))) 18458 return -EFAULT; 18459 break; 18460 default: 18461 fd = insn[0].imm; 18462 break; 18463 } 18464 18465 f = fdget(fd); 18466 map = __bpf_map_get(f); 18467 if (IS_ERR(map)) { 18468 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 18469 return PTR_ERR(map); 18470 } 18471 18472 err = check_map_prog_compatibility(env, map, env->prog); 18473 if (err) { 18474 fdput(f); 18475 return err; 18476 } 18477 18478 aux = &env->insn_aux_data[i]; 18479 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 18480 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 18481 addr = (unsigned long)map; 18482 } else { 18483 u32 off = insn[1].imm; 18484 18485 if (off >= BPF_MAX_VAR_OFF) { 18486 verbose(env, "direct value offset of %u is not allowed\n", off); 18487 fdput(f); 18488 return -EINVAL; 18489 } 18490 18491 if (!map->ops->map_direct_value_addr) { 18492 verbose(env, "no direct value access support for this map type\n"); 18493 fdput(f); 18494 return -EINVAL; 18495 } 18496 18497 err = map->ops->map_direct_value_addr(map, &addr, off); 18498 if (err) { 18499 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 18500 map->value_size, off); 18501 fdput(f); 18502 return err; 18503 } 18504 18505 aux->map_off = off; 18506 addr += off; 18507 } 18508 18509 insn[0].imm = (u32)addr; 18510 insn[1].imm = addr >> 32; 18511 18512 /* check whether we recorded this map already */ 18513 for (j = 0; j < env->used_map_cnt; j++) { 18514 if (env->used_maps[j] == map) { 18515 aux->map_index = j; 18516 fdput(f); 18517 goto next_insn; 18518 } 18519 } 18520 18521 if (env->used_map_cnt >= MAX_USED_MAPS) { 18522 verbose(env, "The total number of maps per program has reached the limit of %u\n", 18523 MAX_USED_MAPS); 18524 fdput(f); 18525 return -E2BIG; 18526 } 18527 18528 if (env->prog->sleepable) 18529 atomic64_inc(&map->sleepable_refcnt); 18530 /* hold the map. If the program is rejected by verifier, 18531 * the map will be released by release_maps() or it 18532 * will be used by the valid program until it's unloaded 18533 * and all maps are released in bpf_free_used_maps() 18534 */ 18535 bpf_map_inc(map); 18536 18537 aux->map_index = env->used_map_cnt; 18538 env->used_maps[env->used_map_cnt++] = map; 18539 18540 if (bpf_map_is_cgroup_storage(map) && 18541 bpf_cgroup_storage_assign(env->prog->aux, map)) { 18542 verbose(env, "only one cgroup storage of each type is allowed\n"); 18543 fdput(f); 18544 return -EBUSY; 18545 } 18546 if (map->map_type == BPF_MAP_TYPE_ARENA) { 18547 if (env->prog->aux->arena) { 18548 verbose(env, "Only one arena per program\n"); 18549 fdput(f); 18550 return -EBUSY; 18551 } 18552 if (!env->allow_ptr_leaks || !env->bpf_capable) { 18553 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n"); 18554 fdput(f); 18555 return -EPERM; 18556 } 18557 if (!env->prog->jit_requested) { 18558 verbose(env, "JIT is required to use arena\n"); 18559 fdput(f); 18560 return -EOPNOTSUPP; 18561 } 18562 if (!bpf_jit_supports_arena()) { 18563 verbose(env, "JIT doesn't support arena\n"); 18564 fdput(f); 18565 return -EOPNOTSUPP; 18566 } 18567 env->prog->aux->arena = (void *)map; 18568 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) { 18569 verbose(env, "arena's user address must be set via map_extra or mmap()\n"); 18570 fdput(f); 18571 return -EINVAL; 18572 } 18573 } 18574 18575 fdput(f); 18576 next_insn: 18577 insn++; 18578 i++; 18579 continue; 18580 } 18581 18582 /* Basic sanity check before we invest more work here. */ 18583 if (!bpf_opcode_in_insntable(insn->code)) { 18584 verbose(env, "unknown opcode %02x\n", insn->code); 18585 return -EINVAL; 18586 } 18587 } 18588 18589 /* now all pseudo BPF_LD_IMM64 instructions load valid 18590 * 'struct bpf_map *' into a register instead of user map_fd. 18591 * These pointers will be used later by verifier to validate map access. 18592 */ 18593 return 0; 18594 } 18595 18596 /* drop refcnt of maps used by the rejected program */ 18597 static void release_maps(struct bpf_verifier_env *env) 18598 { 18599 __bpf_free_used_maps(env->prog->aux, env->used_maps, 18600 env->used_map_cnt); 18601 } 18602 18603 /* drop refcnt of maps used by the rejected program */ 18604 static void release_btfs(struct bpf_verifier_env *env) 18605 { 18606 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 18607 env->used_btf_cnt); 18608 } 18609 18610 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 18611 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 18612 { 18613 struct bpf_insn *insn = env->prog->insnsi; 18614 int insn_cnt = env->prog->len; 18615 int i; 18616 18617 for (i = 0; i < insn_cnt; i++, insn++) { 18618 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 18619 continue; 18620 if (insn->src_reg == BPF_PSEUDO_FUNC) 18621 continue; 18622 insn->src_reg = 0; 18623 } 18624 } 18625 18626 /* single env->prog->insni[off] instruction was replaced with the range 18627 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 18628 * [0, off) and [off, end) to new locations, so the patched range stays zero 18629 */ 18630 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 18631 struct bpf_insn_aux_data *new_data, 18632 struct bpf_prog *new_prog, u32 off, u32 cnt) 18633 { 18634 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 18635 struct bpf_insn *insn = new_prog->insnsi; 18636 u32 old_seen = old_data[off].seen; 18637 u32 prog_len; 18638 int i; 18639 18640 /* aux info at OFF always needs adjustment, no matter fast path 18641 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 18642 * original insn at old prog. 18643 */ 18644 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 18645 18646 if (cnt == 1) 18647 return; 18648 prog_len = new_prog->len; 18649 18650 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 18651 memcpy(new_data + off + cnt - 1, old_data + off, 18652 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 18653 for (i = off; i < off + cnt - 1; i++) { 18654 /* Expand insni[off]'s seen count to the patched range. */ 18655 new_data[i].seen = old_seen; 18656 new_data[i].zext_dst = insn_has_def32(env, insn + i); 18657 } 18658 env->insn_aux_data = new_data; 18659 vfree(old_data); 18660 } 18661 18662 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 18663 { 18664 int i; 18665 18666 if (len == 1) 18667 return; 18668 /* NOTE: fake 'exit' subprog should be updated as well. */ 18669 for (i = 0; i <= env->subprog_cnt; i++) { 18670 if (env->subprog_info[i].start <= off) 18671 continue; 18672 env->subprog_info[i].start += len - 1; 18673 } 18674 } 18675 18676 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 18677 { 18678 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 18679 int i, sz = prog->aux->size_poke_tab; 18680 struct bpf_jit_poke_descriptor *desc; 18681 18682 for (i = 0; i < sz; i++) { 18683 desc = &tab[i]; 18684 if (desc->insn_idx <= off) 18685 continue; 18686 desc->insn_idx += len - 1; 18687 } 18688 } 18689 18690 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 18691 const struct bpf_insn *patch, u32 len) 18692 { 18693 struct bpf_prog *new_prog; 18694 struct bpf_insn_aux_data *new_data = NULL; 18695 18696 if (len > 1) { 18697 new_data = vzalloc(array_size(env->prog->len + len - 1, 18698 sizeof(struct bpf_insn_aux_data))); 18699 if (!new_data) 18700 return NULL; 18701 } 18702 18703 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 18704 if (IS_ERR(new_prog)) { 18705 if (PTR_ERR(new_prog) == -ERANGE) 18706 verbose(env, 18707 "insn %d cannot be patched due to 16-bit range\n", 18708 env->insn_aux_data[off].orig_idx); 18709 vfree(new_data); 18710 return NULL; 18711 } 18712 adjust_insn_aux_data(env, new_data, new_prog, off, len); 18713 adjust_subprog_starts(env, off, len); 18714 adjust_poke_descs(new_prog, off, len); 18715 return new_prog; 18716 } 18717 18718 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 18719 u32 off, u32 cnt) 18720 { 18721 int i, j; 18722 18723 /* find first prog starting at or after off (first to remove) */ 18724 for (i = 0; i < env->subprog_cnt; i++) 18725 if (env->subprog_info[i].start >= off) 18726 break; 18727 /* find first prog starting at or after off + cnt (first to stay) */ 18728 for (j = i; j < env->subprog_cnt; j++) 18729 if (env->subprog_info[j].start >= off + cnt) 18730 break; 18731 /* if j doesn't start exactly at off + cnt, we are just removing 18732 * the front of previous prog 18733 */ 18734 if (env->subprog_info[j].start != off + cnt) 18735 j--; 18736 18737 if (j > i) { 18738 struct bpf_prog_aux *aux = env->prog->aux; 18739 int move; 18740 18741 /* move fake 'exit' subprog as well */ 18742 move = env->subprog_cnt + 1 - j; 18743 18744 memmove(env->subprog_info + i, 18745 env->subprog_info + j, 18746 sizeof(*env->subprog_info) * move); 18747 env->subprog_cnt -= j - i; 18748 18749 /* remove func_info */ 18750 if (aux->func_info) { 18751 move = aux->func_info_cnt - j; 18752 18753 memmove(aux->func_info + i, 18754 aux->func_info + j, 18755 sizeof(*aux->func_info) * move); 18756 aux->func_info_cnt -= j - i; 18757 /* func_info->insn_off is set after all code rewrites, 18758 * in adjust_btf_func() - no need to adjust 18759 */ 18760 } 18761 } else { 18762 /* convert i from "first prog to remove" to "first to adjust" */ 18763 if (env->subprog_info[i].start == off) 18764 i++; 18765 } 18766 18767 /* update fake 'exit' subprog as well */ 18768 for (; i <= env->subprog_cnt; i++) 18769 env->subprog_info[i].start -= cnt; 18770 18771 return 0; 18772 } 18773 18774 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 18775 u32 cnt) 18776 { 18777 struct bpf_prog *prog = env->prog; 18778 u32 i, l_off, l_cnt, nr_linfo; 18779 struct bpf_line_info *linfo; 18780 18781 nr_linfo = prog->aux->nr_linfo; 18782 if (!nr_linfo) 18783 return 0; 18784 18785 linfo = prog->aux->linfo; 18786 18787 /* find first line info to remove, count lines to be removed */ 18788 for (i = 0; i < nr_linfo; i++) 18789 if (linfo[i].insn_off >= off) 18790 break; 18791 18792 l_off = i; 18793 l_cnt = 0; 18794 for (; i < nr_linfo; i++) 18795 if (linfo[i].insn_off < off + cnt) 18796 l_cnt++; 18797 else 18798 break; 18799 18800 /* First live insn doesn't match first live linfo, it needs to "inherit" 18801 * last removed linfo. prog is already modified, so prog->len == off 18802 * means no live instructions after (tail of the program was removed). 18803 */ 18804 if (prog->len != off && l_cnt && 18805 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 18806 l_cnt--; 18807 linfo[--i].insn_off = off + cnt; 18808 } 18809 18810 /* remove the line info which refer to the removed instructions */ 18811 if (l_cnt) { 18812 memmove(linfo + l_off, linfo + i, 18813 sizeof(*linfo) * (nr_linfo - i)); 18814 18815 prog->aux->nr_linfo -= l_cnt; 18816 nr_linfo = prog->aux->nr_linfo; 18817 } 18818 18819 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 18820 for (i = l_off; i < nr_linfo; i++) 18821 linfo[i].insn_off -= cnt; 18822 18823 /* fix up all subprogs (incl. 'exit') which start >= off */ 18824 for (i = 0; i <= env->subprog_cnt; i++) 18825 if (env->subprog_info[i].linfo_idx > l_off) { 18826 /* program may have started in the removed region but 18827 * may not be fully removed 18828 */ 18829 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 18830 env->subprog_info[i].linfo_idx -= l_cnt; 18831 else 18832 env->subprog_info[i].linfo_idx = l_off; 18833 } 18834 18835 return 0; 18836 } 18837 18838 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 18839 { 18840 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18841 unsigned int orig_prog_len = env->prog->len; 18842 int err; 18843 18844 if (bpf_prog_is_offloaded(env->prog->aux)) 18845 bpf_prog_offload_remove_insns(env, off, cnt); 18846 18847 err = bpf_remove_insns(env->prog, off, cnt); 18848 if (err) 18849 return err; 18850 18851 err = adjust_subprog_starts_after_remove(env, off, cnt); 18852 if (err) 18853 return err; 18854 18855 err = bpf_adj_linfo_after_remove(env, off, cnt); 18856 if (err) 18857 return err; 18858 18859 memmove(aux_data + off, aux_data + off + cnt, 18860 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 18861 18862 return 0; 18863 } 18864 18865 /* The verifier does more data flow analysis than llvm and will not 18866 * explore branches that are dead at run time. Malicious programs can 18867 * have dead code too. Therefore replace all dead at-run-time code 18868 * with 'ja -1'. 18869 * 18870 * Just nops are not optimal, e.g. if they would sit at the end of the 18871 * program and through another bug we would manage to jump there, then 18872 * we'd execute beyond program memory otherwise. Returning exception 18873 * code also wouldn't work since we can have subprogs where the dead 18874 * code could be located. 18875 */ 18876 static void sanitize_dead_code(struct bpf_verifier_env *env) 18877 { 18878 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18879 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18880 struct bpf_insn *insn = env->prog->insnsi; 18881 const int insn_cnt = env->prog->len; 18882 int i; 18883 18884 for (i = 0; i < insn_cnt; i++) { 18885 if (aux_data[i].seen) 18886 continue; 18887 memcpy(insn + i, &trap, sizeof(trap)); 18888 aux_data[i].zext_dst = false; 18889 } 18890 } 18891 18892 static bool insn_is_cond_jump(u8 code) 18893 { 18894 u8 op; 18895 18896 op = BPF_OP(code); 18897 if (BPF_CLASS(code) == BPF_JMP32) 18898 return op != BPF_JA; 18899 18900 if (BPF_CLASS(code) != BPF_JMP) 18901 return false; 18902 18903 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 18904 } 18905 18906 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 18907 { 18908 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18909 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18910 struct bpf_insn *insn = env->prog->insnsi; 18911 const int insn_cnt = env->prog->len; 18912 int i; 18913 18914 for (i = 0; i < insn_cnt; i++, insn++) { 18915 if (!insn_is_cond_jump(insn->code)) 18916 continue; 18917 18918 if (!aux_data[i + 1].seen) 18919 ja.off = insn->off; 18920 else if (!aux_data[i + 1 + insn->off].seen) 18921 ja.off = 0; 18922 else 18923 continue; 18924 18925 if (bpf_prog_is_offloaded(env->prog->aux)) 18926 bpf_prog_offload_replace_insn(env, i, &ja); 18927 18928 memcpy(insn, &ja, sizeof(ja)); 18929 } 18930 } 18931 18932 static int opt_remove_dead_code(struct bpf_verifier_env *env) 18933 { 18934 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18935 int insn_cnt = env->prog->len; 18936 int i, err; 18937 18938 for (i = 0; i < insn_cnt; i++) { 18939 int j; 18940 18941 j = 0; 18942 while (i + j < insn_cnt && !aux_data[i + j].seen) 18943 j++; 18944 if (!j) 18945 continue; 18946 18947 err = verifier_remove_insns(env, i, j); 18948 if (err) 18949 return err; 18950 insn_cnt = env->prog->len; 18951 } 18952 18953 return 0; 18954 } 18955 18956 static int opt_remove_nops(struct bpf_verifier_env *env) 18957 { 18958 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18959 struct bpf_insn *insn = env->prog->insnsi; 18960 int insn_cnt = env->prog->len; 18961 int i, err; 18962 18963 for (i = 0; i < insn_cnt; i++) { 18964 if (memcmp(&insn[i], &ja, sizeof(ja))) 18965 continue; 18966 18967 err = verifier_remove_insns(env, i, 1); 18968 if (err) 18969 return err; 18970 insn_cnt--; 18971 i--; 18972 } 18973 18974 return 0; 18975 } 18976 18977 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 18978 const union bpf_attr *attr) 18979 { 18980 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 18981 struct bpf_insn_aux_data *aux = env->insn_aux_data; 18982 int i, patch_len, delta = 0, len = env->prog->len; 18983 struct bpf_insn *insns = env->prog->insnsi; 18984 struct bpf_prog *new_prog; 18985 bool rnd_hi32; 18986 18987 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 18988 zext_patch[1] = BPF_ZEXT_REG(0); 18989 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 18990 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 18991 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 18992 for (i = 0; i < len; i++) { 18993 int adj_idx = i + delta; 18994 struct bpf_insn insn; 18995 int load_reg; 18996 18997 insn = insns[adj_idx]; 18998 load_reg = insn_def_regno(&insn); 18999 if (!aux[adj_idx].zext_dst) { 19000 u8 code, class; 19001 u32 imm_rnd; 19002 19003 if (!rnd_hi32) 19004 continue; 19005 19006 code = insn.code; 19007 class = BPF_CLASS(code); 19008 if (load_reg == -1) 19009 continue; 19010 19011 /* NOTE: arg "reg" (the fourth one) is only used for 19012 * BPF_STX + SRC_OP, so it is safe to pass NULL 19013 * here. 19014 */ 19015 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 19016 if (class == BPF_LD && 19017 BPF_MODE(code) == BPF_IMM) 19018 i++; 19019 continue; 19020 } 19021 19022 /* ctx load could be transformed into wider load. */ 19023 if (class == BPF_LDX && 19024 aux[adj_idx].ptr_type == PTR_TO_CTX) 19025 continue; 19026 19027 imm_rnd = get_random_u32(); 19028 rnd_hi32_patch[0] = insn; 19029 rnd_hi32_patch[1].imm = imm_rnd; 19030 rnd_hi32_patch[3].dst_reg = load_reg; 19031 patch = rnd_hi32_patch; 19032 patch_len = 4; 19033 goto apply_patch_buffer; 19034 } 19035 19036 /* Add in an zero-extend instruction if a) the JIT has requested 19037 * it or b) it's a CMPXCHG. 19038 * 19039 * The latter is because: BPF_CMPXCHG always loads a value into 19040 * R0, therefore always zero-extends. However some archs' 19041 * equivalent instruction only does this load when the 19042 * comparison is successful. This detail of CMPXCHG is 19043 * orthogonal to the general zero-extension behaviour of the 19044 * CPU, so it's treated independently of bpf_jit_needs_zext. 19045 */ 19046 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 19047 continue; 19048 19049 /* Zero-extension is done by the caller. */ 19050 if (bpf_pseudo_kfunc_call(&insn)) 19051 continue; 19052 19053 if (WARN_ON(load_reg == -1)) { 19054 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 19055 return -EFAULT; 19056 } 19057 19058 zext_patch[0] = insn; 19059 zext_patch[1].dst_reg = load_reg; 19060 zext_patch[1].src_reg = load_reg; 19061 patch = zext_patch; 19062 patch_len = 2; 19063 apply_patch_buffer: 19064 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 19065 if (!new_prog) 19066 return -ENOMEM; 19067 env->prog = new_prog; 19068 insns = new_prog->insnsi; 19069 aux = env->insn_aux_data; 19070 delta += patch_len - 1; 19071 } 19072 19073 return 0; 19074 } 19075 19076 /* convert load instructions that access fields of a context type into a 19077 * sequence of instructions that access fields of the underlying structure: 19078 * struct __sk_buff -> struct sk_buff 19079 * struct bpf_sock_ops -> struct sock 19080 */ 19081 static int convert_ctx_accesses(struct bpf_verifier_env *env) 19082 { 19083 const struct bpf_verifier_ops *ops = env->ops; 19084 int i, cnt, size, ctx_field_size, delta = 0; 19085 const int insn_cnt = env->prog->len; 19086 struct bpf_insn insn_buf[16], *insn; 19087 u32 target_size, size_default, off; 19088 struct bpf_prog *new_prog; 19089 enum bpf_access_type type; 19090 bool is_narrower_load; 19091 19092 if (ops->gen_prologue || env->seen_direct_write) { 19093 if (!ops->gen_prologue) { 19094 verbose(env, "bpf verifier is misconfigured\n"); 19095 return -EINVAL; 19096 } 19097 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 19098 env->prog); 19099 if (cnt >= ARRAY_SIZE(insn_buf)) { 19100 verbose(env, "bpf verifier is misconfigured\n"); 19101 return -EINVAL; 19102 } else if (cnt) { 19103 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 19104 if (!new_prog) 19105 return -ENOMEM; 19106 19107 env->prog = new_prog; 19108 delta += cnt - 1; 19109 } 19110 } 19111 19112 if (bpf_prog_is_offloaded(env->prog->aux)) 19113 return 0; 19114 19115 insn = env->prog->insnsi + delta; 19116 19117 for (i = 0; i < insn_cnt; i++, insn++) { 19118 bpf_convert_ctx_access_t convert_ctx_access; 19119 u8 mode; 19120 19121 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 19122 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 19123 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 19124 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 19125 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 19126 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 19127 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 19128 type = BPF_READ; 19129 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 19130 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 19131 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 19132 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 19133 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 19134 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 19135 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 19136 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 19137 type = BPF_WRITE; 19138 } else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) || 19139 insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) && 19140 env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) { 19141 insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code); 19142 env->prog->aux->num_exentries++; 19143 continue; 19144 } else { 19145 continue; 19146 } 19147 19148 if (type == BPF_WRITE && 19149 env->insn_aux_data[i + delta].sanitize_stack_spill) { 19150 struct bpf_insn patch[] = { 19151 *insn, 19152 BPF_ST_NOSPEC(), 19153 }; 19154 19155 cnt = ARRAY_SIZE(patch); 19156 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 19157 if (!new_prog) 19158 return -ENOMEM; 19159 19160 delta += cnt - 1; 19161 env->prog = new_prog; 19162 insn = new_prog->insnsi + i + delta; 19163 continue; 19164 } 19165 19166 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 19167 case PTR_TO_CTX: 19168 if (!ops->convert_ctx_access) 19169 continue; 19170 convert_ctx_access = ops->convert_ctx_access; 19171 break; 19172 case PTR_TO_SOCKET: 19173 case PTR_TO_SOCK_COMMON: 19174 convert_ctx_access = bpf_sock_convert_ctx_access; 19175 break; 19176 case PTR_TO_TCP_SOCK: 19177 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 19178 break; 19179 case PTR_TO_XDP_SOCK: 19180 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 19181 break; 19182 case PTR_TO_BTF_ID: 19183 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 19184 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 19185 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 19186 * be said once it is marked PTR_UNTRUSTED, hence we must handle 19187 * any faults for loads into such types. BPF_WRITE is disallowed 19188 * for this case. 19189 */ 19190 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 19191 if (type == BPF_READ) { 19192 if (BPF_MODE(insn->code) == BPF_MEM) 19193 insn->code = BPF_LDX | BPF_PROBE_MEM | 19194 BPF_SIZE((insn)->code); 19195 else 19196 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 19197 BPF_SIZE((insn)->code); 19198 env->prog->aux->num_exentries++; 19199 } 19200 continue; 19201 case PTR_TO_ARENA: 19202 if (BPF_MODE(insn->code) == BPF_MEMSX) { 19203 verbose(env, "sign extending loads from arena are not supported yet\n"); 19204 return -EOPNOTSUPP; 19205 } 19206 insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code); 19207 env->prog->aux->num_exentries++; 19208 continue; 19209 default: 19210 continue; 19211 } 19212 19213 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 19214 size = BPF_LDST_BYTES(insn); 19215 mode = BPF_MODE(insn->code); 19216 19217 /* If the read access is a narrower load of the field, 19218 * convert to a 4/8-byte load, to minimum program type specific 19219 * convert_ctx_access changes. If conversion is successful, 19220 * we will apply proper mask to the result. 19221 */ 19222 is_narrower_load = size < ctx_field_size; 19223 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 19224 off = insn->off; 19225 if (is_narrower_load) { 19226 u8 size_code; 19227 19228 if (type == BPF_WRITE) { 19229 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 19230 return -EINVAL; 19231 } 19232 19233 size_code = BPF_H; 19234 if (ctx_field_size == 4) 19235 size_code = BPF_W; 19236 else if (ctx_field_size == 8) 19237 size_code = BPF_DW; 19238 19239 insn->off = off & ~(size_default - 1); 19240 insn->code = BPF_LDX | BPF_MEM | size_code; 19241 } 19242 19243 target_size = 0; 19244 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 19245 &target_size); 19246 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 19247 (ctx_field_size && !target_size)) { 19248 verbose(env, "bpf verifier is misconfigured\n"); 19249 return -EINVAL; 19250 } 19251 19252 if (is_narrower_load && size < target_size) { 19253 u8 shift = bpf_ctx_narrow_access_offset( 19254 off, size, size_default) * 8; 19255 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 19256 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 19257 return -EINVAL; 19258 } 19259 if (ctx_field_size <= 4) { 19260 if (shift) 19261 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 19262 insn->dst_reg, 19263 shift); 19264 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 19265 (1 << size * 8) - 1); 19266 } else { 19267 if (shift) 19268 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 19269 insn->dst_reg, 19270 shift); 19271 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 19272 (1ULL << size * 8) - 1); 19273 } 19274 } 19275 if (mode == BPF_MEMSX) 19276 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 19277 insn->dst_reg, insn->dst_reg, 19278 size * 8, 0); 19279 19280 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19281 if (!new_prog) 19282 return -ENOMEM; 19283 19284 delta += cnt - 1; 19285 19286 /* keep walking new program and skip insns we just inserted */ 19287 env->prog = new_prog; 19288 insn = new_prog->insnsi + i + delta; 19289 } 19290 19291 return 0; 19292 } 19293 19294 static int jit_subprogs(struct bpf_verifier_env *env) 19295 { 19296 struct bpf_prog *prog = env->prog, **func, *tmp; 19297 int i, j, subprog_start, subprog_end = 0, len, subprog; 19298 struct bpf_map *map_ptr; 19299 struct bpf_insn *insn; 19300 void *old_bpf_func; 19301 int err, num_exentries; 19302 19303 if (env->subprog_cnt <= 1) 19304 return 0; 19305 19306 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 19307 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 19308 continue; 19309 19310 /* Upon error here we cannot fall back to interpreter but 19311 * need a hard reject of the program. Thus -EFAULT is 19312 * propagated in any case. 19313 */ 19314 subprog = find_subprog(env, i + insn->imm + 1); 19315 if (subprog < 0) { 19316 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 19317 i + insn->imm + 1); 19318 return -EFAULT; 19319 } 19320 /* temporarily remember subprog id inside insn instead of 19321 * aux_data, since next loop will split up all insns into funcs 19322 */ 19323 insn->off = subprog; 19324 /* remember original imm in case JIT fails and fallback 19325 * to interpreter will be needed 19326 */ 19327 env->insn_aux_data[i].call_imm = insn->imm; 19328 /* point imm to __bpf_call_base+1 from JITs point of view */ 19329 insn->imm = 1; 19330 if (bpf_pseudo_func(insn)) { 19331 #if defined(MODULES_VADDR) 19332 u64 addr = MODULES_VADDR; 19333 #else 19334 u64 addr = VMALLOC_START; 19335 #endif 19336 /* jit (e.g. x86_64) may emit fewer instructions 19337 * if it learns a u32 imm is the same as a u64 imm. 19338 * Set close enough to possible prog address. 19339 */ 19340 insn[0].imm = (u32)addr; 19341 insn[1].imm = addr >> 32; 19342 } 19343 } 19344 19345 err = bpf_prog_alloc_jited_linfo(prog); 19346 if (err) 19347 goto out_undo_insn; 19348 19349 err = -ENOMEM; 19350 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 19351 if (!func) 19352 goto out_undo_insn; 19353 19354 for (i = 0; i < env->subprog_cnt; i++) { 19355 subprog_start = subprog_end; 19356 subprog_end = env->subprog_info[i + 1].start; 19357 19358 len = subprog_end - subprog_start; 19359 /* bpf_prog_run() doesn't call subprogs directly, 19360 * hence main prog stats include the runtime of subprogs. 19361 * subprogs don't have IDs and not reachable via prog_get_next_id 19362 * func[i]->stats will never be accessed and stays NULL 19363 */ 19364 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 19365 if (!func[i]) 19366 goto out_free; 19367 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 19368 len * sizeof(struct bpf_insn)); 19369 func[i]->type = prog->type; 19370 func[i]->len = len; 19371 if (bpf_prog_calc_tag(func[i])) 19372 goto out_free; 19373 func[i]->is_func = 1; 19374 func[i]->sleepable = prog->sleepable; 19375 func[i]->aux->func_idx = i; 19376 /* Below members will be freed only at prog->aux */ 19377 func[i]->aux->btf = prog->aux->btf; 19378 func[i]->aux->func_info = prog->aux->func_info; 19379 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 19380 func[i]->aux->poke_tab = prog->aux->poke_tab; 19381 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 19382 19383 for (j = 0; j < prog->aux->size_poke_tab; j++) { 19384 struct bpf_jit_poke_descriptor *poke; 19385 19386 poke = &prog->aux->poke_tab[j]; 19387 if (poke->insn_idx < subprog_end && 19388 poke->insn_idx >= subprog_start) 19389 poke->aux = func[i]->aux; 19390 } 19391 19392 func[i]->aux->name[0] = 'F'; 19393 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 19394 func[i]->jit_requested = 1; 19395 func[i]->blinding_requested = prog->blinding_requested; 19396 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 19397 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 19398 func[i]->aux->linfo = prog->aux->linfo; 19399 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 19400 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 19401 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 19402 func[i]->aux->arena = prog->aux->arena; 19403 num_exentries = 0; 19404 insn = func[i]->insnsi; 19405 for (j = 0; j < func[i]->len; j++, insn++) { 19406 if (BPF_CLASS(insn->code) == BPF_LDX && 19407 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 19408 BPF_MODE(insn->code) == BPF_PROBE_MEM32 || 19409 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 19410 num_exentries++; 19411 if ((BPF_CLASS(insn->code) == BPF_STX || 19412 BPF_CLASS(insn->code) == BPF_ST) && 19413 BPF_MODE(insn->code) == BPF_PROBE_MEM32) 19414 num_exentries++; 19415 if (BPF_CLASS(insn->code) == BPF_STX && 19416 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) 19417 num_exentries++; 19418 } 19419 func[i]->aux->num_exentries = num_exentries; 19420 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 19421 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb; 19422 if (!i) 19423 func[i]->aux->exception_boundary = env->seen_exception; 19424 func[i] = bpf_int_jit_compile(func[i]); 19425 if (!func[i]->jited) { 19426 err = -ENOTSUPP; 19427 goto out_free; 19428 } 19429 cond_resched(); 19430 } 19431 19432 /* at this point all bpf functions were successfully JITed 19433 * now populate all bpf_calls with correct addresses and 19434 * run last pass of JIT 19435 */ 19436 for (i = 0; i < env->subprog_cnt; i++) { 19437 insn = func[i]->insnsi; 19438 for (j = 0; j < func[i]->len; j++, insn++) { 19439 if (bpf_pseudo_func(insn)) { 19440 subprog = insn->off; 19441 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 19442 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 19443 continue; 19444 } 19445 if (!bpf_pseudo_call(insn)) 19446 continue; 19447 subprog = insn->off; 19448 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 19449 } 19450 19451 /* we use the aux data to keep a list of the start addresses 19452 * of the JITed images for each function in the program 19453 * 19454 * for some architectures, such as powerpc64, the imm field 19455 * might not be large enough to hold the offset of the start 19456 * address of the callee's JITed image from __bpf_call_base 19457 * 19458 * in such cases, we can lookup the start address of a callee 19459 * by using its subprog id, available from the off field of 19460 * the call instruction, as an index for this list 19461 */ 19462 func[i]->aux->func = func; 19463 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 19464 func[i]->aux->real_func_cnt = env->subprog_cnt; 19465 } 19466 for (i = 0; i < env->subprog_cnt; i++) { 19467 old_bpf_func = func[i]->bpf_func; 19468 tmp = bpf_int_jit_compile(func[i]); 19469 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 19470 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 19471 err = -ENOTSUPP; 19472 goto out_free; 19473 } 19474 cond_resched(); 19475 } 19476 19477 /* finally lock prog and jit images for all functions and 19478 * populate kallsysm. Begin at the first subprogram, since 19479 * bpf_prog_load will add the kallsyms for the main program. 19480 */ 19481 for (i = 1; i < env->subprog_cnt; i++) { 19482 err = bpf_prog_lock_ro(func[i]); 19483 if (err) 19484 goto out_free; 19485 } 19486 19487 for (i = 1; i < env->subprog_cnt; i++) 19488 bpf_prog_kallsyms_add(func[i]); 19489 19490 /* Last step: make now unused interpreter insns from main 19491 * prog consistent for later dump requests, so they can 19492 * later look the same as if they were interpreted only. 19493 */ 19494 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 19495 if (bpf_pseudo_func(insn)) { 19496 insn[0].imm = env->insn_aux_data[i].call_imm; 19497 insn[1].imm = insn->off; 19498 insn->off = 0; 19499 continue; 19500 } 19501 if (!bpf_pseudo_call(insn)) 19502 continue; 19503 insn->off = env->insn_aux_data[i].call_imm; 19504 subprog = find_subprog(env, i + insn->off + 1); 19505 insn->imm = subprog; 19506 } 19507 19508 prog->jited = 1; 19509 prog->bpf_func = func[0]->bpf_func; 19510 prog->jited_len = func[0]->jited_len; 19511 prog->aux->extable = func[0]->aux->extable; 19512 prog->aux->num_exentries = func[0]->aux->num_exentries; 19513 prog->aux->func = func; 19514 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 19515 prog->aux->real_func_cnt = env->subprog_cnt; 19516 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func; 19517 prog->aux->exception_boundary = func[0]->aux->exception_boundary; 19518 bpf_prog_jit_attempt_done(prog); 19519 return 0; 19520 out_free: 19521 /* We failed JIT'ing, so at this point we need to unregister poke 19522 * descriptors from subprogs, so that kernel is not attempting to 19523 * patch it anymore as we're freeing the subprog JIT memory. 19524 */ 19525 for (i = 0; i < prog->aux->size_poke_tab; i++) { 19526 map_ptr = prog->aux->poke_tab[i].tail_call.map; 19527 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 19528 } 19529 /* At this point we're guaranteed that poke descriptors are not 19530 * live anymore. We can just unlink its descriptor table as it's 19531 * released with the main prog. 19532 */ 19533 for (i = 0; i < env->subprog_cnt; i++) { 19534 if (!func[i]) 19535 continue; 19536 func[i]->aux->poke_tab = NULL; 19537 bpf_jit_free(func[i]); 19538 } 19539 kfree(func); 19540 out_undo_insn: 19541 /* cleanup main prog to be interpreted */ 19542 prog->jit_requested = 0; 19543 prog->blinding_requested = 0; 19544 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 19545 if (!bpf_pseudo_call(insn)) 19546 continue; 19547 insn->off = 0; 19548 insn->imm = env->insn_aux_data[i].call_imm; 19549 } 19550 bpf_prog_jit_attempt_done(prog); 19551 return err; 19552 } 19553 19554 static int fixup_call_args(struct bpf_verifier_env *env) 19555 { 19556 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 19557 struct bpf_prog *prog = env->prog; 19558 struct bpf_insn *insn = prog->insnsi; 19559 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 19560 int i, depth; 19561 #endif 19562 int err = 0; 19563 19564 if (env->prog->jit_requested && 19565 !bpf_prog_is_offloaded(env->prog->aux)) { 19566 err = jit_subprogs(env); 19567 if (err == 0) 19568 return 0; 19569 if (err == -EFAULT) 19570 return err; 19571 } 19572 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 19573 if (has_kfunc_call) { 19574 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 19575 return -EINVAL; 19576 } 19577 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 19578 /* When JIT fails the progs with bpf2bpf calls and tail_calls 19579 * have to be rejected, since interpreter doesn't support them yet. 19580 */ 19581 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 19582 return -EINVAL; 19583 } 19584 for (i = 0; i < prog->len; i++, insn++) { 19585 if (bpf_pseudo_func(insn)) { 19586 /* When JIT fails the progs with callback calls 19587 * have to be rejected, since interpreter doesn't support them yet. 19588 */ 19589 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 19590 return -EINVAL; 19591 } 19592 19593 if (!bpf_pseudo_call(insn)) 19594 continue; 19595 depth = get_callee_stack_depth(env, insn, i); 19596 if (depth < 0) 19597 return depth; 19598 bpf_patch_call_args(insn, depth); 19599 } 19600 err = 0; 19601 #endif 19602 return err; 19603 } 19604 19605 /* replace a generic kfunc with a specialized version if necessary */ 19606 static void specialize_kfunc(struct bpf_verifier_env *env, 19607 u32 func_id, u16 offset, unsigned long *addr) 19608 { 19609 struct bpf_prog *prog = env->prog; 19610 bool seen_direct_write; 19611 void *xdp_kfunc; 19612 bool is_rdonly; 19613 19614 if (bpf_dev_bound_kfunc_id(func_id)) { 19615 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 19616 if (xdp_kfunc) { 19617 *addr = (unsigned long)xdp_kfunc; 19618 return; 19619 } 19620 /* fallback to default kfunc when not supported by netdev */ 19621 } 19622 19623 if (offset) 19624 return; 19625 19626 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 19627 seen_direct_write = env->seen_direct_write; 19628 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 19629 19630 if (is_rdonly) 19631 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 19632 19633 /* restore env->seen_direct_write to its original value, since 19634 * may_access_direct_pkt_data mutates it 19635 */ 19636 env->seen_direct_write = seen_direct_write; 19637 } 19638 } 19639 19640 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 19641 u16 struct_meta_reg, 19642 u16 node_offset_reg, 19643 struct bpf_insn *insn, 19644 struct bpf_insn *insn_buf, 19645 int *cnt) 19646 { 19647 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 19648 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 19649 19650 insn_buf[0] = addr[0]; 19651 insn_buf[1] = addr[1]; 19652 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 19653 insn_buf[3] = *insn; 19654 *cnt = 4; 19655 } 19656 19657 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 19658 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 19659 { 19660 const struct bpf_kfunc_desc *desc; 19661 19662 if (!insn->imm) { 19663 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 19664 return -EINVAL; 19665 } 19666 19667 *cnt = 0; 19668 19669 /* insn->imm has the btf func_id. Replace it with an offset relative to 19670 * __bpf_call_base, unless the JIT needs to call functions that are 19671 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 19672 */ 19673 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 19674 if (!desc) { 19675 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 19676 insn->imm); 19677 return -EFAULT; 19678 } 19679 19680 if (!bpf_jit_supports_far_kfunc_call()) 19681 insn->imm = BPF_CALL_IMM(desc->addr); 19682 if (insn->off) 19683 return 0; 19684 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 19685 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 19686 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19687 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19688 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 19689 19690 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) { 19691 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 19692 insn_idx); 19693 return -EFAULT; 19694 } 19695 19696 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 19697 insn_buf[1] = addr[0]; 19698 insn_buf[2] = addr[1]; 19699 insn_buf[3] = *insn; 19700 *cnt = 4; 19701 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 19702 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] || 19703 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 19704 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19705 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19706 19707 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) { 19708 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 19709 insn_idx); 19710 return -EFAULT; 19711 } 19712 19713 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 19714 !kptr_struct_meta) { 19715 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 19716 insn_idx); 19717 return -EFAULT; 19718 } 19719 19720 insn_buf[0] = addr[0]; 19721 insn_buf[1] = addr[1]; 19722 insn_buf[2] = *insn; 19723 *cnt = 3; 19724 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 19725 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 19726 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 19727 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19728 int struct_meta_reg = BPF_REG_3; 19729 int node_offset_reg = BPF_REG_4; 19730 19731 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 19732 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 19733 struct_meta_reg = BPF_REG_4; 19734 node_offset_reg = BPF_REG_5; 19735 } 19736 19737 if (!kptr_struct_meta) { 19738 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 19739 insn_idx); 19740 return -EFAULT; 19741 } 19742 19743 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 19744 node_offset_reg, insn, insn_buf, cnt); 19745 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 19746 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 19747 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 19748 *cnt = 1; 19749 } else if (is_bpf_wq_set_callback_impl_kfunc(desc->func_id)) { 19750 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(BPF_REG_4, (long)env->prog->aux) }; 19751 19752 insn_buf[0] = ld_addrs[0]; 19753 insn_buf[1] = ld_addrs[1]; 19754 insn_buf[2] = *insn; 19755 *cnt = 3; 19756 } 19757 return 0; 19758 } 19759 19760 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */ 19761 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len) 19762 { 19763 struct bpf_subprog_info *info = env->subprog_info; 19764 int cnt = env->subprog_cnt; 19765 struct bpf_prog *prog; 19766 19767 /* We only reserve one slot for hidden subprogs in subprog_info. */ 19768 if (env->hidden_subprog_cnt) { 19769 verbose(env, "verifier internal error: only one hidden subprog supported\n"); 19770 return -EFAULT; 19771 } 19772 /* We're not patching any existing instruction, just appending the new 19773 * ones for the hidden subprog. Hence all of the adjustment operations 19774 * in bpf_patch_insn_data are no-ops. 19775 */ 19776 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len); 19777 if (!prog) 19778 return -ENOMEM; 19779 env->prog = prog; 19780 info[cnt + 1].start = info[cnt].start; 19781 info[cnt].start = prog->len - len + 1; 19782 env->subprog_cnt++; 19783 env->hidden_subprog_cnt++; 19784 return 0; 19785 } 19786 19787 /* Do various post-verification rewrites in a single program pass. 19788 * These rewrites simplify JIT and interpreter implementations. 19789 */ 19790 static int do_misc_fixups(struct bpf_verifier_env *env) 19791 { 19792 struct bpf_prog *prog = env->prog; 19793 enum bpf_attach_type eatype = prog->expected_attach_type; 19794 enum bpf_prog_type prog_type = resolve_prog_type(prog); 19795 struct bpf_insn *insn = prog->insnsi; 19796 const struct bpf_func_proto *fn; 19797 const int insn_cnt = prog->len; 19798 const struct bpf_map_ops *ops; 19799 struct bpf_insn_aux_data *aux; 19800 struct bpf_insn insn_buf[16]; 19801 struct bpf_prog *new_prog; 19802 struct bpf_map *map_ptr; 19803 int i, ret, cnt, delta = 0, cur_subprog = 0; 19804 struct bpf_subprog_info *subprogs = env->subprog_info; 19805 u16 stack_depth = subprogs[cur_subprog].stack_depth; 19806 u16 stack_depth_extra = 0; 19807 19808 if (env->seen_exception && !env->exception_callback_subprog) { 19809 struct bpf_insn patch[] = { 19810 env->prog->insnsi[insn_cnt - 1], 19811 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1), 19812 BPF_EXIT_INSN(), 19813 }; 19814 19815 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch)); 19816 if (ret < 0) 19817 return ret; 19818 prog = env->prog; 19819 insn = prog->insnsi; 19820 19821 env->exception_callback_subprog = env->subprog_cnt - 1; 19822 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */ 19823 mark_subprog_exc_cb(env, env->exception_callback_subprog); 19824 } 19825 19826 for (i = 0; i < insn_cnt;) { 19827 if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) { 19828 if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) || 19829 (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) { 19830 /* convert to 32-bit mov that clears upper 32-bit */ 19831 insn->code = BPF_ALU | BPF_MOV | BPF_X; 19832 /* clear off and imm, so it's a normal 'wX = wY' from JIT pov */ 19833 insn->off = 0; 19834 insn->imm = 0; 19835 } /* cast from as(0) to as(1) should be handled by JIT */ 19836 goto next_insn; 19837 } 19838 19839 if (env->insn_aux_data[i + delta].needs_zext) 19840 /* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */ 19841 insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code); 19842 19843 /* Make divide-by-zero exceptions impossible. */ 19844 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 19845 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 19846 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 19847 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 19848 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 19849 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 19850 struct bpf_insn *patchlet; 19851 struct bpf_insn chk_and_div[] = { 19852 /* [R,W]x div 0 -> 0 */ 19853 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 19854 BPF_JNE | BPF_K, insn->src_reg, 19855 0, 2, 0), 19856 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 19857 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 19858 *insn, 19859 }; 19860 struct bpf_insn chk_and_mod[] = { 19861 /* [R,W]x mod 0 -> [R,W]x */ 19862 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 19863 BPF_JEQ | BPF_K, insn->src_reg, 19864 0, 1 + (is64 ? 0 : 1), 0), 19865 *insn, 19866 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 19867 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 19868 }; 19869 19870 patchlet = isdiv ? chk_and_div : chk_and_mod; 19871 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 19872 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 19873 19874 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 19875 if (!new_prog) 19876 return -ENOMEM; 19877 19878 delta += cnt - 1; 19879 env->prog = prog = new_prog; 19880 insn = new_prog->insnsi + i + delta; 19881 goto next_insn; 19882 } 19883 19884 /* Make it impossible to de-reference a userspace address */ 19885 if (BPF_CLASS(insn->code) == BPF_LDX && 19886 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 19887 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) { 19888 struct bpf_insn *patch = &insn_buf[0]; 19889 u64 uaddress_limit = bpf_arch_uaddress_limit(); 19890 19891 if (!uaddress_limit) 19892 goto next_insn; 19893 19894 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg); 19895 if (insn->off) 19896 *patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off); 19897 *patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32); 19898 *patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2); 19899 *patch++ = *insn; 19900 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 19901 *patch++ = BPF_MOV64_IMM(insn->dst_reg, 0); 19902 19903 cnt = patch - insn_buf; 19904 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19905 if (!new_prog) 19906 return -ENOMEM; 19907 19908 delta += cnt - 1; 19909 env->prog = prog = new_prog; 19910 insn = new_prog->insnsi + i + delta; 19911 goto next_insn; 19912 } 19913 19914 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 19915 if (BPF_CLASS(insn->code) == BPF_LD && 19916 (BPF_MODE(insn->code) == BPF_ABS || 19917 BPF_MODE(insn->code) == BPF_IND)) { 19918 cnt = env->ops->gen_ld_abs(insn, insn_buf); 19919 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19920 verbose(env, "bpf verifier is misconfigured\n"); 19921 return -EINVAL; 19922 } 19923 19924 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19925 if (!new_prog) 19926 return -ENOMEM; 19927 19928 delta += cnt - 1; 19929 env->prog = prog = new_prog; 19930 insn = new_prog->insnsi + i + delta; 19931 goto next_insn; 19932 } 19933 19934 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 19935 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 19936 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 19937 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 19938 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 19939 struct bpf_insn *patch = &insn_buf[0]; 19940 bool issrc, isneg, isimm; 19941 u32 off_reg; 19942 19943 aux = &env->insn_aux_data[i + delta]; 19944 if (!aux->alu_state || 19945 aux->alu_state == BPF_ALU_NON_POINTER) 19946 goto next_insn; 19947 19948 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 19949 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 19950 BPF_ALU_SANITIZE_SRC; 19951 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 19952 19953 off_reg = issrc ? insn->src_reg : insn->dst_reg; 19954 if (isimm) { 19955 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19956 } else { 19957 if (isneg) 19958 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19959 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19960 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 19961 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 19962 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 19963 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 19964 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 19965 } 19966 if (!issrc) 19967 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 19968 insn->src_reg = BPF_REG_AX; 19969 if (isneg) 19970 insn->code = insn->code == code_add ? 19971 code_sub : code_add; 19972 *patch++ = *insn; 19973 if (issrc && isneg && !isimm) 19974 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19975 cnt = patch - insn_buf; 19976 19977 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19978 if (!new_prog) 19979 return -ENOMEM; 19980 19981 delta += cnt - 1; 19982 env->prog = prog = new_prog; 19983 insn = new_prog->insnsi + i + delta; 19984 goto next_insn; 19985 } 19986 19987 if (is_may_goto_insn(insn)) { 19988 int stack_off = -stack_depth - 8; 19989 19990 stack_depth_extra = 8; 19991 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off); 19992 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2); 19993 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1); 19994 insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off); 19995 cnt = 4; 19996 19997 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19998 if (!new_prog) 19999 return -ENOMEM; 20000 20001 delta += cnt - 1; 20002 env->prog = prog = new_prog; 20003 insn = new_prog->insnsi + i + delta; 20004 goto next_insn; 20005 } 20006 20007 if (insn->code != (BPF_JMP | BPF_CALL)) 20008 goto next_insn; 20009 if (insn->src_reg == BPF_PSEUDO_CALL) 20010 goto next_insn; 20011 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 20012 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 20013 if (ret) 20014 return ret; 20015 if (cnt == 0) 20016 goto next_insn; 20017 20018 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20019 if (!new_prog) 20020 return -ENOMEM; 20021 20022 delta += cnt - 1; 20023 env->prog = prog = new_prog; 20024 insn = new_prog->insnsi + i + delta; 20025 goto next_insn; 20026 } 20027 20028 /* Skip inlining the helper call if the JIT does it. */ 20029 if (bpf_jit_inlines_helper_call(insn->imm)) 20030 goto next_insn; 20031 20032 if (insn->imm == BPF_FUNC_get_route_realm) 20033 prog->dst_needed = 1; 20034 if (insn->imm == BPF_FUNC_get_prandom_u32) 20035 bpf_user_rnd_init_once(); 20036 if (insn->imm == BPF_FUNC_override_return) 20037 prog->kprobe_override = 1; 20038 if (insn->imm == BPF_FUNC_tail_call) { 20039 /* If we tail call into other programs, we 20040 * cannot make any assumptions since they can 20041 * be replaced dynamically during runtime in 20042 * the program array. 20043 */ 20044 prog->cb_access = 1; 20045 if (!allow_tail_call_in_subprogs(env)) 20046 prog->aux->stack_depth = MAX_BPF_STACK; 20047 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 20048 20049 /* mark bpf_tail_call as different opcode to avoid 20050 * conditional branch in the interpreter for every normal 20051 * call and to prevent accidental JITing by JIT compiler 20052 * that doesn't support bpf_tail_call yet 20053 */ 20054 insn->imm = 0; 20055 insn->code = BPF_JMP | BPF_TAIL_CALL; 20056 20057 aux = &env->insn_aux_data[i + delta]; 20058 if (env->bpf_capable && !prog->blinding_requested && 20059 prog->jit_requested && 20060 !bpf_map_key_poisoned(aux) && 20061 !bpf_map_ptr_poisoned(aux) && 20062 !bpf_map_ptr_unpriv(aux)) { 20063 struct bpf_jit_poke_descriptor desc = { 20064 .reason = BPF_POKE_REASON_TAIL_CALL, 20065 .tail_call.map = aux->map_ptr_state.map_ptr, 20066 .tail_call.key = bpf_map_key_immediate(aux), 20067 .insn_idx = i + delta, 20068 }; 20069 20070 ret = bpf_jit_add_poke_descriptor(prog, &desc); 20071 if (ret < 0) { 20072 verbose(env, "adding tail call poke descriptor failed\n"); 20073 return ret; 20074 } 20075 20076 insn->imm = ret + 1; 20077 goto next_insn; 20078 } 20079 20080 if (!bpf_map_ptr_unpriv(aux)) 20081 goto next_insn; 20082 20083 /* instead of changing every JIT dealing with tail_call 20084 * emit two extra insns: 20085 * if (index >= max_entries) goto out; 20086 * index &= array->index_mask; 20087 * to avoid out-of-bounds cpu speculation 20088 */ 20089 if (bpf_map_ptr_poisoned(aux)) { 20090 verbose(env, "tail_call abusing map_ptr\n"); 20091 return -EINVAL; 20092 } 20093 20094 map_ptr = aux->map_ptr_state.map_ptr; 20095 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 20096 map_ptr->max_entries, 2); 20097 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 20098 container_of(map_ptr, 20099 struct bpf_array, 20100 map)->index_mask); 20101 insn_buf[2] = *insn; 20102 cnt = 3; 20103 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20104 if (!new_prog) 20105 return -ENOMEM; 20106 20107 delta += cnt - 1; 20108 env->prog = prog = new_prog; 20109 insn = new_prog->insnsi + i + delta; 20110 goto next_insn; 20111 } 20112 20113 if (insn->imm == BPF_FUNC_timer_set_callback) { 20114 /* The verifier will process callback_fn as many times as necessary 20115 * with different maps and the register states prepared by 20116 * set_timer_callback_state will be accurate. 20117 * 20118 * The following use case is valid: 20119 * map1 is shared by prog1, prog2, prog3. 20120 * prog1 calls bpf_timer_init for some map1 elements 20121 * prog2 calls bpf_timer_set_callback for some map1 elements. 20122 * Those that were not bpf_timer_init-ed will return -EINVAL. 20123 * prog3 calls bpf_timer_start for some map1 elements. 20124 * Those that were not both bpf_timer_init-ed and 20125 * bpf_timer_set_callback-ed will return -EINVAL. 20126 */ 20127 struct bpf_insn ld_addrs[2] = { 20128 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 20129 }; 20130 20131 insn_buf[0] = ld_addrs[0]; 20132 insn_buf[1] = ld_addrs[1]; 20133 insn_buf[2] = *insn; 20134 cnt = 3; 20135 20136 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20137 if (!new_prog) 20138 return -ENOMEM; 20139 20140 delta += cnt - 1; 20141 env->prog = prog = new_prog; 20142 insn = new_prog->insnsi + i + delta; 20143 goto patch_call_imm; 20144 } 20145 20146 if (is_storage_get_function(insn->imm)) { 20147 if (!in_sleepable(env) || 20148 env->insn_aux_data[i + delta].storage_get_func_atomic) 20149 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 20150 else 20151 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 20152 insn_buf[1] = *insn; 20153 cnt = 2; 20154 20155 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20156 if (!new_prog) 20157 return -ENOMEM; 20158 20159 delta += cnt - 1; 20160 env->prog = prog = new_prog; 20161 insn = new_prog->insnsi + i + delta; 20162 goto patch_call_imm; 20163 } 20164 20165 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */ 20166 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) { 20167 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data, 20168 * bpf_mem_alloc() returns a ptr to the percpu data ptr. 20169 */ 20170 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0); 20171 insn_buf[1] = *insn; 20172 cnt = 2; 20173 20174 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20175 if (!new_prog) 20176 return -ENOMEM; 20177 20178 delta += cnt - 1; 20179 env->prog = prog = new_prog; 20180 insn = new_prog->insnsi + i + delta; 20181 goto patch_call_imm; 20182 } 20183 20184 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 20185 * and other inlining handlers are currently limited to 64 bit 20186 * only. 20187 */ 20188 if (prog->jit_requested && BITS_PER_LONG == 64 && 20189 (insn->imm == BPF_FUNC_map_lookup_elem || 20190 insn->imm == BPF_FUNC_map_update_elem || 20191 insn->imm == BPF_FUNC_map_delete_elem || 20192 insn->imm == BPF_FUNC_map_push_elem || 20193 insn->imm == BPF_FUNC_map_pop_elem || 20194 insn->imm == BPF_FUNC_map_peek_elem || 20195 insn->imm == BPF_FUNC_redirect_map || 20196 insn->imm == BPF_FUNC_for_each_map_elem || 20197 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 20198 aux = &env->insn_aux_data[i + delta]; 20199 if (bpf_map_ptr_poisoned(aux)) 20200 goto patch_call_imm; 20201 20202 map_ptr = aux->map_ptr_state.map_ptr; 20203 ops = map_ptr->ops; 20204 if (insn->imm == BPF_FUNC_map_lookup_elem && 20205 ops->map_gen_lookup) { 20206 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 20207 if (cnt == -EOPNOTSUPP) 20208 goto patch_map_ops_generic; 20209 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 20210 verbose(env, "bpf verifier is misconfigured\n"); 20211 return -EINVAL; 20212 } 20213 20214 new_prog = bpf_patch_insn_data(env, i + delta, 20215 insn_buf, cnt); 20216 if (!new_prog) 20217 return -ENOMEM; 20218 20219 delta += cnt - 1; 20220 env->prog = prog = new_prog; 20221 insn = new_prog->insnsi + i + delta; 20222 goto next_insn; 20223 } 20224 20225 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 20226 (void *(*)(struct bpf_map *map, void *key))NULL)); 20227 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 20228 (long (*)(struct bpf_map *map, void *key))NULL)); 20229 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 20230 (long (*)(struct bpf_map *map, void *key, void *value, 20231 u64 flags))NULL)); 20232 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 20233 (long (*)(struct bpf_map *map, void *value, 20234 u64 flags))NULL)); 20235 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 20236 (long (*)(struct bpf_map *map, void *value))NULL)); 20237 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 20238 (long (*)(struct bpf_map *map, void *value))NULL)); 20239 BUILD_BUG_ON(!__same_type(ops->map_redirect, 20240 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 20241 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 20242 (long (*)(struct bpf_map *map, 20243 bpf_callback_t callback_fn, 20244 void *callback_ctx, 20245 u64 flags))NULL)); 20246 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 20247 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 20248 20249 patch_map_ops_generic: 20250 switch (insn->imm) { 20251 case BPF_FUNC_map_lookup_elem: 20252 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 20253 goto next_insn; 20254 case BPF_FUNC_map_update_elem: 20255 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 20256 goto next_insn; 20257 case BPF_FUNC_map_delete_elem: 20258 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 20259 goto next_insn; 20260 case BPF_FUNC_map_push_elem: 20261 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 20262 goto next_insn; 20263 case BPF_FUNC_map_pop_elem: 20264 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 20265 goto next_insn; 20266 case BPF_FUNC_map_peek_elem: 20267 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 20268 goto next_insn; 20269 case BPF_FUNC_redirect_map: 20270 insn->imm = BPF_CALL_IMM(ops->map_redirect); 20271 goto next_insn; 20272 case BPF_FUNC_for_each_map_elem: 20273 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 20274 goto next_insn; 20275 case BPF_FUNC_map_lookup_percpu_elem: 20276 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 20277 goto next_insn; 20278 } 20279 20280 goto patch_call_imm; 20281 } 20282 20283 /* Implement bpf_jiffies64 inline. */ 20284 if (prog->jit_requested && BITS_PER_LONG == 64 && 20285 insn->imm == BPF_FUNC_jiffies64) { 20286 struct bpf_insn ld_jiffies_addr[2] = { 20287 BPF_LD_IMM64(BPF_REG_0, 20288 (unsigned long)&jiffies), 20289 }; 20290 20291 insn_buf[0] = ld_jiffies_addr[0]; 20292 insn_buf[1] = ld_jiffies_addr[1]; 20293 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 20294 BPF_REG_0, 0); 20295 cnt = 3; 20296 20297 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 20298 cnt); 20299 if (!new_prog) 20300 return -ENOMEM; 20301 20302 delta += cnt - 1; 20303 env->prog = prog = new_prog; 20304 insn = new_prog->insnsi + i + delta; 20305 goto next_insn; 20306 } 20307 20308 #ifdef CONFIG_X86_64 20309 /* Implement bpf_get_smp_processor_id() inline. */ 20310 if (insn->imm == BPF_FUNC_get_smp_processor_id && 20311 prog->jit_requested && bpf_jit_supports_percpu_insn()) { 20312 /* BPF_FUNC_get_smp_processor_id inlining is an 20313 * optimization, so if pcpu_hot.cpu_number is ever 20314 * changed in some incompatible and hard to support 20315 * way, it's fine to back out this inlining logic 20316 */ 20317 insn_buf[0] = BPF_MOV32_IMM(BPF_REG_0, (u32)(unsigned long)&pcpu_hot.cpu_number); 20318 insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0); 20319 insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0); 20320 cnt = 3; 20321 20322 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20323 if (!new_prog) 20324 return -ENOMEM; 20325 20326 delta += cnt - 1; 20327 env->prog = prog = new_prog; 20328 insn = new_prog->insnsi + i + delta; 20329 goto next_insn; 20330 } 20331 #endif 20332 /* Implement bpf_get_func_arg inline. */ 20333 if (prog_type == BPF_PROG_TYPE_TRACING && 20334 insn->imm == BPF_FUNC_get_func_arg) { 20335 /* Load nr_args from ctx - 8 */ 20336 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 20337 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 20338 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 20339 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 20340 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 20341 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 20342 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 20343 insn_buf[7] = BPF_JMP_A(1); 20344 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 20345 cnt = 9; 20346 20347 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20348 if (!new_prog) 20349 return -ENOMEM; 20350 20351 delta += cnt - 1; 20352 env->prog = prog = new_prog; 20353 insn = new_prog->insnsi + i + delta; 20354 goto next_insn; 20355 } 20356 20357 /* Implement bpf_get_func_ret inline. */ 20358 if (prog_type == BPF_PROG_TYPE_TRACING && 20359 insn->imm == BPF_FUNC_get_func_ret) { 20360 if (eatype == BPF_TRACE_FEXIT || 20361 eatype == BPF_MODIFY_RETURN) { 20362 /* Load nr_args from ctx - 8 */ 20363 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 20364 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 20365 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 20366 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 20367 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 20368 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 20369 cnt = 6; 20370 } else { 20371 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 20372 cnt = 1; 20373 } 20374 20375 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20376 if (!new_prog) 20377 return -ENOMEM; 20378 20379 delta += cnt - 1; 20380 env->prog = prog = new_prog; 20381 insn = new_prog->insnsi + i + delta; 20382 goto next_insn; 20383 } 20384 20385 /* Implement get_func_arg_cnt inline. */ 20386 if (prog_type == BPF_PROG_TYPE_TRACING && 20387 insn->imm == BPF_FUNC_get_func_arg_cnt) { 20388 /* Load nr_args from ctx - 8 */ 20389 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 20390 20391 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 20392 if (!new_prog) 20393 return -ENOMEM; 20394 20395 env->prog = prog = new_prog; 20396 insn = new_prog->insnsi + i + delta; 20397 goto next_insn; 20398 } 20399 20400 /* Implement bpf_get_func_ip inline. */ 20401 if (prog_type == BPF_PROG_TYPE_TRACING && 20402 insn->imm == BPF_FUNC_get_func_ip) { 20403 /* Load IP address from ctx - 16 */ 20404 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 20405 20406 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 20407 if (!new_prog) 20408 return -ENOMEM; 20409 20410 env->prog = prog = new_prog; 20411 insn = new_prog->insnsi + i + delta; 20412 goto next_insn; 20413 } 20414 20415 /* Implement bpf_get_branch_snapshot inline. */ 20416 if (IS_ENABLED(CONFIG_PERF_EVENTS) && 20417 prog->jit_requested && BITS_PER_LONG == 64 && 20418 insn->imm == BPF_FUNC_get_branch_snapshot) { 20419 /* We are dealing with the following func protos: 20420 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags); 20421 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt); 20422 */ 20423 const u32 br_entry_size = sizeof(struct perf_branch_entry); 20424 20425 /* struct perf_branch_entry is part of UAPI and is 20426 * used as an array element, so extremely unlikely to 20427 * ever grow or shrink 20428 */ 20429 BUILD_BUG_ON(br_entry_size != 24); 20430 20431 /* if (unlikely(flags)) return -EINVAL */ 20432 insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7); 20433 20434 /* Transform size (bytes) into number of entries (cnt = size / 24). 20435 * But to avoid expensive division instruction, we implement 20436 * divide-by-3 through multiplication, followed by further 20437 * division by 8 through 3-bit right shift. 20438 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr., 20439 * p. 227, chapter "Unsigned Division by 3" for details and proofs. 20440 * 20441 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab. 20442 */ 20443 insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab); 20444 insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0); 20445 insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36); 20446 20447 /* call perf_snapshot_branch_stack implementation */ 20448 insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack)); 20449 /* if (entry_cnt == 0) return -ENOENT */ 20450 insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4); 20451 /* return entry_cnt * sizeof(struct perf_branch_entry) */ 20452 insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size); 20453 insn_buf[7] = BPF_JMP_A(3); 20454 /* return -EINVAL; */ 20455 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 20456 insn_buf[9] = BPF_JMP_A(1); 20457 /* return -ENOENT; */ 20458 insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT); 20459 cnt = 11; 20460 20461 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20462 if (!new_prog) 20463 return -ENOMEM; 20464 20465 delta += cnt - 1; 20466 env->prog = prog = new_prog; 20467 insn = new_prog->insnsi + i + delta; 20468 continue; 20469 } 20470 20471 /* Implement bpf_kptr_xchg inline */ 20472 if (prog->jit_requested && BITS_PER_LONG == 64 && 20473 insn->imm == BPF_FUNC_kptr_xchg && 20474 bpf_jit_supports_ptr_xchg()) { 20475 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2); 20476 insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0); 20477 cnt = 2; 20478 20479 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20480 if (!new_prog) 20481 return -ENOMEM; 20482 20483 delta += cnt - 1; 20484 env->prog = prog = new_prog; 20485 insn = new_prog->insnsi + i + delta; 20486 goto next_insn; 20487 } 20488 patch_call_imm: 20489 fn = env->ops->get_func_proto(insn->imm, env->prog); 20490 /* all functions that have prototype and verifier allowed 20491 * programs to call them, must be real in-kernel functions 20492 */ 20493 if (!fn->func) { 20494 verbose(env, 20495 "kernel subsystem misconfigured func %s#%d\n", 20496 func_id_name(insn->imm), insn->imm); 20497 return -EFAULT; 20498 } 20499 insn->imm = fn->func - __bpf_call_base; 20500 next_insn: 20501 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 20502 subprogs[cur_subprog].stack_depth += stack_depth_extra; 20503 subprogs[cur_subprog].stack_extra = stack_depth_extra; 20504 cur_subprog++; 20505 stack_depth = subprogs[cur_subprog].stack_depth; 20506 stack_depth_extra = 0; 20507 } 20508 i++; 20509 insn++; 20510 } 20511 20512 env->prog->aux->stack_depth = subprogs[0].stack_depth; 20513 for (i = 0; i < env->subprog_cnt; i++) { 20514 int subprog_start = subprogs[i].start; 20515 int stack_slots = subprogs[i].stack_extra / 8; 20516 20517 if (!stack_slots) 20518 continue; 20519 if (stack_slots > 1) { 20520 verbose(env, "verifier bug: stack_slots supports may_goto only\n"); 20521 return -EFAULT; 20522 } 20523 20524 /* Add ST insn to subprog prologue to init extra stack */ 20525 insn_buf[0] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, 20526 -subprogs[i].stack_depth, BPF_MAX_LOOPS); 20527 /* Copy first actual insn to preserve it */ 20528 insn_buf[1] = env->prog->insnsi[subprog_start]; 20529 20530 new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, 2); 20531 if (!new_prog) 20532 return -ENOMEM; 20533 env->prog = prog = new_prog; 20534 } 20535 20536 /* Since poke tab is now finalized, publish aux to tracker. */ 20537 for (i = 0; i < prog->aux->size_poke_tab; i++) { 20538 map_ptr = prog->aux->poke_tab[i].tail_call.map; 20539 if (!map_ptr->ops->map_poke_track || 20540 !map_ptr->ops->map_poke_untrack || 20541 !map_ptr->ops->map_poke_run) { 20542 verbose(env, "bpf verifier is misconfigured\n"); 20543 return -EINVAL; 20544 } 20545 20546 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 20547 if (ret < 0) { 20548 verbose(env, "tracking tail call prog failed\n"); 20549 return ret; 20550 } 20551 } 20552 20553 sort_kfunc_descs_by_imm_off(env->prog); 20554 20555 return 0; 20556 } 20557 20558 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 20559 int position, 20560 s32 stack_base, 20561 u32 callback_subprogno, 20562 u32 *cnt) 20563 { 20564 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 20565 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 20566 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 20567 int reg_loop_max = BPF_REG_6; 20568 int reg_loop_cnt = BPF_REG_7; 20569 int reg_loop_ctx = BPF_REG_8; 20570 20571 struct bpf_prog *new_prog; 20572 u32 callback_start; 20573 u32 call_insn_offset; 20574 s32 callback_offset; 20575 20576 /* This represents an inlined version of bpf_iter.c:bpf_loop, 20577 * be careful to modify this code in sync. 20578 */ 20579 struct bpf_insn insn_buf[] = { 20580 /* Return error and jump to the end of the patch if 20581 * expected number of iterations is too big. 20582 */ 20583 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 20584 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 20585 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 20586 /* spill R6, R7, R8 to use these as loop vars */ 20587 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 20588 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 20589 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 20590 /* initialize loop vars */ 20591 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 20592 BPF_MOV32_IMM(reg_loop_cnt, 0), 20593 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 20594 /* loop header, 20595 * if reg_loop_cnt >= reg_loop_max skip the loop body 20596 */ 20597 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 20598 /* callback call, 20599 * correct callback offset would be set after patching 20600 */ 20601 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 20602 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 20603 BPF_CALL_REL(0), 20604 /* increment loop counter */ 20605 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 20606 /* jump to loop header if callback returned 0 */ 20607 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 20608 /* return value of bpf_loop, 20609 * set R0 to the number of iterations 20610 */ 20611 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 20612 /* restore original values of R6, R7, R8 */ 20613 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 20614 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 20615 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 20616 }; 20617 20618 *cnt = ARRAY_SIZE(insn_buf); 20619 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 20620 if (!new_prog) 20621 return new_prog; 20622 20623 /* callback start is known only after patching */ 20624 callback_start = env->subprog_info[callback_subprogno].start; 20625 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 20626 call_insn_offset = position + 12; 20627 callback_offset = callback_start - call_insn_offset - 1; 20628 new_prog->insnsi[call_insn_offset].imm = callback_offset; 20629 20630 return new_prog; 20631 } 20632 20633 static bool is_bpf_loop_call(struct bpf_insn *insn) 20634 { 20635 return insn->code == (BPF_JMP | BPF_CALL) && 20636 insn->src_reg == 0 && 20637 insn->imm == BPF_FUNC_loop; 20638 } 20639 20640 /* For all sub-programs in the program (including main) check 20641 * insn_aux_data to see if there are bpf_loop calls that require 20642 * inlining. If such calls are found the calls are replaced with a 20643 * sequence of instructions produced by `inline_bpf_loop` function and 20644 * subprog stack_depth is increased by the size of 3 registers. 20645 * This stack space is used to spill values of the R6, R7, R8. These 20646 * registers are used to store the loop bound, counter and context 20647 * variables. 20648 */ 20649 static int optimize_bpf_loop(struct bpf_verifier_env *env) 20650 { 20651 struct bpf_subprog_info *subprogs = env->subprog_info; 20652 int i, cur_subprog = 0, cnt, delta = 0; 20653 struct bpf_insn *insn = env->prog->insnsi; 20654 int insn_cnt = env->prog->len; 20655 u16 stack_depth = subprogs[cur_subprog].stack_depth; 20656 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 20657 u16 stack_depth_extra = 0; 20658 20659 for (i = 0; i < insn_cnt; i++, insn++) { 20660 struct bpf_loop_inline_state *inline_state = 20661 &env->insn_aux_data[i + delta].loop_inline_state; 20662 20663 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 20664 struct bpf_prog *new_prog; 20665 20666 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 20667 new_prog = inline_bpf_loop(env, 20668 i + delta, 20669 -(stack_depth + stack_depth_extra), 20670 inline_state->callback_subprogno, 20671 &cnt); 20672 if (!new_prog) 20673 return -ENOMEM; 20674 20675 delta += cnt - 1; 20676 env->prog = new_prog; 20677 insn = new_prog->insnsi + i + delta; 20678 } 20679 20680 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 20681 subprogs[cur_subprog].stack_depth += stack_depth_extra; 20682 cur_subprog++; 20683 stack_depth = subprogs[cur_subprog].stack_depth; 20684 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 20685 stack_depth_extra = 0; 20686 } 20687 } 20688 20689 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 20690 20691 return 0; 20692 } 20693 20694 static void free_states(struct bpf_verifier_env *env) 20695 { 20696 struct bpf_verifier_state_list *sl, *sln; 20697 int i; 20698 20699 sl = env->free_list; 20700 while (sl) { 20701 sln = sl->next; 20702 free_verifier_state(&sl->state, false); 20703 kfree(sl); 20704 sl = sln; 20705 } 20706 env->free_list = NULL; 20707 20708 if (!env->explored_states) 20709 return; 20710 20711 for (i = 0; i < state_htab_size(env); i++) { 20712 sl = env->explored_states[i]; 20713 20714 while (sl) { 20715 sln = sl->next; 20716 free_verifier_state(&sl->state, false); 20717 kfree(sl); 20718 sl = sln; 20719 } 20720 env->explored_states[i] = NULL; 20721 } 20722 } 20723 20724 static int do_check_common(struct bpf_verifier_env *env, int subprog) 20725 { 20726 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 20727 struct bpf_subprog_info *sub = subprog_info(env, subprog); 20728 struct bpf_verifier_state *state; 20729 struct bpf_reg_state *regs; 20730 int ret, i; 20731 20732 env->prev_linfo = NULL; 20733 env->pass_cnt++; 20734 20735 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 20736 if (!state) 20737 return -ENOMEM; 20738 state->curframe = 0; 20739 state->speculative = false; 20740 state->branches = 1; 20741 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 20742 if (!state->frame[0]) { 20743 kfree(state); 20744 return -ENOMEM; 20745 } 20746 env->cur_state = state; 20747 init_func_state(env, state->frame[0], 20748 BPF_MAIN_FUNC /* callsite */, 20749 0 /* frameno */, 20750 subprog); 20751 state->first_insn_idx = env->subprog_info[subprog].start; 20752 state->last_insn_idx = -1; 20753 20754 regs = state->frame[state->curframe]->regs; 20755 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 20756 const char *sub_name = subprog_name(env, subprog); 20757 struct bpf_subprog_arg_info *arg; 20758 struct bpf_reg_state *reg; 20759 20760 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 20761 ret = btf_prepare_func_args(env, subprog); 20762 if (ret) 20763 goto out; 20764 20765 if (subprog_is_exc_cb(env, subprog)) { 20766 state->frame[0]->in_exception_callback_fn = true; 20767 /* We have already ensured that the callback returns an integer, just 20768 * like all global subprogs. We need to determine it only has a single 20769 * scalar argument. 20770 */ 20771 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 20772 verbose(env, "exception cb only supports single integer argument\n"); 20773 ret = -EINVAL; 20774 goto out; 20775 } 20776 } 20777 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) { 20778 arg = &sub->args[i - BPF_REG_1]; 20779 reg = ®s[i]; 20780 20781 if (arg->arg_type == ARG_PTR_TO_CTX) { 20782 reg->type = PTR_TO_CTX; 20783 mark_reg_known_zero(env, regs, i); 20784 } else if (arg->arg_type == ARG_ANYTHING) { 20785 reg->type = SCALAR_VALUE; 20786 mark_reg_unknown(env, regs, i); 20787 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 20788 /* assume unspecial LOCAL dynptr type */ 20789 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen); 20790 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 20791 reg->type = PTR_TO_MEM; 20792 if (arg->arg_type & PTR_MAYBE_NULL) 20793 reg->type |= PTR_MAYBE_NULL; 20794 mark_reg_known_zero(env, regs, i); 20795 reg->mem_size = arg->mem_size; 20796 reg->id = ++env->id_gen; 20797 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 20798 reg->type = PTR_TO_BTF_ID; 20799 if (arg->arg_type & PTR_MAYBE_NULL) 20800 reg->type |= PTR_MAYBE_NULL; 20801 if (arg->arg_type & PTR_UNTRUSTED) 20802 reg->type |= PTR_UNTRUSTED; 20803 if (arg->arg_type & PTR_TRUSTED) 20804 reg->type |= PTR_TRUSTED; 20805 mark_reg_known_zero(env, regs, i); 20806 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */ 20807 reg->btf_id = arg->btf_id; 20808 reg->id = ++env->id_gen; 20809 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 20810 /* caller can pass either PTR_TO_ARENA or SCALAR */ 20811 mark_reg_unknown(env, regs, i); 20812 } else { 20813 WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n", 20814 i - BPF_REG_1, arg->arg_type); 20815 ret = -EFAULT; 20816 goto out; 20817 } 20818 } 20819 } else { 20820 /* if main BPF program has associated BTF info, validate that 20821 * it's matching expected signature, and otherwise mark BTF 20822 * info for main program as unreliable 20823 */ 20824 if (env->prog->aux->func_info_aux) { 20825 ret = btf_prepare_func_args(env, 0); 20826 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) 20827 env->prog->aux->func_info_aux[0].unreliable = true; 20828 } 20829 20830 /* 1st arg to a function */ 20831 regs[BPF_REG_1].type = PTR_TO_CTX; 20832 mark_reg_known_zero(env, regs, BPF_REG_1); 20833 } 20834 20835 ret = do_check(env); 20836 out: 20837 /* check for NULL is necessary, since cur_state can be freed inside 20838 * do_check() under memory pressure. 20839 */ 20840 if (env->cur_state) { 20841 free_verifier_state(env->cur_state, true); 20842 env->cur_state = NULL; 20843 } 20844 while (!pop_stack(env, NULL, NULL, false)); 20845 if (!ret && pop_log) 20846 bpf_vlog_reset(&env->log, 0); 20847 free_states(env); 20848 return ret; 20849 } 20850 20851 /* Lazily verify all global functions based on their BTF, if they are called 20852 * from main BPF program or any of subprograms transitively. 20853 * BPF global subprogs called from dead code are not validated. 20854 * All callable global functions must pass verification. 20855 * Otherwise the whole program is rejected. 20856 * Consider: 20857 * int bar(int); 20858 * int foo(int f) 20859 * { 20860 * return bar(f); 20861 * } 20862 * int bar(int b) 20863 * { 20864 * ... 20865 * } 20866 * foo() will be verified first for R1=any_scalar_value. During verification it 20867 * will be assumed that bar() already verified successfully and call to bar() 20868 * from foo() will be checked for type match only. Later bar() will be verified 20869 * independently to check that it's safe for R1=any_scalar_value. 20870 */ 20871 static int do_check_subprogs(struct bpf_verifier_env *env) 20872 { 20873 struct bpf_prog_aux *aux = env->prog->aux; 20874 struct bpf_func_info_aux *sub_aux; 20875 int i, ret, new_cnt; 20876 20877 if (!aux->func_info) 20878 return 0; 20879 20880 /* exception callback is presumed to be always called */ 20881 if (env->exception_callback_subprog) 20882 subprog_aux(env, env->exception_callback_subprog)->called = true; 20883 20884 again: 20885 new_cnt = 0; 20886 for (i = 1; i < env->subprog_cnt; i++) { 20887 if (!subprog_is_global(env, i)) 20888 continue; 20889 20890 sub_aux = subprog_aux(env, i); 20891 if (!sub_aux->called || sub_aux->verified) 20892 continue; 20893 20894 env->insn_idx = env->subprog_info[i].start; 20895 WARN_ON_ONCE(env->insn_idx == 0); 20896 ret = do_check_common(env, i); 20897 if (ret) { 20898 return ret; 20899 } else if (env->log.level & BPF_LOG_LEVEL) { 20900 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 20901 i, subprog_name(env, i)); 20902 } 20903 20904 /* We verified new global subprog, it might have called some 20905 * more global subprogs that we haven't verified yet, so we 20906 * need to do another pass over subprogs to verify those. 20907 */ 20908 sub_aux->verified = true; 20909 new_cnt++; 20910 } 20911 20912 /* We can't loop forever as we verify at least one global subprog on 20913 * each pass. 20914 */ 20915 if (new_cnt) 20916 goto again; 20917 20918 return 0; 20919 } 20920 20921 static int do_check_main(struct bpf_verifier_env *env) 20922 { 20923 int ret; 20924 20925 env->insn_idx = 0; 20926 ret = do_check_common(env, 0); 20927 if (!ret) 20928 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 20929 return ret; 20930 } 20931 20932 20933 static void print_verification_stats(struct bpf_verifier_env *env) 20934 { 20935 int i; 20936 20937 if (env->log.level & BPF_LOG_STATS) { 20938 verbose(env, "verification time %lld usec\n", 20939 div_u64(env->verification_time, 1000)); 20940 verbose(env, "stack depth "); 20941 for (i = 0; i < env->subprog_cnt; i++) { 20942 u32 depth = env->subprog_info[i].stack_depth; 20943 20944 verbose(env, "%d", depth); 20945 if (i + 1 < env->subprog_cnt) 20946 verbose(env, "+"); 20947 } 20948 verbose(env, "\n"); 20949 } 20950 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 20951 "total_states %d peak_states %d mark_read %d\n", 20952 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 20953 env->max_states_per_insn, env->total_states, 20954 env->peak_states, env->longest_mark_read_walk); 20955 } 20956 20957 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 20958 { 20959 const struct btf_type *t, *func_proto; 20960 const struct bpf_struct_ops_desc *st_ops_desc; 20961 const struct bpf_struct_ops *st_ops; 20962 const struct btf_member *member; 20963 struct bpf_prog *prog = env->prog; 20964 u32 btf_id, member_idx; 20965 struct btf *btf; 20966 const char *mname; 20967 20968 if (!prog->gpl_compatible) { 20969 verbose(env, "struct ops programs must have a GPL compatible license\n"); 20970 return -EINVAL; 20971 } 20972 20973 if (!prog->aux->attach_btf_id) 20974 return -ENOTSUPP; 20975 20976 btf = prog->aux->attach_btf; 20977 if (btf_is_module(btf)) { 20978 /* Make sure st_ops is valid through the lifetime of env */ 20979 env->attach_btf_mod = btf_try_get_module(btf); 20980 if (!env->attach_btf_mod) { 20981 verbose(env, "struct_ops module %s is not found\n", 20982 btf_get_name(btf)); 20983 return -ENOTSUPP; 20984 } 20985 } 20986 20987 btf_id = prog->aux->attach_btf_id; 20988 st_ops_desc = bpf_struct_ops_find(btf, btf_id); 20989 if (!st_ops_desc) { 20990 verbose(env, "attach_btf_id %u is not a supported struct\n", 20991 btf_id); 20992 return -ENOTSUPP; 20993 } 20994 st_ops = st_ops_desc->st_ops; 20995 20996 t = st_ops_desc->type; 20997 member_idx = prog->expected_attach_type; 20998 if (member_idx >= btf_type_vlen(t)) { 20999 verbose(env, "attach to invalid member idx %u of struct %s\n", 21000 member_idx, st_ops->name); 21001 return -EINVAL; 21002 } 21003 21004 member = &btf_type_member(t)[member_idx]; 21005 mname = btf_name_by_offset(btf, member->name_off); 21006 func_proto = btf_type_resolve_func_ptr(btf, member->type, 21007 NULL); 21008 if (!func_proto) { 21009 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 21010 mname, member_idx, st_ops->name); 21011 return -EINVAL; 21012 } 21013 21014 if (st_ops->check_member) { 21015 int err = st_ops->check_member(t, member, prog); 21016 21017 if (err) { 21018 verbose(env, "attach to unsupported member %s of struct %s\n", 21019 mname, st_ops->name); 21020 return err; 21021 } 21022 } 21023 21024 /* btf_ctx_access() used this to provide argument type info */ 21025 prog->aux->ctx_arg_info = 21026 st_ops_desc->arg_info[member_idx].info; 21027 prog->aux->ctx_arg_info_size = 21028 st_ops_desc->arg_info[member_idx].cnt; 21029 21030 prog->aux->attach_func_proto = func_proto; 21031 prog->aux->attach_func_name = mname; 21032 env->ops = st_ops->verifier_ops; 21033 21034 return 0; 21035 } 21036 #define SECURITY_PREFIX "security_" 21037 21038 static int check_attach_modify_return(unsigned long addr, const char *func_name) 21039 { 21040 if (within_error_injection_list(addr) || 21041 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 21042 return 0; 21043 21044 return -EINVAL; 21045 } 21046 21047 /* list of non-sleepable functions that are otherwise on 21048 * ALLOW_ERROR_INJECTION list 21049 */ 21050 BTF_SET_START(btf_non_sleepable_error_inject) 21051 /* Three functions below can be called from sleepable and non-sleepable context. 21052 * Assume non-sleepable from bpf safety point of view. 21053 */ 21054 BTF_ID(func, __filemap_add_folio) 21055 BTF_ID(func, should_fail_alloc_page) 21056 BTF_ID(func, should_failslab) 21057 BTF_SET_END(btf_non_sleepable_error_inject) 21058 21059 static int check_non_sleepable_error_inject(u32 btf_id) 21060 { 21061 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 21062 } 21063 21064 int bpf_check_attach_target(struct bpf_verifier_log *log, 21065 const struct bpf_prog *prog, 21066 const struct bpf_prog *tgt_prog, 21067 u32 btf_id, 21068 struct bpf_attach_target_info *tgt_info) 21069 { 21070 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 21071 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 21072 const char prefix[] = "btf_trace_"; 21073 int ret = 0, subprog = -1, i; 21074 const struct btf_type *t; 21075 bool conservative = true; 21076 const char *tname; 21077 struct btf *btf; 21078 long addr = 0; 21079 struct module *mod = NULL; 21080 21081 if (!btf_id) { 21082 bpf_log(log, "Tracing programs must provide btf_id\n"); 21083 return -EINVAL; 21084 } 21085 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 21086 if (!btf) { 21087 bpf_log(log, 21088 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 21089 return -EINVAL; 21090 } 21091 t = btf_type_by_id(btf, btf_id); 21092 if (!t) { 21093 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 21094 return -EINVAL; 21095 } 21096 tname = btf_name_by_offset(btf, t->name_off); 21097 if (!tname) { 21098 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 21099 return -EINVAL; 21100 } 21101 if (tgt_prog) { 21102 struct bpf_prog_aux *aux = tgt_prog->aux; 21103 21104 if (bpf_prog_is_dev_bound(prog->aux) && 21105 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 21106 bpf_log(log, "Target program bound device mismatch"); 21107 return -EINVAL; 21108 } 21109 21110 for (i = 0; i < aux->func_info_cnt; i++) 21111 if (aux->func_info[i].type_id == btf_id) { 21112 subprog = i; 21113 break; 21114 } 21115 if (subprog == -1) { 21116 bpf_log(log, "Subprog %s doesn't exist\n", tname); 21117 return -EINVAL; 21118 } 21119 if (aux->func && aux->func[subprog]->aux->exception_cb) { 21120 bpf_log(log, 21121 "%s programs cannot attach to exception callback\n", 21122 prog_extension ? "Extension" : "FENTRY/FEXIT"); 21123 return -EINVAL; 21124 } 21125 conservative = aux->func_info_aux[subprog].unreliable; 21126 if (prog_extension) { 21127 if (conservative) { 21128 bpf_log(log, 21129 "Cannot replace static functions\n"); 21130 return -EINVAL; 21131 } 21132 if (!prog->jit_requested) { 21133 bpf_log(log, 21134 "Extension programs should be JITed\n"); 21135 return -EINVAL; 21136 } 21137 } 21138 if (!tgt_prog->jited) { 21139 bpf_log(log, "Can attach to only JITed progs\n"); 21140 return -EINVAL; 21141 } 21142 if (prog_tracing) { 21143 if (aux->attach_tracing_prog) { 21144 /* 21145 * Target program is an fentry/fexit which is already attached 21146 * to another tracing program. More levels of nesting 21147 * attachment are not allowed. 21148 */ 21149 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 21150 return -EINVAL; 21151 } 21152 } else if (tgt_prog->type == prog->type) { 21153 /* 21154 * To avoid potential call chain cycles, prevent attaching of a 21155 * program extension to another extension. It's ok to attach 21156 * fentry/fexit to extension program. 21157 */ 21158 bpf_log(log, "Cannot recursively attach\n"); 21159 return -EINVAL; 21160 } 21161 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 21162 prog_extension && 21163 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 21164 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 21165 /* Program extensions can extend all program types 21166 * except fentry/fexit. The reason is the following. 21167 * The fentry/fexit programs are used for performance 21168 * analysis, stats and can be attached to any program 21169 * type. When extension program is replacing XDP function 21170 * it is necessary to allow performance analysis of all 21171 * functions. Both original XDP program and its program 21172 * extension. Hence attaching fentry/fexit to 21173 * BPF_PROG_TYPE_EXT is allowed. If extending of 21174 * fentry/fexit was allowed it would be possible to create 21175 * long call chain fentry->extension->fentry->extension 21176 * beyond reasonable stack size. Hence extending fentry 21177 * is not allowed. 21178 */ 21179 bpf_log(log, "Cannot extend fentry/fexit\n"); 21180 return -EINVAL; 21181 } 21182 } else { 21183 if (prog_extension) { 21184 bpf_log(log, "Cannot replace kernel functions\n"); 21185 return -EINVAL; 21186 } 21187 } 21188 21189 switch (prog->expected_attach_type) { 21190 case BPF_TRACE_RAW_TP: 21191 if (tgt_prog) { 21192 bpf_log(log, 21193 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 21194 return -EINVAL; 21195 } 21196 if (!btf_type_is_typedef(t)) { 21197 bpf_log(log, "attach_btf_id %u is not a typedef\n", 21198 btf_id); 21199 return -EINVAL; 21200 } 21201 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 21202 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 21203 btf_id, tname); 21204 return -EINVAL; 21205 } 21206 tname += sizeof(prefix) - 1; 21207 t = btf_type_by_id(btf, t->type); 21208 if (!btf_type_is_ptr(t)) 21209 /* should never happen in valid vmlinux build */ 21210 return -EINVAL; 21211 t = btf_type_by_id(btf, t->type); 21212 if (!btf_type_is_func_proto(t)) 21213 /* should never happen in valid vmlinux build */ 21214 return -EINVAL; 21215 21216 break; 21217 case BPF_TRACE_ITER: 21218 if (!btf_type_is_func(t)) { 21219 bpf_log(log, "attach_btf_id %u is not a function\n", 21220 btf_id); 21221 return -EINVAL; 21222 } 21223 t = btf_type_by_id(btf, t->type); 21224 if (!btf_type_is_func_proto(t)) 21225 return -EINVAL; 21226 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 21227 if (ret) 21228 return ret; 21229 break; 21230 default: 21231 if (!prog_extension) 21232 return -EINVAL; 21233 fallthrough; 21234 case BPF_MODIFY_RETURN: 21235 case BPF_LSM_MAC: 21236 case BPF_LSM_CGROUP: 21237 case BPF_TRACE_FENTRY: 21238 case BPF_TRACE_FEXIT: 21239 if (!btf_type_is_func(t)) { 21240 bpf_log(log, "attach_btf_id %u is not a function\n", 21241 btf_id); 21242 return -EINVAL; 21243 } 21244 if (prog_extension && 21245 btf_check_type_match(log, prog, btf, t)) 21246 return -EINVAL; 21247 t = btf_type_by_id(btf, t->type); 21248 if (!btf_type_is_func_proto(t)) 21249 return -EINVAL; 21250 21251 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 21252 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 21253 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 21254 return -EINVAL; 21255 21256 if (tgt_prog && conservative) 21257 t = NULL; 21258 21259 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 21260 if (ret < 0) 21261 return ret; 21262 21263 if (tgt_prog) { 21264 if (subprog == 0) 21265 addr = (long) tgt_prog->bpf_func; 21266 else 21267 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 21268 } else { 21269 if (btf_is_module(btf)) { 21270 mod = btf_try_get_module(btf); 21271 if (mod) 21272 addr = find_kallsyms_symbol_value(mod, tname); 21273 else 21274 addr = 0; 21275 } else { 21276 addr = kallsyms_lookup_name(tname); 21277 } 21278 if (!addr) { 21279 module_put(mod); 21280 bpf_log(log, 21281 "The address of function %s cannot be found\n", 21282 tname); 21283 return -ENOENT; 21284 } 21285 } 21286 21287 if (prog->sleepable) { 21288 ret = -EINVAL; 21289 switch (prog->type) { 21290 case BPF_PROG_TYPE_TRACING: 21291 21292 /* fentry/fexit/fmod_ret progs can be sleepable if they are 21293 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 21294 */ 21295 if (!check_non_sleepable_error_inject(btf_id) && 21296 within_error_injection_list(addr)) 21297 ret = 0; 21298 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 21299 * in the fmodret id set with the KF_SLEEPABLE flag. 21300 */ 21301 else { 21302 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 21303 prog); 21304 21305 if (flags && (*flags & KF_SLEEPABLE)) 21306 ret = 0; 21307 } 21308 break; 21309 case BPF_PROG_TYPE_LSM: 21310 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 21311 * Only some of them are sleepable. 21312 */ 21313 if (bpf_lsm_is_sleepable_hook(btf_id)) 21314 ret = 0; 21315 break; 21316 default: 21317 break; 21318 } 21319 if (ret) { 21320 module_put(mod); 21321 bpf_log(log, "%s is not sleepable\n", tname); 21322 return ret; 21323 } 21324 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 21325 if (tgt_prog) { 21326 module_put(mod); 21327 bpf_log(log, "can't modify return codes of BPF programs\n"); 21328 return -EINVAL; 21329 } 21330 ret = -EINVAL; 21331 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 21332 !check_attach_modify_return(addr, tname)) 21333 ret = 0; 21334 if (ret) { 21335 module_put(mod); 21336 bpf_log(log, "%s() is not modifiable\n", tname); 21337 return ret; 21338 } 21339 } 21340 21341 break; 21342 } 21343 tgt_info->tgt_addr = addr; 21344 tgt_info->tgt_name = tname; 21345 tgt_info->tgt_type = t; 21346 tgt_info->tgt_mod = mod; 21347 return 0; 21348 } 21349 21350 BTF_SET_START(btf_id_deny) 21351 BTF_ID_UNUSED 21352 #ifdef CONFIG_SMP 21353 BTF_ID(func, migrate_disable) 21354 BTF_ID(func, migrate_enable) 21355 #endif 21356 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 21357 BTF_ID(func, rcu_read_unlock_strict) 21358 #endif 21359 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 21360 BTF_ID(func, preempt_count_add) 21361 BTF_ID(func, preempt_count_sub) 21362 #endif 21363 #ifdef CONFIG_PREEMPT_RCU 21364 BTF_ID(func, __rcu_read_lock) 21365 BTF_ID(func, __rcu_read_unlock) 21366 #endif 21367 BTF_SET_END(btf_id_deny) 21368 21369 static bool can_be_sleepable(struct bpf_prog *prog) 21370 { 21371 if (prog->type == BPF_PROG_TYPE_TRACING) { 21372 switch (prog->expected_attach_type) { 21373 case BPF_TRACE_FENTRY: 21374 case BPF_TRACE_FEXIT: 21375 case BPF_MODIFY_RETURN: 21376 case BPF_TRACE_ITER: 21377 return true; 21378 default: 21379 return false; 21380 } 21381 } 21382 return prog->type == BPF_PROG_TYPE_LSM || 21383 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 21384 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 21385 } 21386 21387 static int check_attach_btf_id(struct bpf_verifier_env *env) 21388 { 21389 struct bpf_prog *prog = env->prog; 21390 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 21391 struct bpf_attach_target_info tgt_info = {}; 21392 u32 btf_id = prog->aux->attach_btf_id; 21393 struct bpf_trampoline *tr; 21394 int ret; 21395 u64 key; 21396 21397 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 21398 if (prog->sleepable) 21399 /* attach_btf_id checked to be zero already */ 21400 return 0; 21401 verbose(env, "Syscall programs can only be sleepable\n"); 21402 return -EINVAL; 21403 } 21404 21405 if (prog->sleepable && !can_be_sleepable(prog)) { 21406 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 21407 return -EINVAL; 21408 } 21409 21410 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 21411 return check_struct_ops_btf_id(env); 21412 21413 if (prog->type != BPF_PROG_TYPE_TRACING && 21414 prog->type != BPF_PROG_TYPE_LSM && 21415 prog->type != BPF_PROG_TYPE_EXT) 21416 return 0; 21417 21418 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 21419 if (ret) 21420 return ret; 21421 21422 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 21423 /* to make freplace equivalent to their targets, they need to 21424 * inherit env->ops and expected_attach_type for the rest of the 21425 * verification 21426 */ 21427 env->ops = bpf_verifier_ops[tgt_prog->type]; 21428 prog->expected_attach_type = tgt_prog->expected_attach_type; 21429 } 21430 21431 /* store info about the attachment target that will be used later */ 21432 prog->aux->attach_func_proto = tgt_info.tgt_type; 21433 prog->aux->attach_func_name = tgt_info.tgt_name; 21434 prog->aux->mod = tgt_info.tgt_mod; 21435 21436 if (tgt_prog) { 21437 prog->aux->saved_dst_prog_type = tgt_prog->type; 21438 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 21439 } 21440 21441 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 21442 prog->aux->attach_btf_trace = true; 21443 return 0; 21444 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 21445 if (!bpf_iter_prog_supported(prog)) 21446 return -EINVAL; 21447 return 0; 21448 } 21449 21450 if (prog->type == BPF_PROG_TYPE_LSM) { 21451 ret = bpf_lsm_verify_prog(&env->log, prog); 21452 if (ret < 0) 21453 return ret; 21454 } else if (prog->type == BPF_PROG_TYPE_TRACING && 21455 btf_id_set_contains(&btf_id_deny, btf_id)) { 21456 return -EINVAL; 21457 } 21458 21459 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 21460 tr = bpf_trampoline_get(key, &tgt_info); 21461 if (!tr) 21462 return -ENOMEM; 21463 21464 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 21465 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 21466 21467 prog->aux->dst_trampoline = tr; 21468 return 0; 21469 } 21470 21471 struct btf *bpf_get_btf_vmlinux(void) 21472 { 21473 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 21474 mutex_lock(&bpf_verifier_lock); 21475 if (!btf_vmlinux) 21476 btf_vmlinux = btf_parse_vmlinux(); 21477 mutex_unlock(&bpf_verifier_lock); 21478 } 21479 return btf_vmlinux; 21480 } 21481 21482 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 21483 { 21484 u64 start_time = ktime_get_ns(); 21485 struct bpf_verifier_env *env; 21486 int i, len, ret = -EINVAL, err; 21487 u32 log_true_size; 21488 bool is_priv; 21489 21490 /* no program is valid */ 21491 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 21492 return -EINVAL; 21493 21494 /* 'struct bpf_verifier_env' can be global, but since it's not small, 21495 * allocate/free it every time bpf_check() is called 21496 */ 21497 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 21498 if (!env) 21499 return -ENOMEM; 21500 21501 env->bt.env = env; 21502 21503 len = (*prog)->len; 21504 env->insn_aux_data = 21505 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 21506 ret = -ENOMEM; 21507 if (!env->insn_aux_data) 21508 goto err_free_env; 21509 for (i = 0; i < len; i++) 21510 env->insn_aux_data[i].orig_idx = i; 21511 env->prog = *prog; 21512 env->ops = bpf_verifier_ops[env->prog->type]; 21513 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 21514 21515 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 21516 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 21517 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 21518 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 21519 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 21520 21521 bpf_get_btf_vmlinux(); 21522 21523 /* grab the mutex to protect few globals used by verifier */ 21524 if (!is_priv) 21525 mutex_lock(&bpf_verifier_lock); 21526 21527 /* user could have requested verbose verifier output 21528 * and supplied buffer to store the verification trace 21529 */ 21530 ret = bpf_vlog_init(&env->log, attr->log_level, 21531 (char __user *) (unsigned long) attr->log_buf, 21532 attr->log_size); 21533 if (ret) 21534 goto err_unlock; 21535 21536 mark_verifier_state_clean(env); 21537 21538 if (IS_ERR(btf_vmlinux)) { 21539 /* Either gcc or pahole or kernel are broken. */ 21540 verbose(env, "in-kernel BTF is malformed\n"); 21541 ret = PTR_ERR(btf_vmlinux); 21542 goto skip_full_check; 21543 } 21544 21545 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 21546 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 21547 env->strict_alignment = true; 21548 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 21549 env->strict_alignment = false; 21550 21551 if (is_priv) 21552 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 21553 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 21554 21555 env->explored_states = kvcalloc(state_htab_size(env), 21556 sizeof(struct bpf_verifier_state_list *), 21557 GFP_USER); 21558 ret = -ENOMEM; 21559 if (!env->explored_states) 21560 goto skip_full_check; 21561 21562 ret = check_btf_info_early(env, attr, uattr); 21563 if (ret < 0) 21564 goto skip_full_check; 21565 21566 ret = add_subprog_and_kfunc(env); 21567 if (ret < 0) 21568 goto skip_full_check; 21569 21570 ret = check_subprogs(env); 21571 if (ret < 0) 21572 goto skip_full_check; 21573 21574 ret = check_btf_info(env, attr, uattr); 21575 if (ret < 0) 21576 goto skip_full_check; 21577 21578 ret = check_attach_btf_id(env); 21579 if (ret) 21580 goto skip_full_check; 21581 21582 ret = resolve_pseudo_ldimm64(env); 21583 if (ret < 0) 21584 goto skip_full_check; 21585 21586 if (bpf_prog_is_offloaded(env->prog->aux)) { 21587 ret = bpf_prog_offload_verifier_prep(env->prog); 21588 if (ret) 21589 goto skip_full_check; 21590 } 21591 21592 ret = check_cfg(env); 21593 if (ret < 0) 21594 goto skip_full_check; 21595 21596 ret = do_check_main(env); 21597 ret = ret ?: do_check_subprogs(env); 21598 21599 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 21600 ret = bpf_prog_offload_finalize(env); 21601 21602 skip_full_check: 21603 kvfree(env->explored_states); 21604 21605 if (ret == 0) 21606 ret = check_max_stack_depth(env); 21607 21608 /* instruction rewrites happen after this point */ 21609 if (ret == 0) 21610 ret = optimize_bpf_loop(env); 21611 21612 if (is_priv) { 21613 if (ret == 0) 21614 opt_hard_wire_dead_code_branches(env); 21615 if (ret == 0) 21616 ret = opt_remove_dead_code(env); 21617 if (ret == 0) 21618 ret = opt_remove_nops(env); 21619 } else { 21620 if (ret == 0) 21621 sanitize_dead_code(env); 21622 } 21623 21624 if (ret == 0) 21625 /* program is valid, convert *(u32*)(ctx + off) accesses */ 21626 ret = convert_ctx_accesses(env); 21627 21628 if (ret == 0) 21629 ret = do_misc_fixups(env); 21630 21631 /* do 32-bit optimization after insn patching has done so those patched 21632 * insns could be handled correctly. 21633 */ 21634 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 21635 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 21636 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 21637 : false; 21638 } 21639 21640 if (ret == 0) 21641 ret = fixup_call_args(env); 21642 21643 env->verification_time = ktime_get_ns() - start_time; 21644 print_verification_stats(env); 21645 env->prog->aux->verified_insns = env->insn_processed; 21646 21647 /* preserve original error even if log finalization is successful */ 21648 err = bpf_vlog_finalize(&env->log, &log_true_size); 21649 if (err) 21650 ret = err; 21651 21652 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 21653 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 21654 &log_true_size, sizeof(log_true_size))) { 21655 ret = -EFAULT; 21656 goto err_release_maps; 21657 } 21658 21659 if (ret) 21660 goto err_release_maps; 21661 21662 if (env->used_map_cnt) { 21663 /* if program passed verifier, update used_maps in bpf_prog_info */ 21664 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 21665 sizeof(env->used_maps[0]), 21666 GFP_KERNEL); 21667 21668 if (!env->prog->aux->used_maps) { 21669 ret = -ENOMEM; 21670 goto err_release_maps; 21671 } 21672 21673 memcpy(env->prog->aux->used_maps, env->used_maps, 21674 sizeof(env->used_maps[0]) * env->used_map_cnt); 21675 env->prog->aux->used_map_cnt = env->used_map_cnt; 21676 } 21677 if (env->used_btf_cnt) { 21678 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 21679 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 21680 sizeof(env->used_btfs[0]), 21681 GFP_KERNEL); 21682 if (!env->prog->aux->used_btfs) { 21683 ret = -ENOMEM; 21684 goto err_release_maps; 21685 } 21686 21687 memcpy(env->prog->aux->used_btfs, env->used_btfs, 21688 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 21689 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 21690 } 21691 if (env->used_map_cnt || env->used_btf_cnt) { 21692 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 21693 * bpf_ld_imm64 instructions 21694 */ 21695 convert_pseudo_ld_imm64(env); 21696 } 21697 21698 adjust_btf_func(env); 21699 21700 err_release_maps: 21701 if (!env->prog->aux->used_maps) 21702 /* if we didn't copy map pointers into bpf_prog_info, release 21703 * them now. Otherwise free_used_maps() will release them. 21704 */ 21705 release_maps(env); 21706 if (!env->prog->aux->used_btfs) 21707 release_btfs(env); 21708 21709 /* extension progs temporarily inherit the attach_type of their targets 21710 for verification purposes, so set it back to zero before returning 21711 */ 21712 if (env->prog->type == BPF_PROG_TYPE_EXT) 21713 env->prog->expected_attach_type = 0; 21714 21715 *prog = env->prog; 21716 21717 module_put(env->attach_btf_mod); 21718 err_unlock: 21719 if (!is_priv) 21720 mutex_unlock(&bpf_verifier_lock); 21721 vfree(env->insn_aux_data); 21722 err_free_env: 21723 kfree(env); 21724 return ret; 21725 } 21726