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 *tmp_reg = &env->fake_reg[0]; 4553 4554 memset(tmp_reg, 0, sizeof(*tmp_reg)); 4555 __mark_reg_known(tmp_reg, insn->imm); 4556 tmp_reg->type = SCALAR_VALUE; 4557 save_register_state(env, state, spi, tmp_reg, size); 4558 } else if (reg && is_spillable_regtype(reg->type)) { 4559 /* register containing pointer is being spilled into stack */ 4560 if (size != BPF_REG_SIZE) { 4561 verbose_linfo(env, insn_idx, "; "); 4562 verbose(env, "invalid size of register spill\n"); 4563 return -EACCES; 4564 } 4565 if (state != cur && reg->type == PTR_TO_STACK) { 4566 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4567 return -EINVAL; 4568 } 4569 save_register_state(env, state, spi, reg, size); 4570 } else { 4571 u8 type = STACK_MISC; 4572 4573 /* regular write of data into stack destroys any spilled ptr */ 4574 state->stack[spi].spilled_ptr.type = NOT_INIT; 4575 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 4576 if (is_stack_slot_special(&state->stack[spi])) 4577 for (i = 0; i < BPF_REG_SIZE; i++) 4578 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 4579 4580 /* only mark the slot as written if all 8 bytes were written 4581 * otherwise read propagation may incorrectly stop too soon 4582 * when stack slots are partially written. 4583 * This heuristic means that read propagation will be 4584 * conservative, since it will add reg_live_read marks 4585 * to stack slots all the way to first state when programs 4586 * writes+reads less than 8 bytes 4587 */ 4588 if (size == BPF_REG_SIZE) 4589 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4590 4591 /* when we zero initialize stack slots mark them as such */ 4592 if ((reg && register_is_null(reg)) || 4593 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4594 /* STACK_ZERO case happened because register spill 4595 * wasn't properly aligned at the stack slot boundary, 4596 * so it's not a register spill anymore; force 4597 * originating register to be precise to make 4598 * STACK_ZERO correct for subsequent states 4599 */ 4600 err = mark_chain_precision(env, value_regno); 4601 if (err) 4602 return err; 4603 type = STACK_ZERO; 4604 } 4605 4606 /* Mark slots affected by this stack write. */ 4607 for (i = 0; i < size; i++) 4608 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 4609 insn_flags = 0; /* not a register spill */ 4610 } 4611 4612 if (insn_flags) 4613 return push_jmp_history(env, env->cur_state, insn_flags); 4614 return 0; 4615 } 4616 4617 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 4618 * known to contain a variable offset. 4619 * This function checks whether the write is permitted and conservatively 4620 * tracks the effects of the write, considering that each stack slot in the 4621 * dynamic range is potentially written to. 4622 * 4623 * 'off' includes 'regno->off'. 4624 * 'value_regno' can be -1, meaning that an unknown value is being written to 4625 * the stack. 4626 * 4627 * Spilled pointers in range are not marked as written because we don't know 4628 * what's going to be actually written. This means that read propagation for 4629 * future reads cannot be terminated by this write. 4630 * 4631 * For privileged programs, uninitialized stack slots are considered 4632 * initialized by this write (even though we don't know exactly what offsets 4633 * are going to be written to). The idea is that we don't want the verifier to 4634 * reject future reads that access slots written to through variable offsets. 4635 */ 4636 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4637 /* func where register points to */ 4638 struct bpf_func_state *state, 4639 int ptr_regno, int off, int size, 4640 int value_regno, int insn_idx) 4641 { 4642 struct bpf_func_state *cur; /* state of the current function */ 4643 int min_off, max_off; 4644 int i, err; 4645 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 4646 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4647 bool writing_zero = false; 4648 /* set if the fact that we're writing a zero is used to let any 4649 * stack slots remain STACK_ZERO 4650 */ 4651 bool zero_used = false; 4652 4653 cur = env->cur_state->frame[env->cur_state->curframe]; 4654 ptr_reg = &cur->regs[ptr_regno]; 4655 min_off = ptr_reg->smin_value + off; 4656 max_off = ptr_reg->smax_value + off + size; 4657 if (value_regno >= 0) 4658 value_reg = &cur->regs[value_regno]; 4659 if ((value_reg && register_is_null(value_reg)) || 4660 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4661 writing_zero = true; 4662 4663 for (i = min_off; i < max_off; i++) { 4664 int spi; 4665 4666 spi = __get_spi(i); 4667 err = destroy_if_dynptr_stack_slot(env, state, spi); 4668 if (err) 4669 return err; 4670 } 4671 4672 /* Variable offset writes destroy any spilled pointers in range. */ 4673 for (i = min_off; i < max_off; i++) { 4674 u8 new_type, *stype; 4675 int slot, spi; 4676 4677 slot = -i - 1; 4678 spi = slot / BPF_REG_SIZE; 4679 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4680 mark_stack_slot_scratched(env, spi); 4681 4682 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4683 /* Reject the write if range we may write to has not 4684 * been initialized beforehand. If we didn't reject 4685 * here, the ptr status would be erased below (even 4686 * though not all slots are actually overwritten), 4687 * possibly opening the door to leaks. 4688 * 4689 * We do however catch STACK_INVALID case below, and 4690 * only allow reading possibly uninitialized memory 4691 * later for CAP_PERFMON, as the write may not happen to 4692 * that slot. 4693 */ 4694 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4695 insn_idx, i); 4696 return -EINVAL; 4697 } 4698 4699 /* If writing_zero and the spi slot contains a spill of value 0, 4700 * maintain the spill type. 4701 */ 4702 if (writing_zero && *stype == STACK_SPILL && 4703 is_spilled_scalar_reg(&state->stack[spi])) { 4704 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr; 4705 4706 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) { 4707 zero_used = true; 4708 continue; 4709 } 4710 } 4711 4712 /* Erase all other spilled pointers. */ 4713 state->stack[spi].spilled_ptr.type = NOT_INIT; 4714 4715 /* Update the slot type. */ 4716 new_type = STACK_MISC; 4717 if (writing_zero && *stype == STACK_ZERO) { 4718 new_type = STACK_ZERO; 4719 zero_used = true; 4720 } 4721 /* If the slot is STACK_INVALID, we check whether it's OK to 4722 * pretend that it will be initialized by this write. The slot 4723 * might not actually be written to, and so if we mark it as 4724 * initialized future reads might leak uninitialized memory. 4725 * For privileged programs, we will accept such reads to slots 4726 * that may or may not be written because, if we're reject 4727 * them, the error would be too confusing. 4728 */ 4729 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4730 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4731 insn_idx, i); 4732 return -EINVAL; 4733 } 4734 *stype = new_type; 4735 } 4736 if (zero_used) { 4737 /* backtracking doesn't work for STACK_ZERO yet. */ 4738 err = mark_chain_precision(env, value_regno); 4739 if (err) 4740 return err; 4741 } 4742 return 0; 4743 } 4744 4745 /* When register 'dst_regno' is assigned some values from stack[min_off, 4746 * max_off), we set the register's type according to the types of the 4747 * respective stack slots. If all the stack values are known to be zeros, then 4748 * so is the destination reg. Otherwise, the register is considered to be 4749 * SCALAR. This function does not deal with register filling; the caller must 4750 * ensure that all spilled registers in the stack range have been marked as 4751 * read. 4752 */ 4753 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4754 /* func where src register points to */ 4755 struct bpf_func_state *ptr_state, 4756 int min_off, int max_off, int dst_regno) 4757 { 4758 struct bpf_verifier_state *vstate = env->cur_state; 4759 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4760 int i, slot, spi; 4761 u8 *stype; 4762 int zeros = 0; 4763 4764 for (i = min_off; i < max_off; i++) { 4765 slot = -i - 1; 4766 spi = slot / BPF_REG_SIZE; 4767 mark_stack_slot_scratched(env, spi); 4768 stype = ptr_state->stack[spi].slot_type; 4769 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4770 break; 4771 zeros++; 4772 } 4773 if (zeros == max_off - min_off) { 4774 /* Any access_size read into register is zero extended, 4775 * so the whole register == const_zero. 4776 */ 4777 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4778 } else { 4779 /* have read misc data from the stack */ 4780 mark_reg_unknown(env, state->regs, dst_regno); 4781 } 4782 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4783 } 4784 4785 /* Read the stack at 'off' and put the results into the register indicated by 4786 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4787 * spilled reg. 4788 * 4789 * 'dst_regno' can be -1, meaning that the read value is not going to a 4790 * register. 4791 * 4792 * The access is assumed to be within the current stack bounds. 4793 */ 4794 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4795 /* func where src register points to */ 4796 struct bpf_func_state *reg_state, 4797 int off, int size, int dst_regno) 4798 { 4799 struct bpf_verifier_state *vstate = env->cur_state; 4800 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4801 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4802 struct bpf_reg_state *reg; 4803 u8 *stype, type; 4804 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi); 4805 4806 stype = reg_state->stack[spi].slot_type; 4807 reg = ®_state->stack[spi].spilled_ptr; 4808 4809 mark_stack_slot_scratched(env, spi); 4810 4811 if (is_spilled_reg(®_state->stack[spi])) { 4812 u8 spill_size = 1; 4813 4814 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4815 spill_size++; 4816 4817 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4818 if (reg->type != SCALAR_VALUE) { 4819 verbose_linfo(env, env->insn_idx, "; "); 4820 verbose(env, "invalid size of register fill\n"); 4821 return -EACCES; 4822 } 4823 4824 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4825 if (dst_regno < 0) 4826 return 0; 4827 4828 if (size <= spill_size && 4829 bpf_stack_narrow_access_ok(off, size, spill_size)) { 4830 /* The earlier check_reg_arg() has decided the 4831 * subreg_def for this insn. Save it first. 4832 */ 4833 s32 subreg_def = state->regs[dst_regno].subreg_def; 4834 4835 copy_register_state(&state->regs[dst_regno], reg); 4836 state->regs[dst_regno].subreg_def = subreg_def; 4837 4838 /* Break the relation on a narrowing fill. 4839 * coerce_reg_to_size will adjust the boundaries. 4840 */ 4841 if (get_reg_width(reg) > size * BITS_PER_BYTE) 4842 state->regs[dst_regno].id = 0; 4843 } else { 4844 int spill_cnt = 0, zero_cnt = 0; 4845 4846 for (i = 0; i < size; i++) { 4847 type = stype[(slot - i) % BPF_REG_SIZE]; 4848 if (type == STACK_SPILL) { 4849 spill_cnt++; 4850 continue; 4851 } 4852 if (type == STACK_MISC) 4853 continue; 4854 if (type == STACK_ZERO) { 4855 zero_cnt++; 4856 continue; 4857 } 4858 if (type == STACK_INVALID && env->allow_uninit_stack) 4859 continue; 4860 verbose(env, "invalid read from stack off %d+%d size %d\n", 4861 off, i, size); 4862 return -EACCES; 4863 } 4864 4865 if (spill_cnt == size && 4866 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 4867 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4868 /* this IS register fill, so keep insn_flags */ 4869 } else if (zero_cnt == size) { 4870 /* similarly to mark_reg_stack_read(), preserve zeroes */ 4871 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4872 insn_flags = 0; /* not restoring original register state */ 4873 } else { 4874 mark_reg_unknown(env, state->regs, dst_regno); 4875 insn_flags = 0; /* not restoring original register state */ 4876 } 4877 } 4878 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4879 } else if (dst_regno >= 0) { 4880 /* restore register state from stack */ 4881 copy_register_state(&state->regs[dst_regno], reg); 4882 /* mark reg as written since spilled pointer state likely 4883 * has its liveness marks cleared by is_state_visited() 4884 * which resets stack/reg liveness for state transitions 4885 */ 4886 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4887 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 4888 /* If dst_regno==-1, the caller is asking us whether 4889 * it is acceptable to use this value as a SCALAR_VALUE 4890 * (e.g. for XADD). 4891 * We must not allow unprivileged callers to do that 4892 * with spilled pointers. 4893 */ 4894 verbose(env, "leaking pointer from stack off %d\n", 4895 off); 4896 return -EACCES; 4897 } 4898 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4899 } else { 4900 for (i = 0; i < size; i++) { 4901 type = stype[(slot - i) % BPF_REG_SIZE]; 4902 if (type == STACK_MISC) 4903 continue; 4904 if (type == STACK_ZERO) 4905 continue; 4906 if (type == STACK_INVALID && env->allow_uninit_stack) 4907 continue; 4908 verbose(env, "invalid read from stack off %d+%d size %d\n", 4909 off, i, size); 4910 return -EACCES; 4911 } 4912 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4913 if (dst_regno >= 0) 4914 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 4915 insn_flags = 0; /* we are not restoring spilled register */ 4916 } 4917 if (insn_flags) 4918 return push_jmp_history(env, env->cur_state, insn_flags); 4919 return 0; 4920 } 4921 4922 enum bpf_access_src { 4923 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 4924 ACCESS_HELPER = 2, /* the access is performed by a helper */ 4925 }; 4926 4927 static int check_stack_range_initialized(struct bpf_verifier_env *env, 4928 int regno, int off, int access_size, 4929 bool zero_size_allowed, 4930 enum bpf_access_src type, 4931 struct bpf_call_arg_meta *meta); 4932 4933 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 4934 { 4935 return cur_regs(env) + regno; 4936 } 4937 4938 /* Read the stack at 'ptr_regno + off' and put the result into the register 4939 * 'dst_regno'. 4940 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 4941 * but not its variable offset. 4942 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 4943 * 4944 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 4945 * filling registers (i.e. reads of spilled register cannot be detected when 4946 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 4947 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 4948 * offset; for a fixed offset check_stack_read_fixed_off should be used 4949 * instead. 4950 */ 4951 static int check_stack_read_var_off(struct bpf_verifier_env *env, 4952 int ptr_regno, int off, int size, int dst_regno) 4953 { 4954 /* The state of the source register. */ 4955 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4956 struct bpf_func_state *ptr_state = func(env, reg); 4957 int err; 4958 int min_off, max_off; 4959 4960 /* Note that we pass a NULL meta, so raw access will not be permitted. 4961 */ 4962 err = check_stack_range_initialized(env, ptr_regno, off, size, 4963 false, ACCESS_DIRECT, NULL); 4964 if (err) 4965 return err; 4966 4967 min_off = reg->smin_value + off; 4968 max_off = reg->smax_value + off; 4969 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 4970 return 0; 4971 } 4972 4973 /* check_stack_read dispatches to check_stack_read_fixed_off or 4974 * check_stack_read_var_off. 4975 * 4976 * The caller must ensure that the offset falls within the allocated stack 4977 * bounds. 4978 * 4979 * 'dst_regno' is a register which will receive the value from the stack. It 4980 * can be -1, meaning that the read value is not going to a register. 4981 */ 4982 static int check_stack_read(struct bpf_verifier_env *env, 4983 int ptr_regno, int off, int size, 4984 int dst_regno) 4985 { 4986 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4987 struct bpf_func_state *state = func(env, reg); 4988 int err; 4989 /* Some accesses are only permitted with a static offset. */ 4990 bool var_off = !tnum_is_const(reg->var_off); 4991 4992 /* The offset is required to be static when reads don't go to a 4993 * register, in order to not leak pointers (see 4994 * check_stack_read_fixed_off). 4995 */ 4996 if (dst_regno < 0 && var_off) { 4997 char tn_buf[48]; 4998 4999 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5000 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 5001 tn_buf, off, size); 5002 return -EACCES; 5003 } 5004 /* Variable offset is prohibited for unprivileged mode for simplicity 5005 * since it requires corresponding support in Spectre masking for stack 5006 * ALU. See also retrieve_ptr_limit(). The check in 5007 * check_stack_access_for_ptr_arithmetic() called by 5008 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 5009 * with variable offsets, therefore no check is required here. Further, 5010 * just checking it here would be insufficient as speculative stack 5011 * writes could still lead to unsafe speculative behaviour. 5012 */ 5013 if (!var_off) { 5014 off += reg->var_off.value; 5015 err = check_stack_read_fixed_off(env, state, off, size, 5016 dst_regno); 5017 } else { 5018 /* Variable offset stack reads need more conservative handling 5019 * than fixed offset ones. Note that dst_regno >= 0 on this 5020 * branch. 5021 */ 5022 err = check_stack_read_var_off(env, ptr_regno, off, size, 5023 dst_regno); 5024 } 5025 return err; 5026 } 5027 5028 5029 /* check_stack_write dispatches to check_stack_write_fixed_off or 5030 * check_stack_write_var_off. 5031 * 5032 * 'ptr_regno' is the register used as a pointer into the stack. 5033 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 5034 * 'value_regno' is the register whose value we're writing to the stack. It can 5035 * be -1, meaning that we're not writing from a register. 5036 * 5037 * The caller must ensure that the offset falls within the maximum stack size. 5038 */ 5039 static int check_stack_write(struct bpf_verifier_env *env, 5040 int ptr_regno, int off, int size, 5041 int value_regno, int insn_idx) 5042 { 5043 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5044 struct bpf_func_state *state = func(env, reg); 5045 int err; 5046 5047 if (tnum_is_const(reg->var_off)) { 5048 off += reg->var_off.value; 5049 err = check_stack_write_fixed_off(env, state, off, size, 5050 value_regno, insn_idx); 5051 } else { 5052 /* Variable offset stack reads need more conservative handling 5053 * than fixed offset ones. 5054 */ 5055 err = check_stack_write_var_off(env, state, 5056 ptr_regno, off, size, 5057 value_regno, insn_idx); 5058 } 5059 return err; 5060 } 5061 5062 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 5063 int off, int size, enum bpf_access_type type) 5064 { 5065 struct bpf_reg_state *regs = cur_regs(env); 5066 struct bpf_map *map = regs[regno].map_ptr; 5067 u32 cap = bpf_map_flags_to_cap(map); 5068 5069 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 5070 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 5071 map->value_size, off, size); 5072 return -EACCES; 5073 } 5074 5075 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 5076 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 5077 map->value_size, off, size); 5078 return -EACCES; 5079 } 5080 5081 return 0; 5082 } 5083 5084 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 5085 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 5086 int off, int size, u32 mem_size, 5087 bool zero_size_allowed) 5088 { 5089 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 5090 struct bpf_reg_state *reg; 5091 5092 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 5093 return 0; 5094 5095 reg = &cur_regs(env)[regno]; 5096 switch (reg->type) { 5097 case PTR_TO_MAP_KEY: 5098 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 5099 mem_size, off, size); 5100 break; 5101 case PTR_TO_MAP_VALUE: 5102 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 5103 mem_size, off, size); 5104 break; 5105 case PTR_TO_PACKET: 5106 case PTR_TO_PACKET_META: 5107 case PTR_TO_PACKET_END: 5108 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 5109 off, size, regno, reg->id, off, mem_size); 5110 break; 5111 case PTR_TO_MEM: 5112 default: 5113 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 5114 mem_size, off, size); 5115 } 5116 5117 return -EACCES; 5118 } 5119 5120 /* check read/write into a memory region with possible variable offset */ 5121 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 5122 int off, int size, u32 mem_size, 5123 bool zero_size_allowed) 5124 { 5125 struct bpf_verifier_state *vstate = env->cur_state; 5126 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5127 struct bpf_reg_state *reg = &state->regs[regno]; 5128 int err; 5129 5130 /* We may have adjusted the register pointing to memory region, so we 5131 * need to try adding each of min_value and max_value to off 5132 * to make sure our theoretical access will be safe. 5133 * 5134 * The minimum value is only important with signed 5135 * comparisons where we can't assume the floor of a 5136 * value is 0. If we are using signed variables for our 5137 * index'es we need to make sure that whatever we use 5138 * will have a set floor within our range. 5139 */ 5140 if (reg->smin_value < 0 && 5141 (reg->smin_value == S64_MIN || 5142 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5143 reg->smin_value + off < 0)) { 5144 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5145 regno); 5146 return -EACCES; 5147 } 5148 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5149 mem_size, zero_size_allowed); 5150 if (err) { 5151 verbose(env, "R%d min value is outside of the allowed memory range\n", 5152 regno); 5153 return err; 5154 } 5155 5156 /* If we haven't set a max value then we need to bail since we can't be 5157 * sure we won't do bad things. 5158 * If reg->umax_value + off could overflow, treat that as unbounded too. 5159 */ 5160 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5161 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5162 regno); 5163 return -EACCES; 5164 } 5165 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5166 mem_size, zero_size_allowed); 5167 if (err) { 5168 verbose(env, "R%d max value is outside of the allowed memory range\n", 5169 regno); 5170 return err; 5171 } 5172 5173 return 0; 5174 } 5175 5176 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5177 const struct bpf_reg_state *reg, int regno, 5178 bool fixed_off_ok) 5179 { 5180 /* Access to this pointer-typed register or passing it to a helper 5181 * is only allowed in its original, unmodified form. 5182 */ 5183 5184 if (reg->off < 0) { 5185 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5186 reg_type_str(env, reg->type), regno, reg->off); 5187 return -EACCES; 5188 } 5189 5190 if (!fixed_off_ok && reg->off) { 5191 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5192 reg_type_str(env, reg->type), regno, reg->off); 5193 return -EACCES; 5194 } 5195 5196 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5197 char tn_buf[48]; 5198 5199 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5200 verbose(env, "variable %s access var_off=%s disallowed\n", 5201 reg_type_str(env, reg->type), tn_buf); 5202 return -EACCES; 5203 } 5204 5205 return 0; 5206 } 5207 5208 static int check_ptr_off_reg(struct bpf_verifier_env *env, 5209 const struct bpf_reg_state *reg, int regno) 5210 { 5211 return __check_ptr_off_reg(env, reg, regno, false); 5212 } 5213 5214 static int map_kptr_match_type(struct bpf_verifier_env *env, 5215 struct btf_field *kptr_field, 5216 struct bpf_reg_state *reg, u32 regno) 5217 { 5218 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5219 int perm_flags; 5220 const char *reg_name = ""; 5221 5222 if (btf_is_kernel(reg->btf)) { 5223 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5224 5225 /* Only unreferenced case accepts untrusted pointers */ 5226 if (kptr_field->type == BPF_KPTR_UNREF) 5227 perm_flags |= PTR_UNTRUSTED; 5228 } else { 5229 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5230 if (kptr_field->type == BPF_KPTR_PERCPU) 5231 perm_flags |= MEM_PERCPU; 5232 } 5233 5234 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5235 goto bad_type; 5236 5237 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5238 reg_name = btf_type_name(reg->btf, reg->btf_id); 5239 5240 /* For ref_ptr case, release function check should ensure we get one 5241 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5242 * normal store of unreferenced kptr, we must ensure var_off is zero. 5243 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5244 * reg->off and reg->ref_obj_id are not needed here. 5245 */ 5246 if (__check_ptr_off_reg(env, reg, regno, true)) 5247 return -EACCES; 5248 5249 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5250 * we also need to take into account the reg->off. 5251 * 5252 * We want to support cases like: 5253 * 5254 * struct foo { 5255 * struct bar br; 5256 * struct baz bz; 5257 * }; 5258 * 5259 * struct foo *v; 5260 * v = func(); // PTR_TO_BTF_ID 5261 * val->foo = v; // reg->off is zero, btf and btf_id match type 5262 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5263 * // first member type of struct after comparison fails 5264 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5265 * // to match type 5266 * 5267 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5268 * is zero. We must also ensure that btf_struct_ids_match does not walk 5269 * the struct to match type against first member of struct, i.e. reject 5270 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5271 * strict mode to true for type match. 5272 */ 5273 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5274 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5275 kptr_field->type != BPF_KPTR_UNREF)) 5276 goto bad_type; 5277 return 0; 5278 bad_type: 5279 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5280 reg_type_str(env, reg->type), reg_name); 5281 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5282 if (kptr_field->type == BPF_KPTR_UNREF) 5283 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5284 targ_name); 5285 else 5286 verbose(env, "\n"); 5287 return -EINVAL; 5288 } 5289 5290 static bool in_sleepable(struct bpf_verifier_env *env) 5291 { 5292 return env->prog->sleepable || 5293 (env->cur_state && env->cur_state->in_sleepable); 5294 } 5295 5296 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5297 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5298 */ 5299 static bool in_rcu_cs(struct bpf_verifier_env *env) 5300 { 5301 return env->cur_state->active_rcu_lock || 5302 env->cur_state->active_lock.ptr || 5303 !in_sleepable(env); 5304 } 5305 5306 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5307 BTF_SET_START(rcu_protected_types) 5308 BTF_ID(struct, prog_test_ref_kfunc) 5309 #ifdef CONFIG_CGROUPS 5310 BTF_ID(struct, cgroup) 5311 #endif 5312 #ifdef CONFIG_BPF_JIT 5313 BTF_ID(struct, bpf_cpumask) 5314 #endif 5315 BTF_ID(struct, task_struct) 5316 BTF_ID(struct, bpf_crypto_ctx) 5317 BTF_SET_END(rcu_protected_types) 5318 5319 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5320 { 5321 if (!btf_is_kernel(btf)) 5322 return true; 5323 return btf_id_set_contains(&rcu_protected_types, btf_id); 5324 } 5325 5326 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 5327 { 5328 struct btf_struct_meta *meta; 5329 5330 if (btf_is_kernel(kptr_field->kptr.btf)) 5331 return NULL; 5332 5333 meta = btf_find_struct_meta(kptr_field->kptr.btf, 5334 kptr_field->kptr.btf_id); 5335 5336 return meta ? meta->record : NULL; 5337 } 5338 5339 static bool rcu_safe_kptr(const struct btf_field *field) 5340 { 5341 const struct btf_field_kptr *kptr = &field->kptr; 5342 5343 return field->type == BPF_KPTR_PERCPU || 5344 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 5345 } 5346 5347 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 5348 { 5349 struct btf_record *rec; 5350 u32 ret; 5351 5352 ret = PTR_MAYBE_NULL; 5353 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 5354 ret |= MEM_RCU; 5355 if (kptr_field->type == BPF_KPTR_PERCPU) 5356 ret |= MEM_PERCPU; 5357 else if (!btf_is_kernel(kptr_field->kptr.btf)) 5358 ret |= MEM_ALLOC; 5359 5360 rec = kptr_pointee_btf_record(kptr_field); 5361 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 5362 ret |= NON_OWN_REF; 5363 } else { 5364 ret |= PTR_UNTRUSTED; 5365 } 5366 5367 return ret; 5368 } 5369 5370 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5371 int value_regno, int insn_idx, 5372 struct btf_field *kptr_field) 5373 { 5374 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5375 int class = BPF_CLASS(insn->code); 5376 struct bpf_reg_state *val_reg; 5377 5378 /* Things we already checked for in check_map_access and caller: 5379 * - Reject cases where variable offset may touch kptr 5380 * - size of access (must be BPF_DW) 5381 * - tnum_is_const(reg->var_off) 5382 * - kptr_field->offset == off + reg->var_off.value 5383 */ 5384 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5385 if (BPF_MODE(insn->code) != BPF_MEM) { 5386 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5387 return -EACCES; 5388 } 5389 5390 /* We only allow loading referenced kptr, since it will be marked as 5391 * untrusted, similar to unreferenced kptr. 5392 */ 5393 if (class != BPF_LDX && 5394 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 5395 verbose(env, "store to referenced kptr disallowed\n"); 5396 return -EACCES; 5397 } 5398 5399 if (class == BPF_LDX) { 5400 val_reg = reg_state(env, value_regno); 5401 /* We can simply mark the value_regno receiving the pointer 5402 * value from map as PTR_TO_BTF_ID, with the correct type. 5403 */ 5404 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5405 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field)); 5406 } else if (class == BPF_STX) { 5407 val_reg = reg_state(env, value_regno); 5408 if (!register_is_null(val_reg) && 5409 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5410 return -EACCES; 5411 } else if (class == BPF_ST) { 5412 if (insn->imm) { 5413 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5414 kptr_field->offset); 5415 return -EACCES; 5416 } 5417 } else { 5418 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5419 return -EACCES; 5420 } 5421 return 0; 5422 } 5423 5424 /* check read/write into a map element with possible variable offset */ 5425 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5426 int off, int size, bool zero_size_allowed, 5427 enum bpf_access_src src) 5428 { 5429 struct bpf_verifier_state *vstate = env->cur_state; 5430 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5431 struct bpf_reg_state *reg = &state->regs[regno]; 5432 struct bpf_map *map = reg->map_ptr; 5433 struct btf_record *rec; 5434 int err, i; 5435 5436 err = check_mem_region_access(env, regno, off, size, map->value_size, 5437 zero_size_allowed); 5438 if (err) 5439 return err; 5440 5441 if (IS_ERR_OR_NULL(map->record)) 5442 return 0; 5443 rec = map->record; 5444 for (i = 0; i < rec->cnt; i++) { 5445 struct btf_field *field = &rec->fields[i]; 5446 u32 p = field->offset; 5447 5448 /* If any part of a field can be touched by load/store, reject 5449 * this program. To check that [x1, x2) overlaps with [y1, y2), 5450 * it is sufficient to check x1 < y2 && y1 < x2. 5451 */ 5452 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 5453 p < reg->umax_value + off + size) { 5454 switch (field->type) { 5455 case BPF_KPTR_UNREF: 5456 case BPF_KPTR_REF: 5457 case BPF_KPTR_PERCPU: 5458 if (src != ACCESS_DIRECT) { 5459 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 5460 return -EACCES; 5461 } 5462 if (!tnum_is_const(reg->var_off)) { 5463 verbose(env, "kptr access cannot have variable offset\n"); 5464 return -EACCES; 5465 } 5466 if (p != off + reg->var_off.value) { 5467 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 5468 p, off + reg->var_off.value); 5469 return -EACCES; 5470 } 5471 if (size != bpf_size_to_bytes(BPF_DW)) { 5472 verbose(env, "kptr access size must be BPF_DW\n"); 5473 return -EACCES; 5474 } 5475 break; 5476 default: 5477 verbose(env, "%s cannot be accessed directly by load/store\n", 5478 btf_field_type_name(field->type)); 5479 return -EACCES; 5480 } 5481 } 5482 } 5483 return 0; 5484 } 5485 5486 #define MAX_PACKET_OFF 0xffff 5487 5488 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5489 const struct bpf_call_arg_meta *meta, 5490 enum bpf_access_type t) 5491 { 5492 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5493 5494 switch (prog_type) { 5495 /* Program types only with direct read access go here! */ 5496 case BPF_PROG_TYPE_LWT_IN: 5497 case BPF_PROG_TYPE_LWT_OUT: 5498 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5499 case BPF_PROG_TYPE_SK_REUSEPORT: 5500 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5501 case BPF_PROG_TYPE_CGROUP_SKB: 5502 if (t == BPF_WRITE) 5503 return false; 5504 fallthrough; 5505 5506 /* Program types with direct read + write access go here! */ 5507 case BPF_PROG_TYPE_SCHED_CLS: 5508 case BPF_PROG_TYPE_SCHED_ACT: 5509 case BPF_PROG_TYPE_XDP: 5510 case BPF_PROG_TYPE_LWT_XMIT: 5511 case BPF_PROG_TYPE_SK_SKB: 5512 case BPF_PROG_TYPE_SK_MSG: 5513 if (meta) 5514 return meta->pkt_access; 5515 5516 env->seen_direct_write = true; 5517 return true; 5518 5519 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5520 if (t == BPF_WRITE) 5521 env->seen_direct_write = true; 5522 5523 return true; 5524 5525 default: 5526 return false; 5527 } 5528 } 5529 5530 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5531 int size, bool zero_size_allowed) 5532 { 5533 struct bpf_reg_state *regs = cur_regs(env); 5534 struct bpf_reg_state *reg = ®s[regno]; 5535 int err; 5536 5537 /* We may have added a variable offset to the packet pointer; but any 5538 * reg->range we have comes after that. We are only checking the fixed 5539 * offset. 5540 */ 5541 5542 /* We don't allow negative numbers, because we aren't tracking enough 5543 * detail to prove they're safe. 5544 */ 5545 if (reg->smin_value < 0) { 5546 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5547 regno); 5548 return -EACCES; 5549 } 5550 5551 err = reg->range < 0 ? -EINVAL : 5552 __check_mem_access(env, regno, off, size, reg->range, 5553 zero_size_allowed); 5554 if (err) { 5555 verbose(env, "R%d offset is outside of the packet\n", regno); 5556 return err; 5557 } 5558 5559 /* __check_mem_access has made sure "off + size - 1" is within u16. 5560 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5561 * otherwise find_good_pkt_pointers would have refused to set range info 5562 * that __check_mem_access would have rejected this pkt access. 5563 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5564 */ 5565 env->prog->aux->max_pkt_offset = 5566 max_t(u32, env->prog->aux->max_pkt_offset, 5567 off + reg->umax_value + size - 1); 5568 5569 return err; 5570 } 5571 5572 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5573 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5574 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5575 struct btf **btf, u32 *btf_id) 5576 { 5577 struct bpf_insn_access_aux info = { 5578 .reg_type = *reg_type, 5579 .log = &env->log, 5580 }; 5581 5582 if (env->ops->is_valid_access && 5583 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5584 /* A non zero info.ctx_field_size indicates that this field is a 5585 * candidate for later verifier transformation to load the whole 5586 * field and then apply a mask when accessed with a narrower 5587 * access than actual ctx access size. A zero info.ctx_field_size 5588 * will only allow for whole field access and rejects any other 5589 * type of narrower access. 5590 */ 5591 *reg_type = info.reg_type; 5592 5593 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5594 *btf = info.btf; 5595 *btf_id = info.btf_id; 5596 } else { 5597 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5598 } 5599 /* remember the offset of last byte accessed in ctx */ 5600 if (env->prog->aux->max_ctx_offset < off + size) 5601 env->prog->aux->max_ctx_offset = off + size; 5602 return 0; 5603 } 5604 5605 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5606 return -EACCES; 5607 } 5608 5609 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5610 int size) 5611 { 5612 if (size < 0 || off < 0 || 5613 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5614 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5615 off, size); 5616 return -EACCES; 5617 } 5618 return 0; 5619 } 5620 5621 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5622 u32 regno, int off, int size, 5623 enum bpf_access_type t) 5624 { 5625 struct bpf_reg_state *regs = cur_regs(env); 5626 struct bpf_reg_state *reg = ®s[regno]; 5627 struct bpf_insn_access_aux info = {}; 5628 bool valid; 5629 5630 if (reg->smin_value < 0) { 5631 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5632 regno); 5633 return -EACCES; 5634 } 5635 5636 switch (reg->type) { 5637 case PTR_TO_SOCK_COMMON: 5638 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5639 break; 5640 case PTR_TO_SOCKET: 5641 valid = bpf_sock_is_valid_access(off, size, t, &info); 5642 break; 5643 case PTR_TO_TCP_SOCK: 5644 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5645 break; 5646 case PTR_TO_XDP_SOCK: 5647 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5648 break; 5649 default: 5650 valid = false; 5651 } 5652 5653 5654 if (valid) { 5655 env->insn_aux_data[insn_idx].ctx_field_size = 5656 info.ctx_field_size; 5657 return 0; 5658 } 5659 5660 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5661 regno, reg_type_str(env, reg->type), off, size); 5662 5663 return -EACCES; 5664 } 5665 5666 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5667 { 5668 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5669 } 5670 5671 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5672 { 5673 const struct bpf_reg_state *reg = reg_state(env, regno); 5674 5675 return reg->type == PTR_TO_CTX; 5676 } 5677 5678 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5679 { 5680 const struct bpf_reg_state *reg = reg_state(env, regno); 5681 5682 return type_is_sk_pointer(reg->type); 5683 } 5684 5685 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5686 { 5687 const struct bpf_reg_state *reg = reg_state(env, regno); 5688 5689 return type_is_pkt_pointer(reg->type); 5690 } 5691 5692 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5693 { 5694 const struct bpf_reg_state *reg = reg_state(env, regno); 5695 5696 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5697 return reg->type == PTR_TO_FLOW_KEYS; 5698 } 5699 5700 static bool is_arena_reg(struct bpf_verifier_env *env, int regno) 5701 { 5702 const struct bpf_reg_state *reg = reg_state(env, regno); 5703 5704 return reg->type == PTR_TO_ARENA; 5705 } 5706 5707 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5708 #ifdef CONFIG_NET 5709 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5710 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5711 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5712 #endif 5713 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5714 }; 5715 5716 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5717 { 5718 /* A referenced register is always trusted. */ 5719 if (reg->ref_obj_id) 5720 return true; 5721 5722 /* Types listed in the reg2btf_ids are always trusted */ 5723 if (reg2btf_ids[base_type(reg->type)] && 5724 !bpf_type_has_unsafe_modifiers(reg->type)) 5725 return true; 5726 5727 /* If a register is not referenced, it is trusted if it has the 5728 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5729 * other type modifiers may be safe, but we elect to take an opt-in 5730 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5731 * not. 5732 * 5733 * Eventually, we should make PTR_TRUSTED the single source of truth 5734 * for whether a register is trusted. 5735 */ 5736 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5737 !bpf_type_has_unsafe_modifiers(reg->type); 5738 } 5739 5740 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5741 { 5742 return reg->type & MEM_RCU; 5743 } 5744 5745 static void clear_trusted_flags(enum bpf_type_flag *flag) 5746 { 5747 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5748 } 5749 5750 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5751 const struct bpf_reg_state *reg, 5752 int off, int size, bool strict) 5753 { 5754 struct tnum reg_off; 5755 int ip_align; 5756 5757 /* Byte size accesses are always allowed. */ 5758 if (!strict || size == 1) 5759 return 0; 5760 5761 /* For platforms that do not have a Kconfig enabling 5762 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5763 * NET_IP_ALIGN is universally set to '2'. And on platforms 5764 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5765 * to this code only in strict mode where we want to emulate 5766 * the NET_IP_ALIGN==2 checking. Therefore use an 5767 * unconditional IP align value of '2'. 5768 */ 5769 ip_align = 2; 5770 5771 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5772 if (!tnum_is_aligned(reg_off, size)) { 5773 char tn_buf[48]; 5774 5775 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5776 verbose(env, 5777 "misaligned packet access off %d+%s+%d+%d size %d\n", 5778 ip_align, tn_buf, reg->off, off, size); 5779 return -EACCES; 5780 } 5781 5782 return 0; 5783 } 5784 5785 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5786 const struct bpf_reg_state *reg, 5787 const char *pointer_desc, 5788 int off, int size, bool strict) 5789 { 5790 struct tnum reg_off; 5791 5792 /* Byte size accesses are always allowed. */ 5793 if (!strict || size == 1) 5794 return 0; 5795 5796 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5797 if (!tnum_is_aligned(reg_off, size)) { 5798 char tn_buf[48]; 5799 5800 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5801 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5802 pointer_desc, tn_buf, reg->off, off, size); 5803 return -EACCES; 5804 } 5805 5806 return 0; 5807 } 5808 5809 static int check_ptr_alignment(struct bpf_verifier_env *env, 5810 const struct bpf_reg_state *reg, int off, 5811 int size, bool strict_alignment_once) 5812 { 5813 bool strict = env->strict_alignment || strict_alignment_once; 5814 const char *pointer_desc = ""; 5815 5816 switch (reg->type) { 5817 case PTR_TO_PACKET: 5818 case PTR_TO_PACKET_META: 5819 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5820 * right in front, treat it the very same way. 5821 */ 5822 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5823 case PTR_TO_FLOW_KEYS: 5824 pointer_desc = "flow keys "; 5825 break; 5826 case PTR_TO_MAP_KEY: 5827 pointer_desc = "key "; 5828 break; 5829 case PTR_TO_MAP_VALUE: 5830 pointer_desc = "value "; 5831 break; 5832 case PTR_TO_CTX: 5833 pointer_desc = "context "; 5834 break; 5835 case PTR_TO_STACK: 5836 pointer_desc = "stack "; 5837 /* The stack spill tracking logic in check_stack_write_fixed_off() 5838 * and check_stack_read_fixed_off() relies on stack accesses being 5839 * aligned. 5840 */ 5841 strict = true; 5842 break; 5843 case PTR_TO_SOCKET: 5844 pointer_desc = "sock "; 5845 break; 5846 case PTR_TO_SOCK_COMMON: 5847 pointer_desc = "sock_common "; 5848 break; 5849 case PTR_TO_TCP_SOCK: 5850 pointer_desc = "tcp_sock "; 5851 break; 5852 case PTR_TO_XDP_SOCK: 5853 pointer_desc = "xdp_sock "; 5854 break; 5855 case PTR_TO_ARENA: 5856 return 0; 5857 default: 5858 break; 5859 } 5860 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5861 strict); 5862 } 5863 5864 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth) 5865 { 5866 if (env->prog->jit_requested) 5867 return round_up(stack_depth, 16); 5868 5869 /* round up to 32-bytes, since this is granularity 5870 * of interpreter stack size 5871 */ 5872 return round_up(max_t(u32, stack_depth, 1), 32); 5873 } 5874 5875 /* starting from main bpf function walk all instructions of the function 5876 * and recursively walk all callees that given function can call. 5877 * Ignore jump and exit insns. 5878 * Since recursion is prevented by check_cfg() this algorithm 5879 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 5880 */ 5881 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx) 5882 { 5883 struct bpf_subprog_info *subprog = env->subprog_info; 5884 struct bpf_insn *insn = env->prog->insnsi; 5885 int depth = 0, frame = 0, i, subprog_end; 5886 bool tail_call_reachable = false; 5887 int ret_insn[MAX_CALL_FRAMES]; 5888 int ret_prog[MAX_CALL_FRAMES]; 5889 int j; 5890 5891 i = subprog[idx].start; 5892 process_func: 5893 /* protect against potential stack overflow that might happen when 5894 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5895 * depth for such case down to 256 so that the worst case scenario 5896 * would result in 8k stack size (32 which is tailcall limit * 256 = 5897 * 8k). 5898 * 5899 * To get the idea what might happen, see an example: 5900 * func1 -> sub rsp, 128 5901 * subfunc1 -> sub rsp, 256 5902 * tailcall1 -> add rsp, 256 5903 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5904 * subfunc2 -> sub rsp, 64 5905 * subfunc22 -> sub rsp, 128 5906 * tailcall2 -> add rsp, 128 5907 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5908 * 5909 * tailcall will unwind the current stack frame but it will not get rid 5910 * of caller's stack as shown on the example above. 5911 */ 5912 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5913 verbose(env, 5914 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5915 depth); 5916 return -EACCES; 5917 } 5918 depth += round_up_stack_depth(env, subprog[idx].stack_depth); 5919 if (depth > MAX_BPF_STACK) { 5920 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5921 frame + 1, depth); 5922 return -EACCES; 5923 } 5924 continue_func: 5925 subprog_end = subprog[idx + 1].start; 5926 for (; i < subprog_end; i++) { 5927 int next_insn, sidx; 5928 5929 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 5930 bool err = false; 5931 5932 if (!is_bpf_throw_kfunc(insn + i)) 5933 continue; 5934 if (subprog[idx].is_cb) 5935 err = true; 5936 for (int c = 0; c < frame && !err; c++) { 5937 if (subprog[ret_prog[c]].is_cb) { 5938 err = true; 5939 break; 5940 } 5941 } 5942 if (!err) 5943 continue; 5944 verbose(env, 5945 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 5946 i, idx); 5947 return -EINVAL; 5948 } 5949 5950 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5951 continue; 5952 /* remember insn and function to return to */ 5953 ret_insn[frame] = i + 1; 5954 ret_prog[frame] = idx; 5955 5956 /* find the callee */ 5957 next_insn = i + insn[i].imm + 1; 5958 sidx = find_subprog(env, next_insn); 5959 if (sidx < 0) { 5960 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5961 next_insn); 5962 return -EFAULT; 5963 } 5964 if (subprog[sidx].is_async_cb) { 5965 if (subprog[sidx].has_tail_call) { 5966 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 5967 return -EFAULT; 5968 } 5969 /* async callbacks don't increase bpf prog stack size unless called directly */ 5970 if (!bpf_pseudo_call(insn + i)) 5971 continue; 5972 if (subprog[sidx].is_exception_cb) { 5973 verbose(env, "insn %d cannot call exception cb directly\n", i); 5974 return -EINVAL; 5975 } 5976 } 5977 i = next_insn; 5978 idx = sidx; 5979 5980 if (subprog[idx].has_tail_call) 5981 tail_call_reachable = true; 5982 5983 frame++; 5984 if (frame >= MAX_CALL_FRAMES) { 5985 verbose(env, "the call stack of %d frames is too deep !\n", 5986 frame); 5987 return -E2BIG; 5988 } 5989 goto process_func; 5990 } 5991 /* if tail call got detected across bpf2bpf calls then mark each of the 5992 * currently present subprog frames as tail call reachable subprogs; 5993 * this info will be utilized by JIT so that we will be preserving the 5994 * tail call counter throughout bpf2bpf calls combined with tailcalls 5995 */ 5996 if (tail_call_reachable) 5997 for (j = 0; j < frame; j++) { 5998 if (subprog[ret_prog[j]].is_exception_cb) { 5999 verbose(env, "cannot tail call within exception cb\n"); 6000 return -EINVAL; 6001 } 6002 subprog[ret_prog[j]].tail_call_reachable = true; 6003 } 6004 if (subprog[0].tail_call_reachable) 6005 env->prog->aux->tail_call_reachable = true; 6006 6007 /* end of for() loop means the last insn of the 'subprog' 6008 * was reached. Doesn't matter whether it was JA or EXIT 6009 */ 6010 if (frame == 0) 6011 return 0; 6012 depth -= round_up_stack_depth(env, subprog[idx].stack_depth); 6013 frame--; 6014 i = ret_insn[frame]; 6015 idx = ret_prog[frame]; 6016 goto continue_func; 6017 } 6018 6019 static int check_max_stack_depth(struct bpf_verifier_env *env) 6020 { 6021 struct bpf_subprog_info *si = env->subprog_info; 6022 int ret; 6023 6024 for (int i = 0; i < env->subprog_cnt; i++) { 6025 if (!i || si[i].is_async_cb) { 6026 ret = check_max_stack_depth_subprog(env, i); 6027 if (ret < 0) 6028 return ret; 6029 } 6030 continue; 6031 } 6032 return 0; 6033 } 6034 6035 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 6036 static int get_callee_stack_depth(struct bpf_verifier_env *env, 6037 const struct bpf_insn *insn, int idx) 6038 { 6039 int start = idx + insn->imm + 1, subprog; 6040 6041 subprog = find_subprog(env, start); 6042 if (subprog < 0) { 6043 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 6044 start); 6045 return -EFAULT; 6046 } 6047 return env->subprog_info[subprog].stack_depth; 6048 } 6049 #endif 6050 6051 static int __check_buffer_access(struct bpf_verifier_env *env, 6052 const char *buf_info, 6053 const struct bpf_reg_state *reg, 6054 int regno, int off, int size) 6055 { 6056 if (off < 0) { 6057 verbose(env, 6058 "R%d invalid %s buffer access: off=%d, size=%d\n", 6059 regno, buf_info, off, size); 6060 return -EACCES; 6061 } 6062 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6063 char tn_buf[48]; 6064 6065 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6066 verbose(env, 6067 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 6068 regno, off, tn_buf); 6069 return -EACCES; 6070 } 6071 6072 return 0; 6073 } 6074 6075 static int check_tp_buffer_access(struct bpf_verifier_env *env, 6076 const struct bpf_reg_state *reg, 6077 int regno, int off, int size) 6078 { 6079 int err; 6080 6081 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 6082 if (err) 6083 return err; 6084 6085 if (off + size > env->prog->aux->max_tp_access) 6086 env->prog->aux->max_tp_access = off + size; 6087 6088 return 0; 6089 } 6090 6091 static int check_buffer_access(struct bpf_verifier_env *env, 6092 const struct bpf_reg_state *reg, 6093 int regno, int off, int size, 6094 bool zero_size_allowed, 6095 u32 *max_access) 6096 { 6097 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 6098 int err; 6099 6100 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 6101 if (err) 6102 return err; 6103 6104 if (off + size > *max_access) 6105 *max_access = off + size; 6106 6107 return 0; 6108 } 6109 6110 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 6111 static void zext_32_to_64(struct bpf_reg_state *reg) 6112 { 6113 reg->var_off = tnum_subreg(reg->var_off); 6114 __reg_assign_32_into_64(reg); 6115 } 6116 6117 /* truncate register to smaller size (in bytes) 6118 * must be called with size < BPF_REG_SIZE 6119 */ 6120 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 6121 { 6122 u64 mask; 6123 6124 /* clear high bits in bit representation */ 6125 reg->var_off = tnum_cast(reg->var_off, size); 6126 6127 /* fix arithmetic bounds */ 6128 mask = ((u64)1 << (size * 8)) - 1; 6129 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 6130 reg->umin_value &= mask; 6131 reg->umax_value &= mask; 6132 } else { 6133 reg->umin_value = 0; 6134 reg->umax_value = mask; 6135 } 6136 reg->smin_value = reg->umin_value; 6137 reg->smax_value = reg->umax_value; 6138 6139 /* If size is smaller than 32bit register the 32bit register 6140 * values are also truncated so we push 64-bit bounds into 6141 * 32-bit bounds. Above were truncated < 32-bits already. 6142 */ 6143 if (size < 4) 6144 __mark_reg32_unbounded(reg); 6145 6146 reg_bounds_sync(reg); 6147 } 6148 6149 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 6150 { 6151 if (size == 1) { 6152 reg->smin_value = reg->s32_min_value = S8_MIN; 6153 reg->smax_value = reg->s32_max_value = S8_MAX; 6154 } else if (size == 2) { 6155 reg->smin_value = reg->s32_min_value = S16_MIN; 6156 reg->smax_value = reg->s32_max_value = S16_MAX; 6157 } else { 6158 /* size == 4 */ 6159 reg->smin_value = reg->s32_min_value = S32_MIN; 6160 reg->smax_value = reg->s32_max_value = S32_MAX; 6161 } 6162 reg->umin_value = reg->u32_min_value = 0; 6163 reg->umax_value = U64_MAX; 6164 reg->u32_max_value = U32_MAX; 6165 reg->var_off = tnum_unknown; 6166 } 6167 6168 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6169 { 6170 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6171 u64 top_smax_value, top_smin_value; 6172 u64 num_bits = size * 8; 6173 6174 if (tnum_is_const(reg->var_off)) { 6175 u64_cval = reg->var_off.value; 6176 if (size == 1) 6177 reg->var_off = tnum_const((s8)u64_cval); 6178 else if (size == 2) 6179 reg->var_off = tnum_const((s16)u64_cval); 6180 else 6181 /* size == 4 */ 6182 reg->var_off = tnum_const((s32)u64_cval); 6183 6184 u64_cval = reg->var_off.value; 6185 reg->smax_value = reg->smin_value = u64_cval; 6186 reg->umax_value = reg->umin_value = u64_cval; 6187 reg->s32_max_value = reg->s32_min_value = u64_cval; 6188 reg->u32_max_value = reg->u32_min_value = u64_cval; 6189 return; 6190 } 6191 6192 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6193 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6194 6195 if (top_smax_value != top_smin_value) 6196 goto out; 6197 6198 /* find the s64_min and s64_min after sign extension */ 6199 if (size == 1) { 6200 init_s64_max = (s8)reg->smax_value; 6201 init_s64_min = (s8)reg->smin_value; 6202 } else if (size == 2) { 6203 init_s64_max = (s16)reg->smax_value; 6204 init_s64_min = (s16)reg->smin_value; 6205 } else { 6206 init_s64_max = (s32)reg->smax_value; 6207 init_s64_min = (s32)reg->smin_value; 6208 } 6209 6210 s64_max = max(init_s64_max, init_s64_min); 6211 s64_min = min(init_s64_max, init_s64_min); 6212 6213 /* both of s64_max/s64_min positive or negative */ 6214 if ((s64_max >= 0) == (s64_min >= 0)) { 6215 reg->smin_value = reg->s32_min_value = s64_min; 6216 reg->smax_value = reg->s32_max_value = s64_max; 6217 reg->umin_value = reg->u32_min_value = s64_min; 6218 reg->umax_value = reg->u32_max_value = s64_max; 6219 reg->var_off = tnum_range(s64_min, s64_max); 6220 return; 6221 } 6222 6223 out: 6224 set_sext64_default_val(reg, size); 6225 } 6226 6227 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6228 { 6229 if (size == 1) { 6230 reg->s32_min_value = S8_MIN; 6231 reg->s32_max_value = S8_MAX; 6232 } else { 6233 /* size == 2 */ 6234 reg->s32_min_value = S16_MIN; 6235 reg->s32_max_value = S16_MAX; 6236 } 6237 reg->u32_min_value = 0; 6238 reg->u32_max_value = U32_MAX; 6239 reg->var_off = tnum_subreg(tnum_unknown); 6240 } 6241 6242 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6243 { 6244 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6245 u32 top_smax_value, top_smin_value; 6246 u32 num_bits = size * 8; 6247 6248 if (tnum_is_const(reg->var_off)) { 6249 u32_val = reg->var_off.value; 6250 if (size == 1) 6251 reg->var_off = tnum_const((s8)u32_val); 6252 else 6253 reg->var_off = tnum_const((s16)u32_val); 6254 6255 u32_val = reg->var_off.value; 6256 reg->s32_min_value = reg->s32_max_value = u32_val; 6257 reg->u32_min_value = reg->u32_max_value = u32_val; 6258 return; 6259 } 6260 6261 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 6262 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 6263 6264 if (top_smax_value != top_smin_value) 6265 goto out; 6266 6267 /* find the s32_min and s32_min after sign extension */ 6268 if (size == 1) { 6269 init_s32_max = (s8)reg->s32_max_value; 6270 init_s32_min = (s8)reg->s32_min_value; 6271 } else { 6272 /* size == 2 */ 6273 init_s32_max = (s16)reg->s32_max_value; 6274 init_s32_min = (s16)reg->s32_min_value; 6275 } 6276 s32_max = max(init_s32_max, init_s32_min); 6277 s32_min = min(init_s32_max, init_s32_min); 6278 6279 if ((s32_min >= 0) == (s32_max >= 0)) { 6280 reg->s32_min_value = s32_min; 6281 reg->s32_max_value = s32_max; 6282 reg->u32_min_value = (u32)s32_min; 6283 reg->u32_max_value = (u32)s32_max; 6284 reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max)); 6285 return; 6286 } 6287 6288 out: 6289 set_sext32_default_val(reg, size); 6290 } 6291 6292 static bool bpf_map_is_rdonly(const struct bpf_map *map) 6293 { 6294 /* A map is considered read-only if the following condition are true: 6295 * 6296 * 1) BPF program side cannot change any of the map content. The 6297 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6298 * and was set at map creation time. 6299 * 2) The map value(s) have been initialized from user space by a 6300 * loader and then "frozen", such that no new map update/delete 6301 * operations from syscall side are possible for the rest of 6302 * the map's lifetime from that point onwards. 6303 * 3) Any parallel/pending map update/delete operations from syscall 6304 * side have been completed. Only after that point, it's safe to 6305 * assume that map value(s) are immutable. 6306 */ 6307 return (map->map_flags & BPF_F_RDONLY_PROG) && 6308 READ_ONCE(map->frozen) && 6309 !bpf_map_write_active(map); 6310 } 6311 6312 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6313 bool is_ldsx) 6314 { 6315 void *ptr; 6316 u64 addr; 6317 int err; 6318 6319 err = map->ops->map_direct_value_addr(map, &addr, off); 6320 if (err) 6321 return err; 6322 ptr = (void *)(long)addr + off; 6323 6324 switch (size) { 6325 case sizeof(u8): 6326 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6327 break; 6328 case sizeof(u16): 6329 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6330 break; 6331 case sizeof(u32): 6332 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6333 break; 6334 case sizeof(u64): 6335 *val = *(u64 *)ptr; 6336 break; 6337 default: 6338 return -EINVAL; 6339 } 6340 return 0; 6341 } 6342 6343 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6344 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6345 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6346 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null) 6347 6348 /* 6349 * Allow list few fields as RCU trusted or full trusted. 6350 * This logic doesn't allow mix tagging and will be removed once GCC supports 6351 * btf_type_tag. 6352 */ 6353 6354 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6355 BTF_TYPE_SAFE_RCU(struct task_struct) { 6356 const cpumask_t *cpus_ptr; 6357 struct css_set __rcu *cgroups; 6358 struct task_struct __rcu *real_parent; 6359 struct task_struct *group_leader; 6360 }; 6361 6362 BTF_TYPE_SAFE_RCU(struct cgroup) { 6363 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6364 struct kernfs_node *kn; 6365 }; 6366 6367 BTF_TYPE_SAFE_RCU(struct css_set) { 6368 struct cgroup *dfl_cgrp; 6369 }; 6370 6371 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6372 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6373 struct file __rcu *exe_file; 6374 }; 6375 6376 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6377 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6378 */ 6379 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6380 struct sock *sk; 6381 }; 6382 6383 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6384 struct sock *sk; 6385 }; 6386 6387 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6388 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6389 struct seq_file *seq; 6390 }; 6391 6392 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6393 struct bpf_iter_meta *meta; 6394 struct task_struct *task; 6395 }; 6396 6397 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6398 struct file *file; 6399 }; 6400 6401 BTF_TYPE_SAFE_TRUSTED(struct file) { 6402 struct inode *f_inode; 6403 }; 6404 6405 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 6406 /* no negative dentry-s in places where bpf can see it */ 6407 struct inode *d_inode; 6408 }; 6409 6410 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) { 6411 struct sock *sk; 6412 }; 6413 6414 static bool type_is_rcu(struct bpf_verifier_env *env, 6415 struct bpf_reg_state *reg, 6416 const char *field_name, u32 btf_id) 6417 { 6418 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6419 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6420 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6421 6422 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6423 } 6424 6425 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6426 struct bpf_reg_state *reg, 6427 const char *field_name, u32 btf_id) 6428 { 6429 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6430 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6431 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6432 6433 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6434 } 6435 6436 static bool type_is_trusted(struct bpf_verifier_env *env, 6437 struct bpf_reg_state *reg, 6438 const char *field_name, u32 btf_id) 6439 { 6440 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 6441 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6442 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6443 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6444 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 6445 6446 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6447 } 6448 6449 static bool type_is_trusted_or_null(struct bpf_verifier_env *env, 6450 struct bpf_reg_state *reg, 6451 const char *field_name, u32 btf_id) 6452 { 6453 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)); 6454 6455 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, 6456 "__safe_trusted_or_null"); 6457 } 6458 6459 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6460 struct bpf_reg_state *regs, 6461 int regno, int off, int size, 6462 enum bpf_access_type atype, 6463 int value_regno) 6464 { 6465 struct bpf_reg_state *reg = regs + regno; 6466 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6467 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6468 const char *field_name = NULL; 6469 enum bpf_type_flag flag = 0; 6470 u32 btf_id = 0; 6471 int ret; 6472 6473 if (!env->allow_ptr_leaks) { 6474 verbose(env, 6475 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6476 tname); 6477 return -EPERM; 6478 } 6479 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6480 verbose(env, 6481 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6482 tname); 6483 return -EINVAL; 6484 } 6485 if (off < 0) { 6486 verbose(env, 6487 "R%d is ptr_%s invalid negative access: off=%d\n", 6488 regno, tname, off); 6489 return -EACCES; 6490 } 6491 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6492 char tn_buf[48]; 6493 6494 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6495 verbose(env, 6496 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6497 regno, tname, off, tn_buf); 6498 return -EACCES; 6499 } 6500 6501 if (reg->type & MEM_USER) { 6502 verbose(env, 6503 "R%d is ptr_%s access user memory: off=%d\n", 6504 regno, tname, off); 6505 return -EACCES; 6506 } 6507 6508 if (reg->type & MEM_PERCPU) { 6509 verbose(env, 6510 "R%d is ptr_%s access percpu memory: off=%d\n", 6511 regno, tname, off); 6512 return -EACCES; 6513 } 6514 6515 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6516 if (!btf_is_kernel(reg->btf)) { 6517 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 6518 return -EFAULT; 6519 } 6520 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6521 } else { 6522 /* Writes are permitted with default btf_struct_access for 6523 * program allocated objects (which always have ref_obj_id > 0), 6524 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6525 */ 6526 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6527 verbose(env, "only read is supported\n"); 6528 return -EACCES; 6529 } 6530 6531 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6532 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 6533 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 6534 return -EFAULT; 6535 } 6536 6537 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6538 } 6539 6540 if (ret < 0) 6541 return ret; 6542 6543 if (ret != PTR_TO_BTF_ID) { 6544 /* just mark; */ 6545 6546 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6547 /* If this is an untrusted pointer, all pointers formed by walking it 6548 * also inherit the untrusted flag. 6549 */ 6550 flag = PTR_UNTRUSTED; 6551 6552 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6553 /* By default any pointer obtained from walking a trusted pointer is no 6554 * longer trusted, unless the field being accessed has explicitly been 6555 * marked as inheriting its parent's state of trust (either full or RCU). 6556 * For example: 6557 * 'cgroups' pointer is untrusted if task->cgroups dereference 6558 * happened in a sleepable program outside of bpf_rcu_read_lock() 6559 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6560 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6561 * 6562 * A regular RCU-protected pointer with __rcu tag can also be deemed 6563 * trusted if we are in an RCU CS. Such pointer can be NULL. 6564 */ 6565 if (type_is_trusted(env, reg, field_name, btf_id)) { 6566 flag |= PTR_TRUSTED; 6567 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) { 6568 flag |= PTR_TRUSTED | PTR_MAYBE_NULL; 6569 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6570 if (type_is_rcu(env, reg, field_name, btf_id)) { 6571 /* ignore __rcu tag and mark it MEM_RCU */ 6572 flag |= MEM_RCU; 6573 } else if (flag & MEM_RCU || 6574 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6575 /* __rcu tagged pointers can be NULL */ 6576 flag |= MEM_RCU | PTR_MAYBE_NULL; 6577 6578 /* We always trust them */ 6579 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6580 flag & PTR_UNTRUSTED) 6581 flag &= ~PTR_UNTRUSTED; 6582 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6583 /* keep as-is */ 6584 } else { 6585 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6586 clear_trusted_flags(&flag); 6587 } 6588 } else { 6589 /* 6590 * If not in RCU CS or MEM_RCU pointer can be NULL then 6591 * aggressively mark as untrusted otherwise such 6592 * pointers will be plain PTR_TO_BTF_ID without flags 6593 * and will be allowed to be passed into helpers for 6594 * compat reasons. 6595 */ 6596 flag = PTR_UNTRUSTED; 6597 } 6598 } else { 6599 /* Old compat. Deprecated */ 6600 clear_trusted_flags(&flag); 6601 } 6602 6603 if (atype == BPF_READ && value_regno >= 0) 6604 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6605 6606 return 0; 6607 } 6608 6609 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6610 struct bpf_reg_state *regs, 6611 int regno, int off, int size, 6612 enum bpf_access_type atype, 6613 int value_regno) 6614 { 6615 struct bpf_reg_state *reg = regs + regno; 6616 struct bpf_map *map = reg->map_ptr; 6617 struct bpf_reg_state map_reg; 6618 enum bpf_type_flag flag = 0; 6619 const struct btf_type *t; 6620 const char *tname; 6621 u32 btf_id; 6622 int ret; 6623 6624 if (!btf_vmlinux) { 6625 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6626 return -ENOTSUPP; 6627 } 6628 6629 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6630 verbose(env, "map_ptr access not supported for map type %d\n", 6631 map->map_type); 6632 return -ENOTSUPP; 6633 } 6634 6635 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6636 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6637 6638 if (!env->allow_ptr_leaks) { 6639 verbose(env, 6640 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6641 tname); 6642 return -EPERM; 6643 } 6644 6645 if (off < 0) { 6646 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6647 regno, tname, off); 6648 return -EACCES; 6649 } 6650 6651 if (atype != BPF_READ) { 6652 verbose(env, "only read from %s is supported\n", tname); 6653 return -EACCES; 6654 } 6655 6656 /* Simulate access to a PTR_TO_BTF_ID */ 6657 memset(&map_reg, 0, sizeof(map_reg)); 6658 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6659 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6660 if (ret < 0) 6661 return ret; 6662 6663 if (value_regno >= 0) 6664 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6665 6666 return 0; 6667 } 6668 6669 /* Check that the stack access at the given offset is within bounds. The 6670 * maximum valid offset is -1. 6671 * 6672 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6673 * -state->allocated_stack for reads. 6674 */ 6675 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 6676 s64 off, 6677 struct bpf_func_state *state, 6678 enum bpf_access_type t) 6679 { 6680 int min_valid_off; 6681 6682 if (t == BPF_WRITE || env->allow_uninit_stack) 6683 min_valid_off = -MAX_BPF_STACK; 6684 else 6685 min_valid_off = -state->allocated_stack; 6686 6687 if (off < min_valid_off || off > -1) 6688 return -EACCES; 6689 return 0; 6690 } 6691 6692 /* Check that the stack access at 'regno + off' falls within the maximum stack 6693 * bounds. 6694 * 6695 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6696 */ 6697 static int check_stack_access_within_bounds( 6698 struct bpf_verifier_env *env, 6699 int regno, int off, int access_size, 6700 enum bpf_access_src src, enum bpf_access_type type) 6701 { 6702 struct bpf_reg_state *regs = cur_regs(env); 6703 struct bpf_reg_state *reg = regs + regno; 6704 struct bpf_func_state *state = func(env, reg); 6705 s64 min_off, max_off; 6706 int err; 6707 char *err_extra; 6708 6709 if (src == ACCESS_HELPER) 6710 /* We don't know if helpers are reading or writing (or both). */ 6711 err_extra = " indirect access to"; 6712 else if (type == BPF_READ) 6713 err_extra = " read from"; 6714 else 6715 err_extra = " write to"; 6716 6717 if (tnum_is_const(reg->var_off)) { 6718 min_off = (s64)reg->var_off.value + off; 6719 max_off = min_off + access_size; 6720 } else { 6721 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6722 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6723 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6724 err_extra, regno); 6725 return -EACCES; 6726 } 6727 min_off = reg->smin_value + off; 6728 max_off = reg->smax_value + off + access_size; 6729 } 6730 6731 err = check_stack_slot_within_bounds(env, min_off, state, type); 6732 if (!err && max_off > 0) 6733 err = -EINVAL; /* out of stack access into non-negative offsets */ 6734 if (!err && access_size < 0) 6735 /* access_size should not be negative (or overflow an int); others checks 6736 * along the way should have prevented such an access. 6737 */ 6738 err = -EFAULT; /* invalid negative access size; integer overflow? */ 6739 6740 if (err) { 6741 if (tnum_is_const(reg->var_off)) { 6742 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 6743 err_extra, regno, off, access_size); 6744 } else { 6745 char tn_buf[48]; 6746 6747 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6748 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n", 6749 err_extra, regno, tn_buf, off, access_size); 6750 } 6751 return err; 6752 } 6753 6754 /* Note that there is no stack access with offset zero, so the needed stack 6755 * size is -min_off, not -min_off+1. 6756 */ 6757 return grow_stack_state(env, state, -min_off /* size */); 6758 } 6759 6760 /* check whether memory at (regno + off) is accessible for t = (read | write) 6761 * if t==write, value_regno is a register which value is stored into memory 6762 * if t==read, value_regno is a register which will receive the value from memory 6763 * if t==write && value_regno==-1, some unknown value is stored into memory 6764 * if t==read && value_regno==-1, don't care what we read from memory 6765 */ 6766 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6767 int off, int bpf_size, enum bpf_access_type t, 6768 int value_regno, bool strict_alignment_once, bool is_ldsx) 6769 { 6770 struct bpf_reg_state *regs = cur_regs(env); 6771 struct bpf_reg_state *reg = regs + regno; 6772 int size, err = 0; 6773 6774 size = bpf_size_to_bytes(bpf_size); 6775 if (size < 0) 6776 return size; 6777 6778 /* alignment checks will add in reg->off themselves */ 6779 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6780 if (err) 6781 return err; 6782 6783 /* for access checks, reg->off is just part of off */ 6784 off += reg->off; 6785 6786 if (reg->type == PTR_TO_MAP_KEY) { 6787 if (t == BPF_WRITE) { 6788 verbose(env, "write to change key R%d not allowed\n", regno); 6789 return -EACCES; 6790 } 6791 6792 err = check_mem_region_access(env, regno, off, size, 6793 reg->map_ptr->key_size, false); 6794 if (err) 6795 return err; 6796 if (value_regno >= 0) 6797 mark_reg_unknown(env, regs, value_regno); 6798 } else if (reg->type == PTR_TO_MAP_VALUE) { 6799 struct btf_field *kptr_field = NULL; 6800 6801 if (t == BPF_WRITE && value_regno >= 0 && 6802 is_pointer_value(env, value_regno)) { 6803 verbose(env, "R%d leaks addr into map\n", value_regno); 6804 return -EACCES; 6805 } 6806 err = check_map_access_type(env, regno, off, size, t); 6807 if (err) 6808 return err; 6809 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6810 if (err) 6811 return err; 6812 if (tnum_is_const(reg->var_off)) 6813 kptr_field = btf_record_find(reg->map_ptr->record, 6814 off + reg->var_off.value, BPF_KPTR); 6815 if (kptr_field) { 6816 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6817 } else if (t == BPF_READ && value_regno >= 0) { 6818 struct bpf_map *map = reg->map_ptr; 6819 6820 /* if map is read-only, track its contents as scalars */ 6821 if (tnum_is_const(reg->var_off) && 6822 bpf_map_is_rdonly(map) && 6823 map->ops->map_direct_value_addr) { 6824 int map_off = off + reg->var_off.value; 6825 u64 val = 0; 6826 6827 err = bpf_map_direct_read(map, map_off, size, 6828 &val, is_ldsx); 6829 if (err) 6830 return err; 6831 6832 regs[value_regno].type = SCALAR_VALUE; 6833 __mark_reg_known(®s[value_regno], val); 6834 } else { 6835 mark_reg_unknown(env, regs, value_regno); 6836 } 6837 } 6838 } else if (base_type(reg->type) == PTR_TO_MEM) { 6839 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6840 6841 if (type_may_be_null(reg->type)) { 6842 verbose(env, "R%d invalid mem access '%s'\n", regno, 6843 reg_type_str(env, reg->type)); 6844 return -EACCES; 6845 } 6846 6847 if (t == BPF_WRITE && rdonly_mem) { 6848 verbose(env, "R%d cannot write into %s\n", 6849 regno, reg_type_str(env, reg->type)); 6850 return -EACCES; 6851 } 6852 6853 if (t == BPF_WRITE && value_regno >= 0 && 6854 is_pointer_value(env, value_regno)) { 6855 verbose(env, "R%d leaks addr into mem\n", value_regno); 6856 return -EACCES; 6857 } 6858 6859 err = check_mem_region_access(env, regno, off, size, 6860 reg->mem_size, false); 6861 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6862 mark_reg_unknown(env, regs, value_regno); 6863 } else if (reg->type == PTR_TO_CTX) { 6864 enum bpf_reg_type reg_type = SCALAR_VALUE; 6865 struct btf *btf = NULL; 6866 u32 btf_id = 0; 6867 6868 if (t == BPF_WRITE && value_regno >= 0 && 6869 is_pointer_value(env, value_regno)) { 6870 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6871 return -EACCES; 6872 } 6873 6874 err = check_ptr_off_reg(env, reg, regno); 6875 if (err < 0) 6876 return err; 6877 6878 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 6879 &btf_id); 6880 if (err) 6881 verbose_linfo(env, insn_idx, "; "); 6882 if (!err && t == BPF_READ && value_regno >= 0) { 6883 /* ctx access returns either a scalar, or a 6884 * PTR_TO_PACKET[_META,_END]. In the latter 6885 * case, we know the offset is zero. 6886 */ 6887 if (reg_type == SCALAR_VALUE) { 6888 mark_reg_unknown(env, regs, value_regno); 6889 } else { 6890 mark_reg_known_zero(env, regs, 6891 value_regno); 6892 if (type_may_be_null(reg_type)) 6893 regs[value_regno].id = ++env->id_gen; 6894 /* A load of ctx field could have different 6895 * actual load size with the one encoded in the 6896 * insn. When the dst is PTR, it is for sure not 6897 * a sub-register. 6898 */ 6899 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6900 if (base_type(reg_type) == PTR_TO_BTF_ID) { 6901 regs[value_regno].btf = btf; 6902 regs[value_regno].btf_id = btf_id; 6903 } 6904 } 6905 regs[value_regno].type = reg_type; 6906 } 6907 6908 } else if (reg->type == PTR_TO_STACK) { 6909 /* Basic bounds checks. */ 6910 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 6911 if (err) 6912 return err; 6913 6914 if (t == BPF_READ) 6915 err = check_stack_read(env, regno, off, size, 6916 value_regno); 6917 else 6918 err = check_stack_write(env, regno, off, size, 6919 value_regno, insn_idx); 6920 } else if (reg_is_pkt_pointer(reg)) { 6921 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6922 verbose(env, "cannot write into packet\n"); 6923 return -EACCES; 6924 } 6925 if (t == BPF_WRITE && value_regno >= 0 && 6926 is_pointer_value(env, value_regno)) { 6927 verbose(env, "R%d leaks addr into packet\n", 6928 value_regno); 6929 return -EACCES; 6930 } 6931 err = check_packet_access(env, regno, off, size, false); 6932 if (!err && t == BPF_READ && value_regno >= 0) 6933 mark_reg_unknown(env, regs, value_regno); 6934 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6935 if (t == BPF_WRITE && value_regno >= 0 && 6936 is_pointer_value(env, value_regno)) { 6937 verbose(env, "R%d leaks addr into flow keys\n", 6938 value_regno); 6939 return -EACCES; 6940 } 6941 6942 err = check_flow_keys_access(env, off, size); 6943 if (!err && t == BPF_READ && value_regno >= 0) 6944 mark_reg_unknown(env, regs, value_regno); 6945 } else if (type_is_sk_pointer(reg->type)) { 6946 if (t == BPF_WRITE) { 6947 verbose(env, "R%d cannot write into %s\n", 6948 regno, reg_type_str(env, reg->type)); 6949 return -EACCES; 6950 } 6951 err = check_sock_access(env, insn_idx, regno, off, size, t); 6952 if (!err && value_regno >= 0) 6953 mark_reg_unknown(env, regs, value_regno); 6954 } else if (reg->type == PTR_TO_TP_BUFFER) { 6955 err = check_tp_buffer_access(env, reg, regno, off, size); 6956 if (!err && t == BPF_READ && value_regno >= 0) 6957 mark_reg_unknown(env, regs, value_regno); 6958 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6959 !type_may_be_null(reg->type)) { 6960 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 6961 value_regno); 6962 } else if (reg->type == CONST_PTR_TO_MAP) { 6963 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 6964 value_regno); 6965 } else if (base_type(reg->type) == PTR_TO_BUF) { 6966 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6967 u32 *max_access; 6968 6969 if (rdonly_mem) { 6970 if (t == BPF_WRITE) { 6971 verbose(env, "R%d cannot write into %s\n", 6972 regno, reg_type_str(env, reg->type)); 6973 return -EACCES; 6974 } 6975 max_access = &env->prog->aux->max_rdonly_access; 6976 } else { 6977 max_access = &env->prog->aux->max_rdwr_access; 6978 } 6979 6980 err = check_buffer_access(env, reg, regno, off, size, false, 6981 max_access); 6982 6983 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6984 mark_reg_unknown(env, regs, value_regno); 6985 } else if (reg->type == PTR_TO_ARENA) { 6986 if (t == BPF_READ && value_regno >= 0) 6987 mark_reg_unknown(env, regs, value_regno); 6988 } else { 6989 verbose(env, "R%d invalid mem access '%s'\n", regno, 6990 reg_type_str(env, reg->type)); 6991 return -EACCES; 6992 } 6993 6994 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6995 regs[value_regno].type == SCALAR_VALUE) { 6996 if (!is_ldsx) 6997 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6998 coerce_reg_to_size(®s[value_regno], size); 6999 else 7000 coerce_reg_to_size_sx(®s[value_regno], size); 7001 } 7002 return err; 7003 } 7004 7005 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 7006 bool allow_trust_mismatch); 7007 7008 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 7009 { 7010 int load_reg; 7011 int err; 7012 7013 switch (insn->imm) { 7014 case BPF_ADD: 7015 case BPF_ADD | BPF_FETCH: 7016 case BPF_AND: 7017 case BPF_AND | BPF_FETCH: 7018 case BPF_OR: 7019 case BPF_OR | BPF_FETCH: 7020 case BPF_XOR: 7021 case BPF_XOR | BPF_FETCH: 7022 case BPF_XCHG: 7023 case BPF_CMPXCHG: 7024 break; 7025 default: 7026 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 7027 return -EINVAL; 7028 } 7029 7030 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 7031 verbose(env, "invalid atomic operand size\n"); 7032 return -EINVAL; 7033 } 7034 7035 /* check src1 operand */ 7036 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7037 if (err) 7038 return err; 7039 7040 /* check src2 operand */ 7041 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 7042 if (err) 7043 return err; 7044 7045 if (insn->imm == BPF_CMPXCHG) { 7046 /* Check comparison of R0 with memory location */ 7047 const u32 aux_reg = BPF_REG_0; 7048 7049 err = check_reg_arg(env, aux_reg, SRC_OP); 7050 if (err) 7051 return err; 7052 7053 if (is_pointer_value(env, aux_reg)) { 7054 verbose(env, "R%d leaks addr into mem\n", aux_reg); 7055 return -EACCES; 7056 } 7057 } 7058 7059 if (is_pointer_value(env, insn->src_reg)) { 7060 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 7061 return -EACCES; 7062 } 7063 7064 if (is_ctx_reg(env, insn->dst_reg) || 7065 is_pkt_reg(env, insn->dst_reg) || 7066 is_flow_key_reg(env, insn->dst_reg) || 7067 is_sk_reg(env, insn->dst_reg) || 7068 (is_arena_reg(env, insn->dst_reg) && !bpf_jit_supports_insn(insn, true))) { 7069 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 7070 insn->dst_reg, 7071 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 7072 return -EACCES; 7073 } 7074 7075 if (insn->imm & BPF_FETCH) { 7076 if (insn->imm == BPF_CMPXCHG) 7077 load_reg = BPF_REG_0; 7078 else 7079 load_reg = insn->src_reg; 7080 7081 /* check and record load of old value */ 7082 err = check_reg_arg(env, load_reg, DST_OP); 7083 if (err) 7084 return err; 7085 } else { 7086 /* This instruction accesses a memory location but doesn't 7087 * actually load it into a register. 7088 */ 7089 load_reg = -1; 7090 } 7091 7092 /* Check whether we can read the memory, with second call for fetch 7093 * case to simulate the register fill. 7094 */ 7095 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7096 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 7097 if (!err && load_reg >= 0) 7098 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7099 BPF_SIZE(insn->code), BPF_READ, load_reg, 7100 true, false); 7101 if (err) 7102 return err; 7103 7104 if (is_arena_reg(env, insn->dst_reg)) { 7105 err = save_aux_ptr_type(env, PTR_TO_ARENA, false); 7106 if (err) 7107 return err; 7108 } 7109 /* Check whether we can write into the same memory. */ 7110 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7111 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 7112 if (err) 7113 return err; 7114 return 0; 7115 } 7116 7117 /* When register 'regno' is used to read the stack (either directly or through 7118 * a helper function) make sure that it's within stack boundary and, depending 7119 * on the access type and privileges, that all elements of the stack are 7120 * initialized. 7121 * 7122 * 'off' includes 'regno->off', but not its dynamic part (if any). 7123 * 7124 * All registers that have been spilled on the stack in the slots within the 7125 * read offsets are marked as read. 7126 */ 7127 static int check_stack_range_initialized( 7128 struct bpf_verifier_env *env, int regno, int off, 7129 int access_size, bool zero_size_allowed, 7130 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 7131 { 7132 struct bpf_reg_state *reg = reg_state(env, regno); 7133 struct bpf_func_state *state = func(env, reg); 7134 int err, min_off, max_off, i, j, slot, spi; 7135 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 7136 enum bpf_access_type bounds_check_type; 7137 /* Some accesses can write anything into the stack, others are 7138 * read-only. 7139 */ 7140 bool clobber = false; 7141 7142 if (access_size == 0 && !zero_size_allowed) { 7143 verbose(env, "invalid zero-sized read\n"); 7144 return -EACCES; 7145 } 7146 7147 if (type == ACCESS_HELPER) { 7148 /* The bounds checks for writes are more permissive than for 7149 * reads. However, if raw_mode is not set, we'll do extra 7150 * checks below. 7151 */ 7152 bounds_check_type = BPF_WRITE; 7153 clobber = true; 7154 } else { 7155 bounds_check_type = BPF_READ; 7156 } 7157 err = check_stack_access_within_bounds(env, regno, off, access_size, 7158 type, bounds_check_type); 7159 if (err) 7160 return err; 7161 7162 7163 if (tnum_is_const(reg->var_off)) { 7164 min_off = max_off = reg->var_off.value + off; 7165 } else { 7166 /* Variable offset is prohibited for unprivileged mode for 7167 * simplicity since it requires corresponding support in 7168 * Spectre masking for stack ALU. 7169 * See also retrieve_ptr_limit(). 7170 */ 7171 if (!env->bypass_spec_v1) { 7172 char tn_buf[48]; 7173 7174 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7175 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 7176 regno, err_extra, tn_buf); 7177 return -EACCES; 7178 } 7179 /* Only initialized buffer on stack is allowed to be accessed 7180 * with variable offset. With uninitialized buffer it's hard to 7181 * guarantee that whole memory is marked as initialized on 7182 * helper return since specific bounds are unknown what may 7183 * cause uninitialized stack leaking. 7184 */ 7185 if (meta && meta->raw_mode) 7186 meta = NULL; 7187 7188 min_off = reg->smin_value + off; 7189 max_off = reg->smax_value + off; 7190 } 7191 7192 if (meta && meta->raw_mode) { 7193 /* Ensure we won't be overwriting dynptrs when simulating byte 7194 * by byte access in check_helper_call using meta.access_size. 7195 * This would be a problem if we have a helper in the future 7196 * which takes: 7197 * 7198 * helper(uninit_mem, len, dynptr) 7199 * 7200 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 7201 * may end up writing to dynptr itself when touching memory from 7202 * arg 1. This can be relaxed on a case by case basis for known 7203 * safe cases, but reject due to the possibilitiy of aliasing by 7204 * default. 7205 */ 7206 for (i = min_off; i < max_off + access_size; i++) { 7207 int stack_off = -i - 1; 7208 7209 spi = __get_spi(i); 7210 /* raw_mode may write past allocated_stack */ 7211 if (state->allocated_stack <= stack_off) 7212 continue; 7213 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 7214 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 7215 return -EACCES; 7216 } 7217 } 7218 meta->access_size = access_size; 7219 meta->regno = regno; 7220 return 0; 7221 } 7222 7223 for (i = min_off; i < max_off + access_size; i++) { 7224 u8 *stype; 7225 7226 slot = -i - 1; 7227 spi = slot / BPF_REG_SIZE; 7228 if (state->allocated_stack <= slot) { 7229 verbose(env, "verifier bug: allocated_stack too small"); 7230 return -EFAULT; 7231 } 7232 7233 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 7234 if (*stype == STACK_MISC) 7235 goto mark; 7236 if ((*stype == STACK_ZERO) || 7237 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 7238 if (clobber) { 7239 /* helper can write anything into the stack */ 7240 *stype = STACK_MISC; 7241 } 7242 goto mark; 7243 } 7244 7245 if (is_spilled_reg(&state->stack[spi]) && 7246 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 7247 env->allow_ptr_leaks)) { 7248 if (clobber) { 7249 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 7250 for (j = 0; j < BPF_REG_SIZE; j++) 7251 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 7252 } 7253 goto mark; 7254 } 7255 7256 if (tnum_is_const(reg->var_off)) { 7257 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 7258 err_extra, regno, min_off, i - min_off, access_size); 7259 } else { 7260 char tn_buf[48]; 7261 7262 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7263 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 7264 err_extra, regno, tn_buf, i - min_off, access_size); 7265 } 7266 return -EACCES; 7267 mark: 7268 /* reading any byte out of 8-byte 'spill_slot' will cause 7269 * the whole slot to be marked as 'read' 7270 */ 7271 mark_reg_read(env, &state->stack[spi].spilled_ptr, 7272 state->stack[spi].spilled_ptr.parent, 7273 REG_LIVE_READ64); 7274 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 7275 * be sure that whether stack slot is written to or not. Hence, 7276 * we must still conservatively propagate reads upwards even if 7277 * helper may write to the entire memory range. 7278 */ 7279 } 7280 return 0; 7281 } 7282 7283 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 7284 int access_size, bool zero_size_allowed, 7285 struct bpf_call_arg_meta *meta) 7286 { 7287 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7288 u32 *max_access; 7289 7290 switch (base_type(reg->type)) { 7291 case PTR_TO_PACKET: 7292 case PTR_TO_PACKET_META: 7293 return check_packet_access(env, regno, reg->off, access_size, 7294 zero_size_allowed); 7295 case PTR_TO_MAP_KEY: 7296 if (meta && meta->raw_mode) { 7297 verbose(env, "R%d cannot write into %s\n", regno, 7298 reg_type_str(env, reg->type)); 7299 return -EACCES; 7300 } 7301 return check_mem_region_access(env, regno, reg->off, access_size, 7302 reg->map_ptr->key_size, false); 7303 case PTR_TO_MAP_VALUE: 7304 if (check_map_access_type(env, regno, reg->off, access_size, 7305 meta && meta->raw_mode ? BPF_WRITE : 7306 BPF_READ)) 7307 return -EACCES; 7308 return check_map_access(env, regno, reg->off, access_size, 7309 zero_size_allowed, ACCESS_HELPER); 7310 case PTR_TO_MEM: 7311 if (type_is_rdonly_mem(reg->type)) { 7312 if (meta && meta->raw_mode) { 7313 verbose(env, "R%d cannot write into %s\n", regno, 7314 reg_type_str(env, reg->type)); 7315 return -EACCES; 7316 } 7317 } 7318 return check_mem_region_access(env, regno, reg->off, 7319 access_size, reg->mem_size, 7320 zero_size_allowed); 7321 case PTR_TO_BUF: 7322 if (type_is_rdonly_mem(reg->type)) { 7323 if (meta && meta->raw_mode) { 7324 verbose(env, "R%d cannot write into %s\n", regno, 7325 reg_type_str(env, reg->type)); 7326 return -EACCES; 7327 } 7328 7329 max_access = &env->prog->aux->max_rdonly_access; 7330 } else { 7331 max_access = &env->prog->aux->max_rdwr_access; 7332 } 7333 return check_buffer_access(env, reg, regno, reg->off, 7334 access_size, zero_size_allowed, 7335 max_access); 7336 case PTR_TO_STACK: 7337 return check_stack_range_initialized( 7338 env, 7339 regno, reg->off, access_size, 7340 zero_size_allowed, ACCESS_HELPER, meta); 7341 case PTR_TO_BTF_ID: 7342 return check_ptr_to_btf_access(env, regs, regno, reg->off, 7343 access_size, BPF_READ, -1); 7344 case PTR_TO_CTX: 7345 /* in case the function doesn't know how to access the context, 7346 * (because we are in a program of type SYSCALL for example), we 7347 * can not statically check its size. 7348 * Dynamically check it now. 7349 */ 7350 if (!env->ops->convert_ctx_access) { 7351 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 7352 int offset = access_size - 1; 7353 7354 /* Allow zero-byte read from PTR_TO_CTX */ 7355 if (access_size == 0) 7356 return zero_size_allowed ? 0 : -EACCES; 7357 7358 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 7359 atype, -1, false, false); 7360 } 7361 7362 fallthrough; 7363 default: /* scalar_value or invalid ptr */ 7364 /* Allow zero-byte read from NULL, regardless of pointer type */ 7365 if (zero_size_allowed && access_size == 0 && 7366 register_is_null(reg)) 7367 return 0; 7368 7369 verbose(env, "R%d type=%s ", regno, 7370 reg_type_str(env, reg->type)); 7371 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7372 return -EACCES; 7373 } 7374 } 7375 7376 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 7377 * size. 7378 * 7379 * @regno is the register containing the access size. regno-1 is the register 7380 * containing the pointer. 7381 */ 7382 static int check_mem_size_reg(struct bpf_verifier_env *env, 7383 struct bpf_reg_state *reg, u32 regno, 7384 bool zero_size_allowed, 7385 struct bpf_call_arg_meta *meta) 7386 { 7387 int err; 7388 7389 /* This is used to refine r0 return value bounds for helpers 7390 * that enforce this value as an upper bound on return values. 7391 * See do_refine_retval_range() for helpers that can refine 7392 * the return value. C type of helper is u32 so we pull register 7393 * bound from umax_value however, if negative verifier errors 7394 * out. Only upper bounds can be learned because retval is an 7395 * int type and negative retvals are allowed. 7396 */ 7397 meta->msize_max_value = reg->umax_value; 7398 7399 /* The register is SCALAR_VALUE; the access check 7400 * happens using its boundaries. 7401 */ 7402 if (!tnum_is_const(reg->var_off)) 7403 /* For unprivileged variable accesses, disable raw 7404 * mode so that the program is required to 7405 * initialize all the memory that the helper could 7406 * just partially fill up. 7407 */ 7408 meta = NULL; 7409 7410 if (reg->smin_value < 0) { 7411 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7412 regno); 7413 return -EACCES; 7414 } 7415 7416 if (reg->umin_value == 0 && !zero_size_allowed) { 7417 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n", 7418 regno, reg->umin_value, reg->umax_value); 7419 return -EACCES; 7420 } 7421 7422 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7423 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7424 regno); 7425 return -EACCES; 7426 } 7427 err = check_helper_mem_access(env, regno - 1, 7428 reg->umax_value, 7429 zero_size_allowed, meta); 7430 if (!err) 7431 err = mark_chain_precision(env, regno); 7432 return err; 7433 } 7434 7435 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7436 u32 regno, u32 mem_size) 7437 { 7438 bool may_be_null = type_may_be_null(reg->type); 7439 struct bpf_reg_state saved_reg; 7440 struct bpf_call_arg_meta meta; 7441 int err; 7442 7443 if (register_is_null(reg)) 7444 return 0; 7445 7446 memset(&meta, 0, sizeof(meta)); 7447 /* Assuming that the register contains a value check if the memory 7448 * access is safe. Temporarily save and restore the register's state as 7449 * the conversion shouldn't be visible to a caller. 7450 */ 7451 if (may_be_null) { 7452 saved_reg = *reg; 7453 mark_ptr_not_null_reg(reg); 7454 } 7455 7456 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 7457 /* Check access for BPF_WRITE */ 7458 meta.raw_mode = true; 7459 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 7460 7461 if (may_be_null) 7462 *reg = saved_reg; 7463 7464 return err; 7465 } 7466 7467 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7468 u32 regno) 7469 { 7470 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7471 bool may_be_null = type_may_be_null(mem_reg->type); 7472 struct bpf_reg_state saved_reg; 7473 struct bpf_call_arg_meta meta; 7474 int err; 7475 7476 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7477 7478 memset(&meta, 0, sizeof(meta)); 7479 7480 if (may_be_null) { 7481 saved_reg = *mem_reg; 7482 mark_ptr_not_null_reg(mem_reg); 7483 } 7484 7485 err = check_mem_size_reg(env, reg, regno, true, &meta); 7486 /* Check access for BPF_WRITE */ 7487 meta.raw_mode = true; 7488 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 7489 7490 if (may_be_null) 7491 *mem_reg = saved_reg; 7492 return err; 7493 } 7494 7495 /* Implementation details: 7496 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7497 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7498 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7499 * Two separate bpf_obj_new will also have different reg->id. 7500 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7501 * clears reg->id after value_or_null->value transition, since the verifier only 7502 * cares about the range of access to valid map value pointer and doesn't care 7503 * about actual address of the map element. 7504 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7505 * reg->id > 0 after value_or_null->value transition. By doing so 7506 * two bpf_map_lookups will be considered two different pointers that 7507 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7508 * returned from bpf_obj_new. 7509 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7510 * dead-locks. 7511 * Since only one bpf_spin_lock is allowed the checks are simpler than 7512 * reg_is_refcounted() logic. The verifier needs to remember only 7513 * one spin_lock instead of array of acquired_refs. 7514 * cur_state->active_lock remembers which map value element or allocated 7515 * object got locked and clears it after bpf_spin_unlock. 7516 */ 7517 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 7518 bool is_lock) 7519 { 7520 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7521 struct bpf_verifier_state *cur = env->cur_state; 7522 bool is_const = tnum_is_const(reg->var_off); 7523 u64 val = reg->var_off.value; 7524 struct bpf_map *map = NULL; 7525 struct btf *btf = NULL; 7526 struct btf_record *rec; 7527 7528 if (!is_const) { 7529 verbose(env, 7530 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 7531 regno); 7532 return -EINVAL; 7533 } 7534 if (reg->type == PTR_TO_MAP_VALUE) { 7535 map = reg->map_ptr; 7536 if (!map->btf) { 7537 verbose(env, 7538 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 7539 map->name); 7540 return -EINVAL; 7541 } 7542 } else { 7543 btf = reg->btf; 7544 } 7545 7546 rec = reg_btf_record(reg); 7547 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 7548 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 7549 map ? map->name : "kptr"); 7550 return -EINVAL; 7551 } 7552 if (rec->spin_lock_off != val + reg->off) { 7553 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 7554 val + reg->off, rec->spin_lock_off); 7555 return -EINVAL; 7556 } 7557 if (is_lock) { 7558 if (cur->active_lock.ptr) { 7559 verbose(env, 7560 "Locking two bpf_spin_locks are not allowed\n"); 7561 return -EINVAL; 7562 } 7563 if (map) 7564 cur->active_lock.ptr = map; 7565 else 7566 cur->active_lock.ptr = btf; 7567 cur->active_lock.id = reg->id; 7568 } else { 7569 void *ptr; 7570 7571 if (map) 7572 ptr = map; 7573 else 7574 ptr = btf; 7575 7576 if (!cur->active_lock.ptr) { 7577 verbose(env, "bpf_spin_unlock without taking a lock\n"); 7578 return -EINVAL; 7579 } 7580 if (cur->active_lock.ptr != ptr || 7581 cur->active_lock.id != reg->id) { 7582 verbose(env, "bpf_spin_unlock of different lock\n"); 7583 return -EINVAL; 7584 } 7585 7586 invalidate_non_owning_refs(env); 7587 7588 cur->active_lock.ptr = NULL; 7589 cur->active_lock.id = 0; 7590 } 7591 return 0; 7592 } 7593 7594 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7595 struct bpf_call_arg_meta *meta) 7596 { 7597 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7598 bool is_const = tnum_is_const(reg->var_off); 7599 struct bpf_map *map = reg->map_ptr; 7600 u64 val = reg->var_off.value; 7601 7602 if (!is_const) { 7603 verbose(env, 7604 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 7605 regno); 7606 return -EINVAL; 7607 } 7608 if (!map->btf) { 7609 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 7610 map->name); 7611 return -EINVAL; 7612 } 7613 if (!btf_record_has_field(map->record, BPF_TIMER)) { 7614 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 7615 return -EINVAL; 7616 } 7617 if (map->record->timer_off != val + reg->off) { 7618 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 7619 val + reg->off, map->record->timer_off); 7620 return -EINVAL; 7621 } 7622 if (meta->map_ptr) { 7623 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 7624 return -EFAULT; 7625 } 7626 meta->map_uid = reg->map_uid; 7627 meta->map_ptr = map; 7628 return 0; 7629 } 7630 7631 static int process_wq_func(struct bpf_verifier_env *env, int regno, 7632 struct bpf_kfunc_call_arg_meta *meta) 7633 { 7634 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7635 struct bpf_map *map = reg->map_ptr; 7636 u64 val = reg->var_off.value; 7637 7638 if (map->record->wq_off != val + reg->off) { 7639 verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n", 7640 val + reg->off, map->record->wq_off); 7641 return -EINVAL; 7642 } 7643 meta->map.uid = reg->map_uid; 7644 meta->map.ptr = map; 7645 return 0; 7646 } 7647 7648 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7649 struct bpf_call_arg_meta *meta) 7650 { 7651 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7652 struct bpf_map *map_ptr = reg->map_ptr; 7653 struct btf_field *kptr_field; 7654 u32 kptr_off; 7655 7656 if (!tnum_is_const(reg->var_off)) { 7657 verbose(env, 7658 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7659 regno); 7660 return -EINVAL; 7661 } 7662 if (!map_ptr->btf) { 7663 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7664 map_ptr->name); 7665 return -EINVAL; 7666 } 7667 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 7668 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 7669 return -EINVAL; 7670 } 7671 7672 meta->map_ptr = map_ptr; 7673 kptr_off = reg->off + reg->var_off.value; 7674 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 7675 if (!kptr_field) { 7676 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7677 return -EACCES; 7678 } 7679 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7680 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7681 return -EACCES; 7682 } 7683 meta->kptr_field = kptr_field; 7684 return 0; 7685 } 7686 7687 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7688 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7689 * 7690 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7691 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7692 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7693 * 7694 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7695 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7696 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7697 * mutate the view of the dynptr and also possibly destroy it. In the latter 7698 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7699 * memory that dynptr points to. 7700 * 7701 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7702 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7703 * readonly dynptr view yet, hence only the first case is tracked and checked. 7704 * 7705 * This is consistent with how C applies the const modifier to a struct object, 7706 * where the pointer itself inside bpf_dynptr becomes const but not what it 7707 * points to. 7708 * 7709 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7710 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7711 */ 7712 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7713 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7714 { 7715 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7716 int err; 7717 7718 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7719 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7720 */ 7721 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7722 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 7723 return -EFAULT; 7724 } 7725 7726 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7727 * constructing a mutable bpf_dynptr object. 7728 * 7729 * Currently, this is only possible with PTR_TO_STACK 7730 * pointing to a region of at least 16 bytes which doesn't 7731 * contain an existing bpf_dynptr. 7732 * 7733 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7734 * mutated or destroyed. However, the memory it points to 7735 * may be mutated. 7736 * 7737 * None - Points to a initialized dynptr that can be mutated and 7738 * destroyed, including mutation of the memory it points 7739 * to. 7740 */ 7741 if (arg_type & MEM_UNINIT) { 7742 int i; 7743 7744 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7745 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7746 return -EINVAL; 7747 } 7748 7749 /* we write BPF_DW bits (8 bytes) at a time */ 7750 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7751 err = check_mem_access(env, insn_idx, regno, 7752 i, BPF_DW, BPF_WRITE, -1, false, false); 7753 if (err) 7754 return err; 7755 } 7756 7757 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7758 } else /* MEM_RDONLY and None case from above */ { 7759 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7760 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7761 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7762 return -EINVAL; 7763 } 7764 7765 if (!is_dynptr_reg_valid_init(env, reg)) { 7766 verbose(env, 7767 "Expected an initialized dynptr as arg #%d\n", 7768 regno); 7769 return -EINVAL; 7770 } 7771 7772 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7773 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7774 verbose(env, 7775 "Expected a dynptr of type %s as arg #%d\n", 7776 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 7777 return -EINVAL; 7778 } 7779 7780 err = mark_dynptr_read(env, reg); 7781 } 7782 return err; 7783 } 7784 7785 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7786 { 7787 struct bpf_func_state *state = func(env, reg); 7788 7789 return state->stack[spi].spilled_ptr.ref_obj_id; 7790 } 7791 7792 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7793 { 7794 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7795 } 7796 7797 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7798 { 7799 return meta->kfunc_flags & KF_ITER_NEW; 7800 } 7801 7802 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7803 { 7804 return meta->kfunc_flags & KF_ITER_NEXT; 7805 } 7806 7807 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7808 { 7809 return meta->kfunc_flags & KF_ITER_DESTROY; 7810 } 7811 7812 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg) 7813 { 7814 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7815 * kfunc is iter state pointer 7816 */ 7817 return arg == 0 && is_iter_kfunc(meta); 7818 } 7819 7820 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7821 struct bpf_kfunc_call_arg_meta *meta) 7822 { 7823 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7824 const struct btf_type *t; 7825 const struct btf_param *arg; 7826 int spi, err, i, nr_slots; 7827 u32 btf_id; 7828 7829 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */ 7830 arg = &btf_params(meta->func_proto)[0]; 7831 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */ 7832 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */ 7833 nr_slots = t->size / BPF_REG_SIZE; 7834 7835 if (is_iter_new_kfunc(meta)) { 7836 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7837 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7838 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 7839 iter_type_str(meta->btf, btf_id), regno); 7840 return -EINVAL; 7841 } 7842 7843 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7844 err = check_mem_access(env, insn_idx, regno, 7845 i, BPF_DW, BPF_WRITE, -1, false, false); 7846 if (err) 7847 return err; 7848 } 7849 7850 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 7851 if (err) 7852 return err; 7853 } else { 7854 /* iter_next() or iter_destroy() expect initialized iter state*/ 7855 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 7856 switch (err) { 7857 case 0: 7858 break; 7859 case -EINVAL: 7860 verbose(env, "expected an initialized iter_%s as arg #%d\n", 7861 iter_type_str(meta->btf, btf_id), regno); 7862 return err; 7863 case -EPROTO: 7864 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 7865 return err; 7866 default: 7867 return err; 7868 } 7869 7870 spi = iter_get_spi(env, reg, nr_slots); 7871 if (spi < 0) 7872 return spi; 7873 7874 err = mark_iter_read(env, reg, spi, nr_slots); 7875 if (err) 7876 return err; 7877 7878 /* remember meta->iter info for process_iter_next_call() */ 7879 meta->iter.spi = spi; 7880 meta->iter.frameno = reg->frameno; 7881 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 7882 7883 if (is_iter_destroy_kfunc(meta)) { 7884 err = unmark_stack_slots_iter(env, reg, nr_slots); 7885 if (err) 7886 return err; 7887 } 7888 } 7889 7890 return 0; 7891 } 7892 7893 /* Look for a previous loop entry at insn_idx: nearest parent state 7894 * stopped at insn_idx with callsites matching those in cur->frame. 7895 */ 7896 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 7897 struct bpf_verifier_state *cur, 7898 int insn_idx) 7899 { 7900 struct bpf_verifier_state_list *sl; 7901 struct bpf_verifier_state *st; 7902 7903 /* Explored states are pushed in stack order, most recent states come first */ 7904 sl = *explored_state(env, insn_idx); 7905 for (; sl; sl = sl->next) { 7906 /* If st->branches != 0 state is a part of current DFS verification path, 7907 * hence cur & st for a loop. 7908 */ 7909 st = &sl->state; 7910 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 7911 st->dfs_depth < cur->dfs_depth) 7912 return st; 7913 } 7914 7915 return NULL; 7916 } 7917 7918 static void reset_idmap_scratch(struct bpf_verifier_env *env); 7919 static bool regs_exact(const struct bpf_reg_state *rold, 7920 const struct bpf_reg_state *rcur, 7921 struct bpf_idmap *idmap); 7922 7923 static void maybe_widen_reg(struct bpf_verifier_env *env, 7924 struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 7925 struct bpf_idmap *idmap) 7926 { 7927 if (rold->type != SCALAR_VALUE) 7928 return; 7929 if (rold->type != rcur->type) 7930 return; 7931 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap)) 7932 return; 7933 __mark_reg_unknown(env, rcur); 7934 } 7935 7936 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 7937 struct bpf_verifier_state *old, 7938 struct bpf_verifier_state *cur) 7939 { 7940 struct bpf_func_state *fold, *fcur; 7941 int i, fr; 7942 7943 reset_idmap_scratch(env); 7944 for (fr = old->curframe; fr >= 0; fr--) { 7945 fold = old->frame[fr]; 7946 fcur = cur->frame[fr]; 7947 7948 for (i = 0; i < MAX_BPF_REG; i++) 7949 maybe_widen_reg(env, 7950 &fold->regs[i], 7951 &fcur->regs[i], 7952 &env->idmap_scratch); 7953 7954 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) { 7955 if (!is_spilled_reg(&fold->stack[i]) || 7956 !is_spilled_reg(&fcur->stack[i])) 7957 continue; 7958 7959 maybe_widen_reg(env, 7960 &fold->stack[i].spilled_ptr, 7961 &fcur->stack[i].spilled_ptr, 7962 &env->idmap_scratch); 7963 } 7964 } 7965 return 0; 7966 } 7967 7968 /* process_iter_next_call() is called when verifier gets to iterator's next 7969 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7970 * to it as just "iter_next()" in comments below. 7971 * 7972 * BPF verifier relies on a crucial contract for any iter_next() 7973 * implementation: it should *eventually* return NULL, and once that happens 7974 * it should keep returning NULL. That is, once iterator exhausts elements to 7975 * iterate, it should never reset or spuriously return new elements. 7976 * 7977 * With the assumption of such contract, process_iter_next_call() simulates 7978 * a fork in the verifier state to validate loop logic correctness and safety 7979 * without having to simulate infinite amount of iterations. 7980 * 7981 * In current state, we first assume that iter_next() returned NULL and 7982 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7983 * conditions we should not form an infinite loop and should eventually reach 7984 * exit. 7985 * 7986 * Besides that, we also fork current state and enqueue it for later 7987 * verification. In a forked state we keep iterator state as ACTIVE 7988 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7989 * also bump iteration depth to prevent erroneous infinite loop detection 7990 * later on (see iter_active_depths_differ() comment for details). In this 7991 * state we assume that we'll eventually loop back to another iter_next() 7992 * calls (it could be in exactly same location or in some other instruction, 7993 * it doesn't matter, we don't make any unnecessary assumptions about this, 7994 * everything revolves around iterator state in a stack slot, not which 7995 * instruction is calling iter_next()). When that happens, we either will come 7996 * to iter_next() with equivalent state and can conclude that next iteration 7997 * will proceed in exactly the same way as we just verified, so it's safe to 7998 * assume that loop converges. If not, we'll go on another iteration 7999 * simulation with a different input state, until all possible starting states 8000 * are validated or we reach maximum number of instructions limit. 8001 * 8002 * This way, we will either exhaustively discover all possible input states 8003 * that iterator loop can start with and eventually will converge, or we'll 8004 * effectively regress into bounded loop simulation logic and either reach 8005 * maximum number of instructions if loop is not provably convergent, or there 8006 * is some statically known limit on number of iterations (e.g., if there is 8007 * an explicit `if n > 100 then break;` statement somewhere in the loop). 8008 * 8009 * Iteration convergence logic in is_state_visited() relies on exact 8010 * states comparison, which ignores read and precision marks. 8011 * This is necessary because read and precision marks are not finalized 8012 * while in the loop. Exact comparison might preclude convergence for 8013 * simple programs like below: 8014 * 8015 * i = 0; 8016 * while(iter_next(&it)) 8017 * i++; 8018 * 8019 * At each iteration step i++ would produce a new distinct state and 8020 * eventually instruction processing limit would be reached. 8021 * 8022 * To avoid such behavior speculatively forget (widen) range for 8023 * imprecise scalar registers, if those registers were not precise at the 8024 * end of the previous iteration and do not match exactly. 8025 * 8026 * This is a conservative heuristic that allows to verify wide range of programs, 8027 * however it precludes verification of programs that conjure an 8028 * imprecise value on the first loop iteration and use it as precise on a second. 8029 * For example, the following safe program would fail to verify: 8030 * 8031 * struct bpf_num_iter it; 8032 * int arr[10]; 8033 * int i = 0, a = 0; 8034 * bpf_iter_num_new(&it, 0, 10); 8035 * while (bpf_iter_num_next(&it)) { 8036 * if (a == 0) { 8037 * a = 1; 8038 * i = 7; // Because i changed verifier would forget 8039 * // it's range on second loop entry. 8040 * } else { 8041 * arr[i] = 42; // This would fail to verify. 8042 * } 8043 * } 8044 * bpf_iter_num_destroy(&it); 8045 */ 8046 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 8047 struct bpf_kfunc_call_arg_meta *meta) 8048 { 8049 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 8050 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 8051 struct bpf_reg_state *cur_iter, *queued_iter; 8052 int iter_frameno = meta->iter.frameno; 8053 int iter_spi = meta->iter.spi; 8054 8055 BTF_TYPE_EMIT(struct bpf_iter); 8056 8057 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 8058 8059 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 8060 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 8061 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 8062 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 8063 return -EFAULT; 8064 } 8065 8066 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 8067 /* Because iter_next() call is a checkpoint is_state_visitied() 8068 * should guarantee parent state with same call sites and insn_idx. 8069 */ 8070 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 8071 !same_callsites(cur_st->parent, cur_st)) { 8072 verbose(env, "bug: bad parent state for iter next call"); 8073 return -EFAULT; 8074 } 8075 /* Note cur_st->parent in the call below, it is necessary to skip 8076 * checkpoint created for cur_st by is_state_visited() 8077 * right at this instruction. 8078 */ 8079 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 8080 /* branch out active iter state */ 8081 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 8082 if (!queued_st) 8083 return -ENOMEM; 8084 8085 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 8086 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 8087 queued_iter->iter.depth++; 8088 if (prev_st) 8089 widen_imprecise_scalars(env, prev_st, queued_st); 8090 8091 queued_fr = queued_st->frame[queued_st->curframe]; 8092 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 8093 } 8094 8095 /* switch to DRAINED state, but keep the depth unchanged */ 8096 /* mark current iter state as drained and assume returned NULL */ 8097 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 8098 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 8099 8100 return 0; 8101 } 8102 8103 static bool arg_type_is_mem_size(enum bpf_arg_type type) 8104 { 8105 return type == ARG_CONST_SIZE || 8106 type == ARG_CONST_SIZE_OR_ZERO; 8107 } 8108 8109 static bool arg_type_is_release(enum bpf_arg_type type) 8110 { 8111 return type & OBJ_RELEASE; 8112 } 8113 8114 static bool arg_type_is_dynptr(enum bpf_arg_type type) 8115 { 8116 return base_type(type) == ARG_PTR_TO_DYNPTR; 8117 } 8118 8119 static int int_ptr_type_to_size(enum bpf_arg_type type) 8120 { 8121 if (type == ARG_PTR_TO_INT) 8122 return sizeof(u32); 8123 else if (type == ARG_PTR_TO_LONG) 8124 return sizeof(u64); 8125 8126 return -EINVAL; 8127 } 8128 8129 static int resolve_map_arg_type(struct bpf_verifier_env *env, 8130 const struct bpf_call_arg_meta *meta, 8131 enum bpf_arg_type *arg_type) 8132 { 8133 if (!meta->map_ptr) { 8134 /* kernel subsystem misconfigured verifier */ 8135 verbose(env, "invalid map_ptr to access map->type\n"); 8136 return -EACCES; 8137 } 8138 8139 switch (meta->map_ptr->map_type) { 8140 case BPF_MAP_TYPE_SOCKMAP: 8141 case BPF_MAP_TYPE_SOCKHASH: 8142 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 8143 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 8144 } else { 8145 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 8146 return -EINVAL; 8147 } 8148 break; 8149 case BPF_MAP_TYPE_BLOOM_FILTER: 8150 if (meta->func_id == BPF_FUNC_map_peek_elem) 8151 *arg_type = ARG_PTR_TO_MAP_VALUE; 8152 break; 8153 default: 8154 break; 8155 } 8156 return 0; 8157 } 8158 8159 struct bpf_reg_types { 8160 const enum bpf_reg_type types[10]; 8161 u32 *btf_id; 8162 }; 8163 8164 static const struct bpf_reg_types sock_types = { 8165 .types = { 8166 PTR_TO_SOCK_COMMON, 8167 PTR_TO_SOCKET, 8168 PTR_TO_TCP_SOCK, 8169 PTR_TO_XDP_SOCK, 8170 }, 8171 }; 8172 8173 #ifdef CONFIG_NET 8174 static const struct bpf_reg_types btf_id_sock_common_types = { 8175 .types = { 8176 PTR_TO_SOCK_COMMON, 8177 PTR_TO_SOCKET, 8178 PTR_TO_TCP_SOCK, 8179 PTR_TO_XDP_SOCK, 8180 PTR_TO_BTF_ID, 8181 PTR_TO_BTF_ID | PTR_TRUSTED, 8182 }, 8183 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 8184 }; 8185 #endif 8186 8187 static const struct bpf_reg_types mem_types = { 8188 .types = { 8189 PTR_TO_STACK, 8190 PTR_TO_PACKET, 8191 PTR_TO_PACKET_META, 8192 PTR_TO_MAP_KEY, 8193 PTR_TO_MAP_VALUE, 8194 PTR_TO_MEM, 8195 PTR_TO_MEM | MEM_RINGBUF, 8196 PTR_TO_BUF, 8197 PTR_TO_BTF_ID | PTR_TRUSTED, 8198 }, 8199 }; 8200 8201 static const struct bpf_reg_types int_ptr_types = { 8202 .types = { 8203 PTR_TO_STACK, 8204 PTR_TO_PACKET, 8205 PTR_TO_PACKET_META, 8206 PTR_TO_MAP_KEY, 8207 PTR_TO_MAP_VALUE, 8208 }, 8209 }; 8210 8211 static const struct bpf_reg_types spin_lock_types = { 8212 .types = { 8213 PTR_TO_MAP_VALUE, 8214 PTR_TO_BTF_ID | MEM_ALLOC, 8215 } 8216 }; 8217 8218 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 8219 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 8220 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 8221 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 8222 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 8223 static const struct bpf_reg_types btf_ptr_types = { 8224 .types = { 8225 PTR_TO_BTF_ID, 8226 PTR_TO_BTF_ID | PTR_TRUSTED, 8227 PTR_TO_BTF_ID | MEM_RCU, 8228 }, 8229 }; 8230 static const struct bpf_reg_types percpu_btf_ptr_types = { 8231 .types = { 8232 PTR_TO_BTF_ID | MEM_PERCPU, 8233 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 8234 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 8235 } 8236 }; 8237 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 8238 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 8239 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8240 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 8241 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8242 static const struct bpf_reg_types dynptr_types = { 8243 .types = { 8244 PTR_TO_STACK, 8245 CONST_PTR_TO_DYNPTR, 8246 } 8247 }; 8248 8249 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 8250 [ARG_PTR_TO_MAP_KEY] = &mem_types, 8251 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 8252 [ARG_CONST_SIZE] = &scalar_types, 8253 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 8254 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 8255 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 8256 [ARG_PTR_TO_CTX] = &context_types, 8257 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 8258 #ifdef CONFIG_NET 8259 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 8260 #endif 8261 [ARG_PTR_TO_SOCKET] = &fullsock_types, 8262 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 8263 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 8264 [ARG_PTR_TO_MEM] = &mem_types, 8265 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 8266 [ARG_PTR_TO_INT] = &int_ptr_types, 8267 [ARG_PTR_TO_LONG] = &int_ptr_types, 8268 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 8269 [ARG_PTR_TO_FUNC] = &func_ptr_types, 8270 [ARG_PTR_TO_STACK] = &stack_ptr_types, 8271 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 8272 [ARG_PTR_TO_TIMER] = &timer_types, 8273 [ARG_PTR_TO_KPTR] = &kptr_types, 8274 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 8275 }; 8276 8277 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 8278 enum bpf_arg_type arg_type, 8279 const u32 *arg_btf_id, 8280 struct bpf_call_arg_meta *meta) 8281 { 8282 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8283 enum bpf_reg_type expected, type = reg->type; 8284 const struct bpf_reg_types *compatible; 8285 int i, j; 8286 8287 compatible = compatible_reg_types[base_type(arg_type)]; 8288 if (!compatible) { 8289 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 8290 return -EFAULT; 8291 } 8292 8293 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 8294 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 8295 * 8296 * Same for MAYBE_NULL: 8297 * 8298 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 8299 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 8300 * 8301 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 8302 * 8303 * Therefore we fold these flags depending on the arg_type before comparison. 8304 */ 8305 if (arg_type & MEM_RDONLY) 8306 type &= ~MEM_RDONLY; 8307 if (arg_type & PTR_MAYBE_NULL) 8308 type &= ~PTR_MAYBE_NULL; 8309 if (base_type(arg_type) == ARG_PTR_TO_MEM) 8310 type &= ~DYNPTR_TYPE_FLAG_MASK; 8311 8312 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) { 8313 type &= ~MEM_ALLOC; 8314 type &= ~MEM_PERCPU; 8315 } 8316 8317 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 8318 expected = compatible->types[i]; 8319 if (expected == NOT_INIT) 8320 break; 8321 8322 if (type == expected) 8323 goto found; 8324 } 8325 8326 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 8327 for (j = 0; j + 1 < i; j++) 8328 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 8329 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 8330 return -EACCES; 8331 8332 found: 8333 if (base_type(reg->type) != PTR_TO_BTF_ID) 8334 return 0; 8335 8336 if (compatible == &mem_types) { 8337 if (!(arg_type & MEM_RDONLY)) { 8338 verbose(env, 8339 "%s() may write into memory pointed by R%d type=%s\n", 8340 func_id_name(meta->func_id), 8341 regno, reg_type_str(env, reg->type)); 8342 return -EACCES; 8343 } 8344 return 0; 8345 } 8346 8347 switch ((int)reg->type) { 8348 case PTR_TO_BTF_ID: 8349 case PTR_TO_BTF_ID | PTR_TRUSTED: 8350 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL: 8351 case PTR_TO_BTF_ID | MEM_RCU: 8352 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 8353 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 8354 { 8355 /* For bpf_sk_release, it needs to match against first member 8356 * 'struct sock_common', hence make an exception for it. This 8357 * allows bpf_sk_release to work for multiple socket types. 8358 */ 8359 bool strict_type_match = arg_type_is_release(arg_type) && 8360 meta->func_id != BPF_FUNC_sk_release; 8361 8362 if (type_may_be_null(reg->type) && 8363 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 8364 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 8365 return -EACCES; 8366 } 8367 8368 if (!arg_btf_id) { 8369 if (!compatible->btf_id) { 8370 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 8371 return -EFAULT; 8372 } 8373 arg_btf_id = compatible->btf_id; 8374 } 8375 8376 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8377 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8378 return -EACCES; 8379 } else { 8380 if (arg_btf_id == BPF_PTR_POISON) { 8381 verbose(env, "verifier internal error:"); 8382 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 8383 regno); 8384 return -EACCES; 8385 } 8386 8387 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 8388 btf_vmlinux, *arg_btf_id, 8389 strict_type_match)) { 8390 verbose(env, "R%d is of type %s but %s is expected\n", 8391 regno, btf_type_name(reg->btf, reg->btf_id), 8392 btf_type_name(btf_vmlinux, *arg_btf_id)); 8393 return -EACCES; 8394 } 8395 } 8396 break; 8397 } 8398 case PTR_TO_BTF_ID | MEM_ALLOC: 8399 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 8400 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8401 meta->func_id != BPF_FUNC_kptr_xchg) { 8402 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 8403 return -EFAULT; 8404 } 8405 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8406 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8407 return -EACCES; 8408 } 8409 break; 8410 case PTR_TO_BTF_ID | MEM_PERCPU: 8411 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 8412 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8413 /* Handled by helper specific checks */ 8414 break; 8415 default: 8416 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 8417 return -EFAULT; 8418 } 8419 return 0; 8420 } 8421 8422 static struct btf_field * 8423 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8424 { 8425 struct btf_field *field; 8426 struct btf_record *rec; 8427 8428 rec = reg_btf_record(reg); 8429 if (!rec) 8430 return NULL; 8431 8432 field = btf_record_find(rec, off, fields); 8433 if (!field) 8434 return NULL; 8435 8436 return field; 8437 } 8438 8439 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 8440 const struct bpf_reg_state *reg, int regno, 8441 enum bpf_arg_type arg_type) 8442 { 8443 u32 type = reg->type; 8444 8445 /* When referenced register is passed to release function, its fixed 8446 * offset must be 0. 8447 * 8448 * We will check arg_type_is_release reg has ref_obj_id when storing 8449 * meta->release_regno. 8450 */ 8451 if (arg_type_is_release(arg_type)) { 8452 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8453 * may not directly point to the object being released, but to 8454 * dynptr pointing to such object, which might be at some offset 8455 * on the stack. In that case, we simply to fallback to the 8456 * default handling. 8457 */ 8458 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8459 return 0; 8460 8461 /* Doing check_ptr_off_reg check for the offset will catch this 8462 * because fixed_off_ok is false, but checking here allows us 8463 * to give the user a better error message. 8464 */ 8465 if (reg->off) { 8466 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 8467 regno); 8468 return -EINVAL; 8469 } 8470 return __check_ptr_off_reg(env, reg, regno, false); 8471 } 8472 8473 switch (type) { 8474 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8475 case PTR_TO_STACK: 8476 case PTR_TO_PACKET: 8477 case PTR_TO_PACKET_META: 8478 case PTR_TO_MAP_KEY: 8479 case PTR_TO_MAP_VALUE: 8480 case PTR_TO_MEM: 8481 case PTR_TO_MEM | MEM_RDONLY: 8482 case PTR_TO_MEM | MEM_RINGBUF: 8483 case PTR_TO_BUF: 8484 case PTR_TO_BUF | MEM_RDONLY: 8485 case PTR_TO_ARENA: 8486 case SCALAR_VALUE: 8487 return 0; 8488 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8489 * fixed offset. 8490 */ 8491 case PTR_TO_BTF_ID: 8492 case PTR_TO_BTF_ID | MEM_ALLOC: 8493 case PTR_TO_BTF_ID | PTR_TRUSTED: 8494 case PTR_TO_BTF_ID | MEM_RCU: 8495 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8496 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8497 /* When referenced PTR_TO_BTF_ID is passed to release function, 8498 * its fixed offset must be 0. In the other cases, fixed offset 8499 * can be non-zero. This was already checked above. So pass 8500 * fixed_off_ok as true to allow fixed offset for all other 8501 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8502 * still need to do checks instead of returning. 8503 */ 8504 return __check_ptr_off_reg(env, reg, regno, true); 8505 default: 8506 return __check_ptr_off_reg(env, reg, regno, false); 8507 } 8508 } 8509 8510 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8511 const struct bpf_func_proto *fn, 8512 struct bpf_reg_state *regs) 8513 { 8514 struct bpf_reg_state *state = NULL; 8515 int i; 8516 8517 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8518 if (arg_type_is_dynptr(fn->arg_type[i])) { 8519 if (state) { 8520 verbose(env, "verifier internal error: multiple dynptr args\n"); 8521 return NULL; 8522 } 8523 state = ®s[BPF_REG_1 + i]; 8524 } 8525 8526 if (!state) 8527 verbose(env, "verifier internal error: no dynptr arg found\n"); 8528 8529 return state; 8530 } 8531 8532 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8533 { 8534 struct bpf_func_state *state = func(env, reg); 8535 int spi; 8536 8537 if (reg->type == CONST_PTR_TO_DYNPTR) 8538 return reg->id; 8539 spi = dynptr_get_spi(env, reg); 8540 if (spi < 0) 8541 return spi; 8542 return state->stack[spi].spilled_ptr.id; 8543 } 8544 8545 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8546 { 8547 struct bpf_func_state *state = func(env, reg); 8548 int spi; 8549 8550 if (reg->type == CONST_PTR_TO_DYNPTR) 8551 return reg->ref_obj_id; 8552 spi = dynptr_get_spi(env, reg); 8553 if (spi < 0) 8554 return spi; 8555 return state->stack[spi].spilled_ptr.ref_obj_id; 8556 } 8557 8558 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8559 struct bpf_reg_state *reg) 8560 { 8561 struct bpf_func_state *state = func(env, reg); 8562 int spi; 8563 8564 if (reg->type == CONST_PTR_TO_DYNPTR) 8565 return reg->dynptr.type; 8566 8567 spi = __get_spi(reg->off); 8568 if (spi < 0) { 8569 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8570 return BPF_DYNPTR_TYPE_INVALID; 8571 } 8572 8573 return state->stack[spi].spilled_ptr.dynptr.type; 8574 } 8575 8576 static int check_reg_const_str(struct bpf_verifier_env *env, 8577 struct bpf_reg_state *reg, u32 regno) 8578 { 8579 struct bpf_map *map = reg->map_ptr; 8580 int err; 8581 int map_off; 8582 u64 map_addr; 8583 char *str_ptr; 8584 8585 if (reg->type != PTR_TO_MAP_VALUE) 8586 return -EINVAL; 8587 8588 if (!bpf_map_is_rdonly(map)) { 8589 verbose(env, "R%d does not point to a readonly map'\n", regno); 8590 return -EACCES; 8591 } 8592 8593 if (!tnum_is_const(reg->var_off)) { 8594 verbose(env, "R%d is not a constant address'\n", regno); 8595 return -EACCES; 8596 } 8597 8598 if (!map->ops->map_direct_value_addr) { 8599 verbose(env, "no direct value access support for this map type\n"); 8600 return -EACCES; 8601 } 8602 8603 err = check_map_access(env, regno, reg->off, 8604 map->value_size - reg->off, false, 8605 ACCESS_HELPER); 8606 if (err) 8607 return err; 8608 8609 map_off = reg->off + reg->var_off.value; 8610 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8611 if (err) { 8612 verbose(env, "direct value access on string failed\n"); 8613 return err; 8614 } 8615 8616 str_ptr = (char *)(long)(map_addr); 8617 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8618 verbose(env, "string is not zero-terminated\n"); 8619 return -EINVAL; 8620 } 8621 return 0; 8622 } 8623 8624 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8625 struct bpf_call_arg_meta *meta, 8626 const struct bpf_func_proto *fn, 8627 int insn_idx) 8628 { 8629 u32 regno = BPF_REG_1 + arg; 8630 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8631 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8632 enum bpf_reg_type type = reg->type; 8633 u32 *arg_btf_id = NULL; 8634 int err = 0; 8635 8636 if (arg_type == ARG_DONTCARE) 8637 return 0; 8638 8639 err = check_reg_arg(env, regno, SRC_OP); 8640 if (err) 8641 return err; 8642 8643 if (arg_type == ARG_ANYTHING) { 8644 if (is_pointer_value(env, regno)) { 8645 verbose(env, "R%d leaks addr into helper function\n", 8646 regno); 8647 return -EACCES; 8648 } 8649 return 0; 8650 } 8651 8652 if (type_is_pkt_pointer(type) && 8653 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8654 verbose(env, "helper access to the packet is not allowed\n"); 8655 return -EACCES; 8656 } 8657 8658 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8659 err = resolve_map_arg_type(env, meta, &arg_type); 8660 if (err) 8661 return err; 8662 } 8663 8664 if (register_is_null(reg) && type_may_be_null(arg_type)) 8665 /* A NULL register has a SCALAR_VALUE type, so skip 8666 * type checking. 8667 */ 8668 goto skip_type_check; 8669 8670 /* arg_btf_id and arg_size are in a union. */ 8671 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8672 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8673 arg_btf_id = fn->arg_btf_id[arg]; 8674 8675 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 8676 if (err) 8677 return err; 8678 8679 err = check_func_arg_reg_off(env, reg, regno, arg_type); 8680 if (err) 8681 return err; 8682 8683 skip_type_check: 8684 if (arg_type_is_release(arg_type)) { 8685 if (arg_type_is_dynptr(arg_type)) { 8686 struct bpf_func_state *state = func(env, reg); 8687 int spi; 8688 8689 /* Only dynptr created on stack can be released, thus 8690 * the get_spi and stack state checks for spilled_ptr 8691 * should only be done before process_dynptr_func for 8692 * PTR_TO_STACK. 8693 */ 8694 if (reg->type == PTR_TO_STACK) { 8695 spi = dynptr_get_spi(env, reg); 8696 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8697 verbose(env, "arg %d is an unacquired reference\n", regno); 8698 return -EINVAL; 8699 } 8700 } else { 8701 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8702 return -EINVAL; 8703 } 8704 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 8705 verbose(env, "R%d must be referenced when passed to release function\n", 8706 regno); 8707 return -EINVAL; 8708 } 8709 if (meta->release_regno) { 8710 verbose(env, "verifier internal error: more than one release argument\n"); 8711 return -EFAULT; 8712 } 8713 meta->release_regno = regno; 8714 } 8715 8716 if (reg->ref_obj_id) { 8717 if (meta->ref_obj_id) { 8718 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 8719 regno, reg->ref_obj_id, 8720 meta->ref_obj_id); 8721 return -EFAULT; 8722 } 8723 meta->ref_obj_id = reg->ref_obj_id; 8724 } 8725 8726 switch (base_type(arg_type)) { 8727 case ARG_CONST_MAP_PTR: 8728 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8729 if (meta->map_ptr) { 8730 /* Use map_uid (which is unique id of inner map) to reject: 8731 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8732 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8733 * if (inner_map1 && inner_map2) { 8734 * timer = bpf_map_lookup_elem(inner_map1); 8735 * if (timer) 8736 * // mismatch would have been allowed 8737 * bpf_timer_init(timer, inner_map2); 8738 * } 8739 * 8740 * Comparing map_ptr is enough to distinguish normal and outer maps. 8741 */ 8742 if (meta->map_ptr != reg->map_ptr || 8743 meta->map_uid != reg->map_uid) { 8744 verbose(env, 8745 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8746 meta->map_uid, reg->map_uid); 8747 return -EINVAL; 8748 } 8749 } 8750 meta->map_ptr = reg->map_ptr; 8751 meta->map_uid = reg->map_uid; 8752 break; 8753 case ARG_PTR_TO_MAP_KEY: 8754 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8755 * check that [key, key + map->key_size) are within 8756 * stack limits and initialized 8757 */ 8758 if (!meta->map_ptr) { 8759 /* in function declaration map_ptr must come before 8760 * map_key, so that it's verified and known before 8761 * we have to check map_key here. Otherwise it means 8762 * that kernel subsystem misconfigured verifier 8763 */ 8764 verbose(env, "invalid map_ptr to access map->key\n"); 8765 return -EACCES; 8766 } 8767 err = check_helper_mem_access(env, regno, 8768 meta->map_ptr->key_size, false, 8769 NULL); 8770 break; 8771 case ARG_PTR_TO_MAP_VALUE: 8772 if (type_may_be_null(arg_type) && register_is_null(reg)) 8773 return 0; 8774 8775 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8776 * check [value, value + map->value_size) validity 8777 */ 8778 if (!meta->map_ptr) { 8779 /* kernel subsystem misconfigured verifier */ 8780 verbose(env, "invalid map_ptr to access map->value\n"); 8781 return -EACCES; 8782 } 8783 meta->raw_mode = arg_type & MEM_UNINIT; 8784 err = check_helper_mem_access(env, regno, 8785 meta->map_ptr->value_size, false, 8786 meta); 8787 break; 8788 case ARG_PTR_TO_PERCPU_BTF_ID: 8789 if (!reg->btf_id) { 8790 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8791 return -EACCES; 8792 } 8793 meta->ret_btf = reg->btf; 8794 meta->ret_btf_id = reg->btf_id; 8795 break; 8796 case ARG_PTR_TO_SPIN_LOCK: 8797 if (in_rbtree_lock_required_cb(env)) { 8798 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8799 return -EACCES; 8800 } 8801 if (meta->func_id == BPF_FUNC_spin_lock) { 8802 err = process_spin_lock(env, regno, true); 8803 if (err) 8804 return err; 8805 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8806 err = process_spin_lock(env, regno, false); 8807 if (err) 8808 return err; 8809 } else { 8810 verbose(env, "verifier internal error\n"); 8811 return -EFAULT; 8812 } 8813 break; 8814 case ARG_PTR_TO_TIMER: 8815 err = process_timer_func(env, regno, meta); 8816 if (err) 8817 return err; 8818 break; 8819 case ARG_PTR_TO_FUNC: 8820 meta->subprogno = reg->subprogno; 8821 break; 8822 case ARG_PTR_TO_MEM: 8823 /* The access to this pointer is only checked when we hit the 8824 * next is_mem_size argument below. 8825 */ 8826 meta->raw_mode = arg_type & MEM_UNINIT; 8827 if (arg_type & MEM_FIXED_SIZE) { 8828 err = check_helper_mem_access(env, regno, 8829 fn->arg_size[arg], false, 8830 meta); 8831 } 8832 break; 8833 case ARG_CONST_SIZE: 8834 err = check_mem_size_reg(env, reg, regno, false, meta); 8835 break; 8836 case ARG_CONST_SIZE_OR_ZERO: 8837 err = check_mem_size_reg(env, reg, regno, true, meta); 8838 break; 8839 case ARG_PTR_TO_DYNPTR: 8840 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 8841 if (err) 8842 return err; 8843 break; 8844 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8845 if (!tnum_is_const(reg->var_off)) { 8846 verbose(env, "R%d is not a known constant'\n", 8847 regno); 8848 return -EACCES; 8849 } 8850 meta->mem_size = reg->var_off.value; 8851 err = mark_chain_precision(env, regno); 8852 if (err) 8853 return err; 8854 break; 8855 case ARG_PTR_TO_INT: 8856 case ARG_PTR_TO_LONG: 8857 { 8858 int size = int_ptr_type_to_size(arg_type); 8859 8860 err = check_helper_mem_access(env, regno, size, false, meta); 8861 if (err) 8862 return err; 8863 err = check_ptr_alignment(env, reg, 0, size, true); 8864 break; 8865 } 8866 case ARG_PTR_TO_CONST_STR: 8867 { 8868 err = check_reg_const_str(env, reg, regno); 8869 if (err) 8870 return err; 8871 break; 8872 } 8873 case ARG_PTR_TO_KPTR: 8874 err = process_kptr_func(env, regno, meta); 8875 if (err) 8876 return err; 8877 break; 8878 } 8879 8880 return err; 8881 } 8882 8883 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8884 { 8885 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8886 enum bpf_prog_type type = resolve_prog_type(env->prog); 8887 8888 if (func_id != BPF_FUNC_map_update_elem && 8889 func_id != BPF_FUNC_map_delete_elem) 8890 return false; 8891 8892 /* It's not possible to get access to a locked struct sock in these 8893 * contexts, so updating is safe. 8894 */ 8895 switch (type) { 8896 case BPF_PROG_TYPE_TRACING: 8897 if (eatype == BPF_TRACE_ITER) 8898 return true; 8899 break; 8900 case BPF_PROG_TYPE_SOCK_OPS: 8901 /* map_update allowed only via dedicated helpers with event type checks */ 8902 if (func_id == BPF_FUNC_map_delete_elem) 8903 return true; 8904 break; 8905 case BPF_PROG_TYPE_SOCKET_FILTER: 8906 case BPF_PROG_TYPE_SCHED_CLS: 8907 case BPF_PROG_TYPE_SCHED_ACT: 8908 case BPF_PROG_TYPE_XDP: 8909 case BPF_PROG_TYPE_SK_REUSEPORT: 8910 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8911 case BPF_PROG_TYPE_SK_LOOKUP: 8912 return true; 8913 default: 8914 break; 8915 } 8916 8917 verbose(env, "cannot update sockmap in this context\n"); 8918 return false; 8919 } 8920 8921 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8922 { 8923 return env->prog->jit_requested && 8924 bpf_jit_supports_subprog_tailcalls(); 8925 } 8926 8927 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8928 struct bpf_map *map, int func_id) 8929 { 8930 if (!map) 8931 return 0; 8932 8933 /* We need a two way check, first is from map perspective ... */ 8934 switch (map->map_type) { 8935 case BPF_MAP_TYPE_PROG_ARRAY: 8936 if (func_id != BPF_FUNC_tail_call) 8937 goto error; 8938 break; 8939 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8940 if (func_id != BPF_FUNC_perf_event_read && 8941 func_id != BPF_FUNC_perf_event_output && 8942 func_id != BPF_FUNC_skb_output && 8943 func_id != BPF_FUNC_perf_event_read_value && 8944 func_id != BPF_FUNC_xdp_output) 8945 goto error; 8946 break; 8947 case BPF_MAP_TYPE_RINGBUF: 8948 if (func_id != BPF_FUNC_ringbuf_output && 8949 func_id != BPF_FUNC_ringbuf_reserve && 8950 func_id != BPF_FUNC_ringbuf_query && 8951 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8952 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8953 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8954 goto error; 8955 break; 8956 case BPF_MAP_TYPE_USER_RINGBUF: 8957 if (func_id != BPF_FUNC_user_ringbuf_drain) 8958 goto error; 8959 break; 8960 case BPF_MAP_TYPE_STACK_TRACE: 8961 if (func_id != BPF_FUNC_get_stackid) 8962 goto error; 8963 break; 8964 case BPF_MAP_TYPE_CGROUP_ARRAY: 8965 if (func_id != BPF_FUNC_skb_under_cgroup && 8966 func_id != BPF_FUNC_current_task_under_cgroup) 8967 goto error; 8968 break; 8969 case BPF_MAP_TYPE_CGROUP_STORAGE: 8970 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8971 if (func_id != BPF_FUNC_get_local_storage) 8972 goto error; 8973 break; 8974 case BPF_MAP_TYPE_DEVMAP: 8975 case BPF_MAP_TYPE_DEVMAP_HASH: 8976 if (func_id != BPF_FUNC_redirect_map && 8977 func_id != BPF_FUNC_map_lookup_elem) 8978 goto error; 8979 break; 8980 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8981 * appear. 8982 */ 8983 case BPF_MAP_TYPE_CPUMAP: 8984 if (func_id != BPF_FUNC_redirect_map) 8985 goto error; 8986 break; 8987 case BPF_MAP_TYPE_XSKMAP: 8988 if (func_id != BPF_FUNC_redirect_map && 8989 func_id != BPF_FUNC_map_lookup_elem) 8990 goto error; 8991 break; 8992 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8993 case BPF_MAP_TYPE_HASH_OF_MAPS: 8994 if (func_id != BPF_FUNC_map_lookup_elem) 8995 goto error; 8996 break; 8997 case BPF_MAP_TYPE_SOCKMAP: 8998 if (func_id != BPF_FUNC_sk_redirect_map && 8999 func_id != BPF_FUNC_sock_map_update && 9000 func_id != BPF_FUNC_msg_redirect_map && 9001 func_id != BPF_FUNC_sk_select_reuseport && 9002 func_id != BPF_FUNC_map_lookup_elem && 9003 !may_update_sockmap(env, func_id)) 9004 goto error; 9005 break; 9006 case BPF_MAP_TYPE_SOCKHASH: 9007 if (func_id != BPF_FUNC_sk_redirect_hash && 9008 func_id != BPF_FUNC_sock_hash_update && 9009 func_id != BPF_FUNC_msg_redirect_hash && 9010 func_id != BPF_FUNC_sk_select_reuseport && 9011 func_id != BPF_FUNC_map_lookup_elem && 9012 !may_update_sockmap(env, func_id)) 9013 goto error; 9014 break; 9015 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 9016 if (func_id != BPF_FUNC_sk_select_reuseport) 9017 goto error; 9018 break; 9019 case BPF_MAP_TYPE_QUEUE: 9020 case BPF_MAP_TYPE_STACK: 9021 if (func_id != BPF_FUNC_map_peek_elem && 9022 func_id != BPF_FUNC_map_pop_elem && 9023 func_id != BPF_FUNC_map_push_elem) 9024 goto error; 9025 break; 9026 case BPF_MAP_TYPE_SK_STORAGE: 9027 if (func_id != BPF_FUNC_sk_storage_get && 9028 func_id != BPF_FUNC_sk_storage_delete && 9029 func_id != BPF_FUNC_kptr_xchg) 9030 goto error; 9031 break; 9032 case BPF_MAP_TYPE_INODE_STORAGE: 9033 if (func_id != BPF_FUNC_inode_storage_get && 9034 func_id != BPF_FUNC_inode_storage_delete && 9035 func_id != BPF_FUNC_kptr_xchg) 9036 goto error; 9037 break; 9038 case BPF_MAP_TYPE_TASK_STORAGE: 9039 if (func_id != BPF_FUNC_task_storage_get && 9040 func_id != BPF_FUNC_task_storage_delete && 9041 func_id != BPF_FUNC_kptr_xchg) 9042 goto error; 9043 break; 9044 case BPF_MAP_TYPE_CGRP_STORAGE: 9045 if (func_id != BPF_FUNC_cgrp_storage_get && 9046 func_id != BPF_FUNC_cgrp_storage_delete && 9047 func_id != BPF_FUNC_kptr_xchg) 9048 goto error; 9049 break; 9050 case BPF_MAP_TYPE_BLOOM_FILTER: 9051 if (func_id != BPF_FUNC_map_peek_elem && 9052 func_id != BPF_FUNC_map_push_elem) 9053 goto error; 9054 break; 9055 default: 9056 break; 9057 } 9058 9059 /* ... and second from the function itself. */ 9060 switch (func_id) { 9061 case BPF_FUNC_tail_call: 9062 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 9063 goto error; 9064 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 9065 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 9066 return -EINVAL; 9067 } 9068 break; 9069 case BPF_FUNC_perf_event_read: 9070 case BPF_FUNC_perf_event_output: 9071 case BPF_FUNC_perf_event_read_value: 9072 case BPF_FUNC_skb_output: 9073 case BPF_FUNC_xdp_output: 9074 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 9075 goto error; 9076 break; 9077 case BPF_FUNC_ringbuf_output: 9078 case BPF_FUNC_ringbuf_reserve: 9079 case BPF_FUNC_ringbuf_query: 9080 case BPF_FUNC_ringbuf_reserve_dynptr: 9081 case BPF_FUNC_ringbuf_submit_dynptr: 9082 case BPF_FUNC_ringbuf_discard_dynptr: 9083 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 9084 goto error; 9085 break; 9086 case BPF_FUNC_user_ringbuf_drain: 9087 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 9088 goto error; 9089 break; 9090 case BPF_FUNC_get_stackid: 9091 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 9092 goto error; 9093 break; 9094 case BPF_FUNC_current_task_under_cgroup: 9095 case BPF_FUNC_skb_under_cgroup: 9096 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 9097 goto error; 9098 break; 9099 case BPF_FUNC_redirect_map: 9100 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 9101 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 9102 map->map_type != BPF_MAP_TYPE_CPUMAP && 9103 map->map_type != BPF_MAP_TYPE_XSKMAP) 9104 goto error; 9105 break; 9106 case BPF_FUNC_sk_redirect_map: 9107 case BPF_FUNC_msg_redirect_map: 9108 case BPF_FUNC_sock_map_update: 9109 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 9110 goto error; 9111 break; 9112 case BPF_FUNC_sk_redirect_hash: 9113 case BPF_FUNC_msg_redirect_hash: 9114 case BPF_FUNC_sock_hash_update: 9115 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 9116 goto error; 9117 break; 9118 case BPF_FUNC_get_local_storage: 9119 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 9120 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 9121 goto error; 9122 break; 9123 case BPF_FUNC_sk_select_reuseport: 9124 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 9125 map->map_type != BPF_MAP_TYPE_SOCKMAP && 9126 map->map_type != BPF_MAP_TYPE_SOCKHASH) 9127 goto error; 9128 break; 9129 case BPF_FUNC_map_pop_elem: 9130 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9131 map->map_type != BPF_MAP_TYPE_STACK) 9132 goto error; 9133 break; 9134 case BPF_FUNC_map_peek_elem: 9135 case BPF_FUNC_map_push_elem: 9136 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9137 map->map_type != BPF_MAP_TYPE_STACK && 9138 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 9139 goto error; 9140 break; 9141 case BPF_FUNC_map_lookup_percpu_elem: 9142 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 9143 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 9144 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 9145 goto error; 9146 break; 9147 case BPF_FUNC_sk_storage_get: 9148 case BPF_FUNC_sk_storage_delete: 9149 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 9150 goto error; 9151 break; 9152 case BPF_FUNC_inode_storage_get: 9153 case BPF_FUNC_inode_storage_delete: 9154 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 9155 goto error; 9156 break; 9157 case BPF_FUNC_task_storage_get: 9158 case BPF_FUNC_task_storage_delete: 9159 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 9160 goto error; 9161 break; 9162 case BPF_FUNC_cgrp_storage_get: 9163 case BPF_FUNC_cgrp_storage_delete: 9164 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 9165 goto error; 9166 break; 9167 default: 9168 break; 9169 } 9170 9171 return 0; 9172 error: 9173 verbose(env, "cannot pass map_type %d into func %s#%d\n", 9174 map->map_type, func_id_name(func_id), func_id); 9175 return -EINVAL; 9176 } 9177 9178 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 9179 { 9180 int count = 0; 9181 9182 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 9183 count++; 9184 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 9185 count++; 9186 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 9187 count++; 9188 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 9189 count++; 9190 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 9191 count++; 9192 9193 /* We only support one arg being in raw mode at the moment, 9194 * which is sufficient for the helper functions we have 9195 * right now. 9196 */ 9197 return count <= 1; 9198 } 9199 9200 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 9201 { 9202 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 9203 bool has_size = fn->arg_size[arg] != 0; 9204 bool is_next_size = false; 9205 9206 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 9207 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 9208 9209 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 9210 return is_next_size; 9211 9212 return has_size == is_next_size || is_next_size == is_fixed; 9213 } 9214 9215 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 9216 { 9217 /* bpf_xxx(..., buf, len) call will access 'len' 9218 * bytes from memory 'buf'. Both arg types need 9219 * to be paired, so make sure there's no buggy 9220 * helper function specification. 9221 */ 9222 if (arg_type_is_mem_size(fn->arg1_type) || 9223 check_args_pair_invalid(fn, 0) || 9224 check_args_pair_invalid(fn, 1) || 9225 check_args_pair_invalid(fn, 2) || 9226 check_args_pair_invalid(fn, 3) || 9227 check_args_pair_invalid(fn, 4)) 9228 return false; 9229 9230 return true; 9231 } 9232 9233 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 9234 { 9235 int i; 9236 9237 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 9238 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 9239 return !!fn->arg_btf_id[i]; 9240 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 9241 return fn->arg_btf_id[i] == BPF_PTR_POISON; 9242 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 9243 /* arg_btf_id and arg_size are in a union. */ 9244 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 9245 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 9246 return false; 9247 } 9248 9249 return true; 9250 } 9251 9252 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 9253 { 9254 return check_raw_mode_ok(fn) && 9255 check_arg_pair_ok(fn) && 9256 check_btf_id_ok(fn) ? 0 : -EINVAL; 9257 } 9258 9259 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 9260 * are now invalid, so turn them into unknown SCALAR_VALUE. 9261 * 9262 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 9263 * since these slices point to packet data. 9264 */ 9265 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 9266 { 9267 struct bpf_func_state *state; 9268 struct bpf_reg_state *reg; 9269 9270 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9271 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 9272 mark_reg_invalid(env, reg); 9273 })); 9274 } 9275 9276 enum { 9277 AT_PKT_END = -1, 9278 BEYOND_PKT_END = -2, 9279 }; 9280 9281 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 9282 { 9283 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9284 struct bpf_reg_state *reg = &state->regs[regn]; 9285 9286 if (reg->type != PTR_TO_PACKET) 9287 /* PTR_TO_PACKET_META is not supported yet */ 9288 return; 9289 9290 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 9291 * How far beyond pkt_end it goes is unknown. 9292 * if (!range_open) it's the case of pkt >= pkt_end 9293 * if (range_open) it's the case of pkt > pkt_end 9294 * hence this pointer is at least 1 byte bigger than pkt_end 9295 */ 9296 if (range_open) 9297 reg->range = BEYOND_PKT_END; 9298 else 9299 reg->range = AT_PKT_END; 9300 } 9301 9302 /* The pointer with the specified id has released its reference to kernel 9303 * resources. Identify all copies of the same pointer and clear the reference. 9304 */ 9305 static int release_reference(struct bpf_verifier_env *env, 9306 int ref_obj_id) 9307 { 9308 struct bpf_func_state *state; 9309 struct bpf_reg_state *reg; 9310 int err; 9311 9312 err = release_reference_state(cur_func(env), ref_obj_id); 9313 if (err) 9314 return err; 9315 9316 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9317 if (reg->ref_obj_id == ref_obj_id) 9318 mark_reg_invalid(env, reg); 9319 })); 9320 9321 return 0; 9322 } 9323 9324 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9325 { 9326 struct bpf_func_state *unused; 9327 struct bpf_reg_state *reg; 9328 9329 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9330 if (type_is_non_owning_ref(reg->type)) 9331 mark_reg_invalid(env, reg); 9332 })); 9333 } 9334 9335 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9336 struct bpf_reg_state *regs) 9337 { 9338 int i; 9339 9340 /* after the call registers r0 - r5 were scratched */ 9341 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9342 mark_reg_not_init(env, regs, caller_saved[i]); 9343 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9344 } 9345 } 9346 9347 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9348 struct bpf_func_state *caller, 9349 struct bpf_func_state *callee, 9350 int insn_idx); 9351 9352 static int set_callee_state(struct bpf_verifier_env *env, 9353 struct bpf_func_state *caller, 9354 struct bpf_func_state *callee, int insn_idx); 9355 9356 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9357 set_callee_state_fn set_callee_state_cb, 9358 struct bpf_verifier_state *state) 9359 { 9360 struct bpf_func_state *caller, *callee; 9361 int err; 9362 9363 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9364 verbose(env, "the call stack of %d frames is too deep\n", 9365 state->curframe + 2); 9366 return -E2BIG; 9367 } 9368 9369 if (state->frame[state->curframe + 1]) { 9370 verbose(env, "verifier bug. Frame %d already allocated\n", 9371 state->curframe + 1); 9372 return -EFAULT; 9373 } 9374 9375 caller = state->frame[state->curframe]; 9376 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 9377 if (!callee) 9378 return -ENOMEM; 9379 state->frame[state->curframe + 1] = callee; 9380 9381 /* callee cannot access r0, r6 - r9 for reading and has to write 9382 * into its own stack before reading from it. 9383 * callee can read/write into caller's stack 9384 */ 9385 init_func_state(env, callee, 9386 /* remember the callsite, it will be used by bpf_exit */ 9387 callsite, 9388 state->curframe + 1 /* frameno within this callchain */, 9389 subprog /* subprog number within this prog */); 9390 /* Transfer references to the callee */ 9391 err = copy_reference_state(callee, caller); 9392 err = err ?: set_callee_state_cb(env, caller, callee, callsite); 9393 if (err) 9394 goto err_out; 9395 9396 /* only increment it after check_reg_arg() finished */ 9397 state->curframe++; 9398 9399 return 0; 9400 9401 err_out: 9402 free_func_state(callee); 9403 state->frame[state->curframe + 1] = NULL; 9404 return err; 9405 } 9406 9407 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, 9408 const struct btf *btf, 9409 struct bpf_reg_state *regs) 9410 { 9411 struct bpf_subprog_info *sub = subprog_info(env, subprog); 9412 struct bpf_verifier_log *log = &env->log; 9413 u32 i; 9414 int ret; 9415 9416 ret = btf_prepare_func_args(env, subprog); 9417 if (ret) 9418 return ret; 9419 9420 /* check that BTF function arguments match actual types that the 9421 * verifier sees. 9422 */ 9423 for (i = 0; i < sub->arg_cnt; i++) { 9424 u32 regno = i + 1; 9425 struct bpf_reg_state *reg = ®s[regno]; 9426 struct bpf_subprog_arg_info *arg = &sub->args[i]; 9427 9428 if (arg->arg_type == ARG_ANYTHING) { 9429 if (reg->type != SCALAR_VALUE) { 9430 bpf_log(log, "R%d is not a scalar\n", regno); 9431 return -EINVAL; 9432 } 9433 } else if (arg->arg_type == ARG_PTR_TO_CTX) { 9434 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9435 if (ret < 0) 9436 return ret; 9437 /* If function expects ctx type in BTF check that caller 9438 * is passing PTR_TO_CTX. 9439 */ 9440 if (reg->type != PTR_TO_CTX) { 9441 bpf_log(log, "arg#%d expects pointer to ctx\n", i); 9442 return -EINVAL; 9443 } 9444 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 9445 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9446 if (ret < 0) 9447 return ret; 9448 if (check_mem_reg(env, reg, regno, arg->mem_size)) 9449 return -EINVAL; 9450 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) { 9451 bpf_log(log, "arg#%d is expected to be non-NULL\n", i); 9452 return -EINVAL; 9453 } 9454 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 9455 /* 9456 * Can pass any value and the kernel won't crash, but 9457 * only PTR_TO_ARENA or SCALAR make sense. Everything 9458 * else is a bug in the bpf program. Point it out to 9459 * the user at the verification time instead of 9460 * run-time debug nightmare. 9461 */ 9462 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) { 9463 bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno); 9464 return -EINVAL; 9465 } 9466 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 9467 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0); 9468 if (ret) 9469 return ret; 9470 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 9471 struct bpf_call_arg_meta meta; 9472 int err; 9473 9474 if (register_is_null(reg) && type_may_be_null(arg->arg_type)) 9475 continue; 9476 9477 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */ 9478 err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta); 9479 err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type); 9480 if (err) 9481 return err; 9482 } else { 9483 bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n", 9484 i, arg->arg_type); 9485 return -EFAULT; 9486 } 9487 } 9488 9489 return 0; 9490 } 9491 9492 /* Compare BTF of a function call with given bpf_reg_state. 9493 * Returns: 9494 * EFAULT - there is a verifier bug. Abort verification. 9495 * EINVAL - there is a type mismatch or BTF is not available. 9496 * 0 - BTF matches with what bpf_reg_state expects. 9497 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized. 9498 */ 9499 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog, 9500 struct bpf_reg_state *regs) 9501 { 9502 struct bpf_prog *prog = env->prog; 9503 struct btf *btf = prog->aux->btf; 9504 u32 btf_id; 9505 int err; 9506 9507 if (!prog->aux->func_info) 9508 return -EINVAL; 9509 9510 btf_id = prog->aux->func_info[subprog].type_id; 9511 if (!btf_id) 9512 return -EFAULT; 9513 9514 if (prog->aux->func_info_aux[subprog].unreliable) 9515 return -EINVAL; 9516 9517 err = btf_check_func_arg_match(env, subprog, btf, regs); 9518 /* Compiler optimizations can remove arguments from static functions 9519 * or mismatched type can be passed into a global function. 9520 * In such cases mark the function as unreliable from BTF point of view. 9521 */ 9522 if (err) 9523 prog->aux->func_info_aux[subprog].unreliable = true; 9524 return err; 9525 } 9526 9527 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9528 int insn_idx, int subprog, 9529 set_callee_state_fn set_callee_state_cb) 9530 { 9531 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9532 struct bpf_func_state *caller, *callee; 9533 int err; 9534 9535 caller = state->frame[state->curframe]; 9536 err = btf_check_subprog_call(env, subprog, caller->regs); 9537 if (err == -EFAULT) 9538 return err; 9539 9540 /* set_callee_state is used for direct subprog calls, but we are 9541 * interested in validating only BPF helpers that can call subprogs as 9542 * callbacks 9543 */ 9544 env->subprog_info[subprog].is_cb = true; 9545 if (bpf_pseudo_kfunc_call(insn) && 9546 !is_callback_calling_kfunc(insn->imm)) { 9547 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 9548 func_id_name(insn->imm), insn->imm); 9549 return -EFAULT; 9550 } else if (!bpf_pseudo_kfunc_call(insn) && 9551 !is_callback_calling_function(insn->imm)) { /* helper */ 9552 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 9553 func_id_name(insn->imm), insn->imm); 9554 return -EFAULT; 9555 } 9556 9557 if (is_async_callback_calling_insn(insn)) { 9558 struct bpf_verifier_state *async_cb; 9559 9560 /* there is no real recursion here. timer and workqueue callbacks are async */ 9561 env->subprog_info[subprog].is_async_cb = true; 9562 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9563 insn_idx, subprog, 9564 is_bpf_wq_set_callback_impl_kfunc(insn->imm)); 9565 if (!async_cb) 9566 return -EFAULT; 9567 callee = async_cb->frame[0]; 9568 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9569 9570 /* Convert bpf_timer_set_callback() args into timer callback args */ 9571 err = set_callee_state_cb(env, caller, callee, insn_idx); 9572 if (err) 9573 return err; 9574 9575 return 0; 9576 } 9577 9578 /* for callback functions enqueue entry to callback and 9579 * proceed with next instruction within current frame. 9580 */ 9581 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9582 if (!callback_state) 9583 return -ENOMEM; 9584 9585 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9586 callback_state); 9587 if (err) 9588 return err; 9589 9590 callback_state->callback_unroll_depth++; 9591 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9592 caller->callback_depth = 0; 9593 return 0; 9594 } 9595 9596 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9597 int *insn_idx) 9598 { 9599 struct bpf_verifier_state *state = env->cur_state; 9600 struct bpf_func_state *caller; 9601 int err, subprog, target_insn; 9602 9603 target_insn = *insn_idx + insn->imm + 1; 9604 subprog = find_subprog(env, target_insn); 9605 if (subprog < 0) { 9606 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn); 9607 return -EFAULT; 9608 } 9609 9610 caller = state->frame[state->curframe]; 9611 err = btf_check_subprog_call(env, subprog, caller->regs); 9612 if (err == -EFAULT) 9613 return err; 9614 if (subprog_is_global(env, subprog)) { 9615 const char *sub_name = subprog_name(env, subprog); 9616 9617 /* Only global subprogs cannot be called with a lock held. */ 9618 if (env->cur_state->active_lock.ptr) { 9619 verbose(env, "global function calls are not allowed while holding a lock,\n" 9620 "use static function instead\n"); 9621 return -EINVAL; 9622 } 9623 9624 /* Only global subprogs cannot be called with preemption disabled. */ 9625 if (env->cur_state->active_preempt_lock) { 9626 verbose(env, "global function calls are not allowed with preemption disabled,\n" 9627 "use static function instead\n"); 9628 return -EINVAL; 9629 } 9630 9631 if (err) { 9632 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 9633 subprog, sub_name); 9634 return err; 9635 } 9636 9637 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 9638 subprog, sub_name); 9639 /* mark global subprog for verifying after main prog */ 9640 subprog_aux(env, subprog)->called = true; 9641 clear_caller_saved_regs(env, caller->regs); 9642 9643 /* All global functions return a 64-bit SCALAR_VALUE */ 9644 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9645 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9646 9647 /* continue with next insn after call */ 9648 return 0; 9649 } 9650 9651 /* for regular function entry setup new frame and continue 9652 * from that frame. 9653 */ 9654 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9655 if (err) 9656 return err; 9657 9658 clear_caller_saved_regs(env, caller->regs); 9659 9660 /* and go analyze first insn of the callee */ 9661 *insn_idx = env->subprog_info[subprog].start - 1; 9662 9663 if (env->log.level & BPF_LOG_LEVEL) { 9664 verbose(env, "caller:\n"); 9665 print_verifier_state(env, caller, true); 9666 verbose(env, "callee:\n"); 9667 print_verifier_state(env, state->frame[state->curframe], true); 9668 } 9669 9670 return 0; 9671 } 9672 9673 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9674 struct bpf_func_state *caller, 9675 struct bpf_func_state *callee) 9676 { 9677 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9678 * void *callback_ctx, u64 flags); 9679 * callback_fn(struct bpf_map *map, void *key, void *value, 9680 * void *callback_ctx); 9681 */ 9682 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9683 9684 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9685 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9686 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9687 9688 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9689 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9690 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9691 9692 /* pointer to stack or null */ 9693 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9694 9695 /* unused */ 9696 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9697 return 0; 9698 } 9699 9700 static int set_callee_state(struct bpf_verifier_env *env, 9701 struct bpf_func_state *caller, 9702 struct bpf_func_state *callee, int insn_idx) 9703 { 9704 int i; 9705 9706 /* copy r1 - r5 args that callee can access. The copy includes parent 9707 * pointers, which connects us up to the liveness chain 9708 */ 9709 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9710 callee->regs[i] = caller->regs[i]; 9711 return 0; 9712 } 9713 9714 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9715 struct bpf_func_state *caller, 9716 struct bpf_func_state *callee, 9717 int insn_idx) 9718 { 9719 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9720 struct bpf_map *map; 9721 int err; 9722 9723 /* valid map_ptr and poison value does not matter */ 9724 map = insn_aux->map_ptr_state.map_ptr; 9725 if (!map->ops->map_set_for_each_callback_args || 9726 !map->ops->map_for_each_callback) { 9727 verbose(env, "callback function not allowed for map\n"); 9728 return -ENOTSUPP; 9729 } 9730 9731 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9732 if (err) 9733 return err; 9734 9735 callee->in_callback_fn = true; 9736 callee->callback_ret_range = retval_range(0, 1); 9737 return 0; 9738 } 9739 9740 static int set_loop_callback_state(struct bpf_verifier_env *env, 9741 struct bpf_func_state *caller, 9742 struct bpf_func_state *callee, 9743 int insn_idx) 9744 { 9745 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9746 * u64 flags); 9747 * callback_fn(u32 index, void *callback_ctx); 9748 */ 9749 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9750 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9751 9752 /* unused */ 9753 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9754 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9755 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9756 9757 callee->in_callback_fn = true; 9758 callee->callback_ret_range = retval_range(0, 1); 9759 return 0; 9760 } 9761 9762 static int set_timer_callback_state(struct bpf_verifier_env *env, 9763 struct bpf_func_state *caller, 9764 struct bpf_func_state *callee, 9765 int insn_idx) 9766 { 9767 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9768 9769 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9770 * callback_fn(struct bpf_map *map, void *key, void *value); 9771 */ 9772 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9773 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9774 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9775 9776 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9777 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9778 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9779 9780 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9781 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9782 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9783 9784 /* unused */ 9785 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9786 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9787 callee->in_async_callback_fn = true; 9788 callee->callback_ret_range = retval_range(0, 1); 9789 return 0; 9790 } 9791 9792 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9793 struct bpf_func_state *caller, 9794 struct bpf_func_state *callee, 9795 int insn_idx) 9796 { 9797 /* bpf_find_vma(struct task_struct *task, u64 addr, 9798 * void *callback_fn, void *callback_ctx, u64 flags) 9799 * (callback_fn)(struct task_struct *task, 9800 * struct vm_area_struct *vma, void *callback_ctx); 9801 */ 9802 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9803 9804 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9805 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9806 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9807 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 9808 9809 /* pointer to stack or null */ 9810 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9811 9812 /* unused */ 9813 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9814 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9815 callee->in_callback_fn = true; 9816 callee->callback_ret_range = retval_range(0, 1); 9817 return 0; 9818 } 9819 9820 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9821 struct bpf_func_state *caller, 9822 struct bpf_func_state *callee, 9823 int insn_idx) 9824 { 9825 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9826 * callback_ctx, u64 flags); 9827 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9828 */ 9829 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9830 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9831 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9832 9833 /* unused */ 9834 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9835 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9836 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9837 9838 callee->in_callback_fn = true; 9839 callee->callback_ret_range = retval_range(0, 1); 9840 return 0; 9841 } 9842 9843 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9844 struct bpf_func_state *caller, 9845 struct bpf_func_state *callee, 9846 int insn_idx) 9847 { 9848 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9849 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9850 * 9851 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9852 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9853 * by this point, so look at 'root' 9854 */ 9855 struct btf_field *field; 9856 9857 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 9858 BPF_RB_ROOT); 9859 if (!field || !field->graph_root.value_btf_id) 9860 return -EFAULT; 9861 9862 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9863 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9864 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9865 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9866 9867 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9868 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9869 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9870 callee->in_callback_fn = true; 9871 callee->callback_ret_range = retval_range(0, 1); 9872 return 0; 9873 } 9874 9875 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9876 9877 /* Are we currently verifying the callback for a rbtree helper that must 9878 * be called with lock held? If so, no need to complain about unreleased 9879 * lock 9880 */ 9881 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9882 { 9883 struct bpf_verifier_state *state = env->cur_state; 9884 struct bpf_insn *insn = env->prog->insnsi; 9885 struct bpf_func_state *callee; 9886 int kfunc_btf_id; 9887 9888 if (!state->curframe) 9889 return false; 9890 9891 callee = state->frame[state->curframe]; 9892 9893 if (!callee->in_callback_fn) 9894 return false; 9895 9896 kfunc_btf_id = insn[callee->callsite].imm; 9897 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9898 } 9899 9900 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg) 9901 { 9902 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval; 9903 } 9904 9905 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9906 { 9907 struct bpf_verifier_state *state = env->cur_state, *prev_st; 9908 struct bpf_func_state *caller, *callee; 9909 struct bpf_reg_state *r0; 9910 bool in_callback_fn; 9911 int err; 9912 9913 callee = state->frame[state->curframe]; 9914 r0 = &callee->regs[BPF_REG_0]; 9915 if (r0->type == PTR_TO_STACK) { 9916 /* technically it's ok to return caller's stack pointer 9917 * (or caller's caller's pointer) back to the caller, 9918 * since these pointers are valid. Only current stack 9919 * pointer will be invalid as soon as function exits, 9920 * but let's be conservative 9921 */ 9922 verbose(env, "cannot return stack pointer to the caller\n"); 9923 return -EINVAL; 9924 } 9925 9926 caller = state->frame[state->curframe - 1]; 9927 if (callee->in_callback_fn) { 9928 if (r0->type != SCALAR_VALUE) { 9929 verbose(env, "R0 not a scalar value\n"); 9930 return -EACCES; 9931 } 9932 9933 /* we are going to rely on register's precise value */ 9934 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64); 9935 err = err ?: mark_chain_precision(env, BPF_REG_0); 9936 if (err) 9937 return err; 9938 9939 /* enforce R0 return value range */ 9940 if (!retval_range_within(callee->callback_ret_range, r0)) { 9941 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 9942 "At callback return", "R0"); 9943 return -EINVAL; 9944 } 9945 if (!calls_callback(env, callee->callsite)) { 9946 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n", 9947 *insn_idx, callee->callsite); 9948 return -EFAULT; 9949 } 9950 } else { 9951 /* return to the caller whatever r0 had in the callee */ 9952 caller->regs[BPF_REG_0] = *r0; 9953 } 9954 9955 /* callback_fn frame should have released its own additions to parent's 9956 * reference state at this point, or check_reference_leak would 9957 * complain, hence it must be the same as the caller. There is no need 9958 * to copy it back. 9959 */ 9960 if (!callee->in_callback_fn) { 9961 /* Transfer references to the caller */ 9962 err = copy_reference_state(caller, callee); 9963 if (err) 9964 return err; 9965 } 9966 9967 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 9968 * there function call logic would reschedule callback visit. If iteration 9969 * converges is_state_visited() would prune that visit eventually. 9970 */ 9971 in_callback_fn = callee->in_callback_fn; 9972 if (in_callback_fn) 9973 *insn_idx = callee->callsite; 9974 else 9975 *insn_idx = callee->callsite + 1; 9976 9977 if (env->log.level & BPF_LOG_LEVEL) { 9978 verbose(env, "returning from callee:\n"); 9979 print_verifier_state(env, callee, true); 9980 verbose(env, "to caller at %d:\n", *insn_idx); 9981 print_verifier_state(env, caller, true); 9982 } 9983 /* clear everything in the callee. In case of exceptional exits using 9984 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 9985 free_func_state(callee); 9986 state->frame[state->curframe--] = NULL; 9987 9988 /* for callbacks widen imprecise scalars to make programs like below verify: 9989 * 9990 * struct ctx { int i; } 9991 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 9992 * ... 9993 * struct ctx = { .i = 0; } 9994 * bpf_loop(100, cb, &ctx, 0); 9995 * 9996 * This is similar to what is done in process_iter_next_call() for open 9997 * coded iterators. 9998 */ 9999 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 10000 if (prev_st) { 10001 err = widen_imprecise_scalars(env, prev_st, state); 10002 if (err) 10003 return err; 10004 } 10005 return 0; 10006 } 10007 10008 static int do_refine_retval_range(struct bpf_verifier_env *env, 10009 struct bpf_reg_state *regs, int ret_type, 10010 int func_id, 10011 struct bpf_call_arg_meta *meta) 10012 { 10013 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 10014 10015 if (ret_type != RET_INTEGER) 10016 return 0; 10017 10018 switch (func_id) { 10019 case BPF_FUNC_get_stack: 10020 case BPF_FUNC_get_task_stack: 10021 case BPF_FUNC_probe_read_str: 10022 case BPF_FUNC_probe_read_kernel_str: 10023 case BPF_FUNC_probe_read_user_str: 10024 ret_reg->smax_value = meta->msize_max_value; 10025 ret_reg->s32_max_value = meta->msize_max_value; 10026 ret_reg->smin_value = -MAX_ERRNO; 10027 ret_reg->s32_min_value = -MAX_ERRNO; 10028 reg_bounds_sync(ret_reg); 10029 break; 10030 case BPF_FUNC_get_smp_processor_id: 10031 ret_reg->umax_value = nr_cpu_ids - 1; 10032 ret_reg->u32_max_value = nr_cpu_ids - 1; 10033 ret_reg->smax_value = nr_cpu_ids - 1; 10034 ret_reg->s32_max_value = nr_cpu_ids - 1; 10035 ret_reg->umin_value = 0; 10036 ret_reg->u32_min_value = 0; 10037 ret_reg->smin_value = 0; 10038 ret_reg->s32_min_value = 0; 10039 reg_bounds_sync(ret_reg); 10040 break; 10041 } 10042 10043 return reg_bounds_sanity_check(env, ret_reg, "retval"); 10044 } 10045 10046 static int 10047 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 10048 int func_id, int insn_idx) 10049 { 10050 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 10051 struct bpf_map *map = meta->map_ptr; 10052 10053 if (func_id != BPF_FUNC_tail_call && 10054 func_id != BPF_FUNC_map_lookup_elem && 10055 func_id != BPF_FUNC_map_update_elem && 10056 func_id != BPF_FUNC_map_delete_elem && 10057 func_id != BPF_FUNC_map_push_elem && 10058 func_id != BPF_FUNC_map_pop_elem && 10059 func_id != BPF_FUNC_map_peek_elem && 10060 func_id != BPF_FUNC_for_each_map_elem && 10061 func_id != BPF_FUNC_redirect_map && 10062 func_id != BPF_FUNC_map_lookup_percpu_elem) 10063 return 0; 10064 10065 if (map == NULL) { 10066 verbose(env, "kernel subsystem misconfigured verifier\n"); 10067 return -EINVAL; 10068 } 10069 10070 /* In case of read-only, some additional restrictions 10071 * need to be applied in order to prevent altering the 10072 * state of the map from program side. 10073 */ 10074 if ((map->map_flags & BPF_F_RDONLY_PROG) && 10075 (func_id == BPF_FUNC_map_delete_elem || 10076 func_id == BPF_FUNC_map_update_elem || 10077 func_id == BPF_FUNC_map_push_elem || 10078 func_id == BPF_FUNC_map_pop_elem)) { 10079 verbose(env, "write into map forbidden\n"); 10080 return -EACCES; 10081 } 10082 10083 if (!aux->map_ptr_state.map_ptr) 10084 bpf_map_ptr_store(aux, meta->map_ptr, 10085 !meta->map_ptr->bypass_spec_v1, false); 10086 else if (aux->map_ptr_state.map_ptr != meta->map_ptr) 10087 bpf_map_ptr_store(aux, meta->map_ptr, 10088 !meta->map_ptr->bypass_spec_v1, true); 10089 return 0; 10090 } 10091 10092 static int 10093 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 10094 int func_id, int insn_idx) 10095 { 10096 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 10097 struct bpf_reg_state *regs = cur_regs(env), *reg; 10098 struct bpf_map *map = meta->map_ptr; 10099 u64 val, max; 10100 int err; 10101 10102 if (func_id != BPF_FUNC_tail_call) 10103 return 0; 10104 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 10105 verbose(env, "kernel subsystem misconfigured verifier\n"); 10106 return -EINVAL; 10107 } 10108 10109 reg = ®s[BPF_REG_3]; 10110 val = reg->var_off.value; 10111 max = map->max_entries; 10112 10113 if (!(is_reg_const(reg, false) && val < max)) { 10114 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 10115 return 0; 10116 } 10117 10118 err = mark_chain_precision(env, BPF_REG_3); 10119 if (err) 10120 return err; 10121 if (bpf_map_key_unseen(aux)) 10122 bpf_map_key_store(aux, val); 10123 else if (!bpf_map_key_poisoned(aux) && 10124 bpf_map_key_immediate(aux) != val) 10125 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 10126 return 0; 10127 } 10128 10129 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 10130 { 10131 struct bpf_func_state *state = cur_func(env); 10132 bool refs_lingering = false; 10133 int i; 10134 10135 if (!exception_exit && state->frameno && !state->in_callback_fn) 10136 return 0; 10137 10138 for (i = 0; i < state->acquired_refs; i++) { 10139 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 10140 continue; 10141 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 10142 state->refs[i].id, state->refs[i].insn_idx); 10143 refs_lingering = true; 10144 } 10145 return refs_lingering ? -EINVAL : 0; 10146 } 10147 10148 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 10149 struct bpf_reg_state *regs) 10150 { 10151 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 10152 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 10153 struct bpf_map *fmt_map = fmt_reg->map_ptr; 10154 struct bpf_bprintf_data data = {}; 10155 int err, fmt_map_off, num_args; 10156 u64 fmt_addr; 10157 char *fmt; 10158 10159 /* data must be an array of u64 */ 10160 if (data_len_reg->var_off.value % 8) 10161 return -EINVAL; 10162 num_args = data_len_reg->var_off.value / 8; 10163 10164 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 10165 * and map_direct_value_addr is set. 10166 */ 10167 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 10168 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 10169 fmt_map_off); 10170 if (err) { 10171 verbose(env, "verifier bug\n"); 10172 return -EFAULT; 10173 } 10174 fmt = (char *)(long)fmt_addr + fmt_map_off; 10175 10176 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 10177 * can focus on validating the format specifiers. 10178 */ 10179 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 10180 if (err < 0) 10181 verbose(env, "Invalid format string\n"); 10182 10183 return err; 10184 } 10185 10186 static int check_get_func_ip(struct bpf_verifier_env *env) 10187 { 10188 enum bpf_prog_type type = resolve_prog_type(env->prog); 10189 int func_id = BPF_FUNC_get_func_ip; 10190 10191 if (type == BPF_PROG_TYPE_TRACING) { 10192 if (!bpf_prog_has_trampoline(env->prog)) { 10193 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 10194 func_id_name(func_id), func_id); 10195 return -ENOTSUPP; 10196 } 10197 return 0; 10198 } else if (type == BPF_PROG_TYPE_KPROBE) { 10199 return 0; 10200 } 10201 10202 verbose(env, "func %s#%d not supported for program type %d\n", 10203 func_id_name(func_id), func_id, type); 10204 return -ENOTSUPP; 10205 } 10206 10207 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 10208 { 10209 return &env->insn_aux_data[env->insn_idx]; 10210 } 10211 10212 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 10213 { 10214 struct bpf_reg_state *regs = cur_regs(env); 10215 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 10216 bool reg_is_null = register_is_null(reg); 10217 10218 if (reg_is_null) 10219 mark_chain_precision(env, BPF_REG_4); 10220 10221 return reg_is_null; 10222 } 10223 10224 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 10225 { 10226 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 10227 10228 if (!state->initialized) { 10229 state->initialized = 1; 10230 state->fit_for_inline = loop_flag_is_zero(env); 10231 state->callback_subprogno = subprogno; 10232 return; 10233 } 10234 10235 if (!state->fit_for_inline) 10236 return; 10237 10238 state->fit_for_inline = (loop_flag_is_zero(env) && 10239 state->callback_subprogno == subprogno); 10240 } 10241 10242 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10243 int *insn_idx_p) 10244 { 10245 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 10246 bool returns_cpu_specific_alloc_ptr = false; 10247 const struct bpf_func_proto *fn = NULL; 10248 enum bpf_return_type ret_type; 10249 enum bpf_type_flag ret_flag; 10250 struct bpf_reg_state *regs; 10251 struct bpf_call_arg_meta meta; 10252 int insn_idx = *insn_idx_p; 10253 bool changes_data; 10254 int i, err, func_id; 10255 10256 /* find function prototype */ 10257 func_id = insn->imm; 10258 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 10259 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 10260 func_id); 10261 return -EINVAL; 10262 } 10263 10264 if (env->ops->get_func_proto) 10265 fn = env->ops->get_func_proto(func_id, env->prog); 10266 if (!fn) { 10267 verbose(env, "program of this type cannot use helper %s#%d\n", 10268 func_id_name(func_id), func_id); 10269 return -EINVAL; 10270 } 10271 10272 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 10273 if (!env->prog->gpl_compatible && fn->gpl_only) { 10274 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10275 return -EINVAL; 10276 } 10277 10278 if (fn->allowed && !fn->allowed(env->prog)) { 10279 verbose(env, "helper call is not allowed in probe\n"); 10280 return -EINVAL; 10281 } 10282 10283 if (!in_sleepable(env) && fn->might_sleep) { 10284 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 10285 return -EINVAL; 10286 } 10287 10288 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10289 changes_data = bpf_helper_changes_pkt_data(fn->func); 10290 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10291 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 10292 func_id_name(func_id), func_id); 10293 return -EINVAL; 10294 } 10295 10296 memset(&meta, 0, sizeof(meta)); 10297 meta.pkt_access = fn->pkt_access; 10298 10299 err = check_func_proto(fn, func_id); 10300 if (err) { 10301 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 10302 func_id_name(func_id), func_id); 10303 return err; 10304 } 10305 10306 if (env->cur_state->active_rcu_lock) { 10307 if (fn->might_sleep) { 10308 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 10309 func_id_name(func_id), func_id); 10310 return -EINVAL; 10311 } 10312 10313 if (in_sleepable(env) && is_storage_get_function(func_id)) 10314 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10315 } 10316 10317 if (env->cur_state->active_preempt_lock) { 10318 if (fn->might_sleep) { 10319 verbose(env, "sleepable helper %s#%d in non-preemptible region\n", 10320 func_id_name(func_id), func_id); 10321 return -EINVAL; 10322 } 10323 10324 if (in_sleepable(env) && is_storage_get_function(func_id)) 10325 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10326 } 10327 10328 meta.func_id = func_id; 10329 /* check args */ 10330 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10331 err = check_func_arg(env, i, &meta, fn, insn_idx); 10332 if (err) 10333 return err; 10334 } 10335 10336 err = record_func_map(env, &meta, func_id, insn_idx); 10337 if (err) 10338 return err; 10339 10340 err = record_func_key(env, &meta, func_id, insn_idx); 10341 if (err) 10342 return err; 10343 10344 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10345 * is inferred from register state. 10346 */ 10347 for (i = 0; i < meta.access_size; i++) { 10348 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 10349 BPF_WRITE, -1, false, false); 10350 if (err) 10351 return err; 10352 } 10353 10354 regs = cur_regs(env); 10355 10356 if (meta.release_regno) { 10357 err = -EINVAL; 10358 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 10359 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 10360 * is safe to do directly. 10361 */ 10362 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 10363 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 10364 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 10365 return -EFAULT; 10366 } 10367 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 10368 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 10369 u32 ref_obj_id = meta.ref_obj_id; 10370 bool in_rcu = in_rcu_cs(env); 10371 struct bpf_func_state *state; 10372 struct bpf_reg_state *reg; 10373 10374 err = release_reference_state(cur_func(env), ref_obj_id); 10375 if (!err) { 10376 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10377 if (reg->ref_obj_id == ref_obj_id) { 10378 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 10379 reg->ref_obj_id = 0; 10380 reg->type &= ~MEM_ALLOC; 10381 reg->type |= MEM_RCU; 10382 } else { 10383 mark_reg_invalid(env, reg); 10384 } 10385 } 10386 })); 10387 } 10388 } else if (meta.ref_obj_id) { 10389 err = release_reference(env, meta.ref_obj_id); 10390 } else if (register_is_null(®s[meta.release_regno])) { 10391 /* meta.ref_obj_id can only be 0 if register that is meant to be 10392 * released is NULL, which must be > R0. 10393 */ 10394 err = 0; 10395 } 10396 if (err) { 10397 verbose(env, "func %s#%d reference has not been acquired before\n", 10398 func_id_name(func_id), func_id); 10399 return err; 10400 } 10401 } 10402 10403 switch (func_id) { 10404 case BPF_FUNC_tail_call: 10405 err = check_reference_leak(env, false); 10406 if (err) { 10407 verbose(env, "tail_call would lead to reference leak\n"); 10408 return err; 10409 } 10410 break; 10411 case BPF_FUNC_get_local_storage: 10412 /* check that flags argument in get_local_storage(map, flags) is 0, 10413 * this is required because get_local_storage() can't return an error. 10414 */ 10415 if (!register_is_null(®s[BPF_REG_2])) { 10416 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10417 return -EINVAL; 10418 } 10419 break; 10420 case BPF_FUNC_for_each_map_elem: 10421 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10422 set_map_elem_callback_state); 10423 break; 10424 case BPF_FUNC_timer_set_callback: 10425 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10426 set_timer_callback_state); 10427 break; 10428 case BPF_FUNC_find_vma: 10429 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10430 set_find_vma_callback_state); 10431 break; 10432 case BPF_FUNC_snprintf: 10433 err = check_bpf_snprintf_call(env, regs); 10434 break; 10435 case BPF_FUNC_loop: 10436 update_loop_inline_state(env, meta.subprogno); 10437 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10438 * is finished, thus mark it precise. 10439 */ 10440 err = mark_chain_precision(env, BPF_REG_1); 10441 if (err) 10442 return err; 10443 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) { 10444 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10445 set_loop_callback_state); 10446 } else { 10447 cur_func(env)->callback_depth = 0; 10448 if (env->log.level & BPF_LOG_LEVEL2) 10449 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10450 env->cur_state->curframe); 10451 } 10452 break; 10453 case BPF_FUNC_dynptr_from_mem: 10454 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10455 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10456 reg_type_str(env, regs[BPF_REG_1].type)); 10457 return -EACCES; 10458 } 10459 break; 10460 case BPF_FUNC_set_retval: 10461 if (prog_type == BPF_PROG_TYPE_LSM && 10462 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10463 if (!env->prog->aux->attach_func_proto->type) { 10464 /* Make sure programs that attach to void 10465 * hooks don't try to modify return value. 10466 */ 10467 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10468 return -EINVAL; 10469 } 10470 } 10471 break; 10472 case BPF_FUNC_dynptr_data: 10473 { 10474 struct bpf_reg_state *reg; 10475 int id, ref_obj_id; 10476 10477 reg = get_dynptr_arg_reg(env, fn, regs); 10478 if (!reg) 10479 return -EFAULT; 10480 10481 10482 if (meta.dynptr_id) { 10483 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 10484 return -EFAULT; 10485 } 10486 if (meta.ref_obj_id) { 10487 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 10488 return -EFAULT; 10489 } 10490 10491 id = dynptr_id(env, reg); 10492 if (id < 0) { 10493 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 10494 return id; 10495 } 10496 10497 ref_obj_id = dynptr_ref_obj_id(env, reg); 10498 if (ref_obj_id < 0) { 10499 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 10500 return ref_obj_id; 10501 } 10502 10503 meta.dynptr_id = id; 10504 meta.ref_obj_id = ref_obj_id; 10505 10506 break; 10507 } 10508 case BPF_FUNC_dynptr_write: 10509 { 10510 enum bpf_dynptr_type dynptr_type; 10511 struct bpf_reg_state *reg; 10512 10513 reg = get_dynptr_arg_reg(env, fn, regs); 10514 if (!reg) 10515 return -EFAULT; 10516 10517 dynptr_type = dynptr_get_type(env, reg); 10518 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10519 return -EFAULT; 10520 10521 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 10522 /* this will trigger clear_all_pkt_pointers(), which will 10523 * invalidate all dynptr slices associated with the skb 10524 */ 10525 changes_data = true; 10526 10527 break; 10528 } 10529 case BPF_FUNC_per_cpu_ptr: 10530 case BPF_FUNC_this_cpu_ptr: 10531 { 10532 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 10533 const struct btf_type *type; 10534 10535 if (reg->type & MEM_RCU) { 10536 type = btf_type_by_id(reg->btf, reg->btf_id); 10537 if (!type || !btf_type_is_struct(type)) { 10538 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 10539 return -EFAULT; 10540 } 10541 returns_cpu_specific_alloc_ptr = true; 10542 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 10543 } 10544 break; 10545 } 10546 case BPF_FUNC_user_ringbuf_drain: 10547 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10548 set_user_ringbuf_callback_state); 10549 break; 10550 } 10551 10552 if (err) 10553 return err; 10554 10555 /* reset caller saved regs */ 10556 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10557 mark_reg_not_init(env, regs, caller_saved[i]); 10558 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10559 } 10560 10561 /* helper call returns 64-bit value. */ 10562 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10563 10564 /* update return register (already marked as written above) */ 10565 ret_type = fn->ret_type; 10566 ret_flag = type_flag(ret_type); 10567 10568 switch (base_type(ret_type)) { 10569 case RET_INTEGER: 10570 /* sets type to SCALAR_VALUE */ 10571 mark_reg_unknown(env, regs, BPF_REG_0); 10572 break; 10573 case RET_VOID: 10574 regs[BPF_REG_0].type = NOT_INIT; 10575 break; 10576 case RET_PTR_TO_MAP_VALUE: 10577 /* There is no offset yet applied, variable or fixed */ 10578 mark_reg_known_zero(env, regs, BPF_REG_0); 10579 /* remember map_ptr, so that check_map_access() 10580 * can check 'value_size' boundary of memory access 10581 * to map element returned from bpf_map_lookup_elem() 10582 */ 10583 if (meta.map_ptr == NULL) { 10584 verbose(env, 10585 "kernel subsystem misconfigured verifier\n"); 10586 return -EINVAL; 10587 } 10588 regs[BPF_REG_0].map_ptr = meta.map_ptr; 10589 regs[BPF_REG_0].map_uid = meta.map_uid; 10590 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10591 if (!type_may_be_null(ret_type) && 10592 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 10593 regs[BPF_REG_0].id = ++env->id_gen; 10594 } 10595 break; 10596 case RET_PTR_TO_SOCKET: 10597 mark_reg_known_zero(env, regs, BPF_REG_0); 10598 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10599 break; 10600 case RET_PTR_TO_SOCK_COMMON: 10601 mark_reg_known_zero(env, regs, BPF_REG_0); 10602 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10603 break; 10604 case RET_PTR_TO_TCP_SOCK: 10605 mark_reg_known_zero(env, regs, BPF_REG_0); 10606 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10607 break; 10608 case RET_PTR_TO_MEM: 10609 mark_reg_known_zero(env, regs, BPF_REG_0); 10610 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10611 regs[BPF_REG_0].mem_size = meta.mem_size; 10612 break; 10613 case RET_PTR_TO_MEM_OR_BTF_ID: 10614 { 10615 const struct btf_type *t; 10616 10617 mark_reg_known_zero(env, regs, BPF_REG_0); 10618 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10619 if (!btf_type_is_struct(t)) { 10620 u32 tsize; 10621 const struct btf_type *ret; 10622 const char *tname; 10623 10624 /* resolve the type size of ksym. */ 10625 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10626 if (IS_ERR(ret)) { 10627 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10628 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10629 tname, PTR_ERR(ret)); 10630 return -EINVAL; 10631 } 10632 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10633 regs[BPF_REG_0].mem_size = tsize; 10634 } else { 10635 if (returns_cpu_specific_alloc_ptr) { 10636 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10637 } else { 10638 /* MEM_RDONLY may be carried from ret_flag, but it 10639 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10640 * it will confuse the check of PTR_TO_BTF_ID in 10641 * check_mem_access(). 10642 */ 10643 ret_flag &= ~MEM_RDONLY; 10644 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10645 } 10646 10647 regs[BPF_REG_0].btf = meta.ret_btf; 10648 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10649 } 10650 break; 10651 } 10652 case RET_PTR_TO_BTF_ID: 10653 { 10654 struct btf *ret_btf; 10655 int ret_btf_id; 10656 10657 mark_reg_known_zero(env, regs, BPF_REG_0); 10658 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10659 if (func_id == BPF_FUNC_kptr_xchg) { 10660 ret_btf = meta.kptr_field->kptr.btf; 10661 ret_btf_id = meta.kptr_field->kptr.btf_id; 10662 if (!btf_is_kernel(ret_btf)) { 10663 regs[BPF_REG_0].type |= MEM_ALLOC; 10664 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10665 regs[BPF_REG_0].type |= MEM_PERCPU; 10666 } 10667 } else { 10668 if (fn->ret_btf_id == BPF_PTR_POISON) { 10669 verbose(env, "verifier internal error:"); 10670 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 10671 func_id_name(func_id)); 10672 return -EINVAL; 10673 } 10674 ret_btf = btf_vmlinux; 10675 ret_btf_id = *fn->ret_btf_id; 10676 } 10677 if (ret_btf_id == 0) { 10678 verbose(env, "invalid return type %u of func %s#%d\n", 10679 base_type(ret_type), func_id_name(func_id), 10680 func_id); 10681 return -EINVAL; 10682 } 10683 regs[BPF_REG_0].btf = ret_btf; 10684 regs[BPF_REG_0].btf_id = ret_btf_id; 10685 break; 10686 } 10687 default: 10688 verbose(env, "unknown return type %u of func %s#%d\n", 10689 base_type(ret_type), func_id_name(func_id), func_id); 10690 return -EINVAL; 10691 } 10692 10693 if (type_may_be_null(regs[BPF_REG_0].type)) 10694 regs[BPF_REG_0].id = ++env->id_gen; 10695 10696 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 10697 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 10698 func_id_name(func_id), func_id); 10699 return -EFAULT; 10700 } 10701 10702 if (is_dynptr_ref_function(func_id)) 10703 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 10704 10705 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 10706 /* For release_reference() */ 10707 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10708 } else if (is_acquire_function(func_id, meta.map_ptr)) { 10709 int id = acquire_reference_state(env, insn_idx); 10710 10711 if (id < 0) 10712 return id; 10713 /* For mark_ptr_or_null_reg() */ 10714 regs[BPF_REG_0].id = id; 10715 /* For release_reference() */ 10716 regs[BPF_REG_0].ref_obj_id = id; 10717 } 10718 10719 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 10720 if (err) 10721 return err; 10722 10723 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 10724 if (err) 10725 return err; 10726 10727 if ((func_id == BPF_FUNC_get_stack || 10728 func_id == BPF_FUNC_get_task_stack) && 10729 !env->prog->has_callchain_buf) { 10730 const char *err_str; 10731 10732 #ifdef CONFIG_PERF_EVENTS 10733 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10734 err_str = "cannot get callchain buffer for func %s#%d\n"; 10735 #else 10736 err = -ENOTSUPP; 10737 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10738 #endif 10739 if (err) { 10740 verbose(env, err_str, func_id_name(func_id), func_id); 10741 return err; 10742 } 10743 10744 env->prog->has_callchain_buf = true; 10745 } 10746 10747 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10748 env->prog->call_get_stack = true; 10749 10750 if (func_id == BPF_FUNC_get_func_ip) { 10751 if (check_get_func_ip(env)) 10752 return -ENOTSUPP; 10753 env->prog->call_get_func_ip = true; 10754 } 10755 10756 if (changes_data) 10757 clear_all_pkt_pointers(env); 10758 return 0; 10759 } 10760 10761 /* mark_btf_func_reg_size() is used when the reg size is determined by 10762 * the BTF func_proto's return value size and argument. 10763 */ 10764 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10765 size_t reg_size) 10766 { 10767 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 10768 10769 if (regno == BPF_REG_0) { 10770 /* Function return value */ 10771 reg->live |= REG_LIVE_WRITTEN; 10772 reg->subreg_def = reg_size == sizeof(u64) ? 10773 DEF_NOT_SUBREG : env->insn_idx + 1; 10774 } else { 10775 /* Function argument */ 10776 if (reg_size == sizeof(u64)) { 10777 mark_insn_zext(env, reg); 10778 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 10779 } else { 10780 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 10781 } 10782 } 10783 } 10784 10785 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10786 { 10787 return meta->kfunc_flags & KF_ACQUIRE; 10788 } 10789 10790 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10791 { 10792 return meta->kfunc_flags & KF_RELEASE; 10793 } 10794 10795 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 10796 { 10797 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 10798 } 10799 10800 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 10801 { 10802 return meta->kfunc_flags & KF_SLEEPABLE; 10803 } 10804 10805 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10806 { 10807 return meta->kfunc_flags & KF_DESTRUCTIVE; 10808 } 10809 10810 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10811 { 10812 return meta->kfunc_flags & KF_RCU; 10813 } 10814 10815 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 10816 { 10817 return meta->kfunc_flags & KF_RCU_PROTECTED; 10818 } 10819 10820 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10821 const struct btf_param *arg, 10822 const struct bpf_reg_state *reg) 10823 { 10824 const struct btf_type *t; 10825 10826 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10827 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10828 return false; 10829 10830 return btf_param_match_suffix(btf, arg, "__sz"); 10831 } 10832 10833 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10834 const struct btf_param *arg, 10835 const struct bpf_reg_state *reg) 10836 { 10837 const struct btf_type *t; 10838 10839 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10840 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10841 return false; 10842 10843 return btf_param_match_suffix(btf, arg, "__szk"); 10844 } 10845 10846 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 10847 { 10848 return btf_param_match_suffix(btf, arg, "__opt"); 10849 } 10850 10851 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10852 { 10853 return btf_param_match_suffix(btf, arg, "__k"); 10854 } 10855 10856 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10857 { 10858 return btf_param_match_suffix(btf, arg, "__ign"); 10859 } 10860 10861 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg) 10862 { 10863 return btf_param_match_suffix(btf, arg, "__map"); 10864 } 10865 10866 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10867 { 10868 return btf_param_match_suffix(btf, arg, "__alloc"); 10869 } 10870 10871 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10872 { 10873 return btf_param_match_suffix(btf, arg, "__uninit"); 10874 } 10875 10876 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10877 { 10878 return btf_param_match_suffix(btf, arg, "__refcounted_kptr"); 10879 } 10880 10881 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 10882 { 10883 return btf_param_match_suffix(btf, arg, "__nullable"); 10884 } 10885 10886 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 10887 { 10888 return btf_param_match_suffix(btf, arg, "__str"); 10889 } 10890 10891 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10892 const struct btf_param *arg, 10893 const char *name) 10894 { 10895 int len, target_len = strlen(name); 10896 const char *param_name; 10897 10898 param_name = btf_name_by_offset(btf, arg->name_off); 10899 if (str_is_empty(param_name)) 10900 return false; 10901 len = strlen(param_name); 10902 if (len != target_len) 10903 return false; 10904 if (strcmp(param_name, name)) 10905 return false; 10906 10907 return true; 10908 } 10909 10910 enum { 10911 KF_ARG_DYNPTR_ID, 10912 KF_ARG_LIST_HEAD_ID, 10913 KF_ARG_LIST_NODE_ID, 10914 KF_ARG_RB_ROOT_ID, 10915 KF_ARG_RB_NODE_ID, 10916 KF_ARG_WORKQUEUE_ID, 10917 }; 10918 10919 BTF_ID_LIST(kf_arg_btf_ids) 10920 BTF_ID(struct, bpf_dynptr_kern) 10921 BTF_ID(struct, bpf_list_head) 10922 BTF_ID(struct, bpf_list_node) 10923 BTF_ID(struct, bpf_rb_root) 10924 BTF_ID(struct, bpf_rb_node) 10925 BTF_ID(struct, bpf_wq) 10926 10927 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10928 const struct btf_param *arg, int type) 10929 { 10930 const struct btf_type *t; 10931 u32 res_id; 10932 10933 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10934 if (!t) 10935 return false; 10936 if (!btf_type_is_ptr(t)) 10937 return false; 10938 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10939 if (!t) 10940 return false; 10941 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10942 } 10943 10944 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10945 { 10946 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10947 } 10948 10949 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10950 { 10951 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10952 } 10953 10954 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10955 { 10956 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10957 } 10958 10959 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10960 { 10961 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10962 } 10963 10964 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10965 { 10966 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10967 } 10968 10969 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg) 10970 { 10971 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID); 10972 } 10973 10974 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10975 const struct btf_param *arg) 10976 { 10977 const struct btf_type *t; 10978 10979 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10980 if (!t) 10981 return false; 10982 10983 return true; 10984 } 10985 10986 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10987 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10988 const struct btf *btf, 10989 const struct btf_type *t, int rec) 10990 { 10991 const struct btf_type *member_type; 10992 const struct btf_member *member; 10993 u32 i; 10994 10995 if (!btf_type_is_struct(t)) 10996 return false; 10997 10998 for_each_member(i, t, member) { 10999 const struct btf_array *array; 11000 11001 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 11002 if (btf_type_is_struct(member_type)) { 11003 if (rec >= 3) { 11004 verbose(env, "max struct nesting depth exceeded\n"); 11005 return false; 11006 } 11007 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 11008 return false; 11009 continue; 11010 } 11011 if (btf_type_is_array(member_type)) { 11012 array = btf_array(member_type); 11013 if (!array->nelems) 11014 return false; 11015 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 11016 if (!btf_type_is_scalar(member_type)) 11017 return false; 11018 continue; 11019 } 11020 if (!btf_type_is_scalar(member_type)) 11021 return false; 11022 } 11023 return true; 11024 } 11025 11026 enum kfunc_ptr_arg_type { 11027 KF_ARG_PTR_TO_CTX, 11028 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 11029 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 11030 KF_ARG_PTR_TO_DYNPTR, 11031 KF_ARG_PTR_TO_ITER, 11032 KF_ARG_PTR_TO_LIST_HEAD, 11033 KF_ARG_PTR_TO_LIST_NODE, 11034 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 11035 KF_ARG_PTR_TO_MEM, 11036 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 11037 KF_ARG_PTR_TO_CALLBACK, 11038 KF_ARG_PTR_TO_RB_ROOT, 11039 KF_ARG_PTR_TO_RB_NODE, 11040 KF_ARG_PTR_TO_NULL, 11041 KF_ARG_PTR_TO_CONST_STR, 11042 KF_ARG_PTR_TO_MAP, 11043 KF_ARG_PTR_TO_WORKQUEUE, 11044 }; 11045 11046 enum special_kfunc_type { 11047 KF_bpf_obj_new_impl, 11048 KF_bpf_obj_drop_impl, 11049 KF_bpf_refcount_acquire_impl, 11050 KF_bpf_list_push_front_impl, 11051 KF_bpf_list_push_back_impl, 11052 KF_bpf_list_pop_front, 11053 KF_bpf_list_pop_back, 11054 KF_bpf_cast_to_kern_ctx, 11055 KF_bpf_rdonly_cast, 11056 KF_bpf_rcu_read_lock, 11057 KF_bpf_rcu_read_unlock, 11058 KF_bpf_rbtree_remove, 11059 KF_bpf_rbtree_add_impl, 11060 KF_bpf_rbtree_first, 11061 KF_bpf_dynptr_from_skb, 11062 KF_bpf_dynptr_from_xdp, 11063 KF_bpf_dynptr_slice, 11064 KF_bpf_dynptr_slice_rdwr, 11065 KF_bpf_dynptr_clone, 11066 KF_bpf_percpu_obj_new_impl, 11067 KF_bpf_percpu_obj_drop_impl, 11068 KF_bpf_throw, 11069 KF_bpf_wq_set_callback_impl, 11070 KF_bpf_preempt_disable, 11071 KF_bpf_preempt_enable, 11072 KF_bpf_iter_css_task_new, 11073 KF_bpf_session_cookie, 11074 }; 11075 11076 BTF_SET_START(special_kfunc_set) 11077 BTF_ID(func, bpf_obj_new_impl) 11078 BTF_ID(func, bpf_obj_drop_impl) 11079 BTF_ID(func, bpf_refcount_acquire_impl) 11080 BTF_ID(func, bpf_list_push_front_impl) 11081 BTF_ID(func, bpf_list_push_back_impl) 11082 BTF_ID(func, bpf_list_pop_front) 11083 BTF_ID(func, bpf_list_pop_back) 11084 BTF_ID(func, bpf_cast_to_kern_ctx) 11085 BTF_ID(func, bpf_rdonly_cast) 11086 BTF_ID(func, bpf_rbtree_remove) 11087 BTF_ID(func, bpf_rbtree_add_impl) 11088 BTF_ID(func, bpf_rbtree_first) 11089 BTF_ID(func, bpf_dynptr_from_skb) 11090 BTF_ID(func, bpf_dynptr_from_xdp) 11091 BTF_ID(func, bpf_dynptr_slice) 11092 BTF_ID(func, bpf_dynptr_slice_rdwr) 11093 BTF_ID(func, bpf_dynptr_clone) 11094 BTF_ID(func, bpf_percpu_obj_new_impl) 11095 BTF_ID(func, bpf_percpu_obj_drop_impl) 11096 BTF_ID(func, bpf_throw) 11097 BTF_ID(func, bpf_wq_set_callback_impl) 11098 #ifdef CONFIG_CGROUPS 11099 BTF_ID(func, bpf_iter_css_task_new) 11100 #endif 11101 BTF_SET_END(special_kfunc_set) 11102 11103 BTF_ID_LIST(special_kfunc_list) 11104 BTF_ID(func, bpf_obj_new_impl) 11105 BTF_ID(func, bpf_obj_drop_impl) 11106 BTF_ID(func, bpf_refcount_acquire_impl) 11107 BTF_ID(func, bpf_list_push_front_impl) 11108 BTF_ID(func, bpf_list_push_back_impl) 11109 BTF_ID(func, bpf_list_pop_front) 11110 BTF_ID(func, bpf_list_pop_back) 11111 BTF_ID(func, bpf_cast_to_kern_ctx) 11112 BTF_ID(func, bpf_rdonly_cast) 11113 BTF_ID(func, bpf_rcu_read_lock) 11114 BTF_ID(func, bpf_rcu_read_unlock) 11115 BTF_ID(func, bpf_rbtree_remove) 11116 BTF_ID(func, bpf_rbtree_add_impl) 11117 BTF_ID(func, bpf_rbtree_first) 11118 BTF_ID(func, bpf_dynptr_from_skb) 11119 BTF_ID(func, bpf_dynptr_from_xdp) 11120 BTF_ID(func, bpf_dynptr_slice) 11121 BTF_ID(func, bpf_dynptr_slice_rdwr) 11122 BTF_ID(func, bpf_dynptr_clone) 11123 BTF_ID(func, bpf_percpu_obj_new_impl) 11124 BTF_ID(func, bpf_percpu_obj_drop_impl) 11125 BTF_ID(func, bpf_throw) 11126 BTF_ID(func, bpf_wq_set_callback_impl) 11127 BTF_ID(func, bpf_preempt_disable) 11128 BTF_ID(func, bpf_preempt_enable) 11129 #ifdef CONFIG_CGROUPS 11130 BTF_ID(func, bpf_iter_css_task_new) 11131 #else 11132 BTF_ID_UNUSED 11133 #endif 11134 #ifdef CONFIG_BPF_EVENTS 11135 BTF_ID(func, bpf_session_cookie) 11136 #else 11137 BTF_ID_UNUSED 11138 #endif 11139 11140 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 11141 { 11142 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 11143 meta->arg_owning_ref) { 11144 return false; 11145 } 11146 11147 return meta->kfunc_flags & KF_RET_NULL; 11148 } 11149 11150 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 11151 { 11152 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 11153 } 11154 11155 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 11156 { 11157 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 11158 } 11159 11160 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta) 11161 { 11162 return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable]; 11163 } 11164 11165 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta) 11166 { 11167 return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable]; 11168 } 11169 11170 static enum kfunc_ptr_arg_type 11171 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 11172 struct bpf_kfunc_call_arg_meta *meta, 11173 const struct btf_type *t, const struct btf_type *ref_t, 11174 const char *ref_tname, const struct btf_param *args, 11175 int argno, int nargs) 11176 { 11177 u32 regno = argno + 1; 11178 struct bpf_reg_state *regs = cur_regs(env); 11179 struct bpf_reg_state *reg = ®s[regno]; 11180 bool arg_mem_size = false; 11181 11182 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 11183 return KF_ARG_PTR_TO_CTX; 11184 11185 /* In this function, we verify the kfunc's BTF as per the argument type, 11186 * leaving the rest of the verification with respect to the register 11187 * type to our caller. When a set of conditions hold in the BTF type of 11188 * arguments, we resolve it to a known kfunc_ptr_arg_type. 11189 */ 11190 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 11191 return KF_ARG_PTR_TO_CTX; 11192 11193 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 11194 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 11195 11196 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 11197 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 11198 11199 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 11200 return KF_ARG_PTR_TO_DYNPTR; 11201 11202 if (is_kfunc_arg_iter(meta, argno)) 11203 return KF_ARG_PTR_TO_ITER; 11204 11205 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 11206 return KF_ARG_PTR_TO_LIST_HEAD; 11207 11208 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 11209 return KF_ARG_PTR_TO_LIST_NODE; 11210 11211 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 11212 return KF_ARG_PTR_TO_RB_ROOT; 11213 11214 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 11215 return KF_ARG_PTR_TO_RB_NODE; 11216 11217 if (is_kfunc_arg_const_str(meta->btf, &args[argno])) 11218 return KF_ARG_PTR_TO_CONST_STR; 11219 11220 if (is_kfunc_arg_map(meta->btf, &args[argno])) 11221 return KF_ARG_PTR_TO_MAP; 11222 11223 if (is_kfunc_arg_wq(meta->btf, &args[argno])) 11224 return KF_ARG_PTR_TO_WORKQUEUE; 11225 11226 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 11227 if (!btf_type_is_struct(ref_t)) { 11228 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 11229 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 11230 return -EINVAL; 11231 } 11232 return KF_ARG_PTR_TO_BTF_ID; 11233 } 11234 11235 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 11236 return KF_ARG_PTR_TO_CALLBACK; 11237 11238 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg)) 11239 return KF_ARG_PTR_TO_NULL; 11240 11241 if (argno + 1 < nargs && 11242 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 11243 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 11244 arg_mem_size = true; 11245 11246 /* This is the catch all argument type of register types supported by 11247 * check_helper_mem_access. However, we only allow when argument type is 11248 * pointer to scalar, or struct composed (recursively) of scalars. When 11249 * arg_mem_size is true, the pointer can be void *. 11250 */ 11251 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 11252 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 11253 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 11254 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 11255 return -EINVAL; 11256 } 11257 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 11258 } 11259 11260 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 11261 struct bpf_reg_state *reg, 11262 const struct btf_type *ref_t, 11263 const char *ref_tname, u32 ref_id, 11264 struct bpf_kfunc_call_arg_meta *meta, 11265 int argno) 11266 { 11267 const struct btf_type *reg_ref_t; 11268 bool strict_type_match = false; 11269 const struct btf *reg_btf; 11270 const char *reg_ref_tname; 11271 u32 reg_ref_id; 11272 11273 if (base_type(reg->type) == PTR_TO_BTF_ID) { 11274 reg_btf = reg->btf; 11275 reg_ref_id = reg->btf_id; 11276 } else { 11277 reg_btf = btf_vmlinux; 11278 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 11279 } 11280 11281 /* Enforce strict type matching for calls to kfuncs that are acquiring 11282 * or releasing a reference, or are no-cast aliases. We do _not_ 11283 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 11284 * as we want to enable BPF programs to pass types that are bitwise 11285 * equivalent without forcing them to explicitly cast with something 11286 * like bpf_cast_to_kern_ctx(). 11287 * 11288 * For example, say we had a type like the following: 11289 * 11290 * struct bpf_cpumask { 11291 * cpumask_t cpumask; 11292 * refcount_t usage; 11293 * }; 11294 * 11295 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 11296 * to a struct cpumask, so it would be safe to pass a struct 11297 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 11298 * 11299 * The philosophy here is similar to how we allow scalars of different 11300 * types to be passed to kfuncs as long as the size is the same. The 11301 * only difference here is that we're simply allowing 11302 * btf_struct_ids_match() to walk the struct at the 0th offset, and 11303 * resolve types. 11304 */ 11305 if (is_kfunc_acquire(meta) || 11306 (is_kfunc_release(meta) && reg->ref_obj_id) || 11307 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 11308 strict_type_match = true; 11309 11310 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 11311 11312 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 11313 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 11314 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 11315 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 11316 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 11317 btf_type_str(reg_ref_t), reg_ref_tname); 11318 return -EINVAL; 11319 } 11320 return 0; 11321 } 11322 11323 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11324 { 11325 struct bpf_verifier_state *state = env->cur_state; 11326 struct btf_record *rec = reg_btf_record(reg); 11327 11328 if (!state->active_lock.ptr) { 11329 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 11330 return -EFAULT; 11331 } 11332 11333 if (type_flag(reg->type) & NON_OWN_REF) { 11334 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 11335 return -EFAULT; 11336 } 11337 11338 reg->type |= NON_OWN_REF; 11339 if (rec->refcount_off >= 0) 11340 reg->type |= MEM_RCU; 11341 11342 return 0; 11343 } 11344 11345 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 11346 { 11347 struct bpf_func_state *state, *unused; 11348 struct bpf_reg_state *reg; 11349 int i; 11350 11351 state = cur_func(env); 11352 11353 if (!ref_obj_id) { 11354 verbose(env, "verifier internal error: ref_obj_id is zero for " 11355 "owning -> non-owning conversion\n"); 11356 return -EFAULT; 11357 } 11358 11359 for (i = 0; i < state->acquired_refs; i++) { 11360 if (state->refs[i].id != ref_obj_id) 11361 continue; 11362 11363 /* Clear ref_obj_id here so release_reference doesn't clobber 11364 * the whole reg 11365 */ 11366 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11367 if (reg->ref_obj_id == ref_obj_id) { 11368 reg->ref_obj_id = 0; 11369 ref_set_non_owning(env, reg); 11370 } 11371 })); 11372 return 0; 11373 } 11374 11375 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 11376 return -EFAULT; 11377 } 11378 11379 /* Implementation details: 11380 * 11381 * Each register points to some region of memory, which we define as an 11382 * allocation. Each allocation may embed a bpf_spin_lock which protects any 11383 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 11384 * allocation. The lock and the data it protects are colocated in the same 11385 * memory region. 11386 * 11387 * Hence, everytime a register holds a pointer value pointing to such 11388 * allocation, the verifier preserves a unique reg->id for it. 11389 * 11390 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 11391 * bpf_spin_lock is called. 11392 * 11393 * To enable this, lock state in the verifier captures two values: 11394 * active_lock.ptr = Register's type specific pointer 11395 * active_lock.id = A unique ID for each register pointer value 11396 * 11397 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11398 * supported register types. 11399 * 11400 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11401 * allocated objects is the reg->btf pointer. 11402 * 11403 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11404 * can establish the provenance of the map value statically for each distinct 11405 * lookup into such maps. They always contain a single map value hence unique 11406 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11407 * 11408 * So, in case of global variables, they use array maps with max_entries = 1, 11409 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11410 * into the same map value as max_entries is 1, as described above). 11411 * 11412 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11413 * outer map pointer (in verifier context), but each lookup into an inner map 11414 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11415 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11416 * will get different reg->id assigned to each lookup, hence different 11417 * active_lock.id. 11418 * 11419 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11420 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11421 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11422 */ 11423 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11424 { 11425 void *ptr; 11426 u32 id; 11427 11428 switch ((int)reg->type) { 11429 case PTR_TO_MAP_VALUE: 11430 ptr = reg->map_ptr; 11431 break; 11432 case PTR_TO_BTF_ID | MEM_ALLOC: 11433 ptr = reg->btf; 11434 break; 11435 default: 11436 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 11437 return -EFAULT; 11438 } 11439 id = reg->id; 11440 11441 if (!env->cur_state->active_lock.ptr) 11442 return -EINVAL; 11443 if (env->cur_state->active_lock.ptr != ptr || 11444 env->cur_state->active_lock.id != id) { 11445 verbose(env, "held lock and object are not in the same allocation\n"); 11446 return -EINVAL; 11447 } 11448 return 0; 11449 } 11450 11451 static bool is_bpf_list_api_kfunc(u32 btf_id) 11452 { 11453 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11454 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11455 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11456 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 11457 } 11458 11459 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11460 { 11461 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 11462 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11463 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 11464 } 11465 11466 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11467 { 11468 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 11469 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11470 } 11471 11472 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11473 { 11474 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11475 } 11476 11477 static bool is_async_callback_calling_kfunc(u32 btf_id) 11478 { 11479 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl]; 11480 } 11481 11482 static bool is_bpf_throw_kfunc(struct bpf_insn *insn) 11483 { 11484 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 11485 insn->imm == special_kfunc_list[KF_bpf_throw]; 11486 } 11487 11488 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id) 11489 { 11490 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl]; 11491 } 11492 11493 static bool is_callback_calling_kfunc(u32 btf_id) 11494 { 11495 return is_sync_callback_calling_kfunc(btf_id) || 11496 is_async_callback_calling_kfunc(btf_id); 11497 } 11498 11499 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11500 { 11501 return is_bpf_rbtree_api_kfunc(btf_id); 11502 } 11503 11504 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11505 enum btf_field_type head_field_type, 11506 u32 kfunc_btf_id) 11507 { 11508 bool ret; 11509 11510 switch (head_field_type) { 11511 case BPF_LIST_HEAD: 11512 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11513 break; 11514 case BPF_RB_ROOT: 11515 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11516 break; 11517 default: 11518 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11519 btf_field_type_name(head_field_type)); 11520 return false; 11521 } 11522 11523 if (!ret) 11524 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11525 btf_field_type_name(head_field_type)); 11526 return ret; 11527 } 11528 11529 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11530 enum btf_field_type node_field_type, 11531 u32 kfunc_btf_id) 11532 { 11533 bool ret; 11534 11535 switch (node_field_type) { 11536 case BPF_LIST_NODE: 11537 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11538 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 11539 break; 11540 case BPF_RB_NODE: 11541 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11542 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 11543 break; 11544 default: 11545 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11546 btf_field_type_name(node_field_type)); 11547 return false; 11548 } 11549 11550 if (!ret) 11551 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11552 btf_field_type_name(node_field_type)); 11553 return ret; 11554 } 11555 11556 static int 11557 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11558 struct bpf_reg_state *reg, u32 regno, 11559 struct bpf_kfunc_call_arg_meta *meta, 11560 enum btf_field_type head_field_type, 11561 struct btf_field **head_field) 11562 { 11563 const char *head_type_name; 11564 struct btf_field *field; 11565 struct btf_record *rec; 11566 u32 head_off; 11567 11568 if (meta->btf != btf_vmlinux) { 11569 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11570 return -EFAULT; 11571 } 11572 11573 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11574 return -EFAULT; 11575 11576 head_type_name = btf_field_type_name(head_field_type); 11577 if (!tnum_is_const(reg->var_off)) { 11578 verbose(env, 11579 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11580 regno, head_type_name); 11581 return -EINVAL; 11582 } 11583 11584 rec = reg_btf_record(reg); 11585 head_off = reg->off + reg->var_off.value; 11586 field = btf_record_find(rec, head_off, head_field_type); 11587 if (!field) { 11588 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11589 return -EINVAL; 11590 } 11591 11592 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11593 if (check_reg_allocation_locked(env, reg)) { 11594 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11595 rec->spin_lock_off, head_type_name); 11596 return -EINVAL; 11597 } 11598 11599 if (*head_field) { 11600 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 11601 return -EFAULT; 11602 } 11603 *head_field = field; 11604 return 0; 11605 } 11606 11607 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11608 struct bpf_reg_state *reg, u32 regno, 11609 struct bpf_kfunc_call_arg_meta *meta) 11610 { 11611 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 11612 &meta->arg_list_head.field); 11613 } 11614 11615 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11616 struct bpf_reg_state *reg, u32 regno, 11617 struct bpf_kfunc_call_arg_meta *meta) 11618 { 11619 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 11620 &meta->arg_rbtree_root.field); 11621 } 11622 11623 static int 11624 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11625 struct bpf_reg_state *reg, u32 regno, 11626 struct bpf_kfunc_call_arg_meta *meta, 11627 enum btf_field_type head_field_type, 11628 enum btf_field_type node_field_type, 11629 struct btf_field **node_field) 11630 { 11631 const char *node_type_name; 11632 const struct btf_type *et, *t; 11633 struct btf_field *field; 11634 u32 node_off; 11635 11636 if (meta->btf != btf_vmlinux) { 11637 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11638 return -EFAULT; 11639 } 11640 11641 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11642 return -EFAULT; 11643 11644 node_type_name = btf_field_type_name(node_field_type); 11645 if (!tnum_is_const(reg->var_off)) { 11646 verbose(env, 11647 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11648 regno, node_type_name); 11649 return -EINVAL; 11650 } 11651 11652 node_off = reg->off + reg->var_off.value; 11653 field = reg_find_field_offset(reg, node_off, node_field_type); 11654 if (!field || field->offset != node_off) { 11655 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11656 return -EINVAL; 11657 } 11658 11659 field = *node_field; 11660 11661 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11662 t = btf_type_by_id(reg->btf, reg->btf_id); 11663 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11664 field->graph_root.value_btf_id, true)) { 11665 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11666 "in struct %s, but arg is at offset=%d in struct %s\n", 11667 btf_field_type_name(head_field_type), 11668 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 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11672 return -EINVAL; 11673 } 11674 meta->arg_btf = reg->btf; 11675 meta->arg_btf_id = reg->btf_id; 11676 11677 if (node_off != field->graph_root.node_offset) { 11678 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11679 node_off, btf_field_type_name(node_field_type), 11680 field->graph_root.node_offset, 11681 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11682 return -EINVAL; 11683 } 11684 11685 return 0; 11686 } 11687 11688 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11689 struct bpf_reg_state *reg, u32 regno, 11690 struct bpf_kfunc_call_arg_meta *meta) 11691 { 11692 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11693 BPF_LIST_HEAD, BPF_LIST_NODE, 11694 &meta->arg_list_head.field); 11695 } 11696 11697 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11698 struct bpf_reg_state *reg, u32 regno, 11699 struct bpf_kfunc_call_arg_meta *meta) 11700 { 11701 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11702 BPF_RB_ROOT, BPF_RB_NODE, 11703 &meta->arg_rbtree_root.field); 11704 } 11705 11706 /* 11707 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 11708 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 11709 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 11710 * them can only be attached to some specific hook points. 11711 */ 11712 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 11713 { 11714 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11715 11716 switch (prog_type) { 11717 case BPF_PROG_TYPE_LSM: 11718 return true; 11719 case BPF_PROG_TYPE_TRACING: 11720 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 11721 return true; 11722 fallthrough; 11723 default: 11724 return in_sleepable(env); 11725 } 11726 } 11727 11728 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11729 int insn_idx) 11730 { 11731 const char *func_name = meta->func_name, *ref_tname; 11732 const struct btf *btf = meta->btf; 11733 const struct btf_param *args; 11734 struct btf_record *rec; 11735 u32 i, nargs; 11736 int ret; 11737 11738 args = (const struct btf_param *)(meta->func_proto + 1); 11739 nargs = btf_type_vlen(meta->func_proto); 11740 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 11741 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11742 MAX_BPF_FUNC_REG_ARGS); 11743 return -EINVAL; 11744 } 11745 11746 /* Check that BTF function arguments match actual types that the 11747 * verifier sees. 11748 */ 11749 for (i = 0; i < nargs; i++) { 11750 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 11751 const struct btf_type *t, *ref_t, *resolve_ret; 11752 enum bpf_arg_type arg_type = ARG_DONTCARE; 11753 u32 regno = i + 1, ref_id, type_size; 11754 bool is_ret_buf_sz = false; 11755 int kf_arg_type; 11756 11757 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11758 11759 if (is_kfunc_arg_ignore(btf, &args[i])) 11760 continue; 11761 11762 if (btf_type_is_scalar(t)) { 11763 if (reg->type != SCALAR_VALUE) { 11764 verbose(env, "R%d is not a scalar\n", regno); 11765 return -EINVAL; 11766 } 11767 11768 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11769 if (meta->arg_constant.found) { 11770 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11771 return -EFAULT; 11772 } 11773 if (!tnum_is_const(reg->var_off)) { 11774 verbose(env, "R%d must be a known constant\n", regno); 11775 return -EINVAL; 11776 } 11777 ret = mark_chain_precision(env, regno); 11778 if (ret < 0) 11779 return ret; 11780 meta->arg_constant.found = true; 11781 meta->arg_constant.value = reg->var_off.value; 11782 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 11783 meta->r0_rdonly = true; 11784 is_ret_buf_sz = true; 11785 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 11786 is_ret_buf_sz = true; 11787 } 11788 11789 if (is_ret_buf_sz) { 11790 if (meta->r0_size) { 11791 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 11792 return -EINVAL; 11793 } 11794 11795 if (!tnum_is_const(reg->var_off)) { 11796 verbose(env, "R%d is not a const\n", regno); 11797 return -EINVAL; 11798 } 11799 11800 meta->r0_size = reg->var_off.value; 11801 ret = mark_chain_precision(env, regno); 11802 if (ret) 11803 return ret; 11804 } 11805 continue; 11806 } 11807 11808 if (!btf_type_is_ptr(t)) { 11809 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 11810 return -EINVAL; 11811 } 11812 11813 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 11814 (register_is_null(reg) || type_may_be_null(reg->type)) && 11815 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 11816 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 11817 return -EACCES; 11818 } 11819 11820 if (reg->ref_obj_id) { 11821 if (is_kfunc_release(meta) && meta->ref_obj_id) { 11822 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 11823 regno, reg->ref_obj_id, 11824 meta->ref_obj_id); 11825 return -EFAULT; 11826 } 11827 meta->ref_obj_id = reg->ref_obj_id; 11828 if (is_kfunc_release(meta)) 11829 meta->release_regno = regno; 11830 } 11831 11832 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 11833 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 11834 11835 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 11836 if (kf_arg_type < 0) 11837 return kf_arg_type; 11838 11839 switch (kf_arg_type) { 11840 case KF_ARG_PTR_TO_NULL: 11841 continue; 11842 case KF_ARG_PTR_TO_MAP: 11843 if (!reg->map_ptr) { 11844 verbose(env, "pointer in R%d isn't map pointer\n", regno); 11845 return -EINVAL; 11846 } 11847 if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) { 11848 /* Use map_uid (which is unique id of inner map) to reject: 11849 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 11850 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 11851 * if (inner_map1 && inner_map2) { 11852 * wq = bpf_map_lookup_elem(inner_map1); 11853 * if (wq) 11854 * // mismatch would have been allowed 11855 * bpf_wq_init(wq, inner_map2); 11856 * } 11857 * 11858 * Comparing map_ptr is enough to distinguish normal and outer maps. 11859 */ 11860 if (meta->map.ptr != reg->map_ptr || 11861 meta->map.uid != reg->map_uid) { 11862 verbose(env, 11863 "workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 11864 meta->map.uid, reg->map_uid); 11865 return -EINVAL; 11866 } 11867 } 11868 meta->map.ptr = reg->map_ptr; 11869 meta->map.uid = reg->map_uid; 11870 fallthrough; 11871 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11872 case KF_ARG_PTR_TO_BTF_ID: 11873 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 11874 break; 11875 11876 if (!is_trusted_reg(reg)) { 11877 if (!is_kfunc_rcu(meta)) { 11878 verbose(env, "R%d must be referenced or trusted\n", regno); 11879 return -EINVAL; 11880 } 11881 if (!is_rcu_reg(reg)) { 11882 verbose(env, "R%d must be a rcu pointer\n", regno); 11883 return -EINVAL; 11884 } 11885 } 11886 11887 fallthrough; 11888 case KF_ARG_PTR_TO_CTX: 11889 /* Trusted arguments have the same offset checks as release arguments */ 11890 arg_type |= OBJ_RELEASE; 11891 break; 11892 case KF_ARG_PTR_TO_DYNPTR: 11893 case KF_ARG_PTR_TO_ITER: 11894 case KF_ARG_PTR_TO_LIST_HEAD: 11895 case KF_ARG_PTR_TO_LIST_NODE: 11896 case KF_ARG_PTR_TO_RB_ROOT: 11897 case KF_ARG_PTR_TO_RB_NODE: 11898 case KF_ARG_PTR_TO_MEM: 11899 case KF_ARG_PTR_TO_MEM_SIZE: 11900 case KF_ARG_PTR_TO_CALLBACK: 11901 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11902 case KF_ARG_PTR_TO_CONST_STR: 11903 case KF_ARG_PTR_TO_WORKQUEUE: 11904 /* Trusted by default */ 11905 break; 11906 default: 11907 WARN_ON_ONCE(1); 11908 return -EFAULT; 11909 } 11910 11911 if (is_kfunc_release(meta) && reg->ref_obj_id) 11912 arg_type |= OBJ_RELEASE; 11913 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 11914 if (ret < 0) 11915 return ret; 11916 11917 switch (kf_arg_type) { 11918 case KF_ARG_PTR_TO_CTX: 11919 if (reg->type != PTR_TO_CTX) { 11920 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 11921 return -EINVAL; 11922 } 11923 11924 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11925 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 11926 if (ret < 0) 11927 return -EINVAL; 11928 meta->ret_btf_id = ret; 11929 } 11930 break; 11931 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11932 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 11933 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) { 11934 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i); 11935 return -EINVAL; 11936 } 11937 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 11938 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 11939 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i); 11940 return -EINVAL; 11941 } 11942 } else { 11943 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11944 return -EINVAL; 11945 } 11946 if (!reg->ref_obj_id) { 11947 verbose(env, "allocated object must be referenced\n"); 11948 return -EINVAL; 11949 } 11950 if (meta->btf == btf_vmlinux) { 11951 meta->arg_btf = reg->btf; 11952 meta->arg_btf_id = reg->btf_id; 11953 } 11954 break; 11955 case KF_ARG_PTR_TO_DYNPTR: 11956 { 11957 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 11958 int clone_ref_obj_id = 0; 11959 11960 if (reg->type != PTR_TO_STACK && 11961 reg->type != CONST_PTR_TO_DYNPTR) { 11962 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 11963 return -EINVAL; 11964 } 11965 11966 if (reg->type == CONST_PTR_TO_DYNPTR) 11967 dynptr_arg_type |= MEM_RDONLY; 11968 11969 if (is_kfunc_arg_uninit(btf, &args[i])) 11970 dynptr_arg_type |= MEM_UNINIT; 11971 11972 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 11973 dynptr_arg_type |= DYNPTR_TYPE_SKB; 11974 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 11975 dynptr_arg_type |= DYNPTR_TYPE_XDP; 11976 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 11977 (dynptr_arg_type & MEM_UNINIT)) { 11978 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 11979 11980 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 11981 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 11982 return -EFAULT; 11983 } 11984 11985 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 11986 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 11987 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 11988 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 11989 return -EFAULT; 11990 } 11991 } 11992 11993 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 11994 if (ret < 0) 11995 return ret; 11996 11997 if (!(dynptr_arg_type & MEM_UNINIT)) { 11998 int id = dynptr_id(env, reg); 11999 12000 if (id < 0) { 12001 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 12002 return id; 12003 } 12004 meta->initialized_dynptr.id = id; 12005 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 12006 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 12007 } 12008 12009 break; 12010 } 12011 case KF_ARG_PTR_TO_ITER: 12012 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 12013 if (!check_css_task_iter_allowlist(env)) { 12014 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 12015 return -EINVAL; 12016 } 12017 } 12018 ret = process_iter_arg(env, regno, insn_idx, meta); 12019 if (ret < 0) 12020 return ret; 12021 break; 12022 case KF_ARG_PTR_TO_LIST_HEAD: 12023 if (reg->type != PTR_TO_MAP_VALUE && 12024 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12025 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 12026 return -EINVAL; 12027 } 12028 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 12029 verbose(env, "allocated object must be referenced\n"); 12030 return -EINVAL; 12031 } 12032 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 12033 if (ret < 0) 12034 return ret; 12035 break; 12036 case KF_ARG_PTR_TO_RB_ROOT: 12037 if (reg->type != PTR_TO_MAP_VALUE && 12038 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12039 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 12040 return -EINVAL; 12041 } 12042 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 12043 verbose(env, "allocated object must be referenced\n"); 12044 return -EINVAL; 12045 } 12046 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 12047 if (ret < 0) 12048 return ret; 12049 break; 12050 case KF_ARG_PTR_TO_LIST_NODE: 12051 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12052 verbose(env, "arg#%d expected pointer to allocated object\n", i); 12053 return -EINVAL; 12054 } 12055 if (!reg->ref_obj_id) { 12056 verbose(env, "allocated object must be referenced\n"); 12057 return -EINVAL; 12058 } 12059 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 12060 if (ret < 0) 12061 return ret; 12062 break; 12063 case KF_ARG_PTR_TO_RB_NODE: 12064 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 12065 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 12066 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 12067 return -EINVAL; 12068 } 12069 if (in_rbtree_lock_required_cb(env)) { 12070 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 12071 return -EINVAL; 12072 } 12073 } else { 12074 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12075 verbose(env, "arg#%d expected pointer to allocated object\n", i); 12076 return -EINVAL; 12077 } 12078 if (!reg->ref_obj_id) { 12079 verbose(env, "allocated object must be referenced\n"); 12080 return -EINVAL; 12081 } 12082 } 12083 12084 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 12085 if (ret < 0) 12086 return ret; 12087 break; 12088 case KF_ARG_PTR_TO_MAP: 12089 /* If argument has '__map' suffix expect 'struct bpf_map *' */ 12090 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP]; 12091 ref_t = btf_type_by_id(btf_vmlinux, ref_id); 12092 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12093 fallthrough; 12094 case KF_ARG_PTR_TO_BTF_ID: 12095 /* Only base_type is checked, further checks are done here */ 12096 if ((base_type(reg->type) != PTR_TO_BTF_ID || 12097 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 12098 !reg2btf_ids[base_type(reg->type)]) { 12099 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 12100 verbose(env, "expected %s or socket\n", 12101 reg_type_str(env, base_type(reg->type) | 12102 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 12103 return -EINVAL; 12104 } 12105 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 12106 if (ret < 0) 12107 return ret; 12108 break; 12109 case KF_ARG_PTR_TO_MEM: 12110 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 12111 if (IS_ERR(resolve_ret)) { 12112 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 12113 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 12114 return -EINVAL; 12115 } 12116 ret = check_mem_reg(env, reg, regno, type_size); 12117 if (ret < 0) 12118 return ret; 12119 break; 12120 case KF_ARG_PTR_TO_MEM_SIZE: 12121 { 12122 struct bpf_reg_state *buff_reg = ®s[regno]; 12123 const struct btf_param *buff_arg = &args[i]; 12124 struct bpf_reg_state *size_reg = ®s[regno + 1]; 12125 const struct btf_param *size_arg = &args[i + 1]; 12126 12127 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 12128 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 12129 if (ret < 0) { 12130 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 12131 return ret; 12132 } 12133 } 12134 12135 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 12136 if (meta->arg_constant.found) { 12137 verbose(env, "verifier internal error: only one constant argument permitted\n"); 12138 return -EFAULT; 12139 } 12140 if (!tnum_is_const(size_reg->var_off)) { 12141 verbose(env, "R%d must be a known constant\n", regno + 1); 12142 return -EINVAL; 12143 } 12144 meta->arg_constant.found = true; 12145 meta->arg_constant.value = size_reg->var_off.value; 12146 } 12147 12148 /* Skip next '__sz' or '__szk' argument */ 12149 i++; 12150 break; 12151 } 12152 case KF_ARG_PTR_TO_CALLBACK: 12153 if (reg->type != PTR_TO_FUNC) { 12154 verbose(env, "arg%d expected pointer to func\n", i); 12155 return -EINVAL; 12156 } 12157 meta->subprogno = reg->subprogno; 12158 break; 12159 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12160 if (!type_is_ptr_alloc_obj(reg->type)) { 12161 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 12162 return -EINVAL; 12163 } 12164 if (!type_is_non_owning_ref(reg->type)) 12165 meta->arg_owning_ref = true; 12166 12167 rec = reg_btf_record(reg); 12168 if (!rec) { 12169 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 12170 return -EFAULT; 12171 } 12172 12173 if (rec->refcount_off < 0) { 12174 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 12175 return -EINVAL; 12176 } 12177 12178 meta->arg_btf = reg->btf; 12179 meta->arg_btf_id = reg->btf_id; 12180 break; 12181 case KF_ARG_PTR_TO_CONST_STR: 12182 if (reg->type != PTR_TO_MAP_VALUE) { 12183 verbose(env, "arg#%d doesn't point to a const string\n", i); 12184 return -EINVAL; 12185 } 12186 ret = check_reg_const_str(env, reg, regno); 12187 if (ret) 12188 return ret; 12189 break; 12190 case KF_ARG_PTR_TO_WORKQUEUE: 12191 if (reg->type != PTR_TO_MAP_VALUE) { 12192 verbose(env, "arg#%d doesn't point to a map value\n", i); 12193 return -EINVAL; 12194 } 12195 ret = process_wq_func(env, regno, meta); 12196 if (ret < 0) 12197 return ret; 12198 break; 12199 } 12200 } 12201 12202 if (is_kfunc_release(meta) && !meta->release_regno) { 12203 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 12204 func_name); 12205 return -EINVAL; 12206 } 12207 12208 return 0; 12209 } 12210 12211 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 12212 struct bpf_insn *insn, 12213 struct bpf_kfunc_call_arg_meta *meta, 12214 const char **kfunc_name) 12215 { 12216 const struct btf_type *func, *func_proto; 12217 u32 func_id, *kfunc_flags; 12218 const char *func_name; 12219 struct btf *desc_btf; 12220 12221 if (kfunc_name) 12222 *kfunc_name = NULL; 12223 12224 if (!insn->imm) 12225 return -EINVAL; 12226 12227 desc_btf = find_kfunc_desc_btf(env, insn->off); 12228 if (IS_ERR(desc_btf)) 12229 return PTR_ERR(desc_btf); 12230 12231 func_id = insn->imm; 12232 func = btf_type_by_id(desc_btf, func_id); 12233 func_name = btf_name_by_offset(desc_btf, func->name_off); 12234 if (kfunc_name) 12235 *kfunc_name = func_name; 12236 func_proto = btf_type_by_id(desc_btf, func->type); 12237 12238 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 12239 if (!kfunc_flags) { 12240 return -EACCES; 12241 } 12242 12243 memset(meta, 0, sizeof(*meta)); 12244 meta->btf = desc_btf; 12245 meta->func_id = func_id; 12246 meta->kfunc_flags = *kfunc_flags; 12247 meta->func_proto = func_proto; 12248 meta->func_name = func_name; 12249 12250 return 0; 12251 } 12252 12253 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 12254 12255 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 12256 int *insn_idx_p) 12257 { 12258 bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable; 12259 u32 i, nargs, ptr_type_id, release_ref_obj_id; 12260 struct bpf_reg_state *regs = cur_regs(env); 12261 const char *func_name, *ptr_type_name; 12262 const struct btf_type *t, *ptr_type; 12263 struct bpf_kfunc_call_arg_meta meta; 12264 struct bpf_insn_aux_data *insn_aux; 12265 int err, insn_idx = *insn_idx_p; 12266 const struct btf_param *args; 12267 const struct btf_type *ret_t; 12268 struct btf *desc_btf; 12269 12270 /* skip for now, but return error when we find this in fixup_kfunc_call */ 12271 if (!insn->imm) 12272 return 0; 12273 12274 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 12275 if (err == -EACCES && func_name) 12276 verbose(env, "calling kernel function %s is not allowed\n", func_name); 12277 if (err) 12278 return err; 12279 desc_btf = meta.btf; 12280 insn_aux = &env->insn_aux_data[insn_idx]; 12281 12282 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 12283 12284 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 12285 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 12286 return -EACCES; 12287 } 12288 12289 sleepable = is_kfunc_sleepable(&meta); 12290 if (sleepable && !in_sleepable(env)) { 12291 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 12292 return -EACCES; 12293 } 12294 12295 /* Check the arguments */ 12296 err = check_kfunc_args(env, &meta, insn_idx); 12297 if (err < 0) 12298 return err; 12299 12300 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12301 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12302 set_rbtree_add_callback_state); 12303 if (err) { 12304 verbose(env, "kfunc %s#%d failed callback verification\n", 12305 func_name, meta.func_id); 12306 return err; 12307 } 12308 } 12309 12310 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) { 12311 meta.r0_size = sizeof(u64); 12312 meta.r0_rdonly = false; 12313 } 12314 12315 if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) { 12316 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12317 set_timer_callback_state); 12318 if (err) { 12319 verbose(env, "kfunc %s#%d failed callback verification\n", 12320 func_name, meta.func_id); 12321 return err; 12322 } 12323 } 12324 12325 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 12326 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 12327 12328 preempt_disable = is_kfunc_bpf_preempt_disable(&meta); 12329 preempt_enable = is_kfunc_bpf_preempt_enable(&meta); 12330 12331 if (env->cur_state->active_rcu_lock) { 12332 struct bpf_func_state *state; 12333 struct bpf_reg_state *reg; 12334 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 12335 12336 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 12337 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 12338 return -EACCES; 12339 } 12340 12341 if (rcu_lock) { 12342 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 12343 return -EINVAL; 12344 } else if (rcu_unlock) { 12345 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({ 12346 if (reg->type & MEM_RCU) { 12347 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 12348 reg->type |= PTR_UNTRUSTED; 12349 } 12350 })); 12351 env->cur_state->active_rcu_lock = false; 12352 } else if (sleepable) { 12353 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 12354 return -EACCES; 12355 } 12356 } else if (rcu_lock) { 12357 env->cur_state->active_rcu_lock = true; 12358 } else if (rcu_unlock) { 12359 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 12360 return -EINVAL; 12361 } 12362 12363 if (env->cur_state->active_preempt_lock) { 12364 if (preempt_disable) { 12365 env->cur_state->active_preempt_lock++; 12366 } else if (preempt_enable) { 12367 env->cur_state->active_preempt_lock--; 12368 } else if (sleepable) { 12369 verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name); 12370 return -EACCES; 12371 } 12372 } else if (preempt_disable) { 12373 env->cur_state->active_preempt_lock++; 12374 } else if (preempt_enable) { 12375 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name); 12376 return -EINVAL; 12377 } 12378 12379 /* In case of release function, we get register number of refcounted 12380 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 12381 */ 12382 if (meta.release_regno) { 12383 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 12384 if (err) { 12385 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12386 func_name, meta.func_id); 12387 return err; 12388 } 12389 } 12390 12391 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 12392 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 12393 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12394 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 12395 insn_aux->insert_off = regs[BPF_REG_2].off; 12396 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 12397 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 12398 if (err) { 12399 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 12400 func_name, meta.func_id); 12401 return err; 12402 } 12403 12404 err = release_reference(env, release_ref_obj_id); 12405 if (err) { 12406 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12407 func_name, meta.func_id); 12408 return err; 12409 } 12410 } 12411 12412 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 12413 if (!bpf_jit_supports_exceptions()) { 12414 verbose(env, "JIT does not support calling kfunc %s#%d\n", 12415 func_name, meta.func_id); 12416 return -ENOTSUPP; 12417 } 12418 env->seen_exception = true; 12419 12420 /* In the case of the default callback, the cookie value passed 12421 * to bpf_throw becomes the return value of the program. 12422 */ 12423 if (!env->exception_callback_subprog) { 12424 err = check_return_code(env, BPF_REG_1, "R1"); 12425 if (err < 0) 12426 return err; 12427 } 12428 } 12429 12430 for (i = 0; i < CALLER_SAVED_REGS; i++) 12431 mark_reg_not_init(env, regs, caller_saved[i]); 12432 12433 /* Check return type */ 12434 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 12435 12436 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 12437 /* Only exception is bpf_obj_new_impl */ 12438 if (meta.btf != btf_vmlinux || 12439 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 12440 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] && 12441 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 12442 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 12443 return -EINVAL; 12444 } 12445 } 12446 12447 if (btf_type_is_scalar(t)) { 12448 mark_reg_unknown(env, regs, BPF_REG_0); 12449 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 12450 } else if (btf_type_is_ptr(t)) { 12451 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 12452 12453 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12454 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 12455 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12456 struct btf_struct_meta *struct_meta; 12457 struct btf *ret_btf; 12458 u32 ret_btf_id; 12459 12460 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set) 12461 return -ENOMEM; 12462 12463 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 12464 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 12465 return -EINVAL; 12466 } 12467 12468 ret_btf = env->prog->aux->btf; 12469 ret_btf_id = meta.arg_constant.value; 12470 12471 /* This may be NULL due to user not supplying a BTF */ 12472 if (!ret_btf) { 12473 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 12474 return -EINVAL; 12475 } 12476 12477 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 12478 if (!ret_t || !__btf_type_is_struct(ret_t)) { 12479 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 12480 return -EINVAL; 12481 } 12482 12483 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12484 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 12485 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 12486 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 12487 return -EINVAL; 12488 } 12489 12490 if (!bpf_global_percpu_ma_set) { 12491 mutex_lock(&bpf_percpu_ma_lock); 12492 if (!bpf_global_percpu_ma_set) { 12493 /* Charge memory allocated with bpf_global_percpu_ma to 12494 * root memcg. The obj_cgroup for root memcg is NULL. 12495 */ 12496 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 12497 if (!err) 12498 bpf_global_percpu_ma_set = true; 12499 } 12500 mutex_unlock(&bpf_percpu_ma_lock); 12501 if (err) 12502 return err; 12503 } 12504 12505 mutex_lock(&bpf_percpu_ma_lock); 12506 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 12507 mutex_unlock(&bpf_percpu_ma_lock); 12508 if (err) 12509 return err; 12510 } 12511 12512 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 12513 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12514 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 12515 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 12516 return -EINVAL; 12517 } 12518 12519 if (struct_meta) { 12520 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 12521 return -EINVAL; 12522 } 12523 } 12524 12525 mark_reg_known_zero(env, regs, BPF_REG_0); 12526 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12527 regs[BPF_REG_0].btf = ret_btf; 12528 regs[BPF_REG_0].btf_id = ret_btf_id; 12529 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) 12530 regs[BPF_REG_0].type |= MEM_PERCPU; 12531 12532 insn_aux->obj_new_size = ret_t->size; 12533 insn_aux->kptr_struct_meta = struct_meta; 12534 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 12535 mark_reg_known_zero(env, regs, BPF_REG_0); 12536 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12537 regs[BPF_REG_0].btf = meta.arg_btf; 12538 regs[BPF_REG_0].btf_id = meta.arg_btf_id; 12539 12540 insn_aux->kptr_struct_meta = 12541 btf_find_struct_meta(meta.arg_btf, 12542 meta.arg_btf_id); 12543 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 12544 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 12545 struct btf_field *field = meta.arg_list_head.field; 12546 12547 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12548 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12549 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12550 struct btf_field *field = meta.arg_rbtree_root.field; 12551 12552 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12553 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12554 mark_reg_known_zero(env, regs, BPF_REG_0); 12555 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 12556 regs[BPF_REG_0].btf = desc_btf; 12557 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 12558 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 12559 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 12560 if (!ret_t || !btf_type_is_struct(ret_t)) { 12561 verbose(env, 12562 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 12563 return -EINVAL; 12564 } 12565 12566 mark_reg_known_zero(env, regs, BPF_REG_0); 12567 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 12568 regs[BPF_REG_0].btf = desc_btf; 12569 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 12570 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 12571 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 12572 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 12573 12574 mark_reg_known_zero(env, regs, BPF_REG_0); 12575 12576 if (!meta.arg_constant.found) { 12577 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 12578 return -EFAULT; 12579 } 12580 12581 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 12582 12583 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 12584 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 12585 12586 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 12587 regs[BPF_REG_0].type |= MEM_RDONLY; 12588 } else { 12589 /* this will set env->seen_direct_write to true */ 12590 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 12591 verbose(env, "the prog does not allow writes to packet data\n"); 12592 return -EINVAL; 12593 } 12594 } 12595 12596 if (!meta.initialized_dynptr.id) { 12597 verbose(env, "verifier internal error: no dynptr id\n"); 12598 return -EFAULT; 12599 } 12600 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 12601 12602 /* we don't need to set BPF_REG_0's ref obj id 12603 * because packet slices are not refcounted (see 12604 * dynptr_type_refcounted) 12605 */ 12606 } else { 12607 verbose(env, "kernel function %s unhandled dynamic return type\n", 12608 meta.func_name); 12609 return -EFAULT; 12610 } 12611 } else if (btf_type_is_void(ptr_type)) { 12612 /* kfunc returning 'void *' is equivalent to returning scalar */ 12613 mark_reg_unknown(env, regs, BPF_REG_0); 12614 } else if (!__btf_type_is_struct(ptr_type)) { 12615 if (!meta.r0_size) { 12616 __u32 sz; 12617 12618 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 12619 meta.r0_size = sz; 12620 meta.r0_rdonly = true; 12621 } 12622 } 12623 if (!meta.r0_size) { 12624 ptr_type_name = btf_name_by_offset(desc_btf, 12625 ptr_type->name_off); 12626 verbose(env, 12627 "kernel function %s returns pointer type %s %s is not supported\n", 12628 func_name, 12629 btf_type_str(ptr_type), 12630 ptr_type_name); 12631 return -EINVAL; 12632 } 12633 12634 mark_reg_known_zero(env, regs, BPF_REG_0); 12635 regs[BPF_REG_0].type = PTR_TO_MEM; 12636 regs[BPF_REG_0].mem_size = meta.r0_size; 12637 12638 if (meta.r0_rdonly) 12639 regs[BPF_REG_0].type |= MEM_RDONLY; 12640 12641 /* Ensures we don't access the memory after a release_reference() */ 12642 if (meta.ref_obj_id) 12643 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 12644 } else { 12645 mark_reg_known_zero(env, regs, BPF_REG_0); 12646 regs[BPF_REG_0].btf = desc_btf; 12647 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 12648 regs[BPF_REG_0].btf_id = ptr_type_id; 12649 } 12650 12651 if (is_kfunc_ret_null(&meta)) { 12652 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 12653 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 12654 regs[BPF_REG_0].id = ++env->id_gen; 12655 } 12656 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 12657 if (is_kfunc_acquire(&meta)) { 12658 int id = acquire_reference_state(env, insn_idx); 12659 12660 if (id < 0) 12661 return id; 12662 if (is_kfunc_ret_null(&meta)) 12663 regs[BPF_REG_0].id = id; 12664 regs[BPF_REG_0].ref_obj_id = id; 12665 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12666 ref_set_non_owning(env, ®s[BPF_REG_0]); 12667 } 12668 12669 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 12670 regs[BPF_REG_0].id = ++env->id_gen; 12671 } else if (btf_type_is_void(t)) { 12672 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12673 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 12674 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 12675 insn_aux->kptr_struct_meta = 12676 btf_find_struct_meta(meta.arg_btf, 12677 meta.arg_btf_id); 12678 } 12679 } 12680 } 12681 12682 nargs = btf_type_vlen(meta.func_proto); 12683 args = (const struct btf_param *)(meta.func_proto + 1); 12684 for (i = 0; i < nargs; i++) { 12685 u32 regno = i + 1; 12686 12687 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 12688 if (btf_type_is_ptr(t)) 12689 mark_btf_func_reg_size(env, regno, sizeof(void *)); 12690 else 12691 /* scalar. ensured by btf_check_kfunc_arg_match() */ 12692 mark_btf_func_reg_size(env, regno, t->size); 12693 } 12694 12695 if (is_iter_next_kfunc(&meta)) { 12696 err = process_iter_next_call(env, insn_idx, &meta); 12697 if (err) 12698 return err; 12699 } 12700 12701 return 0; 12702 } 12703 12704 static bool signed_add_overflows(s64 a, s64 b) 12705 { 12706 /* Do the add in u64, where overflow is well-defined */ 12707 s64 res = (s64)((u64)a + (u64)b); 12708 12709 if (b < 0) 12710 return res > a; 12711 return res < a; 12712 } 12713 12714 static bool signed_add32_overflows(s32 a, s32 b) 12715 { 12716 /* Do the add in u32, where overflow is well-defined */ 12717 s32 res = (s32)((u32)a + (u32)b); 12718 12719 if (b < 0) 12720 return res > a; 12721 return res < a; 12722 } 12723 12724 static bool signed_add16_overflows(s16 a, s16 b) 12725 { 12726 /* Do the add in u16, where overflow is well-defined */ 12727 s16 res = (s16)((u16)a + (u16)b); 12728 12729 if (b < 0) 12730 return res > a; 12731 return res < a; 12732 } 12733 12734 static bool signed_sub_overflows(s64 a, s64 b) 12735 { 12736 /* Do the sub in u64, where overflow is well-defined */ 12737 s64 res = (s64)((u64)a - (u64)b); 12738 12739 if (b < 0) 12740 return res < a; 12741 return res > a; 12742 } 12743 12744 static bool signed_sub32_overflows(s32 a, s32 b) 12745 { 12746 /* Do the sub in u32, where overflow is well-defined */ 12747 s32 res = (s32)((u32)a - (u32)b); 12748 12749 if (b < 0) 12750 return res < a; 12751 return res > a; 12752 } 12753 12754 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 12755 const struct bpf_reg_state *reg, 12756 enum bpf_reg_type type) 12757 { 12758 bool known = tnum_is_const(reg->var_off); 12759 s64 val = reg->var_off.value; 12760 s64 smin = reg->smin_value; 12761 12762 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 12763 verbose(env, "math between %s pointer and %lld is not allowed\n", 12764 reg_type_str(env, type), val); 12765 return false; 12766 } 12767 12768 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 12769 verbose(env, "%s pointer offset %d is not allowed\n", 12770 reg_type_str(env, type), reg->off); 12771 return false; 12772 } 12773 12774 if (smin == S64_MIN) { 12775 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 12776 reg_type_str(env, type)); 12777 return false; 12778 } 12779 12780 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 12781 verbose(env, "value %lld makes %s pointer be out of bounds\n", 12782 smin, reg_type_str(env, type)); 12783 return false; 12784 } 12785 12786 return true; 12787 } 12788 12789 enum { 12790 REASON_BOUNDS = -1, 12791 REASON_TYPE = -2, 12792 REASON_PATHS = -3, 12793 REASON_LIMIT = -4, 12794 REASON_STACK = -5, 12795 }; 12796 12797 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 12798 u32 *alu_limit, bool mask_to_left) 12799 { 12800 u32 max = 0, ptr_limit = 0; 12801 12802 switch (ptr_reg->type) { 12803 case PTR_TO_STACK: 12804 /* Offset 0 is out-of-bounds, but acceptable start for the 12805 * left direction, see BPF_REG_FP. Also, unknown scalar 12806 * offset where we would need to deal with min/max bounds is 12807 * currently prohibited for unprivileged. 12808 */ 12809 max = MAX_BPF_STACK + mask_to_left; 12810 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 12811 break; 12812 case PTR_TO_MAP_VALUE: 12813 max = ptr_reg->map_ptr->value_size; 12814 ptr_limit = (mask_to_left ? 12815 ptr_reg->smin_value : 12816 ptr_reg->umax_value) + ptr_reg->off; 12817 break; 12818 default: 12819 return REASON_TYPE; 12820 } 12821 12822 if (ptr_limit >= max) 12823 return REASON_LIMIT; 12824 *alu_limit = ptr_limit; 12825 return 0; 12826 } 12827 12828 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 12829 const struct bpf_insn *insn) 12830 { 12831 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 12832 } 12833 12834 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 12835 u32 alu_state, u32 alu_limit) 12836 { 12837 /* If we arrived here from different branches with different 12838 * state or limits to sanitize, then this won't work. 12839 */ 12840 if (aux->alu_state && 12841 (aux->alu_state != alu_state || 12842 aux->alu_limit != alu_limit)) 12843 return REASON_PATHS; 12844 12845 /* Corresponding fixup done in do_misc_fixups(). */ 12846 aux->alu_state = alu_state; 12847 aux->alu_limit = alu_limit; 12848 return 0; 12849 } 12850 12851 static int sanitize_val_alu(struct bpf_verifier_env *env, 12852 struct bpf_insn *insn) 12853 { 12854 struct bpf_insn_aux_data *aux = cur_aux(env); 12855 12856 if (can_skip_alu_sanitation(env, insn)) 12857 return 0; 12858 12859 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 12860 } 12861 12862 static bool sanitize_needed(u8 opcode) 12863 { 12864 return opcode == BPF_ADD || opcode == BPF_SUB; 12865 } 12866 12867 struct bpf_sanitize_info { 12868 struct bpf_insn_aux_data aux; 12869 bool mask_to_left; 12870 }; 12871 12872 static struct bpf_verifier_state * 12873 sanitize_speculative_path(struct bpf_verifier_env *env, 12874 const struct bpf_insn *insn, 12875 u32 next_idx, u32 curr_idx) 12876 { 12877 struct bpf_verifier_state *branch; 12878 struct bpf_reg_state *regs; 12879 12880 branch = push_stack(env, next_idx, curr_idx, true); 12881 if (branch && insn) { 12882 regs = branch->frame[branch->curframe]->regs; 12883 if (BPF_SRC(insn->code) == BPF_K) { 12884 mark_reg_unknown(env, regs, insn->dst_reg); 12885 } else if (BPF_SRC(insn->code) == BPF_X) { 12886 mark_reg_unknown(env, regs, insn->dst_reg); 12887 mark_reg_unknown(env, regs, insn->src_reg); 12888 } 12889 } 12890 return branch; 12891 } 12892 12893 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 12894 struct bpf_insn *insn, 12895 const struct bpf_reg_state *ptr_reg, 12896 const struct bpf_reg_state *off_reg, 12897 struct bpf_reg_state *dst_reg, 12898 struct bpf_sanitize_info *info, 12899 const bool commit_window) 12900 { 12901 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 12902 struct bpf_verifier_state *vstate = env->cur_state; 12903 bool off_is_imm = tnum_is_const(off_reg->var_off); 12904 bool off_is_neg = off_reg->smin_value < 0; 12905 bool ptr_is_dst_reg = ptr_reg == dst_reg; 12906 u8 opcode = BPF_OP(insn->code); 12907 u32 alu_state, alu_limit; 12908 struct bpf_reg_state tmp; 12909 bool ret; 12910 int err; 12911 12912 if (can_skip_alu_sanitation(env, insn)) 12913 return 0; 12914 12915 /* We already marked aux for masking from non-speculative 12916 * paths, thus we got here in the first place. We only care 12917 * to explore bad access from here. 12918 */ 12919 if (vstate->speculative) 12920 goto do_sim; 12921 12922 if (!commit_window) { 12923 if (!tnum_is_const(off_reg->var_off) && 12924 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 12925 return REASON_BOUNDS; 12926 12927 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 12928 (opcode == BPF_SUB && !off_is_neg); 12929 } 12930 12931 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 12932 if (err < 0) 12933 return err; 12934 12935 if (commit_window) { 12936 /* In commit phase we narrow the masking window based on 12937 * the observed pointer move after the simulated operation. 12938 */ 12939 alu_state = info->aux.alu_state; 12940 alu_limit = abs(info->aux.alu_limit - alu_limit); 12941 } else { 12942 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 12943 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 12944 alu_state |= ptr_is_dst_reg ? 12945 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 12946 12947 /* Limit pruning on unknown scalars to enable deep search for 12948 * potential masking differences from other program paths. 12949 */ 12950 if (!off_is_imm) 12951 env->explore_alu_limits = true; 12952 } 12953 12954 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 12955 if (err < 0) 12956 return err; 12957 do_sim: 12958 /* If we're in commit phase, we're done here given we already 12959 * pushed the truncated dst_reg into the speculative verification 12960 * stack. 12961 * 12962 * Also, when register is a known constant, we rewrite register-based 12963 * operation to immediate-based, and thus do not need masking (and as 12964 * a consequence, do not need to simulate the zero-truncation either). 12965 */ 12966 if (commit_window || off_is_imm) 12967 return 0; 12968 12969 /* Simulate and find potential out-of-bounds access under 12970 * speculative execution from truncation as a result of 12971 * masking when off was not within expected range. If off 12972 * sits in dst, then we temporarily need to move ptr there 12973 * to simulate dst (== 0) +/-= ptr. Needed, for example, 12974 * for cases where we use K-based arithmetic in one direction 12975 * and truncated reg-based in the other in order to explore 12976 * bad access. 12977 */ 12978 if (!ptr_is_dst_reg) { 12979 tmp = *dst_reg; 12980 copy_register_state(dst_reg, ptr_reg); 12981 } 12982 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 12983 env->insn_idx); 12984 if (!ptr_is_dst_reg && ret) 12985 *dst_reg = tmp; 12986 return !ret ? REASON_STACK : 0; 12987 } 12988 12989 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 12990 { 12991 struct bpf_verifier_state *vstate = env->cur_state; 12992 12993 /* If we simulate paths under speculation, we don't update the 12994 * insn as 'seen' such that when we verify unreachable paths in 12995 * the non-speculative domain, sanitize_dead_code() can still 12996 * rewrite/sanitize them. 12997 */ 12998 if (!vstate->speculative) 12999 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 13000 } 13001 13002 static int sanitize_err(struct bpf_verifier_env *env, 13003 const struct bpf_insn *insn, int reason, 13004 const struct bpf_reg_state *off_reg, 13005 const struct bpf_reg_state *dst_reg) 13006 { 13007 static const char *err = "pointer arithmetic with it prohibited for !root"; 13008 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 13009 u32 dst = insn->dst_reg, src = insn->src_reg; 13010 13011 switch (reason) { 13012 case REASON_BOUNDS: 13013 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 13014 off_reg == dst_reg ? dst : src, err); 13015 break; 13016 case REASON_TYPE: 13017 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 13018 off_reg == dst_reg ? src : dst, err); 13019 break; 13020 case REASON_PATHS: 13021 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 13022 dst, op, err); 13023 break; 13024 case REASON_LIMIT: 13025 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 13026 dst, op, err); 13027 break; 13028 case REASON_STACK: 13029 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 13030 dst, err); 13031 break; 13032 default: 13033 verbose(env, "verifier internal error: unknown reason (%d)\n", 13034 reason); 13035 break; 13036 } 13037 13038 return -EACCES; 13039 } 13040 13041 /* check that stack access falls within stack limits and that 'reg' doesn't 13042 * have a variable offset. 13043 * 13044 * Variable offset is prohibited for unprivileged mode for simplicity since it 13045 * requires corresponding support in Spectre masking for stack ALU. See also 13046 * retrieve_ptr_limit(). 13047 * 13048 * 13049 * 'off' includes 'reg->off'. 13050 */ 13051 static int check_stack_access_for_ptr_arithmetic( 13052 struct bpf_verifier_env *env, 13053 int regno, 13054 const struct bpf_reg_state *reg, 13055 int off) 13056 { 13057 if (!tnum_is_const(reg->var_off)) { 13058 char tn_buf[48]; 13059 13060 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 13061 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 13062 regno, tn_buf, off); 13063 return -EACCES; 13064 } 13065 13066 if (off >= 0 || off < -MAX_BPF_STACK) { 13067 verbose(env, "R%d stack pointer arithmetic goes out of range, " 13068 "prohibited for !root; off=%d\n", regno, off); 13069 return -EACCES; 13070 } 13071 13072 return 0; 13073 } 13074 13075 static int sanitize_check_bounds(struct bpf_verifier_env *env, 13076 const struct bpf_insn *insn, 13077 const struct bpf_reg_state *dst_reg) 13078 { 13079 u32 dst = insn->dst_reg; 13080 13081 /* For unprivileged we require that resulting offset must be in bounds 13082 * in order to be able to sanitize access later on. 13083 */ 13084 if (env->bypass_spec_v1) 13085 return 0; 13086 13087 switch (dst_reg->type) { 13088 case PTR_TO_STACK: 13089 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 13090 dst_reg->off + dst_reg->var_off.value)) 13091 return -EACCES; 13092 break; 13093 case PTR_TO_MAP_VALUE: 13094 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 13095 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 13096 "prohibited for !root\n", dst); 13097 return -EACCES; 13098 } 13099 break; 13100 default: 13101 break; 13102 } 13103 13104 return 0; 13105 } 13106 13107 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 13108 * Caller should also handle BPF_MOV case separately. 13109 * If we return -EACCES, caller may want to try again treating pointer as a 13110 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 13111 */ 13112 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 13113 struct bpf_insn *insn, 13114 const struct bpf_reg_state *ptr_reg, 13115 const struct bpf_reg_state *off_reg) 13116 { 13117 struct bpf_verifier_state *vstate = env->cur_state; 13118 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13119 struct bpf_reg_state *regs = state->regs, *dst_reg; 13120 bool known = tnum_is_const(off_reg->var_off); 13121 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 13122 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 13123 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 13124 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 13125 struct bpf_sanitize_info info = {}; 13126 u8 opcode = BPF_OP(insn->code); 13127 u32 dst = insn->dst_reg; 13128 int ret; 13129 13130 dst_reg = ®s[dst]; 13131 13132 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 13133 smin_val > smax_val || umin_val > umax_val) { 13134 /* Taint dst register if offset had invalid bounds derived from 13135 * e.g. dead branches. 13136 */ 13137 __mark_reg_unknown(env, dst_reg); 13138 return 0; 13139 } 13140 13141 if (BPF_CLASS(insn->code) != BPF_ALU64) { 13142 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 13143 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13144 __mark_reg_unknown(env, dst_reg); 13145 return 0; 13146 } 13147 13148 verbose(env, 13149 "R%d 32-bit pointer arithmetic prohibited\n", 13150 dst); 13151 return -EACCES; 13152 } 13153 13154 if (ptr_reg->type & PTR_MAYBE_NULL) { 13155 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 13156 dst, reg_type_str(env, ptr_reg->type)); 13157 return -EACCES; 13158 } 13159 13160 switch (base_type(ptr_reg->type)) { 13161 case PTR_TO_CTX: 13162 case PTR_TO_MAP_VALUE: 13163 case PTR_TO_MAP_KEY: 13164 case PTR_TO_STACK: 13165 case PTR_TO_PACKET_META: 13166 case PTR_TO_PACKET: 13167 case PTR_TO_TP_BUFFER: 13168 case PTR_TO_BTF_ID: 13169 case PTR_TO_MEM: 13170 case PTR_TO_BUF: 13171 case PTR_TO_FUNC: 13172 case CONST_PTR_TO_DYNPTR: 13173 break; 13174 case PTR_TO_FLOW_KEYS: 13175 if (known) 13176 break; 13177 fallthrough; 13178 case CONST_PTR_TO_MAP: 13179 /* smin_val represents the known value */ 13180 if (known && smin_val == 0 && opcode == BPF_ADD) 13181 break; 13182 fallthrough; 13183 default: 13184 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 13185 dst, reg_type_str(env, ptr_reg->type)); 13186 return -EACCES; 13187 } 13188 13189 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 13190 * The id may be overwritten later if we create a new variable offset. 13191 */ 13192 dst_reg->type = ptr_reg->type; 13193 dst_reg->id = ptr_reg->id; 13194 13195 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 13196 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 13197 return -EINVAL; 13198 13199 /* pointer types do not carry 32-bit bounds at the moment. */ 13200 __mark_reg32_unbounded(dst_reg); 13201 13202 if (sanitize_needed(opcode)) { 13203 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 13204 &info, false); 13205 if (ret < 0) 13206 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13207 } 13208 13209 switch (opcode) { 13210 case BPF_ADD: 13211 /* We can take a fixed offset as long as it doesn't overflow 13212 * the s32 'off' field 13213 */ 13214 if (known && (ptr_reg->off + smin_val == 13215 (s64)(s32)(ptr_reg->off + smin_val))) { 13216 /* pointer += K. Accumulate it into fixed offset */ 13217 dst_reg->smin_value = smin_ptr; 13218 dst_reg->smax_value = smax_ptr; 13219 dst_reg->umin_value = umin_ptr; 13220 dst_reg->umax_value = umax_ptr; 13221 dst_reg->var_off = ptr_reg->var_off; 13222 dst_reg->off = ptr_reg->off + smin_val; 13223 dst_reg->raw = ptr_reg->raw; 13224 break; 13225 } 13226 /* A new variable offset is created. Note that off_reg->off 13227 * == 0, since it's a scalar. 13228 * dst_reg gets the pointer type and since some positive 13229 * integer value was added to the pointer, give it a new 'id' 13230 * if it's a PTR_TO_PACKET. 13231 * this creates a new 'base' pointer, off_reg (variable) gets 13232 * added into the variable offset, and we copy the fixed offset 13233 * from ptr_reg. 13234 */ 13235 if (signed_add_overflows(smin_ptr, smin_val) || 13236 signed_add_overflows(smax_ptr, smax_val)) { 13237 dst_reg->smin_value = S64_MIN; 13238 dst_reg->smax_value = S64_MAX; 13239 } else { 13240 dst_reg->smin_value = smin_ptr + smin_val; 13241 dst_reg->smax_value = smax_ptr + smax_val; 13242 } 13243 if (umin_ptr + umin_val < umin_ptr || 13244 umax_ptr + umax_val < umax_ptr) { 13245 dst_reg->umin_value = 0; 13246 dst_reg->umax_value = U64_MAX; 13247 } else { 13248 dst_reg->umin_value = umin_ptr + umin_val; 13249 dst_reg->umax_value = umax_ptr + umax_val; 13250 } 13251 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 13252 dst_reg->off = ptr_reg->off; 13253 dst_reg->raw = ptr_reg->raw; 13254 if (reg_is_pkt_pointer(ptr_reg)) { 13255 dst_reg->id = ++env->id_gen; 13256 /* something was added to pkt_ptr, set range to zero */ 13257 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13258 } 13259 break; 13260 case BPF_SUB: 13261 if (dst_reg == off_reg) { 13262 /* scalar -= pointer. Creates an unknown scalar */ 13263 verbose(env, "R%d tried to subtract pointer from scalar\n", 13264 dst); 13265 return -EACCES; 13266 } 13267 /* We don't allow subtraction from FP, because (according to 13268 * test_verifier.c test "invalid fp arithmetic", JITs might not 13269 * be able to deal with it. 13270 */ 13271 if (ptr_reg->type == PTR_TO_STACK) { 13272 verbose(env, "R%d subtraction from stack pointer prohibited\n", 13273 dst); 13274 return -EACCES; 13275 } 13276 if (known && (ptr_reg->off - smin_val == 13277 (s64)(s32)(ptr_reg->off - smin_val))) { 13278 /* pointer -= K. Subtract it from fixed offset */ 13279 dst_reg->smin_value = smin_ptr; 13280 dst_reg->smax_value = smax_ptr; 13281 dst_reg->umin_value = umin_ptr; 13282 dst_reg->umax_value = umax_ptr; 13283 dst_reg->var_off = ptr_reg->var_off; 13284 dst_reg->id = ptr_reg->id; 13285 dst_reg->off = ptr_reg->off - smin_val; 13286 dst_reg->raw = ptr_reg->raw; 13287 break; 13288 } 13289 /* A new variable offset is created. If the subtrahend is known 13290 * nonnegative, then any reg->range we had before is still good. 13291 */ 13292 if (signed_sub_overflows(smin_ptr, smax_val) || 13293 signed_sub_overflows(smax_ptr, smin_val)) { 13294 /* Overflow possible, we know nothing */ 13295 dst_reg->smin_value = S64_MIN; 13296 dst_reg->smax_value = S64_MAX; 13297 } else { 13298 dst_reg->smin_value = smin_ptr - smax_val; 13299 dst_reg->smax_value = smax_ptr - smin_val; 13300 } 13301 if (umin_ptr < umax_val) { 13302 /* Overflow possible, we know nothing */ 13303 dst_reg->umin_value = 0; 13304 dst_reg->umax_value = U64_MAX; 13305 } else { 13306 /* Cannot overflow (as long as bounds are consistent) */ 13307 dst_reg->umin_value = umin_ptr - umax_val; 13308 dst_reg->umax_value = umax_ptr - umin_val; 13309 } 13310 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 13311 dst_reg->off = ptr_reg->off; 13312 dst_reg->raw = ptr_reg->raw; 13313 if (reg_is_pkt_pointer(ptr_reg)) { 13314 dst_reg->id = ++env->id_gen; 13315 /* something was added to pkt_ptr, set range to zero */ 13316 if (smin_val < 0) 13317 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13318 } 13319 break; 13320 case BPF_AND: 13321 case BPF_OR: 13322 case BPF_XOR: 13323 /* bitwise ops on pointers are troublesome, prohibit. */ 13324 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 13325 dst, bpf_alu_string[opcode >> 4]); 13326 return -EACCES; 13327 default: 13328 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 13329 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 13330 dst, bpf_alu_string[opcode >> 4]); 13331 return -EACCES; 13332 } 13333 13334 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 13335 return -EINVAL; 13336 reg_bounds_sync(dst_reg); 13337 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 13338 return -EACCES; 13339 if (sanitize_needed(opcode)) { 13340 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 13341 &info, true); 13342 if (ret < 0) 13343 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13344 } 13345 13346 return 0; 13347 } 13348 13349 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 13350 struct bpf_reg_state *src_reg) 13351 { 13352 s32 smin_val = src_reg->s32_min_value; 13353 s32 smax_val = src_reg->s32_max_value; 13354 u32 umin_val = src_reg->u32_min_value; 13355 u32 umax_val = src_reg->u32_max_value; 13356 13357 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 13358 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 13359 dst_reg->s32_min_value = S32_MIN; 13360 dst_reg->s32_max_value = S32_MAX; 13361 } else { 13362 dst_reg->s32_min_value += smin_val; 13363 dst_reg->s32_max_value += smax_val; 13364 } 13365 if (dst_reg->u32_min_value + umin_val < umin_val || 13366 dst_reg->u32_max_value + umax_val < umax_val) { 13367 dst_reg->u32_min_value = 0; 13368 dst_reg->u32_max_value = U32_MAX; 13369 } else { 13370 dst_reg->u32_min_value += umin_val; 13371 dst_reg->u32_max_value += umax_val; 13372 } 13373 } 13374 13375 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 13376 struct bpf_reg_state *src_reg) 13377 { 13378 s64 smin_val = src_reg->smin_value; 13379 s64 smax_val = src_reg->smax_value; 13380 u64 umin_val = src_reg->umin_value; 13381 u64 umax_val = src_reg->umax_value; 13382 13383 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 13384 signed_add_overflows(dst_reg->smax_value, smax_val)) { 13385 dst_reg->smin_value = S64_MIN; 13386 dst_reg->smax_value = S64_MAX; 13387 } else { 13388 dst_reg->smin_value += smin_val; 13389 dst_reg->smax_value += smax_val; 13390 } 13391 if (dst_reg->umin_value + umin_val < umin_val || 13392 dst_reg->umax_value + umax_val < umax_val) { 13393 dst_reg->umin_value = 0; 13394 dst_reg->umax_value = U64_MAX; 13395 } else { 13396 dst_reg->umin_value += umin_val; 13397 dst_reg->umax_value += umax_val; 13398 } 13399 } 13400 13401 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 13402 struct bpf_reg_state *src_reg) 13403 { 13404 s32 smin_val = src_reg->s32_min_value; 13405 s32 smax_val = src_reg->s32_max_value; 13406 u32 umin_val = src_reg->u32_min_value; 13407 u32 umax_val = src_reg->u32_max_value; 13408 13409 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 13410 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 13411 /* Overflow possible, we know nothing */ 13412 dst_reg->s32_min_value = S32_MIN; 13413 dst_reg->s32_max_value = S32_MAX; 13414 } else { 13415 dst_reg->s32_min_value -= smax_val; 13416 dst_reg->s32_max_value -= smin_val; 13417 } 13418 if (dst_reg->u32_min_value < umax_val) { 13419 /* Overflow possible, we know nothing */ 13420 dst_reg->u32_min_value = 0; 13421 dst_reg->u32_max_value = U32_MAX; 13422 } else { 13423 /* Cannot overflow (as long as bounds are consistent) */ 13424 dst_reg->u32_min_value -= umax_val; 13425 dst_reg->u32_max_value -= umin_val; 13426 } 13427 } 13428 13429 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 13430 struct bpf_reg_state *src_reg) 13431 { 13432 s64 smin_val = src_reg->smin_value; 13433 s64 smax_val = src_reg->smax_value; 13434 u64 umin_val = src_reg->umin_value; 13435 u64 umax_val = src_reg->umax_value; 13436 13437 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 13438 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 13439 /* Overflow possible, we know nothing */ 13440 dst_reg->smin_value = S64_MIN; 13441 dst_reg->smax_value = S64_MAX; 13442 } else { 13443 dst_reg->smin_value -= smax_val; 13444 dst_reg->smax_value -= smin_val; 13445 } 13446 if (dst_reg->umin_value < umax_val) { 13447 /* Overflow possible, we know nothing */ 13448 dst_reg->umin_value = 0; 13449 dst_reg->umax_value = U64_MAX; 13450 } else { 13451 /* Cannot overflow (as long as bounds are consistent) */ 13452 dst_reg->umin_value -= umax_val; 13453 dst_reg->umax_value -= umin_val; 13454 } 13455 } 13456 13457 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 13458 struct bpf_reg_state *src_reg) 13459 { 13460 s32 smin_val = src_reg->s32_min_value; 13461 u32 umin_val = src_reg->u32_min_value; 13462 u32 umax_val = src_reg->u32_max_value; 13463 13464 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 13465 /* Ain't nobody got time to multiply that sign */ 13466 __mark_reg32_unbounded(dst_reg); 13467 return; 13468 } 13469 /* Both values are positive, so we can work with unsigned and 13470 * copy the result to signed (unless it exceeds S32_MAX). 13471 */ 13472 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 13473 /* Potential overflow, we know nothing */ 13474 __mark_reg32_unbounded(dst_reg); 13475 return; 13476 } 13477 dst_reg->u32_min_value *= umin_val; 13478 dst_reg->u32_max_value *= umax_val; 13479 if (dst_reg->u32_max_value > S32_MAX) { 13480 /* Overflow possible, we know nothing */ 13481 dst_reg->s32_min_value = S32_MIN; 13482 dst_reg->s32_max_value = S32_MAX; 13483 } else { 13484 dst_reg->s32_min_value = dst_reg->u32_min_value; 13485 dst_reg->s32_max_value = dst_reg->u32_max_value; 13486 } 13487 } 13488 13489 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 13490 struct bpf_reg_state *src_reg) 13491 { 13492 s64 smin_val = src_reg->smin_value; 13493 u64 umin_val = src_reg->umin_value; 13494 u64 umax_val = src_reg->umax_value; 13495 13496 if (smin_val < 0 || dst_reg->smin_value < 0) { 13497 /* Ain't nobody got time to multiply that sign */ 13498 __mark_reg64_unbounded(dst_reg); 13499 return; 13500 } 13501 /* Both values are positive, so we can work with unsigned and 13502 * copy the result to signed (unless it exceeds S64_MAX). 13503 */ 13504 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 13505 /* Potential overflow, we know nothing */ 13506 __mark_reg64_unbounded(dst_reg); 13507 return; 13508 } 13509 dst_reg->umin_value *= umin_val; 13510 dst_reg->umax_value *= umax_val; 13511 if (dst_reg->umax_value > S64_MAX) { 13512 /* Overflow possible, we know nothing */ 13513 dst_reg->smin_value = S64_MIN; 13514 dst_reg->smax_value = S64_MAX; 13515 } else { 13516 dst_reg->smin_value = dst_reg->umin_value; 13517 dst_reg->smax_value = dst_reg->umax_value; 13518 } 13519 } 13520 13521 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 13522 struct bpf_reg_state *src_reg) 13523 { 13524 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13525 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13526 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13527 u32 umax_val = src_reg->u32_max_value; 13528 13529 if (src_known && dst_known) { 13530 __mark_reg32_known(dst_reg, var32_off.value); 13531 return; 13532 } 13533 13534 /* We get our minimum from the var_off, since that's inherently 13535 * bitwise. Our maximum is the minimum of the operands' maxima. 13536 */ 13537 dst_reg->u32_min_value = var32_off.value; 13538 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 13539 13540 /* Safe to set s32 bounds by casting u32 result into s32 when u32 13541 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 13542 */ 13543 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 13544 dst_reg->s32_min_value = dst_reg->u32_min_value; 13545 dst_reg->s32_max_value = dst_reg->u32_max_value; 13546 } else { 13547 dst_reg->s32_min_value = S32_MIN; 13548 dst_reg->s32_max_value = S32_MAX; 13549 } 13550 } 13551 13552 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 13553 struct bpf_reg_state *src_reg) 13554 { 13555 bool src_known = tnum_is_const(src_reg->var_off); 13556 bool dst_known = tnum_is_const(dst_reg->var_off); 13557 u64 umax_val = src_reg->umax_value; 13558 13559 if (src_known && dst_known) { 13560 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13561 return; 13562 } 13563 13564 /* We get our minimum from the var_off, since that's inherently 13565 * bitwise. Our maximum is the minimum of the operands' maxima. 13566 */ 13567 dst_reg->umin_value = dst_reg->var_off.value; 13568 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 13569 13570 /* Safe to set s64 bounds by casting u64 result into s64 when u64 13571 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 13572 */ 13573 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 13574 dst_reg->smin_value = dst_reg->umin_value; 13575 dst_reg->smax_value = dst_reg->umax_value; 13576 } else { 13577 dst_reg->smin_value = S64_MIN; 13578 dst_reg->smax_value = S64_MAX; 13579 } 13580 /* We may learn something more from the var_off */ 13581 __update_reg_bounds(dst_reg); 13582 } 13583 13584 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 13585 struct bpf_reg_state *src_reg) 13586 { 13587 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13588 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13589 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13590 u32 umin_val = src_reg->u32_min_value; 13591 13592 if (src_known && dst_known) { 13593 __mark_reg32_known(dst_reg, var32_off.value); 13594 return; 13595 } 13596 13597 /* We get our maximum from the var_off, and our minimum is the 13598 * maximum of the operands' minima 13599 */ 13600 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 13601 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13602 13603 /* Safe to set s32 bounds by casting u32 result into s32 when u32 13604 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 13605 */ 13606 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 13607 dst_reg->s32_min_value = dst_reg->u32_min_value; 13608 dst_reg->s32_max_value = dst_reg->u32_max_value; 13609 } else { 13610 dst_reg->s32_min_value = S32_MIN; 13611 dst_reg->s32_max_value = S32_MAX; 13612 } 13613 } 13614 13615 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 13616 struct bpf_reg_state *src_reg) 13617 { 13618 bool src_known = tnum_is_const(src_reg->var_off); 13619 bool dst_known = tnum_is_const(dst_reg->var_off); 13620 u64 umin_val = src_reg->umin_value; 13621 13622 if (src_known && dst_known) { 13623 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13624 return; 13625 } 13626 13627 /* We get our maximum from the var_off, and our minimum is the 13628 * maximum of the operands' minima 13629 */ 13630 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 13631 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13632 13633 /* Safe to set s64 bounds by casting u64 result into s64 when u64 13634 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 13635 */ 13636 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 13637 dst_reg->smin_value = dst_reg->umin_value; 13638 dst_reg->smax_value = dst_reg->umax_value; 13639 } else { 13640 dst_reg->smin_value = S64_MIN; 13641 dst_reg->smax_value = S64_MAX; 13642 } 13643 /* We may learn something more from the var_off */ 13644 __update_reg_bounds(dst_reg); 13645 } 13646 13647 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 13648 struct bpf_reg_state *src_reg) 13649 { 13650 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13651 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13652 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13653 13654 if (src_known && dst_known) { 13655 __mark_reg32_known(dst_reg, var32_off.value); 13656 return; 13657 } 13658 13659 /* We get both minimum and maximum from the var32_off. */ 13660 dst_reg->u32_min_value = var32_off.value; 13661 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13662 13663 /* Safe to set s32 bounds by casting u32 result into s32 when u32 13664 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 13665 */ 13666 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 13667 dst_reg->s32_min_value = dst_reg->u32_min_value; 13668 dst_reg->s32_max_value = dst_reg->u32_max_value; 13669 } else { 13670 dst_reg->s32_min_value = S32_MIN; 13671 dst_reg->s32_max_value = S32_MAX; 13672 } 13673 } 13674 13675 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 13676 struct bpf_reg_state *src_reg) 13677 { 13678 bool src_known = tnum_is_const(src_reg->var_off); 13679 bool dst_known = tnum_is_const(dst_reg->var_off); 13680 13681 if (src_known && dst_known) { 13682 /* dst_reg->var_off.value has been updated earlier */ 13683 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13684 return; 13685 } 13686 13687 /* We get both minimum and maximum from the var_off. */ 13688 dst_reg->umin_value = dst_reg->var_off.value; 13689 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13690 13691 /* Safe to set s64 bounds by casting u64 result into s64 when u64 13692 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 13693 */ 13694 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 13695 dst_reg->smin_value = dst_reg->umin_value; 13696 dst_reg->smax_value = dst_reg->umax_value; 13697 } else { 13698 dst_reg->smin_value = S64_MIN; 13699 dst_reg->smax_value = S64_MAX; 13700 } 13701 13702 __update_reg_bounds(dst_reg); 13703 } 13704 13705 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13706 u64 umin_val, u64 umax_val) 13707 { 13708 /* We lose all sign bit information (except what we can pick 13709 * up from var_off) 13710 */ 13711 dst_reg->s32_min_value = S32_MIN; 13712 dst_reg->s32_max_value = S32_MAX; 13713 /* If we might shift our top bit out, then we know nothing */ 13714 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 13715 dst_reg->u32_min_value = 0; 13716 dst_reg->u32_max_value = U32_MAX; 13717 } else { 13718 dst_reg->u32_min_value <<= umin_val; 13719 dst_reg->u32_max_value <<= umax_val; 13720 } 13721 } 13722 13723 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13724 struct bpf_reg_state *src_reg) 13725 { 13726 u32 umax_val = src_reg->u32_max_value; 13727 u32 umin_val = src_reg->u32_min_value; 13728 /* u32 alu operation will zext upper bits */ 13729 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13730 13731 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13732 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 13733 /* Not required but being careful mark reg64 bounds as unknown so 13734 * that we are forced to pick them up from tnum and zext later and 13735 * if some path skips this step we are still safe. 13736 */ 13737 __mark_reg64_unbounded(dst_reg); 13738 __update_reg32_bounds(dst_reg); 13739 } 13740 13741 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 13742 u64 umin_val, u64 umax_val) 13743 { 13744 /* Special case <<32 because it is a common compiler pattern to sign 13745 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 13746 * positive we know this shift will also be positive so we can track 13747 * bounds correctly. Otherwise we lose all sign bit information except 13748 * what we can pick up from var_off. Perhaps we can generalize this 13749 * later to shifts of any length. 13750 */ 13751 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 13752 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 13753 else 13754 dst_reg->smax_value = S64_MAX; 13755 13756 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 13757 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 13758 else 13759 dst_reg->smin_value = S64_MIN; 13760 13761 /* If we might shift our top bit out, then we know nothing */ 13762 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 13763 dst_reg->umin_value = 0; 13764 dst_reg->umax_value = U64_MAX; 13765 } else { 13766 dst_reg->umin_value <<= umin_val; 13767 dst_reg->umax_value <<= umax_val; 13768 } 13769 } 13770 13771 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 13772 struct bpf_reg_state *src_reg) 13773 { 13774 u64 umax_val = src_reg->umax_value; 13775 u64 umin_val = src_reg->umin_value; 13776 13777 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 13778 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 13779 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13780 13781 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 13782 /* We may learn something more from the var_off */ 13783 __update_reg_bounds(dst_reg); 13784 } 13785 13786 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 13787 struct bpf_reg_state *src_reg) 13788 { 13789 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13790 u32 umax_val = src_reg->u32_max_value; 13791 u32 umin_val = src_reg->u32_min_value; 13792 13793 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13794 * be negative, then either: 13795 * 1) src_reg might be zero, so the sign bit of the result is 13796 * unknown, so we lose our signed bounds 13797 * 2) it's known negative, thus the unsigned bounds capture the 13798 * signed bounds 13799 * 3) the signed bounds cross zero, so they tell us nothing 13800 * about the result 13801 * If the value in dst_reg is known nonnegative, then again the 13802 * unsigned bounds capture the signed bounds. 13803 * Thus, in all cases it suffices to blow away our signed bounds 13804 * and rely on inferring new ones from the unsigned bounds and 13805 * var_off of the result. 13806 */ 13807 dst_reg->s32_min_value = S32_MIN; 13808 dst_reg->s32_max_value = S32_MAX; 13809 13810 dst_reg->var_off = tnum_rshift(subreg, umin_val); 13811 dst_reg->u32_min_value >>= umax_val; 13812 dst_reg->u32_max_value >>= umin_val; 13813 13814 __mark_reg64_unbounded(dst_reg); 13815 __update_reg32_bounds(dst_reg); 13816 } 13817 13818 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 13819 struct bpf_reg_state *src_reg) 13820 { 13821 u64 umax_val = src_reg->umax_value; 13822 u64 umin_val = src_reg->umin_value; 13823 13824 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13825 * be negative, then either: 13826 * 1) src_reg might be zero, so the sign bit of the result is 13827 * unknown, so we lose our signed bounds 13828 * 2) it's known negative, thus the unsigned bounds capture the 13829 * signed bounds 13830 * 3) the signed bounds cross zero, so they tell us nothing 13831 * about the result 13832 * If the value in dst_reg is known nonnegative, then again the 13833 * unsigned bounds capture the signed bounds. 13834 * Thus, in all cases it suffices to blow away our signed bounds 13835 * and rely on inferring new ones from the unsigned bounds and 13836 * var_off of the result. 13837 */ 13838 dst_reg->smin_value = S64_MIN; 13839 dst_reg->smax_value = S64_MAX; 13840 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 13841 dst_reg->umin_value >>= umax_val; 13842 dst_reg->umax_value >>= umin_val; 13843 13844 /* Its not easy to operate on alu32 bounds here because it depends 13845 * on bits being shifted in. Take easy way out and mark unbounded 13846 * so we can recalculate later from tnum. 13847 */ 13848 __mark_reg32_unbounded(dst_reg); 13849 __update_reg_bounds(dst_reg); 13850 } 13851 13852 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 13853 struct bpf_reg_state *src_reg) 13854 { 13855 u64 umin_val = src_reg->u32_min_value; 13856 13857 /* Upon reaching here, src_known is true and 13858 * umax_val is equal to umin_val. 13859 */ 13860 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 13861 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 13862 13863 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 13864 13865 /* blow away the dst_reg umin_value/umax_value and rely on 13866 * dst_reg var_off to refine the result. 13867 */ 13868 dst_reg->u32_min_value = 0; 13869 dst_reg->u32_max_value = U32_MAX; 13870 13871 __mark_reg64_unbounded(dst_reg); 13872 __update_reg32_bounds(dst_reg); 13873 } 13874 13875 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 13876 struct bpf_reg_state *src_reg) 13877 { 13878 u64 umin_val = src_reg->umin_value; 13879 13880 /* Upon reaching here, src_known is true and umax_val is equal 13881 * to umin_val. 13882 */ 13883 dst_reg->smin_value >>= umin_val; 13884 dst_reg->smax_value >>= umin_val; 13885 13886 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 13887 13888 /* blow away the dst_reg umin_value/umax_value and rely on 13889 * dst_reg var_off to refine the result. 13890 */ 13891 dst_reg->umin_value = 0; 13892 dst_reg->umax_value = U64_MAX; 13893 13894 /* Its not easy to operate on alu32 bounds here because it depends 13895 * on bits being shifted in from upper 32-bits. Take easy way out 13896 * and mark unbounded so we can recalculate later from tnum. 13897 */ 13898 __mark_reg32_unbounded(dst_reg); 13899 __update_reg_bounds(dst_reg); 13900 } 13901 13902 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn, 13903 const struct bpf_reg_state *src_reg) 13904 { 13905 bool src_is_const = false; 13906 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 13907 13908 if (insn_bitness == 32) { 13909 if (tnum_subreg_is_const(src_reg->var_off) 13910 && src_reg->s32_min_value == src_reg->s32_max_value 13911 && src_reg->u32_min_value == src_reg->u32_max_value) 13912 src_is_const = true; 13913 } else { 13914 if (tnum_is_const(src_reg->var_off) 13915 && src_reg->smin_value == src_reg->smax_value 13916 && src_reg->umin_value == src_reg->umax_value) 13917 src_is_const = true; 13918 } 13919 13920 switch (BPF_OP(insn->code)) { 13921 case BPF_ADD: 13922 case BPF_SUB: 13923 case BPF_AND: 13924 case BPF_XOR: 13925 case BPF_OR: 13926 case BPF_MUL: 13927 return true; 13928 13929 /* Shift operators range is only computable if shift dimension operand 13930 * is a constant. Shifts greater than 31 or 63 are undefined. This 13931 * includes shifts by a negative number. 13932 */ 13933 case BPF_LSH: 13934 case BPF_RSH: 13935 case BPF_ARSH: 13936 return (src_is_const && src_reg->umax_value < insn_bitness); 13937 default: 13938 return false; 13939 } 13940 } 13941 13942 /* WARNING: This function does calculations on 64-bit values, but the actual 13943 * execution may occur on 32-bit values. Therefore, things like bitshifts 13944 * need extra checks in the 32-bit case. 13945 */ 13946 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 13947 struct bpf_insn *insn, 13948 struct bpf_reg_state *dst_reg, 13949 struct bpf_reg_state src_reg) 13950 { 13951 u8 opcode = BPF_OP(insn->code); 13952 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 13953 int ret; 13954 13955 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) { 13956 __mark_reg_unknown(env, dst_reg); 13957 return 0; 13958 } 13959 13960 if (sanitize_needed(opcode)) { 13961 ret = sanitize_val_alu(env, insn); 13962 if (ret < 0) 13963 return sanitize_err(env, insn, ret, NULL, NULL); 13964 } 13965 13966 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 13967 * There are two classes of instructions: The first class we track both 13968 * alu32 and alu64 sign/unsigned bounds independently this provides the 13969 * greatest amount of precision when alu operations are mixed with jmp32 13970 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 13971 * and BPF_OR. This is possible because these ops have fairly easy to 13972 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 13973 * See alu32 verifier tests for examples. The second class of 13974 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 13975 * with regards to tracking sign/unsigned bounds because the bits may 13976 * cross subreg boundaries in the alu64 case. When this happens we mark 13977 * the reg unbounded in the subreg bound space and use the resulting 13978 * tnum to calculate an approximation of the sign/unsigned bounds. 13979 */ 13980 switch (opcode) { 13981 case BPF_ADD: 13982 scalar32_min_max_add(dst_reg, &src_reg); 13983 scalar_min_max_add(dst_reg, &src_reg); 13984 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 13985 break; 13986 case BPF_SUB: 13987 scalar32_min_max_sub(dst_reg, &src_reg); 13988 scalar_min_max_sub(dst_reg, &src_reg); 13989 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 13990 break; 13991 case BPF_MUL: 13992 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 13993 scalar32_min_max_mul(dst_reg, &src_reg); 13994 scalar_min_max_mul(dst_reg, &src_reg); 13995 break; 13996 case BPF_AND: 13997 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 13998 scalar32_min_max_and(dst_reg, &src_reg); 13999 scalar_min_max_and(dst_reg, &src_reg); 14000 break; 14001 case BPF_OR: 14002 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 14003 scalar32_min_max_or(dst_reg, &src_reg); 14004 scalar_min_max_or(dst_reg, &src_reg); 14005 break; 14006 case BPF_XOR: 14007 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 14008 scalar32_min_max_xor(dst_reg, &src_reg); 14009 scalar_min_max_xor(dst_reg, &src_reg); 14010 break; 14011 case BPF_LSH: 14012 if (alu32) 14013 scalar32_min_max_lsh(dst_reg, &src_reg); 14014 else 14015 scalar_min_max_lsh(dst_reg, &src_reg); 14016 break; 14017 case BPF_RSH: 14018 if (alu32) 14019 scalar32_min_max_rsh(dst_reg, &src_reg); 14020 else 14021 scalar_min_max_rsh(dst_reg, &src_reg); 14022 break; 14023 case BPF_ARSH: 14024 if (alu32) 14025 scalar32_min_max_arsh(dst_reg, &src_reg); 14026 else 14027 scalar_min_max_arsh(dst_reg, &src_reg); 14028 break; 14029 default: 14030 break; 14031 } 14032 14033 /* ALU32 ops are zero extended into 64bit register */ 14034 if (alu32) 14035 zext_32_to_64(dst_reg); 14036 reg_bounds_sync(dst_reg); 14037 return 0; 14038 } 14039 14040 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 14041 * and var_off. 14042 */ 14043 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 14044 struct bpf_insn *insn) 14045 { 14046 struct bpf_verifier_state *vstate = env->cur_state; 14047 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14048 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 14049 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 14050 u8 opcode = BPF_OP(insn->code); 14051 int err; 14052 14053 dst_reg = ®s[insn->dst_reg]; 14054 src_reg = NULL; 14055 14056 if (dst_reg->type == PTR_TO_ARENA) { 14057 struct bpf_insn_aux_data *aux = cur_aux(env); 14058 14059 if (BPF_CLASS(insn->code) == BPF_ALU64) 14060 /* 14061 * 32-bit operations zero upper bits automatically. 14062 * 64-bit operations need to be converted to 32. 14063 */ 14064 aux->needs_zext = true; 14065 14066 /* Any arithmetic operations are allowed on arena pointers */ 14067 return 0; 14068 } 14069 14070 if (dst_reg->type != SCALAR_VALUE) 14071 ptr_reg = dst_reg; 14072 else 14073 /* Make sure ID is cleared otherwise dst_reg min/max could be 14074 * incorrectly propagated into other registers by find_equal_scalars() 14075 */ 14076 dst_reg->id = 0; 14077 if (BPF_SRC(insn->code) == BPF_X) { 14078 src_reg = ®s[insn->src_reg]; 14079 if (src_reg->type != SCALAR_VALUE) { 14080 if (dst_reg->type != SCALAR_VALUE) { 14081 /* Combining two pointers by any ALU op yields 14082 * an arbitrary scalar. Disallow all math except 14083 * pointer subtraction 14084 */ 14085 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 14086 mark_reg_unknown(env, regs, insn->dst_reg); 14087 return 0; 14088 } 14089 verbose(env, "R%d pointer %s pointer prohibited\n", 14090 insn->dst_reg, 14091 bpf_alu_string[opcode >> 4]); 14092 return -EACCES; 14093 } else { 14094 /* scalar += pointer 14095 * This is legal, but we have to reverse our 14096 * src/dest handling in computing the range 14097 */ 14098 err = mark_chain_precision(env, insn->dst_reg); 14099 if (err) 14100 return err; 14101 return adjust_ptr_min_max_vals(env, insn, 14102 src_reg, dst_reg); 14103 } 14104 } else if (ptr_reg) { 14105 /* pointer += scalar */ 14106 err = mark_chain_precision(env, insn->src_reg); 14107 if (err) 14108 return err; 14109 return adjust_ptr_min_max_vals(env, insn, 14110 dst_reg, src_reg); 14111 } else if (dst_reg->precise) { 14112 /* if dst_reg is precise, src_reg should be precise as well */ 14113 err = mark_chain_precision(env, insn->src_reg); 14114 if (err) 14115 return err; 14116 } 14117 } else { 14118 /* Pretend the src is a reg with a known value, since we only 14119 * need to be able to read from this state. 14120 */ 14121 off_reg.type = SCALAR_VALUE; 14122 __mark_reg_known(&off_reg, insn->imm); 14123 src_reg = &off_reg; 14124 if (ptr_reg) /* pointer += K */ 14125 return adjust_ptr_min_max_vals(env, insn, 14126 ptr_reg, src_reg); 14127 } 14128 14129 /* Got here implies adding two SCALAR_VALUEs */ 14130 if (WARN_ON_ONCE(ptr_reg)) { 14131 print_verifier_state(env, state, true); 14132 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 14133 return -EINVAL; 14134 } 14135 if (WARN_ON(!src_reg)) { 14136 print_verifier_state(env, state, true); 14137 verbose(env, "verifier internal error: no src_reg\n"); 14138 return -EINVAL; 14139 } 14140 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 14141 } 14142 14143 /* check validity of 32-bit and 64-bit arithmetic operations */ 14144 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 14145 { 14146 struct bpf_reg_state *regs = cur_regs(env); 14147 u8 opcode = BPF_OP(insn->code); 14148 int err; 14149 14150 if (opcode == BPF_END || opcode == BPF_NEG) { 14151 if (opcode == BPF_NEG) { 14152 if (BPF_SRC(insn->code) != BPF_K || 14153 insn->src_reg != BPF_REG_0 || 14154 insn->off != 0 || insn->imm != 0) { 14155 verbose(env, "BPF_NEG uses reserved fields\n"); 14156 return -EINVAL; 14157 } 14158 } else { 14159 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 14160 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 14161 (BPF_CLASS(insn->code) == BPF_ALU64 && 14162 BPF_SRC(insn->code) != BPF_TO_LE)) { 14163 verbose(env, "BPF_END uses reserved fields\n"); 14164 return -EINVAL; 14165 } 14166 } 14167 14168 /* check src operand */ 14169 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14170 if (err) 14171 return err; 14172 14173 if (is_pointer_value(env, insn->dst_reg)) { 14174 verbose(env, "R%d pointer arithmetic prohibited\n", 14175 insn->dst_reg); 14176 return -EACCES; 14177 } 14178 14179 /* check dest operand */ 14180 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14181 if (err) 14182 return err; 14183 14184 } else if (opcode == BPF_MOV) { 14185 14186 if (BPF_SRC(insn->code) == BPF_X) { 14187 if (BPF_CLASS(insn->code) == BPF_ALU) { 14188 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) || 14189 insn->imm) { 14190 verbose(env, "BPF_MOV uses reserved fields\n"); 14191 return -EINVAL; 14192 } 14193 } else if (insn->off == BPF_ADDR_SPACE_CAST) { 14194 if (insn->imm != 1 && insn->imm != 1u << 16) { 14195 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n"); 14196 return -EINVAL; 14197 } 14198 if (!env->prog->aux->arena) { 14199 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n"); 14200 return -EINVAL; 14201 } 14202 } else { 14203 if ((insn->off != 0 && insn->off != 8 && insn->off != 16 && 14204 insn->off != 32) || insn->imm) { 14205 verbose(env, "BPF_MOV uses reserved fields\n"); 14206 return -EINVAL; 14207 } 14208 } 14209 14210 /* check src operand */ 14211 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14212 if (err) 14213 return err; 14214 } else { 14215 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 14216 verbose(env, "BPF_MOV uses reserved fields\n"); 14217 return -EINVAL; 14218 } 14219 } 14220 14221 /* check dest operand, mark as required later */ 14222 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14223 if (err) 14224 return err; 14225 14226 if (BPF_SRC(insn->code) == BPF_X) { 14227 struct bpf_reg_state *src_reg = regs + insn->src_reg; 14228 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 14229 14230 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14231 if (insn->imm) { 14232 /* off == BPF_ADDR_SPACE_CAST */ 14233 mark_reg_unknown(env, regs, insn->dst_reg); 14234 if (insn->imm == 1) { /* cast from as(1) to as(0) */ 14235 dst_reg->type = PTR_TO_ARENA; 14236 /* PTR_TO_ARENA is 32-bit */ 14237 dst_reg->subreg_def = env->insn_idx + 1; 14238 } 14239 } else if (insn->off == 0) { 14240 /* case: R1 = R2 14241 * copy register state to dest reg 14242 */ 14243 assign_scalar_id_before_mov(env, src_reg); 14244 copy_register_state(dst_reg, src_reg); 14245 dst_reg->live |= REG_LIVE_WRITTEN; 14246 dst_reg->subreg_def = DEF_NOT_SUBREG; 14247 } else { 14248 /* case: R1 = (s8, s16 s32)R2 */ 14249 if (is_pointer_value(env, insn->src_reg)) { 14250 verbose(env, 14251 "R%d sign-extension part of pointer\n", 14252 insn->src_reg); 14253 return -EACCES; 14254 } else if (src_reg->type == SCALAR_VALUE) { 14255 bool no_sext; 14256 14257 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 14258 if (no_sext) 14259 assign_scalar_id_before_mov(env, src_reg); 14260 copy_register_state(dst_reg, src_reg); 14261 if (!no_sext) 14262 dst_reg->id = 0; 14263 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 14264 dst_reg->live |= REG_LIVE_WRITTEN; 14265 dst_reg->subreg_def = DEF_NOT_SUBREG; 14266 } else { 14267 mark_reg_unknown(env, regs, insn->dst_reg); 14268 } 14269 } 14270 } else { 14271 /* R1 = (u32) R2 */ 14272 if (is_pointer_value(env, insn->src_reg)) { 14273 verbose(env, 14274 "R%d partial copy of pointer\n", 14275 insn->src_reg); 14276 return -EACCES; 14277 } else if (src_reg->type == SCALAR_VALUE) { 14278 if (insn->off == 0) { 14279 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 14280 14281 if (is_src_reg_u32) 14282 assign_scalar_id_before_mov(env, src_reg); 14283 copy_register_state(dst_reg, src_reg); 14284 /* Make sure ID is cleared if src_reg is not in u32 14285 * range otherwise dst_reg min/max could be incorrectly 14286 * propagated into src_reg by find_equal_scalars() 14287 */ 14288 if (!is_src_reg_u32) 14289 dst_reg->id = 0; 14290 dst_reg->live |= REG_LIVE_WRITTEN; 14291 dst_reg->subreg_def = env->insn_idx + 1; 14292 } else { 14293 /* case: W1 = (s8, s16)W2 */ 14294 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 14295 14296 if (no_sext) 14297 assign_scalar_id_before_mov(env, src_reg); 14298 copy_register_state(dst_reg, src_reg); 14299 if (!no_sext) 14300 dst_reg->id = 0; 14301 dst_reg->live |= REG_LIVE_WRITTEN; 14302 dst_reg->subreg_def = env->insn_idx + 1; 14303 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 14304 } 14305 } else { 14306 mark_reg_unknown(env, regs, 14307 insn->dst_reg); 14308 } 14309 zext_32_to_64(dst_reg); 14310 reg_bounds_sync(dst_reg); 14311 } 14312 } else { 14313 /* case: R = imm 14314 * remember the value we stored into this reg 14315 */ 14316 /* clear any state __mark_reg_known doesn't set */ 14317 mark_reg_unknown(env, regs, insn->dst_reg); 14318 regs[insn->dst_reg].type = SCALAR_VALUE; 14319 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14320 __mark_reg_known(regs + insn->dst_reg, 14321 insn->imm); 14322 } else { 14323 __mark_reg_known(regs + insn->dst_reg, 14324 (u32)insn->imm); 14325 } 14326 } 14327 14328 } else if (opcode > BPF_END) { 14329 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 14330 return -EINVAL; 14331 14332 } else { /* all other ALU ops: and, sub, xor, add, ... */ 14333 14334 if (BPF_SRC(insn->code) == BPF_X) { 14335 if (insn->imm != 0 || insn->off > 1 || 14336 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14337 verbose(env, "BPF_ALU uses reserved fields\n"); 14338 return -EINVAL; 14339 } 14340 /* check src1 operand */ 14341 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14342 if (err) 14343 return err; 14344 } else { 14345 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 14346 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14347 verbose(env, "BPF_ALU uses reserved fields\n"); 14348 return -EINVAL; 14349 } 14350 } 14351 14352 /* check src2 operand */ 14353 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14354 if (err) 14355 return err; 14356 14357 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 14358 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 14359 verbose(env, "div by zero\n"); 14360 return -EINVAL; 14361 } 14362 14363 if ((opcode == BPF_LSH || opcode == BPF_RSH || 14364 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 14365 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 14366 14367 if (insn->imm < 0 || insn->imm >= size) { 14368 verbose(env, "invalid shift %d\n", insn->imm); 14369 return -EINVAL; 14370 } 14371 } 14372 14373 /* check dest operand */ 14374 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14375 err = err ?: adjust_reg_min_max_vals(env, insn); 14376 if (err) 14377 return err; 14378 } 14379 14380 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 14381 } 14382 14383 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 14384 struct bpf_reg_state *dst_reg, 14385 enum bpf_reg_type type, 14386 bool range_right_open) 14387 { 14388 struct bpf_func_state *state; 14389 struct bpf_reg_state *reg; 14390 int new_range; 14391 14392 if (dst_reg->off < 0 || 14393 (dst_reg->off == 0 && range_right_open)) 14394 /* This doesn't give us any range */ 14395 return; 14396 14397 if (dst_reg->umax_value > MAX_PACKET_OFF || 14398 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 14399 /* Risk of overflow. For instance, ptr + (1<<63) may be less 14400 * than pkt_end, but that's because it's also less than pkt. 14401 */ 14402 return; 14403 14404 new_range = dst_reg->off; 14405 if (range_right_open) 14406 new_range++; 14407 14408 /* Examples for register markings: 14409 * 14410 * pkt_data in dst register: 14411 * 14412 * r2 = r3; 14413 * r2 += 8; 14414 * if (r2 > pkt_end) goto <handle exception> 14415 * <access okay> 14416 * 14417 * r2 = r3; 14418 * r2 += 8; 14419 * if (r2 < pkt_end) goto <access okay> 14420 * <handle exception> 14421 * 14422 * Where: 14423 * r2 == dst_reg, pkt_end == src_reg 14424 * r2=pkt(id=n,off=8,r=0) 14425 * r3=pkt(id=n,off=0,r=0) 14426 * 14427 * pkt_data in src register: 14428 * 14429 * r2 = r3; 14430 * r2 += 8; 14431 * if (pkt_end >= r2) goto <access okay> 14432 * <handle exception> 14433 * 14434 * r2 = r3; 14435 * r2 += 8; 14436 * if (pkt_end <= r2) goto <handle exception> 14437 * <access okay> 14438 * 14439 * Where: 14440 * pkt_end == dst_reg, r2 == src_reg 14441 * r2=pkt(id=n,off=8,r=0) 14442 * r3=pkt(id=n,off=0,r=0) 14443 * 14444 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 14445 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 14446 * and [r3, r3 + 8-1) respectively is safe to access depending on 14447 * the check. 14448 */ 14449 14450 /* If our ids match, then we must have the same max_value. And we 14451 * don't care about the other reg's fixed offset, since if it's too big 14452 * the range won't allow anything. 14453 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 14454 */ 14455 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14456 if (reg->type == type && reg->id == dst_reg->id) 14457 /* keep the maximum range already checked */ 14458 reg->range = max(reg->range, new_range); 14459 })); 14460 } 14461 14462 /* 14463 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 14464 */ 14465 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14466 u8 opcode, bool is_jmp32) 14467 { 14468 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 14469 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 14470 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value; 14471 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value; 14472 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value; 14473 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value; 14474 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value; 14475 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value; 14476 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value; 14477 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value; 14478 14479 switch (opcode) { 14480 case BPF_JEQ: 14481 /* constants, umin/umax and smin/smax checks would be 14482 * redundant in this case because they all should match 14483 */ 14484 if (tnum_is_const(t1) && tnum_is_const(t2)) 14485 return t1.value == t2.value; 14486 /* non-overlapping ranges */ 14487 if (umin1 > umax2 || umax1 < umin2) 14488 return 0; 14489 if (smin1 > smax2 || smax1 < smin2) 14490 return 0; 14491 if (!is_jmp32) { 14492 /* if 64-bit ranges are inconclusive, see if we can 14493 * utilize 32-bit subrange knowledge to eliminate 14494 * branches that can't be taken a priori 14495 */ 14496 if (reg1->u32_min_value > reg2->u32_max_value || 14497 reg1->u32_max_value < reg2->u32_min_value) 14498 return 0; 14499 if (reg1->s32_min_value > reg2->s32_max_value || 14500 reg1->s32_max_value < reg2->s32_min_value) 14501 return 0; 14502 } 14503 break; 14504 case BPF_JNE: 14505 /* constants, umin/umax and smin/smax checks would be 14506 * redundant in this case because they all should match 14507 */ 14508 if (tnum_is_const(t1) && tnum_is_const(t2)) 14509 return t1.value != t2.value; 14510 /* non-overlapping ranges */ 14511 if (umin1 > umax2 || umax1 < umin2) 14512 return 1; 14513 if (smin1 > smax2 || smax1 < smin2) 14514 return 1; 14515 if (!is_jmp32) { 14516 /* if 64-bit ranges are inconclusive, see if we can 14517 * utilize 32-bit subrange knowledge to eliminate 14518 * branches that can't be taken a priori 14519 */ 14520 if (reg1->u32_min_value > reg2->u32_max_value || 14521 reg1->u32_max_value < reg2->u32_min_value) 14522 return 1; 14523 if (reg1->s32_min_value > reg2->s32_max_value || 14524 reg1->s32_max_value < reg2->s32_min_value) 14525 return 1; 14526 } 14527 break; 14528 case BPF_JSET: 14529 if (!is_reg_const(reg2, is_jmp32)) { 14530 swap(reg1, reg2); 14531 swap(t1, t2); 14532 } 14533 if (!is_reg_const(reg2, is_jmp32)) 14534 return -1; 14535 if ((~t1.mask & t1.value) & t2.value) 14536 return 1; 14537 if (!((t1.mask | t1.value) & t2.value)) 14538 return 0; 14539 break; 14540 case BPF_JGT: 14541 if (umin1 > umax2) 14542 return 1; 14543 else if (umax1 <= umin2) 14544 return 0; 14545 break; 14546 case BPF_JSGT: 14547 if (smin1 > smax2) 14548 return 1; 14549 else if (smax1 <= smin2) 14550 return 0; 14551 break; 14552 case BPF_JLT: 14553 if (umax1 < umin2) 14554 return 1; 14555 else if (umin1 >= umax2) 14556 return 0; 14557 break; 14558 case BPF_JSLT: 14559 if (smax1 < smin2) 14560 return 1; 14561 else if (smin1 >= smax2) 14562 return 0; 14563 break; 14564 case BPF_JGE: 14565 if (umin1 >= umax2) 14566 return 1; 14567 else if (umax1 < umin2) 14568 return 0; 14569 break; 14570 case BPF_JSGE: 14571 if (smin1 >= smax2) 14572 return 1; 14573 else if (smax1 < smin2) 14574 return 0; 14575 break; 14576 case BPF_JLE: 14577 if (umax1 <= umin2) 14578 return 1; 14579 else if (umin1 > umax2) 14580 return 0; 14581 break; 14582 case BPF_JSLE: 14583 if (smax1 <= smin2) 14584 return 1; 14585 else if (smin1 > smax2) 14586 return 0; 14587 break; 14588 } 14589 14590 return -1; 14591 } 14592 14593 static int flip_opcode(u32 opcode) 14594 { 14595 /* How can we transform "a <op> b" into "b <op> a"? */ 14596 static const u8 opcode_flip[16] = { 14597 /* these stay the same */ 14598 [BPF_JEQ >> 4] = BPF_JEQ, 14599 [BPF_JNE >> 4] = BPF_JNE, 14600 [BPF_JSET >> 4] = BPF_JSET, 14601 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 14602 [BPF_JGE >> 4] = BPF_JLE, 14603 [BPF_JGT >> 4] = BPF_JLT, 14604 [BPF_JLE >> 4] = BPF_JGE, 14605 [BPF_JLT >> 4] = BPF_JGT, 14606 [BPF_JSGE >> 4] = BPF_JSLE, 14607 [BPF_JSGT >> 4] = BPF_JSLT, 14608 [BPF_JSLE >> 4] = BPF_JSGE, 14609 [BPF_JSLT >> 4] = BPF_JSGT 14610 }; 14611 return opcode_flip[opcode >> 4]; 14612 } 14613 14614 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 14615 struct bpf_reg_state *src_reg, 14616 u8 opcode) 14617 { 14618 struct bpf_reg_state *pkt; 14619 14620 if (src_reg->type == PTR_TO_PACKET_END) { 14621 pkt = dst_reg; 14622 } else if (dst_reg->type == PTR_TO_PACKET_END) { 14623 pkt = src_reg; 14624 opcode = flip_opcode(opcode); 14625 } else { 14626 return -1; 14627 } 14628 14629 if (pkt->range >= 0) 14630 return -1; 14631 14632 switch (opcode) { 14633 case BPF_JLE: 14634 /* pkt <= pkt_end */ 14635 fallthrough; 14636 case BPF_JGT: 14637 /* pkt > pkt_end */ 14638 if (pkt->range == BEYOND_PKT_END) 14639 /* pkt has at last one extra byte beyond pkt_end */ 14640 return opcode == BPF_JGT; 14641 break; 14642 case BPF_JLT: 14643 /* pkt < pkt_end */ 14644 fallthrough; 14645 case BPF_JGE: 14646 /* pkt >= pkt_end */ 14647 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 14648 return opcode == BPF_JGE; 14649 break; 14650 } 14651 return -1; 14652 } 14653 14654 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 14655 * and return: 14656 * 1 - branch will be taken and "goto target" will be executed 14657 * 0 - branch will not be taken and fall-through to next insn 14658 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 14659 * range [0,10] 14660 */ 14661 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14662 u8 opcode, bool is_jmp32) 14663 { 14664 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 14665 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 14666 14667 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 14668 u64 val; 14669 14670 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 14671 if (!is_reg_const(reg2, is_jmp32)) { 14672 opcode = flip_opcode(opcode); 14673 swap(reg1, reg2); 14674 } 14675 /* and ensure that reg2 is a constant */ 14676 if (!is_reg_const(reg2, is_jmp32)) 14677 return -1; 14678 14679 if (!reg_not_null(reg1)) 14680 return -1; 14681 14682 /* If pointer is valid tests against zero will fail so we can 14683 * use this to direct branch taken. 14684 */ 14685 val = reg_const_value(reg2, is_jmp32); 14686 if (val != 0) 14687 return -1; 14688 14689 switch (opcode) { 14690 case BPF_JEQ: 14691 return 0; 14692 case BPF_JNE: 14693 return 1; 14694 default: 14695 return -1; 14696 } 14697 } 14698 14699 /* now deal with two scalars, but not necessarily constants */ 14700 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32); 14701 } 14702 14703 /* Opcode that corresponds to a *false* branch condition. 14704 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 14705 */ 14706 static u8 rev_opcode(u8 opcode) 14707 { 14708 switch (opcode) { 14709 case BPF_JEQ: return BPF_JNE; 14710 case BPF_JNE: return BPF_JEQ; 14711 /* JSET doesn't have it's reverse opcode in BPF, so add 14712 * BPF_X flag to denote the reverse of that operation 14713 */ 14714 case BPF_JSET: return BPF_JSET | BPF_X; 14715 case BPF_JSET | BPF_X: return BPF_JSET; 14716 case BPF_JGE: return BPF_JLT; 14717 case BPF_JGT: return BPF_JLE; 14718 case BPF_JLE: return BPF_JGT; 14719 case BPF_JLT: return BPF_JGE; 14720 case BPF_JSGE: return BPF_JSLT; 14721 case BPF_JSGT: return BPF_JSLE; 14722 case BPF_JSLE: return BPF_JSGT; 14723 case BPF_JSLT: return BPF_JSGE; 14724 default: return 0; 14725 } 14726 } 14727 14728 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 14729 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14730 u8 opcode, bool is_jmp32) 14731 { 14732 struct tnum t; 14733 u64 val; 14734 14735 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */ 14736 switch (opcode) { 14737 case BPF_JGE: 14738 case BPF_JGT: 14739 case BPF_JSGE: 14740 case BPF_JSGT: 14741 opcode = flip_opcode(opcode); 14742 swap(reg1, reg2); 14743 break; 14744 default: 14745 break; 14746 } 14747 14748 switch (opcode) { 14749 case BPF_JEQ: 14750 if (is_jmp32) { 14751 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14752 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14753 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14754 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14755 reg2->u32_min_value = reg1->u32_min_value; 14756 reg2->u32_max_value = reg1->u32_max_value; 14757 reg2->s32_min_value = reg1->s32_min_value; 14758 reg2->s32_max_value = reg1->s32_max_value; 14759 14760 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 14761 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14762 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 14763 } else { 14764 reg1->umin_value = max(reg1->umin_value, reg2->umin_value); 14765 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14766 reg1->smin_value = max(reg1->smin_value, reg2->smin_value); 14767 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14768 reg2->umin_value = reg1->umin_value; 14769 reg2->umax_value = reg1->umax_value; 14770 reg2->smin_value = reg1->smin_value; 14771 reg2->smax_value = reg1->smax_value; 14772 14773 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 14774 reg2->var_off = reg1->var_off; 14775 } 14776 break; 14777 case BPF_JNE: 14778 if (!is_reg_const(reg2, is_jmp32)) 14779 swap(reg1, reg2); 14780 if (!is_reg_const(reg2, is_jmp32)) 14781 break; 14782 14783 /* try to recompute the bound of reg1 if reg2 is a const and 14784 * is exactly the edge of reg1. 14785 */ 14786 val = reg_const_value(reg2, is_jmp32); 14787 if (is_jmp32) { 14788 /* u32_min_value is not equal to 0xffffffff at this point, 14789 * because otherwise u32_max_value is 0xffffffff as well, 14790 * in such a case both reg1 and reg2 would be constants, 14791 * jump would be predicted and reg_set_min_max() won't 14792 * be called. 14793 * 14794 * Same reasoning works for all {u,s}{min,max}{32,64} cases 14795 * below. 14796 */ 14797 if (reg1->u32_min_value == (u32)val) 14798 reg1->u32_min_value++; 14799 if (reg1->u32_max_value == (u32)val) 14800 reg1->u32_max_value--; 14801 if (reg1->s32_min_value == (s32)val) 14802 reg1->s32_min_value++; 14803 if (reg1->s32_max_value == (s32)val) 14804 reg1->s32_max_value--; 14805 } else { 14806 if (reg1->umin_value == (u64)val) 14807 reg1->umin_value++; 14808 if (reg1->umax_value == (u64)val) 14809 reg1->umax_value--; 14810 if (reg1->smin_value == (s64)val) 14811 reg1->smin_value++; 14812 if (reg1->smax_value == (s64)val) 14813 reg1->smax_value--; 14814 } 14815 break; 14816 case BPF_JSET: 14817 if (!is_reg_const(reg2, is_jmp32)) 14818 swap(reg1, reg2); 14819 if (!is_reg_const(reg2, is_jmp32)) 14820 break; 14821 val = reg_const_value(reg2, is_jmp32); 14822 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 14823 * requires single bit to learn something useful. E.g., if we 14824 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 14825 * are actually set? We can learn something definite only if 14826 * it's a single-bit value to begin with. 14827 * 14828 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 14829 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 14830 * bit 1 is set, which we can readily use in adjustments. 14831 */ 14832 if (!is_power_of_2(val)) 14833 break; 14834 if (is_jmp32) { 14835 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 14836 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14837 } else { 14838 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 14839 } 14840 break; 14841 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 14842 if (!is_reg_const(reg2, is_jmp32)) 14843 swap(reg1, reg2); 14844 if (!is_reg_const(reg2, is_jmp32)) 14845 break; 14846 val = reg_const_value(reg2, is_jmp32); 14847 if (is_jmp32) { 14848 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 14849 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14850 } else { 14851 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 14852 } 14853 break; 14854 case BPF_JLE: 14855 if (is_jmp32) { 14856 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14857 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14858 } else { 14859 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14860 reg2->umin_value = max(reg1->umin_value, reg2->umin_value); 14861 } 14862 break; 14863 case BPF_JLT: 14864 if (is_jmp32) { 14865 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1); 14866 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value); 14867 } else { 14868 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1); 14869 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value); 14870 } 14871 break; 14872 case BPF_JSLE: 14873 if (is_jmp32) { 14874 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14875 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14876 } else { 14877 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14878 reg2->smin_value = max(reg1->smin_value, reg2->smin_value); 14879 } 14880 break; 14881 case BPF_JSLT: 14882 if (is_jmp32) { 14883 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1); 14884 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value); 14885 } else { 14886 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1); 14887 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value); 14888 } 14889 break; 14890 default: 14891 return; 14892 } 14893 } 14894 14895 /* Adjusts the register min/max values in the case that the dst_reg and 14896 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K 14897 * check, in which case we have a fake SCALAR_VALUE representing insn->imm). 14898 * Technically we can do similar adjustments for pointers to the same object, 14899 * but we don't support that right now. 14900 */ 14901 static int reg_set_min_max(struct bpf_verifier_env *env, 14902 struct bpf_reg_state *true_reg1, 14903 struct bpf_reg_state *true_reg2, 14904 struct bpf_reg_state *false_reg1, 14905 struct bpf_reg_state *false_reg2, 14906 u8 opcode, bool is_jmp32) 14907 { 14908 int err; 14909 14910 /* If either register is a pointer, we can't learn anything about its 14911 * variable offset from the compare (unless they were a pointer into 14912 * the same object, but we don't bother with that). 14913 */ 14914 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE) 14915 return 0; 14916 14917 /* fallthrough (FALSE) branch */ 14918 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32); 14919 reg_bounds_sync(false_reg1); 14920 reg_bounds_sync(false_reg2); 14921 14922 /* jump (TRUE) branch */ 14923 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32); 14924 reg_bounds_sync(true_reg1); 14925 reg_bounds_sync(true_reg2); 14926 14927 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1"); 14928 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2"); 14929 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1"); 14930 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2"); 14931 return err; 14932 } 14933 14934 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 14935 struct bpf_reg_state *reg, u32 id, 14936 bool is_null) 14937 { 14938 if (type_may_be_null(reg->type) && reg->id == id && 14939 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 14940 /* Old offset (both fixed and variable parts) should have been 14941 * known-zero, because we don't allow pointer arithmetic on 14942 * pointers that might be NULL. If we see this happening, don't 14943 * convert the register. 14944 * 14945 * But in some cases, some helpers that return local kptrs 14946 * advance offset for the returned pointer. In those cases, it 14947 * is fine to expect to see reg->off. 14948 */ 14949 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 14950 return; 14951 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 14952 WARN_ON_ONCE(reg->off)) 14953 return; 14954 14955 if (is_null) { 14956 reg->type = SCALAR_VALUE; 14957 /* We don't need id and ref_obj_id from this point 14958 * onwards anymore, thus we should better reset it, 14959 * so that state pruning has chances to take effect. 14960 */ 14961 reg->id = 0; 14962 reg->ref_obj_id = 0; 14963 14964 return; 14965 } 14966 14967 mark_ptr_not_null_reg(reg); 14968 14969 if (!reg_may_point_to_spin_lock(reg)) { 14970 /* For not-NULL ptr, reg->ref_obj_id will be reset 14971 * in release_reference(). 14972 * 14973 * reg->id is still used by spin_lock ptr. Other 14974 * than spin_lock ptr type, reg->id can be reset. 14975 */ 14976 reg->id = 0; 14977 } 14978 } 14979 } 14980 14981 /* The logic is similar to find_good_pkt_pointers(), both could eventually 14982 * be folded together at some point. 14983 */ 14984 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 14985 bool is_null) 14986 { 14987 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14988 struct bpf_reg_state *regs = state->regs, *reg; 14989 u32 ref_obj_id = regs[regno].ref_obj_id; 14990 u32 id = regs[regno].id; 14991 14992 if (ref_obj_id && ref_obj_id == id && is_null) 14993 /* regs[regno] is in the " == NULL" branch. 14994 * No one could have freed the reference state before 14995 * doing the NULL check. 14996 */ 14997 WARN_ON_ONCE(release_reference_state(state, id)); 14998 14999 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15000 mark_ptr_or_null_reg(state, reg, id, is_null); 15001 })); 15002 } 15003 15004 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 15005 struct bpf_reg_state *dst_reg, 15006 struct bpf_reg_state *src_reg, 15007 struct bpf_verifier_state *this_branch, 15008 struct bpf_verifier_state *other_branch) 15009 { 15010 if (BPF_SRC(insn->code) != BPF_X) 15011 return false; 15012 15013 /* Pointers are always 64-bit. */ 15014 if (BPF_CLASS(insn->code) == BPF_JMP32) 15015 return false; 15016 15017 switch (BPF_OP(insn->code)) { 15018 case BPF_JGT: 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(this_branch, dst_reg, 15025 dst_reg->type, false); 15026 mark_pkt_end(other_branch, insn->dst_reg, true); 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(other_branch, src_reg, 15033 src_reg->type, true); 15034 mark_pkt_end(this_branch, insn->src_reg, false); 15035 } else { 15036 return false; 15037 } 15038 break; 15039 case BPF_JLT: 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(other_branch, dst_reg, 15046 dst_reg->type, true); 15047 mark_pkt_end(this_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(this_branch, src_reg, 15054 src_reg->type, false); 15055 mark_pkt_end(other_branch, insn->src_reg, true); 15056 } else { 15057 return false; 15058 } 15059 break; 15060 case BPF_JGE: 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(this_branch, dst_reg, 15067 dst_reg->type, true); 15068 mark_pkt_end(other_branch, insn->dst_reg, false); 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(other_branch, src_reg, 15075 src_reg->type, false); 15076 mark_pkt_end(this_branch, insn->src_reg, true); 15077 } else { 15078 return false; 15079 } 15080 break; 15081 case BPF_JLE: 15082 if ((dst_reg->type == PTR_TO_PACKET && 15083 src_reg->type == PTR_TO_PACKET_END) || 15084 (dst_reg->type == PTR_TO_PACKET_META && 15085 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15086 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 15087 find_good_pkt_pointers(other_branch, dst_reg, 15088 dst_reg->type, false); 15089 mark_pkt_end(this_branch, insn->dst_reg, true); 15090 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15091 src_reg->type == PTR_TO_PACKET) || 15092 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15093 src_reg->type == PTR_TO_PACKET_META)) { 15094 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 15095 find_good_pkt_pointers(this_branch, src_reg, 15096 src_reg->type, true); 15097 mark_pkt_end(other_branch, insn->src_reg, false); 15098 } else { 15099 return false; 15100 } 15101 break; 15102 default: 15103 return false; 15104 } 15105 15106 return true; 15107 } 15108 15109 static void find_equal_scalars(struct bpf_verifier_state *vstate, 15110 struct bpf_reg_state *known_reg) 15111 { 15112 struct bpf_func_state *state; 15113 struct bpf_reg_state *reg; 15114 15115 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15116 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 15117 copy_register_state(reg, known_reg); 15118 })); 15119 } 15120 15121 static int check_cond_jmp_op(struct bpf_verifier_env *env, 15122 struct bpf_insn *insn, int *insn_idx) 15123 { 15124 struct bpf_verifier_state *this_branch = env->cur_state; 15125 struct bpf_verifier_state *other_branch; 15126 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 15127 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 15128 struct bpf_reg_state *eq_branch_regs; 15129 u8 opcode = BPF_OP(insn->code); 15130 bool is_jmp32; 15131 int pred = -1; 15132 int err; 15133 15134 /* Only conditional jumps are expected to reach here. */ 15135 if (opcode == BPF_JA || opcode > BPF_JCOND) { 15136 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 15137 return -EINVAL; 15138 } 15139 15140 if (opcode == BPF_JCOND) { 15141 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 15142 int idx = *insn_idx; 15143 15144 if (insn->code != (BPF_JMP | BPF_JCOND) || 15145 insn->src_reg != BPF_MAY_GOTO || 15146 insn->dst_reg || insn->imm || insn->off == 0) { 15147 verbose(env, "invalid may_goto off %d imm %d\n", 15148 insn->off, insn->imm); 15149 return -EINVAL; 15150 } 15151 prev_st = find_prev_entry(env, cur_st->parent, idx); 15152 15153 /* branch out 'fallthrough' insn as a new state to explore */ 15154 queued_st = push_stack(env, idx + 1, idx, false); 15155 if (!queued_st) 15156 return -ENOMEM; 15157 15158 queued_st->may_goto_depth++; 15159 if (prev_st) 15160 widen_imprecise_scalars(env, prev_st, queued_st); 15161 *insn_idx += insn->off; 15162 return 0; 15163 } 15164 15165 /* check src2 operand */ 15166 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15167 if (err) 15168 return err; 15169 15170 dst_reg = ®s[insn->dst_reg]; 15171 if (BPF_SRC(insn->code) == BPF_X) { 15172 if (insn->imm != 0) { 15173 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 15174 return -EINVAL; 15175 } 15176 15177 /* check src1 operand */ 15178 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15179 if (err) 15180 return err; 15181 15182 src_reg = ®s[insn->src_reg]; 15183 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 15184 is_pointer_value(env, insn->src_reg)) { 15185 verbose(env, "R%d pointer comparison prohibited\n", 15186 insn->src_reg); 15187 return -EACCES; 15188 } 15189 } else { 15190 if (insn->src_reg != BPF_REG_0) { 15191 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 15192 return -EINVAL; 15193 } 15194 src_reg = &env->fake_reg[0]; 15195 memset(src_reg, 0, sizeof(*src_reg)); 15196 src_reg->type = SCALAR_VALUE; 15197 __mark_reg_known(src_reg, insn->imm); 15198 } 15199 15200 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 15201 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32); 15202 if (pred >= 0) { 15203 /* If we get here with a dst_reg pointer type it is because 15204 * above is_branch_taken() special cased the 0 comparison. 15205 */ 15206 if (!__is_pointer_value(false, dst_reg)) 15207 err = mark_chain_precision(env, insn->dst_reg); 15208 if (BPF_SRC(insn->code) == BPF_X && !err && 15209 !__is_pointer_value(false, src_reg)) 15210 err = mark_chain_precision(env, insn->src_reg); 15211 if (err) 15212 return err; 15213 } 15214 15215 if (pred == 1) { 15216 /* Only follow the goto, ignore fall-through. If needed, push 15217 * the fall-through branch for simulation under speculative 15218 * execution. 15219 */ 15220 if (!env->bypass_spec_v1 && 15221 !sanitize_speculative_path(env, insn, *insn_idx + 1, 15222 *insn_idx)) 15223 return -EFAULT; 15224 if (env->log.level & BPF_LOG_LEVEL) 15225 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15226 *insn_idx += insn->off; 15227 return 0; 15228 } else if (pred == 0) { 15229 /* Only follow the fall-through branch, since that's where the 15230 * program will go. If needed, push the goto branch for 15231 * simulation under speculative execution. 15232 */ 15233 if (!env->bypass_spec_v1 && 15234 !sanitize_speculative_path(env, insn, 15235 *insn_idx + insn->off + 1, 15236 *insn_idx)) 15237 return -EFAULT; 15238 if (env->log.level & BPF_LOG_LEVEL) 15239 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15240 return 0; 15241 } 15242 15243 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 15244 false); 15245 if (!other_branch) 15246 return -EFAULT; 15247 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 15248 15249 if (BPF_SRC(insn->code) == BPF_X) { 15250 err = reg_set_min_max(env, 15251 &other_branch_regs[insn->dst_reg], 15252 &other_branch_regs[insn->src_reg], 15253 dst_reg, src_reg, opcode, is_jmp32); 15254 } else /* BPF_SRC(insn->code) == BPF_K */ { 15255 /* reg_set_min_max() can mangle the fake_reg. Make a copy 15256 * so that these are two different memory locations. The 15257 * src_reg is not used beyond here in context of K. 15258 */ 15259 memcpy(&env->fake_reg[1], &env->fake_reg[0], 15260 sizeof(env->fake_reg[0])); 15261 err = reg_set_min_max(env, 15262 &other_branch_regs[insn->dst_reg], 15263 &env->fake_reg[0], 15264 dst_reg, &env->fake_reg[1], 15265 opcode, is_jmp32); 15266 } 15267 if (err) 15268 return err; 15269 15270 if (BPF_SRC(insn->code) == BPF_X && 15271 src_reg->type == SCALAR_VALUE && src_reg->id && 15272 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 15273 find_equal_scalars(this_branch, src_reg); 15274 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 15275 } 15276 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 15277 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 15278 find_equal_scalars(this_branch, dst_reg); 15279 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 15280 } 15281 15282 /* if one pointer register is compared to another pointer 15283 * register check if PTR_MAYBE_NULL could be lifted. 15284 * E.g. register A - maybe null 15285 * register B - not null 15286 * for JNE A, B, ... - A is not null in the false branch; 15287 * for JEQ A, B, ... - A is not null in the true branch. 15288 * 15289 * Since PTR_TO_BTF_ID points to a kernel struct that does 15290 * not need to be null checked by the BPF program, i.e., 15291 * could be null even without PTR_MAYBE_NULL marking, so 15292 * only propagate nullness when neither reg is that type. 15293 */ 15294 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 15295 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 15296 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 15297 base_type(src_reg->type) != PTR_TO_BTF_ID && 15298 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 15299 eq_branch_regs = NULL; 15300 switch (opcode) { 15301 case BPF_JEQ: 15302 eq_branch_regs = other_branch_regs; 15303 break; 15304 case BPF_JNE: 15305 eq_branch_regs = regs; 15306 break; 15307 default: 15308 /* do nothing */ 15309 break; 15310 } 15311 if (eq_branch_regs) { 15312 if (type_may_be_null(src_reg->type)) 15313 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 15314 else 15315 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 15316 } 15317 } 15318 15319 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 15320 * NOTE: these optimizations below are related with pointer comparison 15321 * which will never be JMP32. 15322 */ 15323 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 15324 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 15325 type_may_be_null(dst_reg->type)) { 15326 /* Mark all identical registers in each branch as either 15327 * safe or unknown depending R == 0 or R != 0 conditional. 15328 */ 15329 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 15330 opcode == BPF_JNE); 15331 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 15332 opcode == BPF_JEQ); 15333 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 15334 this_branch, other_branch) && 15335 is_pointer_value(env, insn->dst_reg)) { 15336 verbose(env, "R%d pointer comparison prohibited\n", 15337 insn->dst_reg); 15338 return -EACCES; 15339 } 15340 if (env->log.level & BPF_LOG_LEVEL) 15341 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15342 return 0; 15343 } 15344 15345 /* verify BPF_LD_IMM64 instruction */ 15346 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 15347 { 15348 struct bpf_insn_aux_data *aux = cur_aux(env); 15349 struct bpf_reg_state *regs = cur_regs(env); 15350 struct bpf_reg_state *dst_reg; 15351 struct bpf_map *map; 15352 int err; 15353 15354 if (BPF_SIZE(insn->code) != BPF_DW) { 15355 verbose(env, "invalid BPF_LD_IMM insn\n"); 15356 return -EINVAL; 15357 } 15358 if (insn->off != 0) { 15359 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 15360 return -EINVAL; 15361 } 15362 15363 err = check_reg_arg(env, insn->dst_reg, DST_OP); 15364 if (err) 15365 return err; 15366 15367 dst_reg = ®s[insn->dst_reg]; 15368 if (insn->src_reg == 0) { 15369 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 15370 15371 dst_reg->type = SCALAR_VALUE; 15372 __mark_reg_known(®s[insn->dst_reg], imm); 15373 return 0; 15374 } 15375 15376 /* All special src_reg cases are listed below. From this point onwards 15377 * we either succeed and assign a corresponding dst_reg->type after 15378 * zeroing the offset, or fail and reject the program. 15379 */ 15380 mark_reg_known_zero(env, regs, insn->dst_reg); 15381 15382 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 15383 dst_reg->type = aux->btf_var.reg_type; 15384 switch (base_type(dst_reg->type)) { 15385 case PTR_TO_MEM: 15386 dst_reg->mem_size = aux->btf_var.mem_size; 15387 break; 15388 case PTR_TO_BTF_ID: 15389 dst_reg->btf = aux->btf_var.btf; 15390 dst_reg->btf_id = aux->btf_var.btf_id; 15391 break; 15392 default: 15393 verbose(env, "bpf verifier is misconfigured\n"); 15394 return -EFAULT; 15395 } 15396 return 0; 15397 } 15398 15399 if (insn->src_reg == BPF_PSEUDO_FUNC) { 15400 struct bpf_prog_aux *aux = env->prog->aux; 15401 u32 subprogno = find_subprog(env, 15402 env->insn_idx + insn->imm + 1); 15403 15404 if (!aux->func_info) { 15405 verbose(env, "missing btf func_info\n"); 15406 return -EINVAL; 15407 } 15408 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 15409 verbose(env, "callback function not static\n"); 15410 return -EINVAL; 15411 } 15412 15413 dst_reg->type = PTR_TO_FUNC; 15414 dst_reg->subprogno = subprogno; 15415 return 0; 15416 } 15417 15418 map = env->used_maps[aux->map_index]; 15419 dst_reg->map_ptr = map; 15420 15421 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 15422 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 15423 if (map->map_type == BPF_MAP_TYPE_ARENA) { 15424 __mark_reg_unknown(env, dst_reg); 15425 return 0; 15426 } 15427 dst_reg->type = PTR_TO_MAP_VALUE; 15428 dst_reg->off = aux->map_off; 15429 WARN_ON_ONCE(map->max_entries != 1); 15430 /* We want reg->id to be same (0) as map_value is not distinct */ 15431 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 15432 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 15433 dst_reg->type = CONST_PTR_TO_MAP; 15434 } else { 15435 verbose(env, "bpf verifier is misconfigured\n"); 15436 return -EINVAL; 15437 } 15438 15439 return 0; 15440 } 15441 15442 static bool may_access_skb(enum bpf_prog_type type) 15443 { 15444 switch (type) { 15445 case BPF_PROG_TYPE_SOCKET_FILTER: 15446 case BPF_PROG_TYPE_SCHED_CLS: 15447 case BPF_PROG_TYPE_SCHED_ACT: 15448 return true; 15449 default: 15450 return false; 15451 } 15452 } 15453 15454 /* verify safety of LD_ABS|LD_IND instructions: 15455 * - they can only appear in the programs where ctx == skb 15456 * - since they are wrappers of function calls, they scratch R1-R5 registers, 15457 * preserve R6-R9, and store return value into R0 15458 * 15459 * Implicit input: 15460 * ctx == skb == R6 == CTX 15461 * 15462 * Explicit input: 15463 * SRC == any register 15464 * IMM == 32-bit immediate 15465 * 15466 * Output: 15467 * R0 - 8/16/32-bit skb data converted to cpu endianness 15468 */ 15469 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 15470 { 15471 struct bpf_reg_state *regs = cur_regs(env); 15472 static const int ctx_reg = BPF_REG_6; 15473 u8 mode = BPF_MODE(insn->code); 15474 int i, err; 15475 15476 if (!may_access_skb(resolve_prog_type(env->prog))) { 15477 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 15478 return -EINVAL; 15479 } 15480 15481 if (!env->ops->gen_ld_abs) { 15482 verbose(env, "bpf verifier is misconfigured\n"); 15483 return -EINVAL; 15484 } 15485 15486 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 15487 BPF_SIZE(insn->code) == BPF_DW || 15488 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 15489 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 15490 return -EINVAL; 15491 } 15492 15493 /* check whether implicit source operand (register R6) is readable */ 15494 err = check_reg_arg(env, ctx_reg, SRC_OP); 15495 if (err) 15496 return err; 15497 15498 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 15499 * gen_ld_abs() may terminate the program at runtime, leading to 15500 * reference leak. 15501 */ 15502 err = check_reference_leak(env, false); 15503 if (err) { 15504 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 15505 return err; 15506 } 15507 15508 if (env->cur_state->active_lock.ptr) { 15509 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 15510 return -EINVAL; 15511 } 15512 15513 if (env->cur_state->active_rcu_lock) { 15514 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 15515 return -EINVAL; 15516 } 15517 15518 if (env->cur_state->active_preempt_lock) { 15519 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_preempt_disable-ed region\n"); 15520 return -EINVAL; 15521 } 15522 15523 if (regs[ctx_reg].type != PTR_TO_CTX) { 15524 verbose(env, 15525 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 15526 return -EINVAL; 15527 } 15528 15529 if (mode == BPF_IND) { 15530 /* check explicit source operand */ 15531 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15532 if (err) 15533 return err; 15534 } 15535 15536 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 15537 if (err < 0) 15538 return err; 15539 15540 /* reset caller saved regs to unreadable */ 15541 for (i = 0; i < CALLER_SAVED_REGS; i++) { 15542 mark_reg_not_init(env, regs, caller_saved[i]); 15543 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 15544 } 15545 15546 /* mark destination R0 register as readable, since it contains 15547 * the value fetched from the packet. 15548 * Already marked as written above. 15549 */ 15550 mark_reg_unknown(env, regs, BPF_REG_0); 15551 /* ld_abs load up to 32-bit skb data. */ 15552 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 15553 return 0; 15554 } 15555 15556 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 15557 { 15558 const char *exit_ctx = "At program exit"; 15559 struct tnum enforce_attach_type_range = tnum_unknown; 15560 const struct bpf_prog *prog = env->prog; 15561 struct bpf_reg_state *reg; 15562 struct bpf_retval_range range = retval_range(0, 1); 15563 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 15564 int err; 15565 struct bpf_func_state *frame = env->cur_state->frame[0]; 15566 const bool is_subprog = frame->subprogno; 15567 15568 /* LSM and struct_ops func-ptr's return type could be "void" */ 15569 if (!is_subprog || frame->in_exception_callback_fn) { 15570 switch (prog_type) { 15571 case BPF_PROG_TYPE_LSM: 15572 if (prog->expected_attach_type == BPF_LSM_CGROUP) 15573 /* See below, can be 0 or 0-1 depending on hook. */ 15574 break; 15575 fallthrough; 15576 case BPF_PROG_TYPE_STRUCT_OPS: 15577 if (!prog->aux->attach_func_proto->type) 15578 return 0; 15579 break; 15580 default: 15581 break; 15582 } 15583 } 15584 15585 /* eBPF calling convention is such that R0 is used 15586 * to return the value from eBPF program. 15587 * Make sure that it's readable at this time 15588 * of bpf_exit, which means that program wrote 15589 * something into it earlier 15590 */ 15591 err = check_reg_arg(env, regno, SRC_OP); 15592 if (err) 15593 return err; 15594 15595 if (is_pointer_value(env, regno)) { 15596 verbose(env, "R%d leaks addr as return value\n", regno); 15597 return -EACCES; 15598 } 15599 15600 reg = cur_regs(env) + regno; 15601 15602 if (frame->in_async_callback_fn) { 15603 /* enforce return zero from async callbacks like timer */ 15604 exit_ctx = "At async callback return"; 15605 range = retval_range(0, 0); 15606 goto enforce_retval; 15607 } 15608 15609 if (is_subprog && !frame->in_exception_callback_fn) { 15610 if (reg->type != SCALAR_VALUE) { 15611 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 15612 regno, reg_type_str(env, reg->type)); 15613 return -EINVAL; 15614 } 15615 return 0; 15616 } 15617 15618 switch (prog_type) { 15619 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 15620 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 15621 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 15622 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG || 15623 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 15624 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 15625 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME || 15626 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 15627 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME || 15628 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME) 15629 range = retval_range(1, 1); 15630 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 15631 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 15632 range = retval_range(0, 3); 15633 break; 15634 case BPF_PROG_TYPE_CGROUP_SKB: 15635 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 15636 range = retval_range(0, 3); 15637 enforce_attach_type_range = tnum_range(2, 3); 15638 } 15639 break; 15640 case BPF_PROG_TYPE_CGROUP_SOCK: 15641 case BPF_PROG_TYPE_SOCK_OPS: 15642 case BPF_PROG_TYPE_CGROUP_DEVICE: 15643 case BPF_PROG_TYPE_CGROUP_SYSCTL: 15644 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 15645 break; 15646 case BPF_PROG_TYPE_RAW_TRACEPOINT: 15647 if (!env->prog->aux->attach_btf_id) 15648 return 0; 15649 range = retval_range(0, 0); 15650 break; 15651 case BPF_PROG_TYPE_TRACING: 15652 switch (env->prog->expected_attach_type) { 15653 case BPF_TRACE_FENTRY: 15654 case BPF_TRACE_FEXIT: 15655 range = retval_range(0, 0); 15656 break; 15657 case BPF_TRACE_RAW_TP: 15658 case BPF_MODIFY_RETURN: 15659 return 0; 15660 case BPF_TRACE_ITER: 15661 break; 15662 default: 15663 return -ENOTSUPP; 15664 } 15665 break; 15666 case BPF_PROG_TYPE_SK_LOOKUP: 15667 range = retval_range(SK_DROP, SK_PASS); 15668 break; 15669 15670 case BPF_PROG_TYPE_LSM: 15671 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 15672 /* Regular BPF_PROG_TYPE_LSM programs can return 15673 * any value. 15674 */ 15675 return 0; 15676 } 15677 if (!env->prog->aux->attach_func_proto->type) { 15678 /* Make sure programs that attach to void 15679 * hooks don't try to modify return value. 15680 */ 15681 range = retval_range(1, 1); 15682 } 15683 break; 15684 15685 case BPF_PROG_TYPE_NETFILTER: 15686 range = retval_range(NF_DROP, NF_ACCEPT); 15687 break; 15688 case BPF_PROG_TYPE_EXT: 15689 /* freplace program can return anything as its return value 15690 * depends on the to-be-replaced kernel func or bpf program. 15691 */ 15692 default: 15693 return 0; 15694 } 15695 15696 enforce_retval: 15697 if (reg->type != SCALAR_VALUE) { 15698 verbose(env, "%s the register R%d is not a known value (%s)\n", 15699 exit_ctx, regno, reg_type_str(env, reg->type)); 15700 return -EINVAL; 15701 } 15702 15703 err = mark_chain_precision(env, regno); 15704 if (err) 15705 return err; 15706 15707 if (!retval_range_within(range, reg)) { 15708 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 15709 if (!is_subprog && 15710 prog->expected_attach_type == BPF_LSM_CGROUP && 15711 prog_type == BPF_PROG_TYPE_LSM && 15712 !prog->aux->attach_func_proto->type) 15713 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 15714 return -EINVAL; 15715 } 15716 15717 if (!tnum_is_unknown(enforce_attach_type_range) && 15718 tnum_in(enforce_attach_type_range, reg->var_off)) 15719 env->prog->enforce_expected_attach_type = 1; 15720 return 0; 15721 } 15722 15723 /* non-recursive DFS pseudo code 15724 * 1 procedure DFS-iterative(G,v): 15725 * 2 label v as discovered 15726 * 3 let S be a stack 15727 * 4 S.push(v) 15728 * 5 while S is not empty 15729 * 6 t <- S.peek() 15730 * 7 if t is what we're looking for: 15731 * 8 return t 15732 * 9 for all edges e in G.adjacentEdges(t) do 15733 * 10 if edge e is already labelled 15734 * 11 continue with the next edge 15735 * 12 w <- G.adjacentVertex(t,e) 15736 * 13 if vertex w is not discovered and not explored 15737 * 14 label e as tree-edge 15738 * 15 label w as discovered 15739 * 16 S.push(w) 15740 * 17 continue at 5 15741 * 18 else if vertex w is discovered 15742 * 19 label e as back-edge 15743 * 20 else 15744 * 21 // vertex w is explored 15745 * 22 label e as forward- or cross-edge 15746 * 23 label t as explored 15747 * 24 S.pop() 15748 * 15749 * convention: 15750 * 0x10 - discovered 15751 * 0x11 - discovered and fall-through edge labelled 15752 * 0x12 - discovered and fall-through and branch edges labelled 15753 * 0x20 - explored 15754 */ 15755 15756 enum { 15757 DISCOVERED = 0x10, 15758 EXPLORED = 0x20, 15759 FALLTHROUGH = 1, 15760 BRANCH = 2, 15761 }; 15762 15763 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 15764 { 15765 env->insn_aux_data[idx].prune_point = true; 15766 } 15767 15768 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 15769 { 15770 return env->insn_aux_data[insn_idx].prune_point; 15771 } 15772 15773 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 15774 { 15775 env->insn_aux_data[idx].force_checkpoint = true; 15776 } 15777 15778 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 15779 { 15780 return env->insn_aux_data[insn_idx].force_checkpoint; 15781 } 15782 15783 static void mark_calls_callback(struct bpf_verifier_env *env, int idx) 15784 { 15785 env->insn_aux_data[idx].calls_callback = true; 15786 } 15787 15788 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx) 15789 { 15790 return env->insn_aux_data[insn_idx].calls_callback; 15791 } 15792 15793 enum { 15794 DONE_EXPLORING = 0, 15795 KEEP_EXPLORING = 1, 15796 }; 15797 15798 /* t, w, e - match pseudo-code above: 15799 * t - index of current instruction 15800 * w - next instruction 15801 * e - edge 15802 */ 15803 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 15804 { 15805 int *insn_stack = env->cfg.insn_stack; 15806 int *insn_state = env->cfg.insn_state; 15807 15808 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 15809 return DONE_EXPLORING; 15810 15811 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 15812 return DONE_EXPLORING; 15813 15814 if (w < 0 || w >= env->prog->len) { 15815 verbose_linfo(env, t, "%d: ", t); 15816 verbose(env, "jump out of range from insn %d to %d\n", t, w); 15817 return -EINVAL; 15818 } 15819 15820 if (e == BRANCH) { 15821 /* mark branch target for state pruning */ 15822 mark_prune_point(env, w); 15823 mark_jmp_point(env, w); 15824 } 15825 15826 if (insn_state[w] == 0) { 15827 /* tree-edge */ 15828 insn_state[t] = DISCOVERED | e; 15829 insn_state[w] = DISCOVERED; 15830 if (env->cfg.cur_stack >= env->prog->len) 15831 return -E2BIG; 15832 insn_stack[env->cfg.cur_stack++] = w; 15833 return KEEP_EXPLORING; 15834 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 15835 if (env->bpf_capable) 15836 return DONE_EXPLORING; 15837 verbose_linfo(env, t, "%d: ", t); 15838 verbose_linfo(env, w, "%d: ", w); 15839 verbose(env, "back-edge from insn %d to %d\n", t, w); 15840 return -EINVAL; 15841 } else if (insn_state[w] == EXPLORED) { 15842 /* forward- or cross-edge */ 15843 insn_state[t] = DISCOVERED | e; 15844 } else { 15845 verbose(env, "insn state internal bug\n"); 15846 return -EFAULT; 15847 } 15848 return DONE_EXPLORING; 15849 } 15850 15851 static int visit_func_call_insn(int t, struct bpf_insn *insns, 15852 struct bpf_verifier_env *env, 15853 bool visit_callee) 15854 { 15855 int ret, insn_sz; 15856 15857 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 15858 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 15859 if (ret) 15860 return ret; 15861 15862 mark_prune_point(env, t + insn_sz); 15863 /* when we exit from subprog, we need to record non-linear history */ 15864 mark_jmp_point(env, t + insn_sz); 15865 15866 if (visit_callee) { 15867 mark_prune_point(env, t); 15868 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env); 15869 } 15870 return ret; 15871 } 15872 15873 /* Visits the instruction at index t and returns one of the following: 15874 * < 0 - an error occurred 15875 * DONE_EXPLORING - the instruction was fully explored 15876 * KEEP_EXPLORING - there is still work to be done before it is fully explored 15877 */ 15878 static int visit_insn(int t, struct bpf_verifier_env *env) 15879 { 15880 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 15881 int ret, off, insn_sz; 15882 15883 if (bpf_pseudo_func(insn)) 15884 return visit_func_call_insn(t, insns, env, true); 15885 15886 /* All non-branch instructions have a single fall-through edge. */ 15887 if (BPF_CLASS(insn->code) != BPF_JMP && 15888 BPF_CLASS(insn->code) != BPF_JMP32) { 15889 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 15890 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 15891 } 15892 15893 switch (BPF_OP(insn->code)) { 15894 case BPF_EXIT: 15895 return DONE_EXPLORING; 15896 15897 case BPF_CALL: 15898 if (is_async_callback_calling_insn(insn)) 15899 /* Mark this call insn as a prune point to trigger 15900 * is_state_visited() check before call itself is 15901 * processed by __check_func_call(). Otherwise new 15902 * async state will be pushed for further exploration. 15903 */ 15904 mark_prune_point(env, t); 15905 /* For functions that invoke callbacks it is not known how many times 15906 * callback would be called. Verifier models callback calling functions 15907 * by repeatedly visiting callback bodies and returning to origin call 15908 * instruction. 15909 * In order to stop such iteration verifier needs to identify when a 15910 * state identical some state from a previous iteration is reached. 15911 * Check below forces creation of checkpoint before callback calling 15912 * instruction to allow search for such identical states. 15913 */ 15914 if (is_sync_callback_calling_insn(insn)) { 15915 mark_calls_callback(env, t); 15916 mark_force_checkpoint(env, t); 15917 mark_prune_point(env, t); 15918 mark_jmp_point(env, t); 15919 } 15920 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 15921 struct bpf_kfunc_call_arg_meta meta; 15922 15923 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 15924 if (ret == 0 && is_iter_next_kfunc(&meta)) { 15925 mark_prune_point(env, t); 15926 /* Checking and saving state checkpoints at iter_next() call 15927 * is crucial for fast convergence of open-coded iterator loop 15928 * logic, so we need to force it. If we don't do that, 15929 * is_state_visited() might skip saving a checkpoint, causing 15930 * unnecessarily long sequence of not checkpointed 15931 * instructions and jumps, leading to exhaustion of jump 15932 * history buffer, and potentially other undesired outcomes. 15933 * It is expected that with correct open-coded iterators 15934 * convergence will happen quickly, so we don't run a risk of 15935 * exhausting memory. 15936 */ 15937 mark_force_checkpoint(env, t); 15938 } 15939 } 15940 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 15941 15942 case BPF_JA: 15943 if (BPF_SRC(insn->code) != BPF_K) 15944 return -EINVAL; 15945 15946 if (BPF_CLASS(insn->code) == BPF_JMP) 15947 off = insn->off; 15948 else 15949 off = insn->imm; 15950 15951 /* unconditional jump with single edge */ 15952 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 15953 if (ret) 15954 return ret; 15955 15956 mark_prune_point(env, t + off + 1); 15957 mark_jmp_point(env, t + off + 1); 15958 15959 return ret; 15960 15961 default: 15962 /* conditional jump with two edges */ 15963 mark_prune_point(env, t); 15964 if (is_may_goto_insn(insn)) 15965 mark_force_checkpoint(env, t); 15966 15967 ret = push_insn(t, t + 1, FALLTHROUGH, env); 15968 if (ret) 15969 return ret; 15970 15971 return push_insn(t, t + insn->off + 1, BRANCH, env); 15972 } 15973 } 15974 15975 /* non-recursive depth-first-search to detect loops in BPF program 15976 * loop == back-edge in directed graph 15977 */ 15978 static int check_cfg(struct bpf_verifier_env *env) 15979 { 15980 int insn_cnt = env->prog->len; 15981 int *insn_stack, *insn_state; 15982 int ex_insn_beg, i, ret = 0; 15983 bool ex_done = false; 15984 15985 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15986 if (!insn_state) 15987 return -ENOMEM; 15988 15989 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15990 if (!insn_stack) { 15991 kvfree(insn_state); 15992 return -ENOMEM; 15993 } 15994 15995 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 15996 insn_stack[0] = 0; /* 0 is the first instruction */ 15997 env->cfg.cur_stack = 1; 15998 15999 walk_cfg: 16000 while (env->cfg.cur_stack > 0) { 16001 int t = insn_stack[env->cfg.cur_stack - 1]; 16002 16003 ret = visit_insn(t, env); 16004 switch (ret) { 16005 case DONE_EXPLORING: 16006 insn_state[t] = EXPLORED; 16007 env->cfg.cur_stack--; 16008 break; 16009 case KEEP_EXPLORING: 16010 break; 16011 default: 16012 if (ret > 0) { 16013 verbose(env, "visit_insn internal bug\n"); 16014 ret = -EFAULT; 16015 } 16016 goto err_free; 16017 } 16018 } 16019 16020 if (env->cfg.cur_stack < 0) { 16021 verbose(env, "pop stack internal bug\n"); 16022 ret = -EFAULT; 16023 goto err_free; 16024 } 16025 16026 if (env->exception_callback_subprog && !ex_done) { 16027 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start; 16028 16029 insn_state[ex_insn_beg] = DISCOVERED; 16030 insn_stack[0] = ex_insn_beg; 16031 env->cfg.cur_stack = 1; 16032 ex_done = true; 16033 goto walk_cfg; 16034 } 16035 16036 for (i = 0; i < insn_cnt; i++) { 16037 struct bpf_insn *insn = &env->prog->insnsi[i]; 16038 16039 if (insn_state[i] != EXPLORED) { 16040 verbose(env, "unreachable insn %d\n", i); 16041 ret = -EINVAL; 16042 goto err_free; 16043 } 16044 if (bpf_is_ldimm64(insn)) { 16045 if (insn_state[i + 1] != 0) { 16046 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 16047 ret = -EINVAL; 16048 goto err_free; 16049 } 16050 i++; /* skip second half of ldimm64 */ 16051 } 16052 } 16053 ret = 0; /* cfg looks good */ 16054 16055 err_free: 16056 kvfree(insn_state); 16057 kvfree(insn_stack); 16058 env->cfg.insn_state = env->cfg.insn_stack = NULL; 16059 return ret; 16060 } 16061 16062 static int check_abnormal_return(struct bpf_verifier_env *env) 16063 { 16064 int i; 16065 16066 for (i = 1; i < env->subprog_cnt; i++) { 16067 if (env->subprog_info[i].has_ld_abs) { 16068 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 16069 return -EINVAL; 16070 } 16071 if (env->subprog_info[i].has_tail_call) { 16072 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 16073 return -EINVAL; 16074 } 16075 } 16076 return 0; 16077 } 16078 16079 /* The minimum supported BTF func info size */ 16080 #define MIN_BPF_FUNCINFO_SIZE 8 16081 #define MAX_FUNCINFO_REC_SIZE 252 16082 16083 static int check_btf_func_early(struct bpf_verifier_env *env, 16084 const union bpf_attr *attr, 16085 bpfptr_t uattr) 16086 { 16087 u32 krec_size = sizeof(struct bpf_func_info); 16088 const struct btf_type *type, *func_proto; 16089 u32 i, nfuncs, urec_size, min_size; 16090 struct bpf_func_info *krecord; 16091 struct bpf_prog *prog; 16092 const struct btf *btf; 16093 u32 prev_offset = 0; 16094 bpfptr_t urecord; 16095 int ret = -ENOMEM; 16096 16097 nfuncs = attr->func_info_cnt; 16098 if (!nfuncs) { 16099 if (check_abnormal_return(env)) 16100 return -EINVAL; 16101 return 0; 16102 } 16103 16104 urec_size = attr->func_info_rec_size; 16105 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 16106 urec_size > MAX_FUNCINFO_REC_SIZE || 16107 urec_size % sizeof(u32)) { 16108 verbose(env, "invalid func info rec size %u\n", urec_size); 16109 return -EINVAL; 16110 } 16111 16112 prog = env->prog; 16113 btf = prog->aux->btf; 16114 16115 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 16116 min_size = min_t(u32, krec_size, urec_size); 16117 16118 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 16119 if (!krecord) 16120 return -ENOMEM; 16121 16122 for (i = 0; i < nfuncs; i++) { 16123 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 16124 if (ret) { 16125 if (ret == -E2BIG) { 16126 verbose(env, "nonzero tailing record in func info"); 16127 /* set the size kernel expects so loader can zero 16128 * out the rest of the record. 16129 */ 16130 if (copy_to_bpfptr_offset(uattr, 16131 offsetof(union bpf_attr, func_info_rec_size), 16132 &min_size, sizeof(min_size))) 16133 ret = -EFAULT; 16134 } 16135 goto err_free; 16136 } 16137 16138 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 16139 ret = -EFAULT; 16140 goto err_free; 16141 } 16142 16143 /* check insn_off */ 16144 ret = -EINVAL; 16145 if (i == 0) { 16146 if (krecord[i].insn_off) { 16147 verbose(env, 16148 "nonzero insn_off %u for the first func info record", 16149 krecord[i].insn_off); 16150 goto err_free; 16151 } 16152 } else if (krecord[i].insn_off <= prev_offset) { 16153 verbose(env, 16154 "same or smaller insn offset (%u) than previous func info record (%u)", 16155 krecord[i].insn_off, prev_offset); 16156 goto err_free; 16157 } 16158 16159 /* check type_id */ 16160 type = btf_type_by_id(btf, krecord[i].type_id); 16161 if (!type || !btf_type_is_func(type)) { 16162 verbose(env, "invalid type id %d in func info", 16163 krecord[i].type_id); 16164 goto err_free; 16165 } 16166 16167 func_proto = btf_type_by_id(btf, type->type); 16168 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 16169 /* btf_func_check() already verified it during BTF load */ 16170 goto err_free; 16171 16172 prev_offset = krecord[i].insn_off; 16173 bpfptr_add(&urecord, urec_size); 16174 } 16175 16176 prog->aux->func_info = krecord; 16177 prog->aux->func_info_cnt = nfuncs; 16178 return 0; 16179 16180 err_free: 16181 kvfree(krecord); 16182 return ret; 16183 } 16184 16185 static int check_btf_func(struct bpf_verifier_env *env, 16186 const union bpf_attr *attr, 16187 bpfptr_t uattr) 16188 { 16189 const struct btf_type *type, *func_proto, *ret_type; 16190 u32 i, nfuncs, urec_size; 16191 struct bpf_func_info *krecord; 16192 struct bpf_func_info_aux *info_aux = NULL; 16193 struct bpf_prog *prog; 16194 const struct btf *btf; 16195 bpfptr_t urecord; 16196 bool scalar_return; 16197 int ret = -ENOMEM; 16198 16199 nfuncs = attr->func_info_cnt; 16200 if (!nfuncs) { 16201 if (check_abnormal_return(env)) 16202 return -EINVAL; 16203 return 0; 16204 } 16205 if (nfuncs != env->subprog_cnt) { 16206 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 16207 return -EINVAL; 16208 } 16209 16210 urec_size = attr->func_info_rec_size; 16211 16212 prog = env->prog; 16213 btf = prog->aux->btf; 16214 16215 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 16216 16217 krecord = prog->aux->func_info; 16218 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 16219 if (!info_aux) 16220 return -ENOMEM; 16221 16222 for (i = 0; i < nfuncs; i++) { 16223 /* check insn_off */ 16224 ret = -EINVAL; 16225 16226 if (env->subprog_info[i].start != krecord[i].insn_off) { 16227 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 16228 goto err_free; 16229 } 16230 16231 /* Already checked type_id */ 16232 type = btf_type_by_id(btf, krecord[i].type_id); 16233 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 16234 /* Already checked func_proto */ 16235 func_proto = btf_type_by_id(btf, type->type); 16236 16237 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 16238 scalar_return = 16239 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 16240 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 16241 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 16242 goto err_free; 16243 } 16244 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 16245 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 16246 goto err_free; 16247 } 16248 16249 bpfptr_add(&urecord, urec_size); 16250 } 16251 16252 prog->aux->func_info_aux = info_aux; 16253 return 0; 16254 16255 err_free: 16256 kfree(info_aux); 16257 return ret; 16258 } 16259 16260 static void adjust_btf_func(struct bpf_verifier_env *env) 16261 { 16262 struct bpf_prog_aux *aux = env->prog->aux; 16263 int i; 16264 16265 if (!aux->func_info) 16266 return; 16267 16268 /* func_info is not available for hidden subprogs */ 16269 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 16270 aux->func_info[i].insn_off = env->subprog_info[i].start; 16271 } 16272 16273 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 16274 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 16275 16276 static int check_btf_line(struct bpf_verifier_env *env, 16277 const union bpf_attr *attr, 16278 bpfptr_t uattr) 16279 { 16280 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 16281 struct bpf_subprog_info *sub; 16282 struct bpf_line_info *linfo; 16283 struct bpf_prog *prog; 16284 const struct btf *btf; 16285 bpfptr_t ulinfo; 16286 int err; 16287 16288 nr_linfo = attr->line_info_cnt; 16289 if (!nr_linfo) 16290 return 0; 16291 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 16292 return -EINVAL; 16293 16294 rec_size = attr->line_info_rec_size; 16295 if (rec_size < MIN_BPF_LINEINFO_SIZE || 16296 rec_size > MAX_LINEINFO_REC_SIZE || 16297 rec_size & (sizeof(u32) - 1)) 16298 return -EINVAL; 16299 16300 /* Need to zero it in case the userspace may 16301 * pass in a smaller bpf_line_info object. 16302 */ 16303 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 16304 GFP_KERNEL | __GFP_NOWARN); 16305 if (!linfo) 16306 return -ENOMEM; 16307 16308 prog = env->prog; 16309 btf = prog->aux->btf; 16310 16311 s = 0; 16312 sub = env->subprog_info; 16313 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 16314 expected_size = sizeof(struct bpf_line_info); 16315 ncopy = min_t(u32, expected_size, rec_size); 16316 for (i = 0; i < nr_linfo; i++) { 16317 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 16318 if (err) { 16319 if (err == -E2BIG) { 16320 verbose(env, "nonzero tailing record in line_info"); 16321 if (copy_to_bpfptr_offset(uattr, 16322 offsetof(union bpf_attr, line_info_rec_size), 16323 &expected_size, sizeof(expected_size))) 16324 err = -EFAULT; 16325 } 16326 goto err_free; 16327 } 16328 16329 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 16330 err = -EFAULT; 16331 goto err_free; 16332 } 16333 16334 /* 16335 * Check insn_off to ensure 16336 * 1) strictly increasing AND 16337 * 2) bounded by prog->len 16338 * 16339 * The linfo[0].insn_off == 0 check logically falls into 16340 * the later "missing bpf_line_info for func..." case 16341 * because the first linfo[0].insn_off must be the 16342 * first sub also and the first sub must have 16343 * subprog_info[0].start == 0. 16344 */ 16345 if ((i && linfo[i].insn_off <= prev_offset) || 16346 linfo[i].insn_off >= prog->len) { 16347 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 16348 i, linfo[i].insn_off, prev_offset, 16349 prog->len); 16350 err = -EINVAL; 16351 goto err_free; 16352 } 16353 16354 if (!prog->insnsi[linfo[i].insn_off].code) { 16355 verbose(env, 16356 "Invalid insn code at line_info[%u].insn_off\n", 16357 i); 16358 err = -EINVAL; 16359 goto err_free; 16360 } 16361 16362 if (!btf_name_by_offset(btf, linfo[i].line_off) || 16363 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 16364 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 16365 err = -EINVAL; 16366 goto err_free; 16367 } 16368 16369 if (s != env->subprog_cnt) { 16370 if (linfo[i].insn_off == sub[s].start) { 16371 sub[s].linfo_idx = i; 16372 s++; 16373 } else if (sub[s].start < linfo[i].insn_off) { 16374 verbose(env, "missing bpf_line_info for func#%u\n", s); 16375 err = -EINVAL; 16376 goto err_free; 16377 } 16378 } 16379 16380 prev_offset = linfo[i].insn_off; 16381 bpfptr_add(&ulinfo, rec_size); 16382 } 16383 16384 if (s != env->subprog_cnt) { 16385 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 16386 env->subprog_cnt - s, s); 16387 err = -EINVAL; 16388 goto err_free; 16389 } 16390 16391 prog->aux->linfo = linfo; 16392 prog->aux->nr_linfo = nr_linfo; 16393 16394 return 0; 16395 16396 err_free: 16397 kvfree(linfo); 16398 return err; 16399 } 16400 16401 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 16402 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 16403 16404 static int check_core_relo(struct bpf_verifier_env *env, 16405 const union bpf_attr *attr, 16406 bpfptr_t uattr) 16407 { 16408 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 16409 struct bpf_core_relo core_relo = {}; 16410 struct bpf_prog *prog = env->prog; 16411 const struct btf *btf = prog->aux->btf; 16412 struct bpf_core_ctx ctx = { 16413 .log = &env->log, 16414 .btf = btf, 16415 }; 16416 bpfptr_t u_core_relo; 16417 int err; 16418 16419 nr_core_relo = attr->core_relo_cnt; 16420 if (!nr_core_relo) 16421 return 0; 16422 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 16423 return -EINVAL; 16424 16425 rec_size = attr->core_relo_rec_size; 16426 if (rec_size < MIN_CORE_RELO_SIZE || 16427 rec_size > MAX_CORE_RELO_SIZE || 16428 rec_size % sizeof(u32)) 16429 return -EINVAL; 16430 16431 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 16432 expected_size = sizeof(struct bpf_core_relo); 16433 ncopy = min_t(u32, expected_size, rec_size); 16434 16435 /* Unlike func_info and line_info, copy and apply each CO-RE 16436 * relocation record one at a time. 16437 */ 16438 for (i = 0; i < nr_core_relo; i++) { 16439 /* future proofing when sizeof(bpf_core_relo) changes */ 16440 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 16441 if (err) { 16442 if (err == -E2BIG) { 16443 verbose(env, "nonzero tailing record in core_relo"); 16444 if (copy_to_bpfptr_offset(uattr, 16445 offsetof(union bpf_attr, core_relo_rec_size), 16446 &expected_size, sizeof(expected_size))) 16447 err = -EFAULT; 16448 } 16449 break; 16450 } 16451 16452 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 16453 err = -EFAULT; 16454 break; 16455 } 16456 16457 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 16458 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 16459 i, core_relo.insn_off, prog->len); 16460 err = -EINVAL; 16461 break; 16462 } 16463 16464 err = bpf_core_apply(&ctx, &core_relo, i, 16465 &prog->insnsi[core_relo.insn_off / 8]); 16466 if (err) 16467 break; 16468 bpfptr_add(&u_core_relo, rec_size); 16469 } 16470 return err; 16471 } 16472 16473 static int check_btf_info_early(struct bpf_verifier_env *env, 16474 const union bpf_attr *attr, 16475 bpfptr_t uattr) 16476 { 16477 struct btf *btf; 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 btf = btf_get_by_fd(attr->prog_btf_fd); 16487 if (IS_ERR(btf)) 16488 return PTR_ERR(btf); 16489 if (btf_is_kernel(btf)) { 16490 btf_put(btf); 16491 return -EACCES; 16492 } 16493 env->prog->aux->btf = btf; 16494 16495 err = check_btf_func_early(env, attr, uattr); 16496 if (err) 16497 return err; 16498 return 0; 16499 } 16500 16501 static int check_btf_info(struct bpf_verifier_env *env, 16502 const union bpf_attr *attr, 16503 bpfptr_t uattr) 16504 { 16505 int err; 16506 16507 if (!attr->func_info_cnt && !attr->line_info_cnt) { 16508 if (check_abnormal_return(env)) 16509 return -EINVAL; 16510 return 0; 16511 } 16512 16513 err = check_btf_func(env, attr, uattr); 16514 if (err) 16515 return err; 16516 16517 err = check_btf_line(env, attr, uattr); 16518 if (err) 16519 return err; 16520 16521 err = check_core_relo(env, attr, uattr); 16522 if (err) 16523 return err; 16524 16525 return 0; 16526 } 16527 16528 /* check %cur's range satisfies %old's */ 16529 static bool range_within(const struct bpf_reg_state *old, 16530 const struct bpf_reg_state *cur) 16531 { 16532 return old->umin_value <= cur->umin_value && 16533 old->umax_value >= cur->umax_value && 16534 old->smin_value <= cur->smin_value && 16535 old->smax_value >= cur->smax_value && 16536 old->u32_min_value <= cur->u32_min_value && 16537 old->u32_max_value >= cur->u32_max_value && 16538 old->s32_min_value <= cur->s32_min_value && 16539 old->s32_max_value >= cur->s32_max_value; 16540 } 16541 16542 /* If in the old state two registers had the same id, then they need to have 16543 * the same id in the new state as well. But that id could be different from 16544 * the old state, so we need to track the mapping from old to new ids. 16545 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 16546 * regs with old id 5 must also have new id 9 for the new state to be safe. But 16547 * regs with a different old id could still have new id 9, we don't care about 16548 * that. 16549 * So we look through our idmap to see if this old id has been seen before. If 16550 * so, we require the new id to match; otherwise, we add the id pair to the map. 16551 */ 16552 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 16553 { 16554 struct bpf_id_pair *map = idmap->map; 16555 unsigned int i; 16556 16557 /* either both IDs should be set or both should be zero */ 16558 if (!!old_id != !!cur_id) 16559 return false; 16560 16561 if (old_id == 0) /* cur_id == 0 as well */ 16562 return true; 16563 16564 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 16565 if (!map[i].old) { 16566 /* Reached an empty slot; haven't seen this id before */ 16567 map[i].old = old_id; 16568 map[i].cur = cur_id; 16569 return true; 16570 } 16571 if (map[i].old == old_id) 16572 return map[i].cur == cur_id; 16573 if (map[i].cur == cur_id) 16574 return false; 16575 } 16576 /* We ran out of idmap slots, which should be impossible */ 16577 WARN_ON_ONCE(1); 16578 return false; 16579 } 16580 16581 /* Similar to check_ids(), but allocate a unique temporary ID 16582 * for 'old_id' or 'cur_id' of zero. 16583 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 16584 */ 16585 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 16586 { 16587 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 16588 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 16589 16590 return check_ids(old_id, cur_id, idmap); 16591 } 16592 16593 static void clean_func_state(struct bpf_verifier_env *env, 16594 struct bpf_func_state *st) 16595 { 16596 enum bpf_reg_liveness live; 16597 int i, j; 16598 16599 for (i = 0; i < BPF_REG_FP; i++) { 16600 live = st->regs[i].live; 16601 /* liveness must not touch this register anymore */ 16602 st->regs[i].live |= REG_LIVE_DONE; 16603 if (!(live & REG_LIVE_READ)) 16604 /* since the register is unused, clear its state 16605 * to make further comparison simpler 16606 */ 16607 __mark_reg_not_init(env, &st->regs[i]); 16608 } 16609 16610 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 16611 live = st->stack[i].spilled_ptr.live; 16612 /* liveness must not touch this stack slot anymore */ 16613 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 16614 if (!(live & REG_LIVE_READ)) { 16615 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 16616 for (j = 0; j < BPF_REG_SIZE; j++) 16617 st->stack[i].slot_type[j] = STACK_INVALID; 16618 } 16619 } 16620 } 16621 16622 static void clean_verifier_state(struct bpf_verifier_env *env, 16623 struct bpf_verifier_state *st) 16624 { 16625 int i; 16626 16627 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 16628 /* all regs in this state in all frames were already marked */ 16629 return; 16630 16631 for (i = 0; i <= st->curframe; i++) 16632 clean_func_state(env, st->frame[i]); 16633 } 16634 16635 /* the parentage chains form a tree. 16636 * the verifier states are added to state lists at given insn and 16637 * pushed into state stack for future exploration. 16638 * when the verifier reaches bpf_exit insn some of the verifer states 16639 * stored in the state lists have their final liveness state already, 16640 * but a lot of states will get revised from liveness point of view when 16641 * the verifier explores other branches. 16642 * Example: 16643 * 1: r0 = 1 16644 * 2: if r1 == 100 goto pc+1 16645 * 3: r0 = 2 16646 * 4: exit 16647 * when the verifier reaches exit insn the register r0 in the state list of 16648 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 16649 * of insn 2 and goes exploring further. At the insn 4 it will walk the 16650 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 16651 * 16652 * Since the verifier pushes the branch states as it sees them while exploring 16653 * the program the condition of walking the branch instruction for the second 16654 * time means that all states below this branch were already explored and 16655 * their final liveness marks are already propagated. 16656 * Hence when the verifier completes the search of state list in is_state_visited() 16657 * we can call this clean_live_states() function to mark all liveness states 16658 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 16659 * will not be used. 16660 * This function also clears the registers and stack for states that !READ 16661 * to simplify state merging. 16662 * 16663 * Important note here that walking the same branch instruction in the callee 16664 * doesn't meant that the states are DONE. The verifier has to compare 16665 * the callsites 16666 */ 16667 static void clean_live_states(struct bpf_verifier_env *env, int insn, 16668 struct bpf_verifier_state *cur) 16669 { 16670 struct bpf_verifier_state_list *sl; 16671 16672 sl = *explored_state(env, insn); 16673 while (sl) { 16674 if (sl->state.branches) 16675 goto next; 16676 if (sl->state.insn_idx != insn || 16677 !same_callsites(&sl->state, cur)) 16678 goto next; 16679 clean_verifier_state(env, &sl->state); 16680 next: 16681 sl = sl->next; 16682 } 16683 } 16684 16685 static bool regs_exact(const struct bpf_reg_state *rold, 16686 const struct bpf_reg_state *rcur, 16687 struct bpf_idmap *idmap) 16688 { 16689 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16690 check_ids(rold->id, rcur->id, idmap) && 16691 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16692 } 16693 16694 enum exact_level { 16695 NOT_EXACT, 16696 EXACT, 16697 RANGE_WITHIN 16698 }; 16699 16700 /* Returns true if (rold safe implies rcur safe) */ 16701 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 16702 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, 16703 enum exact_level exact) 16704 { 16705 if (exact == EXACT) 16706 return regs_exact(rold, rcur, idmap); 16707 16708 if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT) 16709 /* explored state didn't use this */ 16710 return true; 16711 if (rold->type == NOT_INIT) { 16712 if (exact == NOT_EXACT || rcur->type == NOT_INIT) 16713 /* explored state can't have used this */ 16714 return true; 16715 } 16716 16717 /* Enforce that register types have to match exactly, including their 16718 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 16719 * rule. 16720 * 16721 * One can make a point that using a pointer register as unbounded 16722 * SCALAR would be technically acceptable, but this could lead to 16723 * pointer leaks because scalars are allowed to leak while pointers 16724 * are not. We could make this safe in special cases if root is 16725 * calling us, but it's probably not worth the hassle. 16726 * 16727 * Also, register types that are *not* MAYBE_NULL could technically be 16728 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 16729 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 16730 * to the same map). 16731 * However, if the old MAYBE_NULL register then got NULL checked, 16732 * doing so could have affected others with the same id, and we can't 16733 * check for that because we lost the id when we converted to 16734 * a non-MAYBE_NULL variant. 16735 * So, as a general rule we don't allow mixing MAYBE_NULL and 16736 * non-MAYBE_NULL registers as well. 16737 */ 16738 if (rold->type != rcur->type) 16739 return false; 16740 16741 switch (base_type(rold->type)) { 16742 case SCALAR_VALUE: 16743 if (env->explore_alu_limits) { 16744 /* explore_alu_limits disables tnum_in() and range_within() 16745 * logic and requires everything to be strict 16746 */ 16747 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16748 check_scalar_ids(rold->id, rcur->id, idmap); 16749 } 16750 if (!rold->precise && exact == NOT_EXACT) 16751 return true; 16752 /* Why check_ids() for scalar registers? 16753 * 16754 * Consider the following BPF code: 16755 * 1: r6 = ... unbound scalar, ID=a ... 16756 * 2: r7 = ... unbound scalar, ID=b ... 16757 * 3: if (r6 > r7) goto +1 16758 * 4: r6 = r7 16759 * 5: if (r6 > X) goto ... 16760 * 6: ... memory operation using r7 ... 16761 * 16762 * First verification path is [1-6]: 16763 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 16764 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark 16765 * r7 <= X, because r6 and r7 share same id. 16766 * Next verification path is [1-4, 6]. 16767 * 16768 * Instruction (6) would be reached in two states: 16769 * I. r6{.id=b}, r7{.id=b} via path 1-6; 16770 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 16771 * 16772 * Use check_ids() to distinguish these states. 16773 * --- 16774 * Also verify that new value satisfies old value range knowledge. 16775 */ 16776 return range_within(rold, rcur) && 16777 tnum_in(rold->var_off, rcur->var_off) && 16778 check_scalar_ids(rold->id, rcur->id, idmap); 16779 case PTR_TO_MAP_KEY: 16780 case PTR_TO_MAP_VALUE: 16781 case PTR_TO_MEM: 16782 case PTR_TO_BUF: 16783 case PTR_TO_TP_BUFFER: 16784 /* If the new min/max/var_off satisfy the old ones and 16785 * everything else matches, we are OK. 16786 */ 16787 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 16788 range_within(rold, rcur) && 16789 tnum_in(rold->var_off, rcur->var_off) && 16790 check_ids(rold->id, rcur->id, idmap) && 16791 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16792 case PTR_TO_PACKET_META: 16793 case PTR_TO_PACKET: 16794 /* We must have at least as much range as the old ptr 16795 * did, so that any accesses which were safe before are 16796 * still safe. This is true even if old range < old off, 16797 * since someone could have accessed through (ptr - k), or 16798 * even done ptr -= k in a register, to get a safe access. 16799 */ 16800 if (rold->range > rcur->range) 16801 return false; 16802 /* If the offsets don't match, we can't trust our alignment; 16803 * nor can we be sure that we won't fall out of range. 16804 */ 16805 if (rold->off != rcur->off) 16806 return false; 16807 /* id relations must be preserved */ 16808 if (!check_ids(rold->id, rcur->id, idmap)) 16809 return false; 16810 /* new val must satisfy old val knowledge */ 16811 return range_within(rold, rcur) && 16812 tnum_in(rold->var_off, rcur->var_off); 16813 case PTR_TO_STACK: 16814 /* two stack pointers are equal only if they're pointing to 16815 * the same stack frame, since fp-8 in foo != fp-8 in bar 16816 */ 16817 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 16818 case PTR_TO_ARENA: 16819 return true; 16820 default: 16821 return regs_exact(rold, rcur, idmap); 16822 } 16823 } 16824 16825 static struct bpf_reg_state unbound_reg; 16826 16827 static __init int unbound_reg_init(void) 16828 { 16829 __mark_reg_unknown_imprecise(&unbound_reg); 16830 unbound_reg.live |= REG_LIVE_READ; 16831 return 0; 16832 } 16833 late_initcall(unbound_reg_init); 16834 16835 static bool is_stack_all_misc(struct bpf_verifier_env *env, 16836 struct bpf_stack_state *stack) 16837 { 16838 u32 i; 16839 16840 for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) { 16841 if ((stack->slot_type[i] == STACK_MISC) || 16842 (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack)) 16843 continue; 16844 return false; 16845 } 16846 16847 return true; 16848 } 16849 16850 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env, 16851 struct bpf_stack_state *stack) 16852 { 16853 if (is_spilled_scalar_reg64(stack)) 16854 return &stack->spilled_ptr; 16855 16856 if (is_stack_all_misc(env, stack)) 16857 return &unbound_reg; 16858 16859 return NULL; 16860 } 16861 16862 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 16863 struct bpf_func_state *cur, struct bpf_idmap *idmap, 16864 enum exact_level exact) 16865 { 16866 int i, spi; 16867 16868 /* walk slots of the explored stack and ignore any additional 16869 * slots in the current stack, since explored(safe) state 16870 * didn't use them 16871 */ 16872 for (i = 0; i < old->allocated_stack; i++) { 16873 struct bpf_reg_state *old_reg, *cur_reg; 16874 16875 spi = i / BPF_REG_SIZE; 16876 16877 if (exact != NOT_EXACT && 16878 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16879 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16880 return false; 16881 16882 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) 16883 && exact == NOT_EXACT) { 16884 i += BPF_REG_SIZE - 1; 16885 /* explored state didn't use this */ 16886 continue; 16887 } 16888 16889 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 16890 continue; 16891 16892 if (env->allow_uninit_stack && 16893 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 16894 continue; 16895 16896 /* explored stack has more populated slots than current stack 16897 * and these slots were used 16898 */ 16899 if (i >= cur->allocated_stack) 16900 return false; 16901 16902 /* 64-bit scalar spill vs all slots MISC and vice versa. 16903 * Load from all slots MISC produces unbound scalar. 16904 * Construct a fake register for such stack and call 16905 * regsafe() to ensure scalar ids are compared. 16906 */ 16907 old_reg = scalar_reg_for_stack(env, &old->stack[spi]); 16908 cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]); 16909 if (old_reg && cur_reg) { 16910 if (!regsafe(env, old_reg, cur_reg, idmap, exact)) 16911 return false; 16912 i += BPF_REG_SIZE - 1; 16913 continue; 16914 } 16915 16916 /* if old state was safe with misc data in the stack 16917 * it will be safe with zero-initialized stack. 16918 * The opposite is not true 16919 */ 16920 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 16921 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 16922 continue; 16923 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16924 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16925 /* Ex: old explored (safe) state has STACK_SPILL in 16926 * this stack slot, but current has STACK_MISC -> 16927 * this verifier states are not equivalent, 16928 * return false to continue verification of this path 16929 */ 16930 return false; 16931 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 16932 continue; 16933 /* Both old and cur are having same slot_type */ 16934 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 16935 case STACK_SPILL: 16936 /* when explored and current stack slot are both storing 16937 * spilled registers, check that stored pointers types 16938 * are the same as well. 16939 * Ex: explored safe path could have stored 16940 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 16941 * but current path has stored: 16942 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 16943 * such verifier states are not equivalent. 16944 * return false to continue verification of this path 16945 */ 16946 if (!regsafe(env, &old->stack[spi].spilled_ptr, 16947 &cur->stack[spi].spilled_ptr, idmap, exact)) 16948 return false; 16949 break; 16950 case STACK_DYNPTR: 16951 old_reg = &old->stack[spi].spilled_ptr; 16952 cur_reg = &cur->stack[spi].spilled_ptr; 16953 if (old_reg->dynptr.type != cur_reg->dynptr.type || 16954 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 16955 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16956 return false; 16957 break; 16958 case STACK_ITER: 16959 old_reg = &old->stack[spi].spilled_ptr; 16960 cur_reg = &cur->stack[spi].spilled_ptr; 16961 /* iter.depth is not compared between states as it 16962 * doesn't matter for correctness and would otherwise 16963 * prevent convergence; we maintain it only to prevent 16964 * infinite loop check triggering, see 16965 * iter_active_depths_differ() 16966 */ 16967 if (old_reg->iter.btf != cur_reg->iter.btf || 16968 old_reg->iter.btf_id != cur_reg->iter.btf_id || 16969 old_reg->iter.state != cur_reg->iter.state || 16970 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 16971 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16972 return false; 16973 break; 16974 case STACK_MISC: 16975 case STACK_ZERO: 16976 case STACK_INVALID: 16977 continue; 16978 /* Ensure that new unhandled slot types return false by default */ 16979 default: 16980 return false; 16981 } 16982 } 16983 return true; 16984 } 16985 16986 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 16987 struct bpf_idmap *idmap) 16988 { 16989 int i; 16990 16991 if (old->acquired_refs != cur->acquired_refs) 16992 return false; 16993 16994 for (i = 0; i < old->acquired_refs; i++) { 16995 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 16996 return false; 16997 } 16998 16999 return true; 17000 } 17001 17002 /* compare two verifier states 17003 * 17004 * all states stored in state_list are known to be valid, since 17005 * verifier reached 'bpf_exit' instruction through them 17006 * 17007 * this function is called when verifier exploring different branches of 17008 * execution popped from the state stack. If it sees an old state that has 17009 * more strict register state and more strict stack state then this execution 17010 * branch doesn't need to be explored further, since verifier already 17011 * concluded that more strict state leads to valid finish. 17012 * 17013 * Therefore two states are equivalent if register state is more conservative 17014 * and explored stack state is more conservative than the current one. 17015 * Example: 17016 * explored current 17017 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 17018 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 17019 * 17020 * In other words if current stack state (one being explored) has more 17021 * valid slots than old one that already passed validation, it means 17022 * the verifier can stop exploring and conclude that current state is valid too 17023 * 17024 * Similarly with registers. If explored state has register type as invalid 17025 * whereas register type in current state is meaningful, it means that 17026 * the current state will reach 'bpf_exit' instruction safely 17027 */ 17028 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 17029 struct bpf_func_state *cur, enum exact_level exact) 17030 { 17031 int i; 17032 17033 if (old->callback_depth > cur->callback_depth) 17034 return false; 17035 17036 for (i = 0; i < MAX_BPF_REG; i++) 17037 if (!regsafe(env, &old->regs[i], &cur->regs[i], 17038 &env->idmap_scratch, exact)) 17039 return false; 17040 17041 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 17042 return false; 17043 17044 if (!refsafe(old, cur, &env->idmap_scratch)) 17045 return false; 17046 17047 return true; 17048 } 17049 17050 static void reset_idmap_scratch(struct bpf_verifier_env *env) 17051 { 17052 env->idmap_scratch.tmp_id_gen = env->id_gen; 17053 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 17054 } 17055 17056 static bool states_equal(struct bpf_verifier_env *env, 17057 struct bpf_verifier_state *old, 17058 struct bpf_verifier_state *cur, 17059 enum exact_level exact) 17060 { 17061 int i; 17062 17063 if (old->curframe != cur->curframe) 17064 return false; 17065 17066 reset_idmap_scratch(env); 17067 17068 /* Verification state from speculative execution simulation 17069 * must never prune a non-speculative execution one. 17070 */ 17071 if (old->speculative && !cur->speculative) 17072 return false; 17073 17074 if (old->active_lock.ptr != cur->active_lock.ptr) 17075 return false; 17076 17077 /* Old and cur active_lock's have to be either both present 17078 * or both absent. 17079 */ 17080 if (!!old->active_lock.id != !!cur->active_lock.id) 17081 return false; 17082 17083 if (old->active_lock.id && 17084 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch)) 17085 return false; 17086 17087 if (old->active_rcu_lock != cur->active_rcu_lock) 17088 return false; 17089 17090 if (old->active_preempt_lock != cur->active_preempt_lock) 17091 return false; 17092 17093 if (old->in_sleepable != cur->in_sleepable) 17094 return false; 17095 17096 /* for states to be equal callsites have to be the same 17097 * and all frame states need to be equivalent 17098 */ 17099 for (i = 0; i <= old->curframe; i++) { 17100 if (old->frame[i]->callsite != cur->frame[i]->callsite) 17101 return false; 17102 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact)) 17103 return false; 17104 } 17105 return true; 17106 } 17107 17108 /* Return 0 if no propagation happened. Return negative error code if error 17109 * happened. Otherwise, return the propagated bit. 17110 */ 17111 static int propagate_liveness_reg(struct bpf_verifier_env *env, 17112 struct bpf_reg_state *reg, 17113 struct bpf_reg_state *parent_reg) 17114 { 17115 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 17116 u8 flag = reg->live & REG_LIVE_READ; 17117 int err; 17118 17119 /* When comes here, read flags of PARENT_REG or REG could be any of 17120 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 17121 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 17122 */ 17123 if (parent_flag == REG_LIVE_READ64 || 17124 /* Or if there is no read flag from REG. */ 17125 !flag || 17126 /* Or if the read flag from REG is the same as PARENT_REG. */ 17127 parent_flag == flag) 17128 return 0; 17129 17130 err = mark_reg_read(env, reg, parent_reg, flag); 17131 if (err) 17132 return err; 17133 17134 return flag; 17135 } 17136 17137 /* A write screens off any subsequent reads; but write marks come from the 17138 * straight-line code between a state and its parent. When we arrive at an 17139 * equivalent state (jump target or such) we didn't arrive by the straight-line 17140 * code, so read marks in the state must propagate to the parent regardless 17141 * of the state's write marks. That's what 'parent == state->parent' comparison 17142 * in mark_reg_read() is for. 17143 */ 17144 static int propagate_liveness(struct bpf_verifier_env *env, 17145 const struct bpf_verifier_state *vstate, 17146 struct bpf_verifier_state *vparent) 17147 { 17148 struct bpf_reg_state *state_reg, *parent_reg; 17149 struct bpf_func_state *state, *parent; 17150 int i, frame, err = 0; 17151 17152 if (vparent->curframe != vstate->curframe) { 17153 WARN(1, "propagate_live: parent frame %d current frame %d\n", 17154 vparent->curframe, vstate->curframe); 17155 return -EFAULT; 17156 } 17157 /* Propagate read liveness of registers... */ 17158 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 17159 for (frame = 0; frame <= vstate->curframe; frame++) { 17160 parent = vparent->frame[frame]; 17161 state = vstate->frame[frame]; 17162 parent_reg = parent->regs; 17163 state_reg = state->regs; 17164 /* We don't need to worry about FP liveness, it's read-only */ 17165 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 17166 err = propagate_liveness_reg(env, &state_reg[i], 17167 &parent_reg[i]); 17168 if (err < 0) 17169 return err; 17170 if (err == REG_LIVE_READ64) 17171 mark_insn_zext(env, &parent_reg[i]); 17172 } 17173 17174 /* Propagate stack slots. */ 17175 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 17176 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 17177 parent_reg = &parent->stack[i].spilled_ptr; 17178 state_reg = &state->stack[i].spilled_ptr; 17179 err = propagate_liveness_reg(env, state_reg, 17180 parent_reg); 17181 if (err < 0) 17182 return err; 17183 } 17184 } 17185 return 0; 17186 } 17187 17188 /* find precise scalars in the previous equivalent state and 17189 * propagate them into the current state 17190 */ 17191 static int propagate_precision(struct bpf_verifier_env *env, 17192 const struct bpf_verifier_state *old) 17193 { 17194 struct bpf_reg_state *state_reg; 17195 struct bpf_func_state *state; 17196 int i, err = 0, fr; 17197 bool first; 17198 17199 for (fr = old->curframe; fr >= 0; fr--) { 17200 state = old->frame[fr]; 17201 state_reg = state->regs; 17202 first = true; 17203 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 17204 if (state_reg->type != SCALAR_VALUE || 17205 !state_reg->precise || 17206 !(state_reg->live & REG_LIVE_READ)) 17207 continue; 17208 if (env->log.level & BPF_LOG_LEVEL2) { 17209 if (first) 17210 verbose(env, "frame %d: propagating r%d", fr, i); 17211 else 17212 verbose(env, ",r%d", i); 17213 } 17214 bt_set_frame_reg(&env->bt, fr, i); 17215 first = false; 17216 } 17217 17218 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 17219 if (!is_spilled_reg(&state->stack[i])) 17220 continue; 17221 state_reg = &state->stack[i].spilled_ptr; 17222 if (state_reg->type != SCALAR_VALUE || 17223 !state_reg->precise || 17224 !(state_reg->live & REG_LIVE_READ)) 17225 continue; 17226 if (env->log.level & BPF_LOG_LEVEL2) { 17227 if (first) 17228 verbose(env, "frame %d: propagating fp%d", 17229 fr, (-i - 1) * BPF_REG_SIZE); 17230 else 17231 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 17232 } 17233 bt_set_frame_slot(&env->bt, fr, i); 17234 first = false; 17235 } 17236 if (!first) 17237 verbose(env, "\n"); 17238 } 17239 17240 err = mark_chain_precision_batch(env); 17241 if (err < 0) 17242 return err; 17243 17244 return 0; 17245 } 17246 17247 static bool states_maybe_looping(struct bpf_verifier_state *old, 17248 struct bpf_verifier_state *cur) 17249 { 17250 struct bpf_func_state *fold, *fcur; 17251 int i, fr = cur->curframe; 17252 17253 if (old->curframe != fr) 17254 return false; 17255 17256 fold = old->frame[fr]; 17257 fcur = cur->frame[fr]; 17258 for (i = 0; i < MAX_BPF_REG; i++) 17259 if (memcmp(&fold->regs[i], &fcur->regs[i], 17260 offsetof(struct bpf_reg_state, parent))) 17261 return false; 17262 return true; 17263 } 17264 17265 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 17266 { 17267 return env->insn_aux_data[insn_idx].is_iter_next; 17268 } 17269 17270 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 17271 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 17272 * states to match, which otherwise would look like an infinite loop. So while 17273 * iter_next() calls are taken care of, we still need to be careful and 17274 * prevent erroneous and too eager declaration of "ininite loop", when 17275 * iterators are involved. 17276 * 17277 * Here's a situation in pseudo-BPF assembly form: 17278 * 17279 * 0: again: ; set up iter_next() call args 17280 * 1: r1 = &it ; <CHECKPOINT HERE> 17281 * 2: call bpf_iter_num_next ; this is iter_next() call 17282 * 3: if r0 == 0 goto done 17283 * 4: ... something useful here ... 17284 * 5: goto again ; another iteration 17285 * 6: done: 17286 * 7: r1 = &it 17287 * 8: call bpf_iter_num_destroy ; clean up iter state 17288 * 9: exit 17289 * 17290 * This is a typical loop. Let's assume that we have a prune point at 1:, 17291 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 17292 * again`, assuming other heuristics don't get in a way). 17293 * 17294 * When we first time come to 1:, let's say we have some state X. We proceed 17295 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 17296 * Now we come back to validate that forked ACTIVE state. We proceed through 17297 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 17298 * are converging. But the problem is that we don't know that yet, as this 17299 * convergence has to happen at iter_next() call site only. So if nothing is 17300 * done, at 1: verifier will use bounded loop logic and declare infinite 17301 * looping (and would be *technically* correct, if not for iterator's 17302 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 17303 * don't want that. So what we do in process_iter_next_call() when we go on 17304 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 17305 * a different iteration. So when we suspect an infinite loop, we additionally 17306 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 17307 * pretend we are not looping and wait for next iter_next() call. 17308 * 17309 * This only applies to ACTIVE state. In DRAINED state we don't expect to 17310 * loop, because that would actually mean infinite loop, as DRAINED state is 17311 * "sticky", and so we'll keep returning into the same instruction with the 17312 * same state (at least in one of possible code paths). 17313 * 17314 * This approach allows to keep infinite loop heuristic even in the face of 17315 * active iterator. E.g., C snippet below is and will be detected as 17316 * inifintely looping: 17317 * 17318 * struct bpf_iter_num it; 17319 * int *p, x; 17320 * 17321 * bpf_iter_num_new(&it, 0, 10); 17322 * while ((p = bpf_iter_num_next(&t))) { 17323 * x = p; 17324 * while (x--) {} // <<-- infinite loop here 17325 * } 17326 * 17327 */ 17328 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 17329 { 17330 struct bpf_reg_state *slot, *cur_slot; 17331 struct bpf_func_state *state; 17332 int i, fr; 17333 17334 for (fr = old->curframe; fr >= 0; fr--) { 17335 state = old->frame[fr]; 17336 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 17337 if (state->stack[i].slot_type[0] != STACK_ITER) 17338 continue; 17339 17340 slot = &state->stack[i].spilled_ptr; 17341 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 17342 continue; 17343 17344 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 17345 if (cur_slot->iter.depth != slot->iter.depth) 17346 return true; 17347 } 17348 } 17349 return false; 17350 } 17351 17352 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 17353 { 17354 struct bpf_verifier_state_list *new_sl; 17355 struct bpf_verifier_state_list *sl, **pprev; 17356 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry; 17357 int i, j, n, err, states_cnt = 0; 17358 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx); 17359 bool add_new_state = force_new_state; 17360 bool force_exact; 17361 17362 /* bpf progs typically have pruning point every 4 instructions 17363 * http://vger.kernel.org/bpfconf2019.html#session-1 17364 * Do not add new state for future pruning if the verifier hasn't seen 17365 * at least 2 jumps and at least 8 instructions. 17366 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 17367 * In tests that amounts to up to 50% reduction into total verifier 17368 * memory consumption and 20% verifier time speedup. 17369 */ 17370 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 17371 env->insn_processed - env->prev_insn_processed >= 8) 17372 add_new_state = true; 17373 17374 pprev = explored_state(env, insn_idx); 17375 sl = *pprev; 17376 17377 clean_live_states(env, insn_idx, cur); 17378 17379 while (sl) { 17380 states_cnt++; 17381 if (sl->state.insn_idx != insn_idx) 17382 goto next; 17383 17384 if (sl->state.branches) { 17385 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 17386 17387 if (frame->in_async_callback_fn && 17388 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 17389 /* Different async_entry_cnt means that the verifier is 17390 * processing another entry into async callback. 17391 * Seeing the same state is not an indication of infinite 17392 * loop or infinite recursion. 17393 * But finding the same state doesn't mean that it's safe 17394 * to stop processing the current state. The previous state 17395 * hasn't yet reached bpf_exit, since state.branches > 0. 17396 * Checking in_async_callback_fn alone is not enough either. 17397 * Since the verifier still needs to catch infinite loops 17398 * inside async callbacks. 17399 */ 17400 goto skip_inf_loop_check; 17401 } 17402 /* BPF open-coded iterators loop detection is special. 17403 * states_maybe_looping() logic is too simplistic in detecting 17404 * states that *might* be equivalent, because it doesn't know 17405 * about ID remapping, so don't even perform it. 17406 * See process_iter_next_call() and iter_active_depths_differ() 17407 * for overview of the logic. When current and one of parent 17408 * states are detected as equivalent, it's a good thing: we prove 17409 * convergence and can stop simulating further iterations. 17410 * It's safe to assume that iterator loop will finish, taking into 17411 * account iter_next() contract of eventually returning 17412 * sticky NULL result. 17413 * 17414 * Note, that states have to be compared exactly in this case because 17415 * read and precision marks might not be finalized inside the loop. 17416 * E.g. as in the program below: 17417 * 17418 * 1. r7 = -16 17419 * 2. r6 = bpf_get_prandom_u32() 17420 * 3. while (bpf_iter_num_next(&fp[-8])) { 17421 * 4. if (r6 != 42) { 17422 * 5. r7 = -32 17423 * 6. r6 = bpf_get_prandom_u32() 17424 * 7. continue 17425 * 8. } 17426 * 9. r0 = r10 17427 * 10. r0 += r7 17428 * 11. r8 = *(u64 *)(r0 + 0) 17429 * 12. r6 = bpf_get_prandom_u32() 17430 * 13. } 17431 * 17432 * Here verifier would first visit path 1-3, create a checkpoint at 3 17433 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 17434 * not have read or precision mark for r7 yet, thus inexact states 17435 * comparison would discard current state with r7=-32 17436 * => unsafe memory access at 11 would not be caught. 17437 */ 17438 if (is_iter_next_insn(env, insn_idx)) { 17439 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 17440 struct bpf_func_state *cur_frame; 17441 struct bpf_reg_state *iter_state, *iter_reg; 17442 int spi; 17443 17444 cur_frame = cur->frame[cur->curframe]; 17445 /* btf_check_iter_kfuncs() enforces that 17446 * iter state pointer is always the first arg 17447 */ 17448 iter_reg = &cur_frame->regs[BPF_REG_1]; 17449 /* current state is valid due to states_equal(), 17450 * so we can assume valid iter and reg state, 17451 * no need for extra (re-)validations 17452 */ 17453 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 17454 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 17455 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 17456 update_loop_entry(cur, &sl->state); 17457 goto hit; 17458 } 17459 } 17460 goto skip_inf_loop_check; 17461 } 17462 if (is_may_goto_insn_at(env, insn_idx)) { 17463 if (sl->state.may_goto_depth != cur->may_goto_depth && 17464 states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 17465 update_loop_entry(cur, &sl->state); 17466 goto hit; 17467 } 17468 } 17469 if (calls_callback(env, insn_idx)) { 17470 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) 17471 goto hit; 17472 goto skip_inf_loop_check; 17473 } 17474 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 17475 if (states_maybe_looping(&sl->state, cur) && 17476 states_equal(env, &sl->state, cur, EXACT) && 17477 !iter_active_depths_differ(&sl->state, cur) && 17478 sl->state.may_goto_depth == cur->may_goto_depth && 17479 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 17480 verbose_linfo(env, insn_idx, "; "); 17481 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 17482 verbose(env, "cur state:"); 17483 print_verifier_state(env, cur->frame[cur->curframe], true); 17484 verbose(env, "old state:"); 17485 print_verifier_state(env, sl->state.frame[cur->curframe], true); 17486 return -EINVAL; 17487 } 17488 /* if the verifier is processing a loop, avoid adding new state 17489 * too often, since different loop iterations have distinct 17490 * states and may not help future pruning. 17491 * This threshold shouldn't be too low to make sure that 17492 * a loop with large bound will be rejected quickly. 17493 * The most abusive loop will be: 17494 * r1 += 1 17495 * if r1 < 1000000 goto pc-2 17496 * 1M insn_procssed limit / 100 == 10k peak states. 17497 * This threshold shouldn't be too high either, since states 17498 * at the end of the loop are likely to be useful in pruning. 17499 */ 17500 skip_inf_loop_check: 17501 if (!force_new_state && 17502 env->jmps_processed - env->prev_jmps_processed < 20 && 17503 env->insn_processed - env->prev_insn_processed < 100) 17504 add_new_state = false; 17505 goto miss; 17506 } 17507 /* If sl->state is a part of a loop and this loop's entry is a part of 17508 * current verification path then states have to be compared exactly. 17509 * 'force_exact' is needed to catch the following case: 17510 * 17511 * initial Here state 'succ' was processed first, 17512 * | it was eventually tracked to produce a 17513 * V state identical to 'hdr'. 17514 * .---------> hdr All branches from 'succ' had been explored 17515 * | | and thus 'succ' has its .branches == 0. 17516 * | V 17517 * | .------... Suppose states 'cur' and 'succ' correspond 17518 * | | | to the same instruction + callsites. 17519 * | V V In such case it is necessary to check 17520 * | ... ... if 'succ' and 'cur' are states_equal(). 17521 * | | | If 'succ' and 'cur' are a part of the 17522 * | V V same loop exact flag has to be set. 17523 * | succ <- cur To check if that is the case, verify 17524 * | | if loop entry of 'succ' is in current 17525 * | V DFS path. 17526 * | ... 17527 * | | 17528 * '----' 17529 * 17530 * Additional details are in the comment before get_loop_entry(). 17531 */ 17532 loop_entry = get_loop_entry(&sl->state); 17533 force_exact = loop_entry && loop_entry->branches > 0; 17534 if (states_equal(env, &sl->state, cur, force_exact ? RANGE_WITHIN : NOT_EXACT)) { 17535 if (force_exact) 17536 update_loop_entry(cur, loop_entry); 17537 hit: 17538 sl->hit_cnt++; 17539 /* reached equivalent register/stack state, 17540 * prune the search. 17541 * Registers read by the continuation are read by us. 17542 * If we have any write marks in env->cur_state, they 17543 * will prevent corresponding reads in the continuation 17544 * from reaching our parent (an explored_state). Our 17545 * own state will get the read marks recorded, but 17546 * they'll be immediately forgotten as we're pruning 17547 * this state and will pop a new one. 17548 */ 17549 err = propagate_liveness(env, &sl->state, cur); 17550 17551 /* if previous state reached the exit with precision and 17552 * current state is equivalent to it (except precision marks) 17553 * the precision needs to be propagated back in 17554 * the current state. 17555 */ 17556 if (is_jmp_point(env, env->insn_idx)) 17557 err = err ? : push_jmp_history(env, cur, 0); 17558 err = err ? : propagate_precision(env, &sl->state); 17559 if (err) 17560 return err; 17561 return 1; 17562 } 17563 miss: 17564 /* when new state is not going to be added do not increase miss count. 17565 * Otherwise several loop iterations will remove the state 17566 * recorded earlier. The goal of these heuristics is to have 17567 * states from some iterations of the loop (some in the beginning 17568 * and some at the end) to help pruning. 17569 */ 17570 if (add_new_state) 17571 sl->miss_cnt++; 17572 /* heuristic to determine whether this state is beneficial 17573 * to keep checking from state equivalence point of view. 17574 * Higher numbers increase max_states_per_insn and verification time, 17575 * but do not meaningfully decrease insn_processed. 17576 * 'n' controls how many times state could miss before eviction. 17577 * Use bigger 'n' for checkpoints because evicting checkpoint states 17578 * too early would hinder iterator convergence. 17579 */ 17580 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 17581 if (sl->miss_cnt > sl->hit_cnt * n + n) { 17582 /* the state is unlikely to be useful. Remove it to 17583 * speed up verification 17584 */ 17585 *pprev = sl->next; 17586 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE && 17587 !sl->state.used_as_loop_entry) { 17588 u32 br = sl->state.branches; 17589 17590 WARN_ONCE(br, 17591 "BUG live_done but branches_to_explore %d\n", 17592 br); 17593 free_verifier_state(&sl->state, false); 17594 kfree(sl); 17595 env->peak_states--; 17596 } else { 17597 /* cannot free this state, since parentage chain may 17598 * walk it later. Add it for free_list instead to 17599 * be freed at the end of verification 17600 */ 17601 sl->next = env->free_list; 17602 env->free_list = sl; 17603 } 17604 sl = *pprev; 17605 continue; 17606 } 17607 next: 17608 pprev = &sl->next; 17609 sl = *pprev; 17610 } 17611 17612 if (env->max_states_per_insn < states_cnt) 17613 env->max_states_per_insn = states_cnt; 17614 17615 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 17616 return 0; 17617 17618 if (!add_new_state) 17619 return 0; 17620 17621 /* There were no equivalent states, remember the current one. 17622 * Technically the current state is not proven to be safe yet, 17623 * but it will either reach outer most bpf_exit (which means it's safe) 17624 * or it will be rejected. When there are no loops the verifier won't be 17625 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 17626 * again on the way to bpf_exit. 17627 * When looping the sl->state.branches will be > 0 and this state 17628 * will not be considered for equivalence until branches == 0. 17629 */ 17630 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 17631 if (!new_sl) 17632 return -ENOMEM; 17633 env->total_states++; 17634 env->peak_states++; 17635 env->prev_jmps_processed = env->jmps_processed; 17636 env->prev_insn_processed = env->insn_processed; 17637 17638 /* forget precise markings we inherited, see __mark_chain_precision */ 17639 if (env->bpf_capable) 17640 mark_all_scalars_imprecise(env, cur); 17641 17642 /* add new state to the head of linked list */ 17643 new = &new_sl->state; 17644 err = copy_verifier_state(new, cur); 17645 if (err) { 17646 free_verifier_state(new, false); 17647 kfree(new_sl); 17648 return err; 17649 } 17650 new->insn_idx = insn_idx; 17651 WARN_ONCE(new->branches != 1, 17652 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 17653 17654 cur->parent = new; 17655 cur->first_insn_idx = insn_idx; 17656 cur->dfs_depth = new->dfs_depth + 1; 17657 clear_jmp_history(cur); 17658 new_sl->next = *explored_state(env, insn_idx); 17659 *explored_state(env, insn_idx) = new_sl; 17660 /* connect new state to parentage chain. Current frame needs all 17661 * registers connected. Only r6 - r9 of the callers are alive (pushed 17662 * to the stack implicitly by JITs) so in callers' frames connect just 17663 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 17664 * the state of the call instruction (with WRITTEN set), and r0 comes 17665 * from callee with its full parentage chain, anyway. 17666 */ 17667 /* clear write marks in current state: the writes we did are not writes 17668 * our child did, so they don't screen off its reads from us. 17669 * (There are no read marks in current state, because reads always mark 17670 * their parent and current state never has children yet. Only 17671 * explored_states can get read marks.) 17672 */ 17673 for (j = 0; j <= cur->curframe; j++) { 17674 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 17675 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 17676 for (i = 0; i < BPF_REG_FP; i++) 17677 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 17678 } 17679 17680 /* all stack frames are accessible from callee, clear them all */ 17681 for (j = 0; j <= cur->curframe; j++) { 17682 struct bpf_func_state *frame = cur->frame[j]; 17683 struct bpf_func_state *newframe = new->frame[j]; 17684 17685 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 17686 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 17687 frame->stack[i].spilled_ptr.parent = 17688 &newframe->stack[i].spilled_ptr; 17689 } 17690 } 17691 return 0; 17692 } 17693 17694 /* Return true if it's OK to have the same insn return a different type. */ 17695 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 17696 { 17697 switch (base_type(type)) { 17698 case PTR_TO_CTX: 17699 case PTR_TO_SOCKET: 17700 case PTR_TO_SOCK_COMMON: 17701 case PTR_TO_TCP_SOCK: 17702 case PTR_TO_XDP_SOCK: 17703 case PTR_TO_BTF_ID: 17704 case PTR_TO_ARENA: 17705 return false; 17706 default: 17707 return true; 17708 } 17709 } 17710 17711 /* If an instruction was previously used with particular pointer types, then we 17712 * need to be careful to avoid cases such as the below, where it may be ok 17713 * for one branch accessing the pointer, but not ok for the other branch: 17714 * 17715 * R1 = sock_ptr 17716 * goto X; 17717 * ... 17718 * R1 = some_other_valid_ptr; 17719 * goto X; 17720 * ... 17721 * R2 = *(u32 *)(R1 + 0); 17722 */ 17723 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 17724 { 17725 return src != prev && (!reg_type_mismatch_ok(src) || 17726 !reg_type_mismatch_ok(prev)); 17727 } 17728 17729 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 17730 bool allow_trust_mismatch) 17731 { 17732 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 17733 17734 if (*prev_type == NOT_INIT) { 17735 /* Saw a valid insn 17736 * dst_reg = *(u32 *)(src_reg + off) 17737 * save type to validate intersecting paths 17738 */ 17739 *prev_type = type; 17740 } else if (reg_type_mismatch(type, *prev_type)) { 17741 /* Abuser program is trying to use the same insn 17742 * dst_reg = *(u32*) (src_reg + off) 17743 * with different pointer types: 17744 * src_reg == ctx in one branch and 17745 * src_reg == stack|map in some other branch. 17746 * Reject it. 17747 */ 17748 if (allow_trust_mismatch && 17749 base_type(type) == PTR_TO_BTF_ID && 17750 base_type(*prev_type) == PTR_TO_BTF_ID) { 17751 /* 17752 * Have to support a use case when one path through 17753 * the program yields TRUSTED pointer while another 17754 * is UNTRUSTED. Fallback to UNTRUSTED to generate 17755 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 17756 */ 17757 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 17758 } else { 17759 verbose(env, "same insn cannot be used with different pointers\n"); 17760 return -EINVAL; 17761 } 17762 } 17763 17764 return 0; 17765 } 17766 17767 static int do_check(struct bpf_verifier_env *env) 17768 { 17769 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17770 struct bpf_verifier_state *state = env->cur_state; 17771 struct bpf_insn *insns = env->prog->insnsi; 17772 struct bpf_reg_state *regs; 17773 int insn_cnt = env->prog->len; 17774 bool do_print_state = false; 17775 int prev_insn_idx = -1; 17776 17777 for (;;) { 17778 bool exception_exit = false; 17779 struct bpf_insn *insn; 17780 u8 class; 17781 int err; 17782 17783 /* reset current history entry on each new instruction */ 17784 env->cur_hist_ent = NULL; 17785 17786 env->prev_insn_idx = prev_insn_idx; 17787 if (env->insn_idx >= insn_cnt) { 17788 verbose(env, "invalid insn idx %d insn_cnt %d\n", 17789 env->insn_idx, insn_cnt); 17790 return -EFAULT; 17791 } 17792 17793 insn = &insns[env->insn_idx]; 17794 class = BPF_CLASS(insn->code); 17795 17796 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 17797 verbose(env, 17798 "BPF program is too large. Processed %d insn\n", 17799 env->insn_processed); 17800 return -E2BIG; 17801 } 17802 17803 state->last_insn_idx = env->prev_insn_idx; 17804 17805 if (is_prune_point(env, env->insn_idx)) { 17806 err = is_state_visited(env, env->insn_idx); 17807 if (err < 0) 17808 return err; 17809 if (err == 1) { 17810 /* found equivalent state, can prune the search */ 17811 if (env->log.level & BPF_LOG_LEVEL) { 17812 if (do_print_state) 17813 verbose(env, "\nfrom %d to %d%s: safe\n", 17814 env->prev_insn_idx, env->insn_idx, 17815 env->cur_state->speculative ? 17816 " (speculative execution)" : ""); 17817 else 17818 verbose(env, "%d: safe\n", env->insn_idx); 17819 } 17820 goto process_bpf_exit; 17821 } 17822 } 17823 17824 if (is_jmp_point(env, env->insn_idx)) { 17825 err = push_jmp_history(env, state, 0); 17826 if (err) 17827 return err; 17828 } 17829 17830 if (signal_pending(current)) 17831 return -EAGAIN; 17832 17833 if (need_resched()) 17834 cond_resched(); 17835 17836 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17837 verbose(env, "\nfrom %d to %d%s:", 17838 env->prev_insn_idx, env->insn_idx, 17839 env->cur_state->speculative ? 17840 " (speculative execution)" : ""); 17841 print_verifier_state(env, state->frame[state->curframe], true); 17842 do_print_state = false; 17843 } 17844 17845 if (env->log.level & BPF_LOG_LEVEL) { 17846 const struct bpf_insn_cbs cbs = { 17847 .cb_call = disasm_kfunc_name, 17848 .cb_print = verbose, 17849 .private_data = env, 17850 }; 17851 17852 if (verifier_state_scratched(env)) 17853 print_insn_state(env, state->frame[state->curframe]); 17854 17855 verbose_linfo(env, env->insn_idx, "; "); 17856 env->prev_log_pos = env->log.end_pos; 17857 verbose(env, "%d: ", env->insn_idx); 17858 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 17859 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17860 env->prev_log_pos = env->log.end_pos; 17861 } 17862 17863 if (bpf_prog_is_offloaded(env->prog->aux)) { 17864 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17865 env->prev_insn_idx); 17866 if (err) 17867 return err; 17868 } 17869 17870 regs = cur_regs(env); 17871 sanitize_mark_insn_seen(env); 17872 prev_insn_idx = env->insn_idx; 17873 17874 if (class == BPF_ALU || class == BPF_ALU64) { 17875 err = check_alu_op(env, insn); 17876 if (err) 17877 return err; 17878 17879 } else if (class == BPF_LDX) { 17880 enum bpf_reg_type src_reg_type; 17881 17882 /* check for reserved fields is already done */ 17883 17884 /* check src operand */ 17885 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17886 if (err) 17887 return err; 17888 17889 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 17890 if (err) 17891 return err; 17892 17893 src_reg_type = regs[insn->src_reg].type; 17894 17895 /* check that memory (src_reg + off) is readable, 17896 * the state of dst_reg will be updated by this func 17897 */ 17898 err = check_mem_access(env, env->insn_idx, insn->src_reg, 17899 insn->off, BPF_SIZE(insn->code), 17900 BPF_READ, insn->dst_reg, false, 17901 BPF_MODE(insn->code) == BPF_MEMSX); 17902 err = err ?: save_aux_ptr_type(env, src_reg_type, true); 17903 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], "ldx"); 17904 if (err) 17905 return err; 17906 } else if (class == BPF_STX) { 17907 enum bpf_reg_type dst_reg_type; 17908 17909 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 17910 err = check_atomic(env, env->insn_idx, insn); 17911 if (err) 17912 return err; 17913 env->insn_idx++; 17914 continue; 17915 } 17916 17917 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 17918 verbose(env, "BPF_STX uses reserved fields\n"); 17919 return -EINVAL; 17920 } 17921 17922 /* check src1 operand */ 17923 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17924 if (err) 17925 return err; 17926 /* check src2 operand */ 17927 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17928 if (err) 17929 return err; 17930 17931 dst_reg_type = regs[insn->dst_reg].type; 17932 17933 /* check that memory (dst_reg + off) is writeable */ 17934 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17935 insn->off, BPF_SIZE(insn->code), 17936 BPF_WRITE, insn->src_reg, false, false); 17937 if (err) 17938 return err; 17939 17940 err = save_aux_ptr_type(env, dst_reg_type, false); 17941 if (err) 17942 return err; 17943 } else if (class == BPF_ST) { 17944 enum bpf_reg_type dst_reg_type; 17945 17946 if (BPF_MODE(insn->code) != BPF_MEM || 17947 insn->src_reg != BPF_REG_0) { 17948 verbose(env, "BPF_ST uses reserved fields\n"); 17949 return -EINVAL; 17950 } 17951 /* check src operand */ 17952 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17953 if (err) 17954 return err; 17955 17956 dst_reg_type = regs[insn->dst_reg].type; 17957 17958 /* check that memory (dst_reg + off) is writeable */ 17959 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17960 insn->off, BPF_SIZE(insn->code), 17961 BPF_WRITE, -1, false, false); 17962 if (err) 17963 return err; 17964 17965 err = save_aux_ptr_type(env, dst_reg_type, false); 17966 if (err) 17967 return err; 17968 } else if (class == BPF_JMP || class == BPF_JMP32) { 17969 u8 opcode = BPF_OP(insn->code); 17970 17971 env->jmps_processed++; 17972 if (opcode == BPF_CALL) { 17973 if (BPF_SRC(insn->code) != BPF_K || 17974 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 17975 && insn->off != 0) || 17976 (insn->src_reg != BPF_REG_0 && 17977 insn->src_reg != BPF_PSEUDO_CALL && 17978 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 17979 insn->dst_reg != BPF_REG_0 || 17980 class == BPF_JMP32) { 17981 verbose(env, "BPF_CALL uses reserved fields\n"); 17982 return -EINVAL; 17983 } 17984 17985 if (env->cur_state->active_lock.ptr) { 17986 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 17987 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17988 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 17989 verbose(env, "function calls are not allowed while holding a lock\n"); 17990 return -EINVAL; 17991 } 17992 } 17993 if (insn->src_reg == BPF_PSEUDO_CALL) { 17994 err = check_func_call(env, insn, &env->insn_idx); 17995 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 17996 err = check_kfunc_call(env, insn, &env->insn_idx); 17997 if (!err && is_bpf_throw_kfunc(insn)) { 17998 exception_exit = true; 17999 goto process_bpf_exit_full; 18000 } 18001 } else { 18002 err = check_helper_call(env, insn, &env->insn_idx); 18003 } 18004 if (err) 18005 return err; 18006 18007 mark_reg_scratched(env, BPF_REG_0); 18008 } else if (opcode == BPF_JA) { 18009 if (BPF_SRC(insn->code) != BPF_K || 18010 insn->src_reg != BPF_REG_0 || 18011 insn->dst_reg != BPF_REG_0 || 18012 (class == BPF_JMP && insn->imm != 0) || 18013 (class == BPF_JMP32 && insn->off != 0)) { 18014 verbose(env, "BPF_JA uses reserved fields\n"); 18015 return -EINVAL; 18016 } 18017 18018 if (class == BPF_JMP) 18019 env->insn_idx += insn->off + 1; 18020 else 18021 env->insn_idx += insn->imm + 1; 18022 continue; 18023 18024 } else if (opcode == BPF_EXIT) { 18025 if (BPF_SRC(insn->code) != BPF_K || 18026 insn->imm != 0 || 18027 insn->src_reg != BPF_REG_0 || 18028 insn->dst_reg != BPF_REG_0 || 18029 class == BPF_JMP32) { 18030 verbose(env, "BPF_EXIT uses reserved fields\n"); 18031 return -EINVAL; 18032 } 18033 process_bpf_exit_full: 18034 if (env->cur_state->active_lock.ptr && !env->cur_state->curframe) { 18035 verbose(env, "bpf_spin_unlock is missing\n"); 18036 return -EINVAL; 18037 } 18038 18039 if (env->cur_state->active_rcu_lock && !env->cur_state->curframe) { 18040 verbose(env, "bpf_rcu_read_unlock is missing\n"); 18041 return -EINVAL; 18042 } 18043 18044 if (env->cur_state->active_preempt_lock && !env->cur_state->curframe) { 18045 verbose(env, "%d bpf_preempt_enable%s missing\n", 18046 env->cur_state->active_preempt_lock, 18047 env->cur_state->active_preempt_lock == 1 ? " is" : "(s) are"); 18048 return -EINVAL; 18049 } 18050 18051 /* We must do check_reference_leak here before 18052 * prepare_func_exit to handle the case when 18053 * state->curframe > 0, it may be a callback 18054 * function, for which reference_state must 18055 * match caller reference state when it exits. 18056 */ 18057 err = check_reference_leak(env, exception_exit); 18058 if (err) 18059 return err; 18060 18061 /* The side effect of the prepare_func_exit 18062 * which is being skipped is that it frees 18063 * bpf_func_state. Typically, process_bpf_exit 18064 * will only be hit with outermost exit. 18065 * copy_verifier_state in pop_stack will handle 18066 * freeing of any extra bpf_func_state left over 18067 * from not processing all nested function 18068 * exits. We also skip return code checks as 18069 * they are not needed for exceptional exits. 18070 */ 18071 if (exception_exit) 18072 goto process_bpf_exit; 18073 18074 if (state->curframe) { 18075 /* exit from nested function */ 18076 err = prepare_func_exit(env, &env->insn_idx); 18077 if (err) 18078 return err; 18079 do_print_state = true; 18080 continue; 18081 } 18082 18083 err = check_return_code(env, BPF_REG_0, "R0"); 18084 if (err) 18085 return err; 18086 process_bpf_exit: 18087 mark_verifier_state_scratched(env); 18088 update_branch_counts(env, env->cur_state); 18089 err = pop_stack(env, &prev_insn_idx, 18090 &env->insn_idx, pop_log); 18091 if (err < 0) { 18092 if (err != -ENOENT) 18093 return err; 18094 break; 18095 } else { 18096 do_print_state = true; 18097 continue; 18098 } 18099 } else { 18100 err = check_cond_jmp_op(env, insn, &env->insn_idx); 18101 if (err) 18102 return err; 18103 } 18104 } else if (class == BPF_LD) { 18105 u8 mode = BPF_MODE(insn->code); 18106 18107 if (mode == BPF_ABS || mode == BPF_IND) { 18108 err = check_ld_abs(env, insn); 18109 if (err) 18110 return err; 18111 18112 } else if (mode == BPF_IMM) { 18113 err = check_ld_imm(env, insn); 18114 if (err) 18115 return err; 18116 18117 env->insn_idx++; 18118 sanitize_mark_insn_seen(env); 18119 } else { 18120 verbose(env, "invalid BPF_LD mode\n"); 18121 return -EINVAL; 18122 } 18123 } else { 18124 verbose(env, "unknown insn class %d\n", class); 18125 return -EINVAL; 18126 } 18127 18128 env->insn_idx++; 18129 } 18130 18131 return 0; 18132 } 18133 18134 static int find_btf_percpu_datasec(struct btf *btf) 18135 { 18136 const struct btf_type *t; 18137 const char *tname; 18138 int i, n; 18139 18140 /* 18141 * Both vmlinux and module each have their own ".data..percpu" 18142 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 18143 * types to look at only module's own BTF types. 18144 */ 18145 n = btf_nr_types(btf); 18146 if (btf_is_module(btf)) 18147 i = btf_nr_types(btf_vmlinux); 18148 else 18149 i = 1; 18150 18151 for(; i < n; i++) { 18152 t = btf_type_by_id(btf, i); 18153 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 18154 continue; 18155 18156 tname = btf_name_by_offset(btf, t->name_off); 18157 if (!strcmp(tname, ".data..percpu")) 18158 return i; 18159 } 18160 18161 return -ENOENT; 18162 } 18163 18164 /* replace pseudo btf_id with kernel symbol address */ 18165 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 18166 struct bpf_insn *insn, 18167 struct bpf_insn_aux_data *aux) 18168 { 18169 const struct btf_var_secinfo *vsi; 18170 const struct btf_type *datasec; 18171 struct btf_mod_pair *btf_mod; 18172 const struct btf_type *t; 18173 const char *sym_name; 18174 bool percpu = false; 18175 u32 type, id = insn->imm; 18176 struct btf *btf; 18177 s32 datasec_id; 18178 u64 addr; 18179 int i, btf_fd, err; 18180 18181 btf_fd = insn[1].imm; 18182 if (btf_fd) { 18183 btf = btf_get_by_fd(btf_fd); 18184 if (IS_ERR(btf)) { 18185 verbose(env, "invalid module BTF object FD specified.\n"); 18186 return -EINVAL; 18187 } 18188 } else { 18189 if (!btf_vmlinux) { 18190 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 18191 return -EINVAL; 18192 } 18193 btf = btf_vmlinux; 18194 btf_get(btf); 18195 } 18196 18197 t = btf_type_by_id(btf, id); 18198 if (!t) { 18199 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 18200 err = -ENOENT; 18201 goto err_put; 18202 } 18203 18204 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 18205 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 18206 err = -EINVAL; 18207 goto err_put; 18208 } 18209 18210 sym_name = btf_name_by_offset(btf, t->name_off); 18211 addr = kallsyms_lookup_name(sym_name); 18212 if (!addr) { 18213 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 18214 sym_name); 18215 err = -ENOENT; 18216 goto err_put; 18217 } 18218 insn[0].imm = (u32)addr; 18219 insn[1].imm = addr >> 32; 18220 18221 if (btf_type_is_func(t)) { 18222 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 18223 aux->btf_var.mem_size = 0; 18224 goto check_btf; 18225 } 18226 18227 datasec_id = find_btf_percpu_datasec(btf); 18228 if (datasec_id > 0) { 18229 datasec = btf_type_by_id(btf, datasec_id); 18230 for_each_vsi(i, datasec, vsi) { 18231 if (vsi->type == id) { 18232 percpu = true; 18233 break; 18234 } 18235 } 18236 } 18237 18238 type = t->type; 18239 t = btf_type_skip_modifiers(btf, type, NULL); 18240 if (percpu) { 18241 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 18242 aux->btf_var.btf = btf; 18243 aux->btf_var.btf_id = type; 18244 } else if (!btf_type_is_struct(t)) { 18245 const struct btf_type *ret; 18246 const char *tname; 18247 u32 tsize; 18248 18249 /* resolve the type size of ksym. */ 18250 ret = btf_resolve_size(btf, t, &tsize); 18251 if (IS_ERR(ret)) { 18252 tname = btf_name_by_offset(btf, t->name_off); 18253 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 18254 tname, PTR_ERR(ret)); 18255 err = -EINVAL; 18256 goto err_put; 18257 } 18258 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 18259 aux->btf_var.mem_size = tsize; 18260 } else { 18261 aux->btf_var.reg_type = PTR_TO_BTF_ID; 18262 aux->btf_var.btf = btf; 18263 aux->btf_var.btf_id = type; 18264 } 18265 check_btf: 18266 /* check whether we recorded this BTF (and maybe module) already */ 18267 for (i = 0; i < env->used_btf_cnt; i++) { 18268 if (env->used_btfs[i].btf == btf) { 18269 btf_put(btf); 18270 return 0; 18271 } 18272 } 18273 18274 if (env->used_btf_cnt >= MAX_USED_BTFS) { 18275 err = -E2BIG; 18276 goto err_put; 18277 } 18278 18279 btf_mod = &env->used_btfs[env->used_btf_cnt]; 18280 btf_mod->btf = btf; 18281 btf_mod->module = NULL; 18282 18283 /* if we reference variables from kernel module, bump its refcount */ 18284 if (btf_is_module(btf)) { 18285 btf_mod->module = btf_try_get_module(btf); 18286 if (!btf_mod->module) { 18287 err = -ENXIO; 18288 goto err_put; 18289 } 18290 } 18291 18292 env->used_btf_cnt++; 18293 18294 return 0; 18295 err_put: 18296 btf_put(btf); 18297 return err; 18298 } 18299 18300 static bool is_tracing_prog_type(enum bpf_prog_type type) 18301 { 18302 switch (type) { 18303 case BPF_PROG_TYPE_KPROBE: 18304 case BPF_PROG_TYPE_TRACEPOINT: 18305 case BPF_PROG_TYPE_PERF_EVENT: 18306 case BPF_PROG_TYPE_RAW_TRACEPOINT: 18307 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 18308 return true; 18309 default: 18310 return false; 18311 } 18312 } 18313 18314 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 18315 struct bpf_map *map, 18316 struct bpf_prog *prog) 18317 18318 { 18319 enum bpf_prog_type prog_type = resolve_prog_type(prog); 18320 18321 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 18322 btf_record_has_field(map->record, BPF_RB_ROOT)) { 18323 if (is_tracing_prog_type(prog_type)) { 18324 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 18325 return -EINVAL; 18326 } 18327 } 18328 18329 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 18330 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 18331 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 18332 return -EINVAL; 18333 } 18334 18335 if (is_tracing_prog_type(prog_type)) { 18336 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 18337 return -EINVAL; 18338 } 18339 } 18340 18341 if (btf_record_has_field(map->record, BPF_TIMER)) { 18342 if (is_tracing_prog_type(prog_type)) { 18343 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 18344 return -EINVAL; 18345 } 18346 } 18347 18348 if (btf_record_has_field(map->record, BPF_WORKQUEUE)) { 18349 if (is_tracing_prog_type(prog_type)) { 18350 verbose(env, "tracing progs cannot use bpf_wq yet\n"); 18351 return -EINVAL; 18352 } 18353 } 18354 18355 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 18356 !bpf_offload_prog_map_match(prog, map)) { 18357 verbose(env, "offload device mismatch between prog and map\n"); 18358 return -EINVAL; 18359 } 18360 18361 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 18362 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 18363 return -EINVAL; 18364 } 18365 18366 if (prog->sleepable) 18367 switch (map->map_type) { 18368 case BPF_MAP_TYPE_HASH: 18369 case BPF_MAP_TYPE_LRU_HASH: 18370 case BPF_MAP_TYPE_ARRAY: 18371 case BPF_MAP_TYPE_PERCPU_HASH: 18372 case BPF_MAP_TYPE_PERCPU_ARRAY: 18373 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 18374 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 18375 case BPF_MAP_TYPE_HASH_OF_MAPS: 18376 case BPF_MAP_TYPE_RINGBUF: 18377 case BPF_MAP_TYPE_USER_RINGBUF: 18378 case BPF_MAP_TYPE_INODE_STORAGE: 18379 case BPF_MAP_TYPE_SK_STORAGE: 18380 case BPF_MAP_TYPE_TASK_STORAGE: 18381 case BPF_MAP_TYPE_CGRP_STORAGE: 18382 case BPF_MAP_TYPE_QUEUE: 18383 case BPF_MAP_TYPE_STACK: 18384 case BPF_MAP_TYPE_ARENA: 18385 break; 18386 default: 18387 verbose(env, 18388 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 18389 return -EINVAL; 18390 } 18391 18392 return 0; 18393 } 18394 18395 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 18396 { 18397 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 18398 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 18399 } 18400 18401 /* find and rewrite pseudo imm in ld_imm64 instructions: 18402 * 18403 * 1. if it accesses map FD, replace it with actual map pointer. 18404 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 18405 * 18406 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 18407 */ 18408 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 18409 { 18410 struct bpf_insn *insn = env->prog->insnsi; 18411 int insn_cnt = env->prog->len; 18412 int i, j, err; 18413 18414 err = bpf_prog_calc_tag(env->prog); 18415 if (err) 18416 return err; 18417 18418 for (i = 0; i < insn_cnt; i++, insn++) { 18419 if (BPF_CLASS(insn->code) == BPF_LDX && 18420 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 18421 insn->imm != 0)) { 18422 verbose(env, "BPF_LDX uses reserved fields\n"); 18423 return -EINVAL; 18424 } 18425 18426 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 18427 struct bpf_insn_aux_data *aux; 18428 struct bpf_map *map; 18429 struct fd f; 18430 u64 addr; 18431 u32 fd; 18432 18433 if (i == insn_cnt - 1 || insn[1].code != 0 || 18434 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 18435 insn[1].off != 0) { 18436 verbose(env, "invalid bpf_ld_imm64 insn\n"); 18437 return -EINVAL; 18438 } 18439 18440 if (insn[0].src_reg == 0) 18441 /* valid generic load 64-bit imm */ 18442 goto next_insn; 18443 18444 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 18445 aux = &env->insn_aux_data[i]; 18446 err = check_pseudo_btf_id(env, insn, aux); 18447 if (err) 18448 return err; 18449 goto next_insn; 18450 } 18451 18452 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 18453 aux = &env->insn_aux_data[i]; 18454 aux->ptr_type = PTR_TO_FUNC; 18455 goto next_insn; 18456 } 18457 18458 /* In final convert_pseudo_ld_imm64() step, this is 18459 * converted into regular 64-bit imm load insn. 18460 */ 18461 switch (insn[0].src_reg) { 18462 case BPF_PSEUDO_MAP_VALUE: 18463 case BPF_PSEUDO_MAP_IDX_VALUE: 18464 break; 18465 case BPF_PSEUDO_MAP_FD: 18466 case BPF_PSEUDO_MAP_IDX: 18467 if (insn[1].imm == 0) 18468 break; 18469 fallthrough; 18470 default: 18471 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 18472 return -EINVAL; 18473 } 18474 18475 switch (insn[0].src_reg) { 18476 case BPF_PSEUDO_MAP_IDX_VALUE: 18477 case BPF_PSEUDO_MAP_IDX: 18478 if (bpfptr_is_null(env->fd_array)) { 18479 verbose(env, "fd_idx without fd_array is invalid\n"); 18480 return -EPROTO; 18481 } 18482 if (copy_from_bpfptr_offset(&fd, env->fd_array, 18483 insn[0].imm * sizeof(fd), 18484 sizeof(fd))) 18485 return -EFAULT; 18486 break; 18487 default: 18488 fd = insn[0].imm; 18489 break; 18490 } 18491 18492 f = fdget(fd); 18493 map = __bpf_map_get(f); 18494 if (IS_ERR(map)) { 18495 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 18496 return PTR_ERR(map); 18497 } 18498 18499 err = check_map_prog_compatibility(env, map, env->prog); 18500 if (err) { 18501 fdput(f); 18502 return err; 18503 } 18504 18505 aux = &env->insn_aux_data[i]; 18506 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 18507 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 18508 addr = (unsigned long)map; 18509 } else { 18510 u32 off = insn[1].imm; 18511 18512 if (off >= BPF_MAX_VAR_OFF) { 18513 verbose(env, "direct value offset of %u is not allowed\n", off); 18514 fdput(f); 18515 return -EINVAL; 18516 } 18517 18518 if (!map->ops->map_direct_value_addr) { 18519 verbose(env, "no direct value access support for this map type\n"); 18520 fdput(f); 18521 return -EINVAL; 18522 } 18523 18524 err = map->ops->map_direct_value_addr(map, &addr, off); 18525 if (err) { 18526 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 18527 map->value_size, off); 18528 fdput(f); 18529 return err; 18530 } 18531 18532 aux->map_off = off; 18533 addr += off; 18534 } 18535 18536 insn[0].imm = (u32)addr; 18537 insn[1].imm = addr >> 32; 18538 18539 /* check whether we recorded this map already */ 18540 for (j = 0; j < env->used_map_cnt; j++) { 18541 if (env->used_maps[j] == map) { 18542 aux->map_index = j; 18543 fdput(f); 18544 goto next_insn; 18545 } 18546 } 18547 18548 if (env->used_map_cnt >= MAX_USED_MAPS) { 18549 verbose(env, "The total number of maps per program has reached the limit of %u\n", 18550 MAX_USED_MAPS); 18551 fdput(f); 18552 return -E2BIG; 18553 } 18554 18555 if (env->prog->sleepable) 18556 atomic64_inc(&map->sleepable_refcnt); 18557 /* hold the map. If the program is rejected by verifier, 18558 * the map will be released by release_maps() or it 18559 * will be used by the valid program until it's unloaded 18560 * and all maps are released in bpf_free_used_maps() 18561 */ 18562 bpf_map_inc(map); 18563 18564 aux->map_index = env->used_map_cnt; 18565 env->used_maps[env->used_map_cnt++] = map; 18566 18567 if (bpf_map_is_cgroup_storage(map) && 18568 bpf_cgroup_storage_assign(env->prog->aux, map)) { 18569 verbose(env, "only one cgroup storage of each type is allowed\n"); 18570 fdput(f); 18571 return -EBUSY; 18572 } 18573 if (map->map_type == BPF_MAP_TYPE_ARENA) { 18574 if (env->prog->aux->arena) { 18575 verbose(env, "Only one arena per program\n"); 18576 fdput(f); 18577 return -EBUSY; 18578 } 18579 if (!env->allow_ptr_leaks || !env->bpf_capable) { 18580 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n"); 18581 fdput(f); 18582 return -EPERM; 18583 } 18584 if (!env->prog->jit_requested) { 18585 verbose(env, "JIT is required to use arena\n"); 18586 fdput(f); 18587 return -EOPNOTSUPP; 18588 } 18589 if (!bpf_jit_supports_arena()) { 18590 verbose(env, "JIT doesn't support arena\n"); 18591 fdput(f); 18592 return -EOPNOTSUPP; 18593 } 18594 env->prog->aux->arena = (void *)map; 18595 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) { 18596 verbose(env, "arena's user address must be set via map_extra or mmap()\n"); 18597 fdput(f); 18598 return -EINVAL; 18599 } 18600 } 18601 18602 fdput(f); 18603 next_insn: 18604 insn++; 18605 i++; 18606 continue; 18607 } 18608 18609 /* Basic sanity check before we invest more work here. */ 18610 if (!bpf_opcode_in_insntable(insn->code)) { 18611 verbose(env, "unknown opcode %02x\n", insn->code); 18612 return -EINVAL; 18613 } 18614 } 18615 18616 /* now all pseudo BPF_LD_IMM64 instructions load valid 18617 * 'struct bpf_map *' into a register instead of user map_fd. 18618 * These pointers will be used later by verifier to validate map access. 18619 */ 18620 return 0; 18621 } 18622 18623 /* drop refcnt of maps used by the rejected program */ 18624 static void release_maps(struct bpf_verifier_env *env) 18625 { 18626 __bpf_free_used_maps(env->prog->aux, env->used_maps, 18627 env->used_map_cnt); 18628 } 18629 18630 /* drop refcnt of maps used by the rejected program */ 18631 static void release_btfs(struct bpf_verifier_env *env) 18632 { 18633 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 18634 env->used_btf_cnt); 18635 } 18636 18637 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 18638 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 18639 { 18640 struct bpf_insn *insn = env->prog->insnsi; 18641 int insn_cnt = env->prog->len; 18642 int i; 18643 18644 for (i = 0; i < insn_cnt; i++, insn++) { 18645 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 18646 continue; 18647 if (insn->src_reg == BPF_PSEUDO_FUNC) 18648 continue; 18649 insn->src_reg = 0; 18650 } 18651 } 18652 18653 /* single env->prog->insni[off] instruction was replaced with the range 18654 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 18655 * [0, off) and [off, end) to new locations, so the patched range stays zero 18656 */ 18657 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 18658 struct bpf_insn_aux_data *new_data, 18659 struct bpf_prog *new_prog, u32 off, u32 cnt) 18660 { 18661 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 18662 struct bpf_insn *insn = new_prog->insnsi; 18663 u32 old_seen = old_data[off].seen; 18664 u32 prog_len; 18665 int i; 18666 18667 /* aux info at OFF always needs adjustment, no matter fast path 18668 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 18669 * original insn at old prog. 18670 */ 18671 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 18672 18673 if (cnt == 1) 18674 return; 18675 prog_len = new_prog->len; 18676 18677 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 18678 memcpy(new_data + off + cnt - 1, old_data + off, 18679 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 18680 for (i = off; i < off + cnt - 1; i++) { 18681 /* Expand insni[off]'s seen count to the patched range. */ 18682 new_data[i].seen = old_seen; 18683 new_data[i].zext_dst = insn_has_def32(env, insn + i); 18684 } 18685 env->insn_aux_data = new_data; 18686 vfree(old_data); 18687 } 18688 18689 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 18690 { 18691 int i; 18692 18693 if (len == 1) 18694 return; 18695 /* NOTE: fake 'exit' subprog should be updated as well. */ 18696 for (i = 0; i <= env->subprog_cnt; i++) { 18697 if (env->subprog_info[i].start <= off) 18698 continue; 18699 env->subprog_info[i].start += len - 1; 18700 } 18701 } 18702 18703 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 18704 { 18705 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 18706 int i, sz = prog->aux->size_poke_tab; 18707 struct bpf_jit_poke_descriptor *desc; 18708 18709 for (i = 0; i < sz; i++) { 18710 desc = &tab[i]; 18711 if (desc->insn_idx <= off) 18712 continue; 18713 desc->insn_idx += len - 1; 18714 } 18715 } 18716 18717 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 18718 const struct bpf_insn *patch, u32 len) 18719 { 18720 struct bpf_prog *new_prog; 18721 struct bpf_insn_aux_data *new_data = NULL; 18722 18723 if (len > 1) { 18724 new_data = vzalloc(array_size(env->prog->len + len - 1, 18725 sizeof(struct bpf_insn_aux_data))); 18726 if (!new_data) 18727 return NULL; 18728 } 18729 18730 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 18731 if (IS_ERR(new_prog)) { 18732 if (PTR_ERR(new_prog) == -ERANGE) 18733 verbose(env, 18734 "insn %d cannot be patched due to 16-bit range\n", 18735 env->insn_aux_data[off].orig_idx); 18736 vfree(new_data); 18737 return NULL; 18738 } 18739 adjust_insn_aux_data(env, new_data, new_prog, off, len); 18740 adjust_subprog_starts(env, off, len); 18741 adjust_poke_descs(new_prog, off, len); 18742 return new_prog; 18743 } 18744 18745 /* 18746 * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the 18747 * jump offset by 'delta'. 18748 */ 18749 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta) 18750 { 18751 struct bpf_insn *insn = prog->insnsi; 18752 u32 insn_cnt = prog->len, i; 18753 18754 for (i = 0; i < insn_cnt; i++, insn++) { 18755 u8 code = insn->code; 18756 18757 if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) || 18758 BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT) 18759 continue; 18760 18761 if (insn->code == (BPF_JMP32 | BPF_JA)) { 18762 if (i + 1 + insn->imm != tgt_idx) 18763 continue; 18764 if (signed_add32_overflows(insn->imm, delta)) 18765 return -ERANGE; 18766 insn->imm += delta; 18767 } else { 18768 if (i + 1 + insn->off != tgt_idx) 18769 continue; 18770 if (signed_add16_overflows(insn->imm, delta)) 18771 return -ERANGE; 18772 insn->off += delta; 18773 } 18774 } 18775 return 0; 18776 } 18777 18778 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 18779 u32 off, u32 cnt) 18780 { 18781 int i, j; 18782 18783 /* find first prog starting at or after off (first to remove) */ 18784 for (i = 0; i < env->subprog_cnt; i++) 18785 if (env->subprog_info[i].start >= off) 18786 break; 18787 /* find first prog starting at or after off + cnt (first to stay) */ 18788 for (j = i; j < env->subprog_cnt; j++) 18789 if (env->subprog_info[j].start >= off + cnt) 18790 break; 18791 /* if j doesn't start exactly at off + cnt, we are just removing 18792 * the front of previous prog 18793 */ 18794 if (env->subprog_info[j].start != off + cnt) 18795 j--; 18796 18797 if (j > i) { 18798 struct bpf_prog_aux *aux = env->prog->aux; 18799 int move; 18800 18801 /* move fake 'exit' subprog as well */ 18802 move = env->subprog_cnt + 1 - j; 18803 18804 memmove(env->subprog_info + i, 18805 env->subprog_info + j, 18806 sizeof(*env->subprog_info) * move); 18807 env->subprog_cnt -= j - i; 18808 18809 /* remove func_info */ 18810 if (aux->func_info) { 18811 move = aux->func_info_cnt - j; 18812 18813 memmove(aux->func_info + i, 18814 aux->func_info + j, 18815 sizeof(*aux->func_info) * move); 18816 aux->func_info_cnt -= j - i; 18817 /* func_info->insn_off is set after all code rewrites, 18818 * in adjust_btf_func() - no need to adjust 18819 */ 18820 } 18821 } else { 18822 /* convert i from "first prog to remove" to "first to adjust" */ 18823 if (env->subprog_info[i].start == off) 18824 i++; 18825 } 18826 18827 /* update fake 'exit' subprog as well */ 18828 for (; i <= env->subprog_cnt; i++) 18829 env->subprog_info[i].start -= cnt; 18830 18831 return 0; 18832 } 18833 18834 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 18835 u32 cnt) 18836 { 18837 struct bpf_prog *prog = env->prog; 18838 u32 i, l_off, l_cnt, nr_linfo; 18839 struct bpf_line_info *linfo; 18840 18841 nr_linfo = prog->aux->nr_linfo; 18842 if (!nr_linfo) 18843 return 0; 18844 18845 linfo = prog->aux->linfo; 18846 18847 /* find first line info to remove, count lines to be removed */ 18848 for (i = 0; i < nr_linfo; i++) 18849 if (linfo[i].insn_off >= off) 18850 break; 18851 18852 l_off = i; 18853 l_cnt = 0; 18854 for (; i < nr_linfo; i++) 18855 if (linfo[i].insn_off < off + cnt) 18856 l_cnt++; 18857 else 18858 break; 18859 18860 /* First live insn doesn't match first live linfo, it needs to "inherit" 18861 * last removed linfo. prog is already modified, so prog->len == off 18862 * means no live instructions after (tail of the program was removed). 18863 */ 18864 if (prog->len != off && l_cnt && 18865 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 18866 l_cnt--; 18867 linfo[--i].insn_off = off + cnt; 18868 } 18869 18870 /* remove the line info which refer to the removed instructions */ 18871 if (l_cnt) { 18872 memmove(linfo + l_off, linfo + i, 18873 sizeof(*linfo) * (nr_linfo - i)); 18874 18875 prog->aux->nr_linfo -= l_cnt; 18876 nr_linfo = prog->aux->nr_linfo; 18877 } 18878 18879 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 18880 for (i = l_off; i < nr_linfo; i++) 18881 linfo[i].insn_off -= cnt; 18882 18883 /* fix up all subprogs (incl. 'exit') which start >= off */ 18884 for (i = 0; i <= env->subprog_cnt; i++) 18885 if (env->subprog_info[i].linfo_idx > l_off) { 18886 /* program may have started in the removed region but 18887 * may not be fully removed 18888 */ 18889 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 18890 env->subprog_info[i].linfo_idx -= l_cnt; 18891 else 18892 env->subprog_info[i].linfo_idx = l_off; 18893 } 18894 18895 return 0; 18896 } 18897 18898 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 18899 { 18900 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18901 unsigned int orig_prog_len = env->prog->len; 18902 int err; 18903 18904 if (bpf_prog_is_offloaded(env->prog->aux)) 18905 bpf_prog_offload_remove_insns(env, off, cnt); 18906 18907 err = bpf_remove_insns(env->prog, off, cnt); 18908 if (err) 18909 return err; 18910 18911 err = adjust_subprog_starts_after_remove(env, off, cnt); 18912 if (err) 18913 return err; 18914 18915 err = bpf_adj_linfo_after_remove(env, off, cnt); 18916 if (err) 18917 return err; 18918 18919 memmove(aux_data + off, aux_data + off + cnt, 18920 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 18921 18922 return 0; 18923 } 18924 18925 /* The verifier does more data flow analysis than llvm and will not 18926 * explore branches that are dead at run time. Malicious programs can 18927 * have dead code too. Therefore replace all dead at-run-time code 18928 * with 'ja -1'. 18929 * 18930 * Just nops are not optimal, e.g. if they would sit at the end of the 18931 * program and through another bug we would manage to jump there, then 18932 * we'd execute beyond program memory otherwise. Returning exception 18933 * code also wouldn't work since we can have subprogs where the dead 18934 * code could be located. 18935 */ 18936 static void sanitize_dead_code(struct bpf_verifier_env *env) 18937 { 18938 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18939 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18940 struct bpf_insn *insn = env->prog->insnsi; 18941 const int insn_cnt = env->prog->len; 18942 int i; 18943 18944 for (i = 0; i < insn_cnt; i++) { 18945 if (aux_data[i].seen) 18946 continue; 18947 memcpy(insn + i, &trap, sizeof(trap)); 18948 aux_data[i].zext_dst = false; 18949 } 18950 } 18951 18952 static bool insn_is_cond_jump(u8 code) 18953 { 18954 u8 op; 18955 18956 op = BPF_OP(code); 18957 if (BPF_CLASS(code) == BPF_JMP32) 18958 return op != BPF_JA; 18959 18960 if (BPF_CLASS(code) != BPF_JMP) 18961 return false; 18962 18963 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 18964 } 18965 18966 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 18967 { 18968 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18969 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18970 struct bpf_insn *insn = env->prog->insnsi; 18971 const int insn_cnt = env->prog->len; 18972 int i; 18973 18974 for (i = 0; i < insn_cnt; i++, insn++) { 18975 if (!insn_is_cond_jump(insn->code)) 18976 continue; 18977 18978 if (!aux_data[i + 1].seen) 18979 ja.off = insn->off; 18980 else if (!aux_data[i + 1 + insn->off].seen) 18981 ja.off = 0; 18982 else 18983 continue; 18984 18985 if (bpf_prog_is_offloaded(env->prog->aux)) 18986 bpf_prog_offload_replace_insn(env, i, &ja); 18987 18988 memcpy(insn, &ja, sizeof(ja)); 18989 } 18990 } 18991 18992 static int opt_remove_dead_code(struct bpf_verifier_env *env) 18993 { 18994 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18995 int insn_cnt = env->prog->len; 18996 int i, err; 18997 18998 for (i = 0; i < insn_cnt; i++) { 18999 int j; 19000 19001 j = 0; 19002 while (i + j < insn_cnt && !aux_data[i + j].seen) 19003 j++; 19004 if (!j) 19005 continue; 19006 19007 err = verifier_remove_insns(env, i, j); 19008 if (err) 19009 return err; 19010 insn_cnt = env->prog->len; 19011 } 19012 19013 return 0; 19014 } 19015 19016 static int opt_remove_nops(struct bpf_verifier_env *env) 19017 { 19018 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 19019 struct bpf_insn *insn = env->prog->insnsi; 19020 int insn_cnt = env->prog->len; 19021 int i, err; 19022 19023 for (i = 0; i < insn_cnt; i++) { 19024 if (memcmp(&insn[i], &ja, sizeof(ja))) 19025 continue; 19026 19027 err = verifier_remove_insns(env, i, 1); 19028 if (err) 19029 return err; 19030 insn_cnt--; 19031 i--; 19032 } 19033 19034 return 0; 19035 } 19036 19037 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 19038 const union bpf_attr *attr) 19039 { 19040 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 19041 struct bpf_insn_aux_data *aux = env->insn_aux_data; 19042 int i, patch_len, delta = 0, len = env->prog->len; 19043 struct bpf_insn *insns = env->prog->insnsi; 19044 struct bpf_prog *new_prog; 19045 bool rnd_hi32; 19046 19047 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 19048 zext_patch[1] = BPF_ZEXT_REG(0); 19049 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 19050 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 19051 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 19052 for (i = 0; i < len; i++) { 19053 int adj_idx = i + delta; 19054 struct bpf_insn insn; 19055 int load_reg; 19056 19057 insn = insns[adj_idx]; 19058 load_reg = insn_def_regno(&insn); 19059 if (!aux[adj_idx].zext_dst) { 19060 u8 code, class; 19061 u32 imm_rnd; 19062 19063 if (!rnd_hi32) 19064 continue; 19065 19066 code = insn.code; 19067 class = BPF_CLASS(code); 19068 if (load_reg == -1) 19069 continue; 19070 19071 /* NOTE: arg "reg" (the fourth one) is only used for 19072 * BPF_STX + SRC_OP, so it is safe to pass NULL 19073 * here. 19074 */ 19075 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 19076 if (class == BPF_LD && 19077 BPF_MODE(code) == BPF_IMM) 19078 i++; 19079 continue; 19080 } 19081 19082 /* ctx load could be transformed into wider load. */ 19083 if (class == BPF_LDX && 19084 aux[adj_idx].ptr_type == PTR_TO_CTX) 19085 continue; 19086 19087 imm_rnd = get_random_u32(); 19088 rnd_hi32_patch[0] = insn; 19089 rnd_hi32_patch[1].imm = imm_rnd; 19090 rnd_hi32_patch[3].dst_reg = load_reg; 19091 patch = rnd_hi32_patch; 19092 patch_len = 4; 19093 goto apply_patch_buffer; 19094 } 19095 19096 /* Add in an zero-extend instruction if a) the JIT has requested 19097 * it or b) it's a CMPXCHG. 19098 * 19099 * The latter is because: BPF_CMPXCHG always loads a value into 19100 * R0, therefore always zero-extends. However some archs' 19101 * equivalent instruction only does this load when the 19102 * comparison is successful. This detail of CMPXCHG is 19103 * orthogonal to the general zero-extension behaviour of the 19104 * CPU, so it's treated independently of bpf_jit_needs_zext. 19105 */ 19106 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 19107 continue; 19108 19109 /* Zero-extension is done by the caller. */ 19110 if (bpf_pseudo_kfunc_call(&insn)) 19111 continue; 19112 19113 if (WARN_ON(load_reg == -1)) { 19114 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 19115 return -EFAULT; 19116 } 19117 19118 zext_patch[0] = insn; 19119 zext_patch[1].dst_reg = load_reg; 19120 zext_patch[1].src_reg = load_reg; 19121 patch = zext_patch; 19122 patch_len = 2; 19123 apply_patch_buffer: 19124 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 19125 if (!new_prog) 19126 return -ENOMEM; 19127 env->prog = new_prog; 19128 insns = new_prog->insnsi; 19129 aux = env->insn_aux_data; 19130 delta += patch_len - 1; 19131 } 19132 19133 return 0; 19134 } 19135 19136 /* convert load instructions that access fields of a context type into a 19137 * sequence of instructions that access fields of the underlying structure: 19138 * struct __sk_buff -> struct sk_buff 19139 * struct bpf_sock_ops -> struct sock 19140 */ 19141 static int convert_ctx_accesses(struct bpf_verifier_env *env) 19142 { 19143 const struct bpf_verifier_ops *ops = env->ops; 19144 int i, cnt, size, ctx_field_size, delta = 0; 19145 const int insn_cnt = env->prog->len; 19146 struct bpf_insn insn_buf[16], *insn; 19147 u32 target_size, size_default, off; 19148 struct bpf_prog *new_prog; 19149 enum bpf_access_type type; 19150 bool is_narrower_load; 19151 19152 if (ops->gen_prologue || env->seen_direct_write) { 19153 if (!ops->gen_prologue) { 19154 verbose(env, "bpf verifier is misconfigured\n"); 19155 return -EINVAL; 19156 } 19157 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 19158 env->prog); 19159 if (cnt >= ARRAY_SIZE(insn_buf)) { 19160 verbose(env, "bpf verifier is misconfigured\n"); 19161 return -EINVAL; 19162 } else if (cnt) { 19163 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 19164 if (!new_prog) 19165 return -ENOMEM; 19166 19167 env->prog = new_prog; 19168 delta += cnt - 1; 19169 } 19170 } 19171 19172 if (bpf_prog_is_offloaded(env->prog->aux)) 19173 return 0; 19174 19175 insn = env->prog->insnsi + delta; 19176 19177 for (i = 0; i < insn_cnt; i++, insn++) { 19178 bpf_convert_ctx_access_t convert_ctx_access; 19179 u8 mode; 19180 19181 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 19182 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 19183 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 19184 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 19185 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 19186 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 19187 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 19188 type = BPF_READ; 19189 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 19190 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 19191 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 19192 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 19193 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 19194 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 19195 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 19196 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 19197 type = BPF_WRITE; 19198 } else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) || 19199 insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) && 19200 env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) { 19201 insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code); 19202 env->prog->aux->num_exentries++; 19203 continue; 19204 } else { 19205 continue; 19206 } 19207 19208 if (type == BPF_WRITE && 19209 env->insn_aux_data[i + delta].sanitize_stack_spill) { 19210 struct bpf_insn patch[] = { 19211 *insn, 19212 BPF_ST_NOSPEC(), 19213 }; 19214 19215 cnt = ARRAY_SIZE(patch); 19216 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 19217 if (!new_prog) 19218 return -ENOMEM; 19219 19220 delta += cnt - 1; 19221 env->prog = new_prog; 19222 insn = new_prog->insnsi + i + delta; 19223 continue; 19224 } 19225 19226 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 19227 case PTR_TO_CTX: 19228 if (!ops->convert_ctx_access) 19229 continue; 19230 convert_ctx_access = ops->convert_ctx_access; 19231 break; 19232 case PTR_TO_SOCKET: 19233 case PTR_TO_SOCK_COMMON: 19234 convert_ctx_access = bpf_sock_convert_ctx_access; 19235 break; 19236 case PTR_TO_TCP_SOCK: 19237 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 19238 break; 19239 case PTR_TO_XDP_SOCK: 19240 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 19241 break; 19242 case PTR_TO_BTF_ID: 19243 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 19244 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 19245 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 19246 * be said once it is marked PTR_UNTRUSTED, hence we must handle 19247 * any faults for loads into such types. BPF_WRITE is disallowed 19248 * for this case. 19249 */ 19250 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 19251 if (type == BPF_READ) { 19252 if (BPF_MODE(insn->code) == BPF_MEM) 19253 insn->code = BPF_LDX | BPF_PROBE_MEM | 19254 BPF_SIZE((insn)->code); 19255 else 19256 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 19257 BPF_SIZE((insn)->code); 19258 env->prog->aux->num_exentries++; 19259 } 19260 continue; 19261 case PTR_TO_ARENA: 19262 if (BPF_MODE(insn->code) == BPF_MEMSX) { 19263 verbose(env, "sign extending loads from arena are not supported yet\n"); 19264 return -EOPNOTSUPP; 19265 } 19266 insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code); 19267 env->prog->aux->num_exentries++; 19268 continue; 19269 default: 19270 continue; 19271 } 19272 19273 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 19274 size = BPF_LDST_BYTES(insn); 19275 mode = BPF_MODE(insn->code); 19276 19277 /* If the read access is a narrower load of the field, 19278 * convert to a 4/8-byte load, to minimum program type specific 19279 * convert_ctx_access changes. If conversion is successful, 19280 * we will apply proper mask to the result. 19281 */ 19282 is_narrower_load = size < ctx_field_size; 19283 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 19284 off = insn->off; 19285 if (is_narrower_load) { 19286 u8 size_code; 19287 19288 if (type == BPF_WRITE) { 19289 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 19290 return -EINVAL; 19291 } 19292 19293 size_code = BPF_H; 19294 if (ctx_field_size == 4) 19295 size_code = BPF_W; 19296 else if (ctx_field_size == 8) 19297 size_code = BPF_DW; 19298 19299 insn->off = off & ~(size_default - 1); 19300 insn->code = BPF_LDX | BPF_MEM | size_code; 19301 } 19302 19303 target_size = 0; 19304 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 19305 &target_size); 19306 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 19307 (ctx_field_size && !target_size)) { 19308 verbose(env, "bpf verifier is misconfigured\n"); 19309 return -EINVAL; 19310 } 19311 19312 if (is_narrower_load && size < target_size) { 19313 u8 shift = bpf_ctx_narrow_access_offset( 19314 off, size, size_default) * 8; 19315 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 19316 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 19317 return -EINVAL; 19318 } 19319 if (ctx_field_size <= 4) { 19320 if (shift) 19321 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 19322 insn->dst_reg, 19323 shift); 19324 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 19325 (1 << size * 8) - 1); 19326 } else { 19327 if (shift) 19328 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 19329 insn->dst_reg, 19330 shift); 19331 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 19332 (1ULL << size * 8) - 1); 19333 } 19334 } 19335 if (mode == BPF_MEMSX) 19336 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 19337 insn->dst_reg, insn->dst_reg, 19338 size * 8, 0); 19339 19340 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19341 if (!new_prog) 19342 return -ENOMEM; 19343 19344 delta += cnt - 1; 19345 19346 /* keep walking new program and skip insns we just inserted */ 19347 env->prog = new_prog; 19348 insn = new_prog->insnsi + i + delta; 19349 } 19350 19351 return 0; 19352 } 19353 19354 static int jit_subprogs(struct bpf_verifier_env *env) 19355 { 19356 struct bpf_prog *prog = env->prog, **func, *tmp; 19357 int i, j, subprog_start, subprog_end = 0, len, subprog; 19358 struct bpf_map *map_ptr; 19359 struct bpf_insn *insn; 19360 void *old_bpf_func; 19361 int err, num_exentries; 19362 19363 if (env->subprog_cnt <= 1) 19364 return 0; 19365 19366 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 19367 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 19368 continue; 19369 19370 /* Upon error here we cannot fall back to interpreter but 19371 * need a hard reject of the program. Thus -EFAULT is 19372 * propagated in any case. 19373 */ 19374 subprog = find_subprog(env, i + insn->imm + 1); 19375 if (subprog < 0) { 19376 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 19377 i + insn->imm + 1); 19378 return -EFAULT; 19379 } 19380 /* temporarily remember subprog id inside insn instead of 19381 * aux_data, since next loop will split up all insns into funcs 19382 */ 19383 insn->off = subprog; 19384 /* remember original imm in case JIT fails and fallback 19385 * to interpreter will be needed 19386 */ 19387 env->insn_aux_data[i].call_imm = insn->imm; 19388 /* point imm to __bpf_call_base+1 from JITs point of view */ 19389 insn->imm = 1; 19390 if (bpf_pseudo_func(insn)) { 19391 #if defined(MODULES_VADDR) 19392 u64 addr = MODULES_VADDR; 19393 #else 19394 u64 addr = VMALLOC_START; 19395 #endif 19396 /* jit (e.g. x86_64) may emit fewer instructions 19397 * if it learns a u32 imm is the same as a u64 imm. 19398 * Set close enough to possible prog address. 19399 */ 19400 insn[0].imm = (u32)addr; 19401 insn[1].imm = addr >> 32; 19402 } 19403 } 19404 19405 err = bpf_prog_alloc_jited_linfo(prog); 19406 if (err) 19407 goto out_undo_insn; 19408 19409 err = -ENOMEM; 19410 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 19411 if (!func) 19412 goto out_undo_insn; 19413 19414 for (i = 0; i < env->subprog_cnt; i++) { 19415 subprog_start = subprog_end; 19416 subprog_end = env->subprog_info[i + 1].start; 19417 19418 len = subprog_end - subprog_start; 19419 /* bpf_prog_run() doesn't call subprogs directly, 19420 * hence main prog stats include the runtime of subprogs. 19421 * subprogs don't have IDs and not reachable via prog_get_next_id 19422 * func[i]->stats will never be accessed and stays NULL 19423 */ 19424 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 19425 if (!func[i]) 19426 goto out_free; 19427 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 19428 len * sizeof(struct bpf_insn)); 19429 func[i]->type = prog->type; 19430 func[i]->len = len; 19431 if (bpf_prog_calc_tag(func[i])) 19432 goto out_free; 19433 func[i]->is_func = 1; 19434 func[i]->sleepable = prog->sleepable; 19435 func[i]->aux->func_idx = i; 19436 /* Below members will be freed only at prog->aux */ 19437 func[i]->aux->btf = prog->aux->btf; 19438 func[i]->aux->func_info = prog->aux->func_info; 19439 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 19440 func[i]->aux->poke_tab = prog->aux->poke_tab; 19441 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 19442 19443 for (j = 0; j < prog->aux->size_poke_tab; j++) { 19444 struct bpf_jit_poke_descriptor *poke; 19445 19446 poke = &prog->aux->poke_tab[j]; 19447 if (poke->insn_idx < subprog_end && 19448 poke->insn_idx >= subprog_start) 19449 poke->aux = func[i]->aux; 19450 } 19451 19452 func[i]->aux->name[0] = 'F'; 19453 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 19454 func[i]->jit_requested = 1; 19455 func[i]->blinding_requested = prog->blinding_requested; 19456 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 19457 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 19458 func[i]->aux->linfo = prog->aux->linfo; 19459 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 19460 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 19461 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 19462 func[i]->aux->arena = prog->aux->arena; 19463 num_exentries = 0; 19464 insn = func[i]->insnsi; 19465 for (j = 0; j < func[i]->len; j++, insn++) { 19466 if (BPF_CLASS(insn->code) == BPF_LDX && 19467 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 19468 BPF_MODE(insn->code) == BPF_PROBE_MEM32 || 19469 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 19470 num_exentries++; 19471 if ((BPF_CLASS(insn->code) == BPF_STX || 19472 BPF_CLASS(insn->code) == BPF_ST) && 19473 BPF_MODE(insn->code) == BPF_PROBE_MEM32) 19474 num_exentries++; 19475 if (BPF_CLASS(insn->code) == BPF_STX && 19476 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) 19477 num_exentries++; 19478 } 19479 func[i]->aux->num_exentries = num_exentries; 19480 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 19481 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb; 19482 if (!i) 19483 func[i]->aux->exception_boundary = env->seen_exception; 19484 func[i] = bpf_int_jit_compile(func[i]); 19485 if (!func[i]->jited) { 19486 err = -ENOTSUPP; 19487 goto out_free; 19488 } 19489 cond_resched(); 19490 } 19491 19492 /* at this point all bpf functions were successfully JITed 19493 * now populate all bpf_calls with correct addresses and 19494 * run last pass of JIT 19495 */ 19496 for (i = 0; i < env->subprog_cnt; i++) { 19497 insn = func[i]->insnsi; 19498 for (j = 0; j < func[i]->len; j++, insn++) { 19499 if (bpf_pseudo_func(insn)) { 19500 subprog = insn->off; 19501 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 19502 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 19503 continue; 19504 } 19505 if (!bpf_pseudo_call(insn)) 19506 continue; 19507 subprog = insn->off; 19508 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 19509 } 19510 19511 /* we use the aux data to keep a list of the start addresses 19512 * of the JITed images for each function in the program 19513 * 19514 * for some architectures, such as powerpc64, the imm field 19515 * might not be large enough to hold the offset of the start 19516 * address of the callee's JITed image from __bpf_call_base 19517 * 19518 * in such cases, we can lookup the start address of a callee 19519 * by using its subprog id, available from the off field of 19520 * the call instruction, as an index for this list 19521 */ 19522 func[i]->aux->func = func; 19523 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 19524 func[i]->aux->real_func_cnt = env->subprog_cnt; 19525 } 19526 for (i = 0; i < env->subprog_cnt; i++) { 19527 old_bpf_func = func[i]->bpf_func; 19528 tmp = bpf_int_jit_compile(func[i]); 19529 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 19530 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 19531 err = -ENOTSUPP; 19532 goto out_free; 19533 } 19534 cond_resched(); 19535 } 19536 19537 /* finally lock prog and jit images for all functions and 19538 * populate kallsysm. Begin at the first subprogram, since 19539 * bpf_prog_load will add the kallsyms for the main program. 19540 */ 19541 for (i = 1; i < env->subprog_cnt; i++) { 19542 err = bpf_prog_lock_ro(func[i]); 19543 if (err) 19544 goto out_free; 19545 } 19546 19547 for (i = 1; i < env->subprog_cnt; i++) 19548 bpf_prog_kallsyms_add(func[i]); 19549 19550 /* Last step: make now unused interpreter insns from main 19551 * prog consistent for later dump requests, so they can 19552 * later look the same as if they were interpreted only. 19553 */ 19554 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 19555 if (bpf_pseudo_func(insn)) { 19556 insn[0].imm = env->insn_aux_data[i].call_imm; 19557 insn[1].imm = insn->off; 19558 insn->off = 0; 19559 continue; 19560 } 19561 if (!bpf_pseudo_call(insn)) 19562 continue; 19563 insn->off = env->insn_aux_data[i].call_imm; 19564 subprog = find_subprog(env, i + insn->off + 1); 19565 insn->imm = subprog; 19566 } 19567 19568 prog->jited = 1; 19569 prog->bpf_func = func[0]->bpf_func; 19570 prog->jited_len = func[0]->jited_len; 19571 prog->aux->extable = func[0]->aux->extable; 19572 prog->aux->num_exentries = func[0]->aux->num_exentries; 19573 prog->aux->func = func; 19574 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 19575 prog->aux->real_func_cnt = env->subprog_cnt; 19576 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func; 19577 prog->aux->exception_boundary = func[0]->aux->exception_boundary; 19578 bpf_prog_jit_attempt_done(prog); 19579 return 0; 19580 out_free: 19581 /* We failed JIT'ing, so at this point we need to unregister poke 19582 * descriptors from subprogs, so that kernel is not attempting to 19583 * patch it anymore as we're freeing the subprog JIT memory. 19584 */ 19585 for (i = 0; i < prog->aux->size_poke_tab; i++) { 19586 map_ptr = prog->aux->poke_tab[i].tail_call.map; 19587 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 19588 } 19589 /* At this point we're guaranteed that poke descriptors are not 19590 * live anymore. We can just unlink its descriptor table as it's 19591 * released with the main prog. 19592 */ 19593 for (i = 0; i < env->subprog_cnt; i++) { 19594 if (!func[i]) 19595 continue; 19596 func[i]->aux->poke_tab = NULL; 19597 bpf_jit_free(func[i]); 19598 } 19599 kfree(func); 19600 out_undo_insn: 19601 /* cleanup main prog to be interpreted */ 19602 prog->jit_requested = 0; 19603 prog->blinding_requested = 0; 19604 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 19605 if (!bpf_pseudo_call(insn)) 19606 continue; 19607 insn->off = 0; 19608 insn->imm = env->insn_aux_data[i].call_imm; 19609 } 19610 bpf_prog_jit_attempt_done(prog); 19611 return err; 19612 } 19613 19614 static int fixup_call_args(struct bpf_verifier_env *env) 19615 { 19616 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 19617 struct bpf_prog *prog = env->prog; 19618 struct bpf_insn *insn = prog->insnsi; 19619 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 19620 int i, depth; 19621 #endif 19622 int err = 0; 19623 19624 if (env->prog->jit_requested && 19625 !bpf_prog_is_offloaded(env->prog->aux)) { 19626 err = jit_subprogs(env); 19627 if (err == 0) 19628 return 0; 19629 if (err == -EFAULT) 19630 return err; 19631 } 19632 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 19633 if (has_kfunc_call) { 19634 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 19635 return -EINVAL; 19636 } 19637 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 19638 /* When JIT fails the progs with bpf2bpf calls and tail_calls 19639 * have to be rejected, since interpreter doesn't support them yet. 19640 */ 19641 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 19642 return -EINVAL; 19643 } 19644 for (i = 0; i < prog->len; i++, insn++) { 19645 if (bpf_pseudo_func(insn)) { 19646 /* When JIT fails the progs with callback calls 19647 * have to be rejected, since interpreter doesn't support them yet. 19648 */ 19649 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 19650 return -EINVAL; 19651 } 19652 19653 if (!bpf_pseudo_call(insn)) 19654 continue; 19655 depth = get_callee_stack_depth(env, insn, i); 19656 if (depth < 0) 19657 return depth; 19658 bpf_patch_call_args(insn, depth); 19659 } 19660 err = 0; 19661 #endif 19662 return err; 19663 } 19664 19665 /* replace a generic kfunc with a specialized version if necessary */ 19666 static void specialize_kfunc(struct bpf_verifier_env *env, 19667 u32 func_id, u16 offset, unsigned long *addr) 19668 { 19669 struct bpf_prog *prog = env->prog; 19670 bool seen_direct_write; 19671 void *xdp_kfunc; 19672 bool is_rdonly; 19673 19674 if (bpf_dev_bound_kfunc_id(func_id)) { 19675 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 19676 if (xdp_kfunc) { 19677 *addr = (unsigned long)xdp_kfunc; 19678 return; 19679 } 19680 /* fallback to default kfunc when not supported by netdev */ 19681 } 19682 19683 if (offset) 19684 return; 19685 19686 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 19687 seen_direct_write = env->seen_direct_write; 19688 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 19689 19690 if (is_rdonly) 19691 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 19692 19693 /* restore env->seen_direct_write to its original value, since 19694 * may_access_direct_pkt_data mutates it 19695 */ 19696 env->seen_direct_write = seen_direct_write; 19697 } 19698 } 19699 19700 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 19701 u16 struct_meta_reg, 19702 u16 node_offset_reg, 19703 struct bpf_insn *insn, 19704 struct bpf_insn *insn_buf, 19705 int *cnt) 19706 { 19707 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 19708 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 19709 19710 insn_buf[0] = addr[0]; 19711 insn_buf[1] = addr[1]; 19712 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 19713 insn_buf[3] = *insn; 19714 *cnt = 4; 19715 } 19716 19717 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 19718 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 19719 { 19720 const struct bpf_kfunc_desc *desc; 19721 19722 if (!insn->imm) { 19723 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 19724 return -EINVAL; 19725 } 19726 19727 *cnt = 0; 19728 19729 /* insn->imm has the btf func_id. Replace it with an offset relative to 19730 * __bpf_call_base, unless the JIT needs to call functions that are 19731 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 19732 */ 19733 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 19734 if (!desc) { 19735 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 19736 insn->imm); 19737 return -EFAULT; 19738 } 19739 19740 if (!bpf_jit_supports_far_kfunc_call()) 19741 insn->imm = BPF_CALL_IMM(desc->addr); 19742 if (insn->off) 19743 return 0; 19744 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 19745 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 19746 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19747 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19748 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 19749 19750 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) { 19751 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 19752 insn_idx); 19753 return -EFAULT; 19754 } 19755 19756 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 19757 insn_buf[1] = addr[0]; 19758 insn_buf[2] = addr[1]; 19759 insn_buf[3] = *insn; 19760 *cnt = 4; 19761 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 19762 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] || 19763 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 19764 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19765 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19766 19767 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) { 19768 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 19769 insn_idx); 19770 return -EFAULT; 19771 } 19772 19773 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 19774 !kptr_struct_meta) { 19775 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 19776 insn_idx); 19777 return -EFAULT; 19778 } 19779 19780 insn_buf[0] = addr[0]; 19781 insn_buf[1] = addr[1]; 19782 insn_buf[2] = *insn; 19783 *cnt = 3; 19784 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 19785 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 19786 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 19787 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19788 int struct_meta_reg = BPF_REG_3; 19789 int node_offset_reg = BPF_REG_4; 19790 19791 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 19792 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 19793 struct_meta_reg = BPF_REG_4; 19794 node_offset_reg = BPF_REG_5; 19795 } 19796 19797 if (!kptr_struct_meta) { 19798 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 19799 insn_idx); 19800 return -EFAULT; 19801 } 19802 19803 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 19804 node_offset_reg, insn, insn_buf, cnt); 19805 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 19806 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 19807 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 19808 *cnt = 1; 19809 } else if (is_bpf_wq_set_callback_impl_kfunc(desc->func_id)) { 19810 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(BPF_REG_4, (long)env->prog->aux) }; 19811 19812 insn_buf[0] = ld_addrs[0]; 19813 insn_buf[1] = ld_addrs[1]; 19814 insn_buf[2] = *insn; 19815 *cnt = 3; 19816 } 19817 return 0; 19818 } 19819 19820 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */ 19821 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len) 19822 { 19823 struct bpf_subprog_info *info = env->subprog_info; 19824 int cnt = env->subprog_cnt; 19825 struct bpf_prog *prog; 19826 19827 /* We only reserve one slot for hidden subprogs in subprog_info. */ 19828 if (env->hidden_subprog_cnt) { 19829 verbose(env, "verifier internal error: only one hidden subprog supported\n"); 19830 return -EFAULT; 19831 } 19832 /* We're not patching any existing instruction, just appending the new 19833 * ones for the hidden subprog. Hence all of the adjustment operations 19834 * in bpf_patch_insn_data are no-ops. 19835 */ 19836 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len); 19837 if (!prog) 19838 return -ENOMEM; 19839 env->prog = prog; 19840 info[cnt + 1].start = info[cnt].start; 19841 info[cnt].start = prog->len - len + 1; 19842 env->subprog_cnt++; 19843 env->hidden_subprog_cnt++; 19844 return 0; 19845 } 19846 19847 /* Do various post-verification rewrites in a single program pass. 19848 * These rewrites simplify JIT and interpreter implementations. 19849 */ 19850 static int do_misc_fixups(struct bpf_verifier_env *env) 19851 { 19852 struct bpf_prog *prog = env->prog; 19853 enum bpf_attach_type eatype = prog->expected_attach_type; 19854 enum bpf_prog_type prog_type = resolve_prog_type(prog); 19855 struct bpf_insn *insn = prog->insnsi; 19856 const struct bpf_func_proto *fn; 19857 const int insn_cnt = prog->len; 19858 const struct bpf_map_ops *ops; 19859 struct bpf_insn_aux_data *aux; 19860 struct bpf_insn insn_buf[16]; 19861 struct bpf_prog *new_prog; 19862 struct bpf_map *map_ptr; 19863 int i, ret, cnt, delta = 0, cur_subprog = 0; 19864 struct bpf_subprog_info *subprogs = env->subprog_info; 19865 u16 stack_depth = subprogs[cur_subprog].stack_depth; 19866 u16 stack_depth_extra = 0; 19867 19868 if (env->seen_exception && !env->exception_callback_subprog) { 19869 struct bpf_insn patch[] = { 19870 env->prog->insnsi[insn_cnt - 1], 19871 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1), 19872 BPF_EXIT_INSN(), 19873 }; 19874 19875 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch)); 19876 if (ret < 0) 19877 return ret; 19878 prog = env->prog; 19879 insn = prog->insnsi; 19880 19881 env->exception_callback_subprog = env->subprog_cnt - 1; 19882 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */ 19883 mark_subprog_exc_cb(env, env->exception_callback_subprog); 19884 } 19885 19886 for (i = 0; i < insn_cnt;) { 19887 if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) { 19888 if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) || 19889 (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) { 19890 /* convert to 32-bit mov that clears upper 32-bit */ 19891 insn->code = BPF_ALU | BPF_MOV | BPF_X; 19892 /* clear off and imm, so it's a normal 'wX = wY' from JIT pov */ 19893 insn->off = 0; 19894 insn->imm = 0; 19895 } /* cast from as(0) to as(1) should be handled by JIT */ 19896 goto next_insn; 19897 } 19898 19899 if (env->insn_aux_data[i + delta].needs_zext) 19900 /* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */ 19901 insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code); 19902 19903 /* Make divide-by-zero exceptions impossible. */ 19904 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 19905 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 19906 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 19907 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 19908 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 19909 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 19910 struct bpf_insn *patchlet; 19911 struct bpf_insn chk_and_div[] = { 19912 /* [R,W]x div 0 -> 0 */ 19913 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 19914 BPF_JNE | BPF_K, insn->src_reg, 19915 0, 2, 0), 19916 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 19917 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 19918 *insn, 19919 }; 19920 struct bpf_insn chk_and_mod[] = { 19921 /* [R,W]x mod 0 -> [R,W]x */ 19922 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 19923 BPF_JEQ | BPF_K, insn->src_reg, 19924 0, 1 + (is64 ? 0 : 1), 0), 19925 *insn, 19926 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 19927 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 19928 }; 19929 19930 patchlet = isdiv ? chk_and_div : chk_and_mod; 19931 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 19932 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 19933 19934 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 19935 if (!new_prog) 19936 return -ENOMEM; 19937 19938 delta += cnt - 1; 19939 env->prog = prog = new_prog; 19940 insn = new_prog->insnsi + i + delta; 19941 goto next_insn; 19942 } 19943 19944 /* Make it impossible to de-reference a userspace address */ 19945 if (BPF_CLASS(insn->code) == BPF_LDX && 19946 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 19947 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) { 19948 struct bpf_insn *patch = &insn_buf[0]; 19949 u64 uaddress_limit = bpf_arch_uaddress_limit(); 19950 19951 if (!uaddress_limit) 19952 goto next_insn; 19953 19954 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg); 19955 if (insn->off) 19956 *patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off); 19957 *patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32); 19958 *patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2); 19959 *patch++ = *insn; 19960 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 19961 *patch++ = BPF_MOV64_IMM(insn->dst_reg, 0); 19962 19963 cnt = patch - insn_buf; 19964 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19965 if (!new_prog) 19966 return -ENOMEM; 19967 19968 delta += cnt - 1; 19969 env->prog = prog = new_prog; 19970 insn = new_prog->insnsi + i + delta; 19971 goto next_insn; 19972 } 19973 19974 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 19975 if (BPF_CLASS(insn->code) == BPF_LD && 19976 (BPF_MODE(insn->code) == BPF_ABS || 19977 BPF_MODE(insn->code) == BPF_IND)) { 19978 cnt = env->ops->gen_ld_abs(insn, insn_buf); 19979 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19980 verbose(env, "bpf verifier is misconfigured\n"); 19981 return -EINVAL; 19982 } 19983 19984 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19985 if (!new_prog) 19986 return -ENOMEM; 19987 19988 delta += cnt - 1; 19989 env->prog = prog = new_prog; 19990 insn = new_prog->insnsi + i + delta; 19991 goto next_insn; 19992 } 19993 19994 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 19995 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 19996 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 19997 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 19998 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 19999 struct bpf_insn *patch = &insn_buf[0]; 20000 bool issrc, isneg, isimm; 20001 u32 off_reg; 20002 20003 aux = &env->insn_aux_data[i + delta]; 20004 if (!aux->alu_state || 20005 aux->alu_state == BPF_ALU_NON_POINTER) 20006 goto next_insn; 20007 20008 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 20009 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 20010 BPF_ALU_SANITIZE_SRC; 20011 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 20012 20013 off_reg = issrc ? insn->src_reg : insn->dst_reg; 20014 if (isimm) { 20015 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 20016 } else { 20017 if (isneg) 20018 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 20019 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 20020 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 20021 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 20022 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 20023 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 20024 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 20025 } 20026 if (!issrc) 20027 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 20028 insn->src_reg = BPF_REG_AX; 20029 if (isneg) 20030 insn->code = insn->code == code_add ? 20031 code_sub : code_add; 20032 *patch++ = *insn; 20033 if (issrc && isneg && !isimm) 20034 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 20035 cnt = patch - insn_buf; 20036 20037 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20038 if (!new_prog) 20039 return -ENOMEM; 20040 20041 delta += cnt - 1; 20042 env->prog = prog = new_prog; 20043 insn = new_prog->insnsi + i + delta; 20044 goto next_insn; 20045 } 20046 20047 if (is_may_goto_insn(insn)) { 20048 int stack_off = -stack_depth - 8; 20049 20050 stack_depth_extra = 8; 20051 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off); 20052 if (insn->off >= 0) 20053 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2); 20054 else 20055 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1); 20056 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1); 20057 insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off); 20058 cnt = 4; 20059 20060 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20061 if (!new_prog) 20062 return -ENOMEM; 20063 20064 delta += cnt - 1; 20065 env->prog = prog = new_prog; 20066 insn = new_prog->insnsi + i + delta; 20067 goto next_insn; 20068 } 20069 20070 if (insn->code != (BPF_JMP | BPF_CALL)) 20071 goto next_insn; 20072 if (insn->src_reg == BPF_PSEUDO_CALL) 20073 goto next_insn; 20074 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 20075 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 20076 if (ret) 20077 return ret; 20078 if (cnt == 0) 20079 goto next_insn; 20080 20081 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20082 if (!new_prog) 20083 return -ENOMEM; 20084 20085 delta += cnt - 1; 20086 env->prog = prog = new_prog; 20087 insn = new_prog->insnsi + i + delta; 20088 goto next_insn; 20089 } 20090 20091 /* Skip inlining the helper call if the JIT does it. */ 20092 if (bpf_jit_inlines_helper_call(insn->imm)) 20093 goto next_insn; 20094 20095 if (insn->imm == BPF_FUNC_get_route_realm) 20096 prog->dst_needed = 1; 20097 if (insn->imm == BPF_FUNC_get_prandom_u32) 20098 bpf_user_rnd_init_once(); 20099 if (insn->imm == BPF_FUNC_override_return) 20100 prog->kprobe_override = 1; 20101 if (insn->imm == BPF_FUNC_tail_call) { 20102 /* If we tail call into other programs, we 20103 * cannot make any assumptions since they can 20104 * be replaced dynamically during runtime in 20105 * the program array. 20106 */ 20107 prog->cb_access = 1; 20108 if (!allow_tail_call_in_subprogs(env)) 20109 prog->aux->stack_depth = MAX_BPF_STACK; 20110 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 20111 20112 /* mark bpf_tail_call as different opcode to avoid 20113 * conditional branch in the interpreter for every normal 20114 * call and to prevent accidental JITing by JIT compiler 20115 * that doesn't support bpf_tail_call yet 20116 */ 20117 insn->imm = 0; 20118 insn->code = BPF_JMP | BPF_TAIL_CALL; 20119 20120 aux = &env->insn_aux_data[i + delta]; 20121 if (env->bpf_capable && !prog->blinding_requested && 20122 prog->jit_requested && 20123 !bpf_map_key_poisoned(aux) && 20124 !bpf_map_ptr_poisoned(aux) && 20125 !bpf_map_ptr_unpriv(aux)) { 20126 struct bpf_jit_poke_descriptor desc = { 20127 .reason = BPF_POKE_REASON_TAIL_CALL, 20128 .tail_call.map = aux->map_ptr_state.map_ptr, 20129 .tail_call.key = bpf_map_key_immediate(aux), 20130 .insn_idx = i + delta, 20131 }; 20132 20133 ret = bpf_jit_add_poke_descriptor(prog, &desc); 20134 if (ret < 0) { 20135 verbose(env, "adding tail call poke descriptor failed\n"); 20136 return ret; 20137 } 20138 20139 insn->imm = ret + 1; 20140 goto next_insn; 20141 } 20142 20143 if (!bpf_map_ptr_unpriv(aux)) 20144 goto next_insn; 20145 20146 /* instead of changing every JIT dealing with tail_call 20147 * emit two extra insns: 20148 * if (index >= max_entries) goto out; 20149 * index &= array->index_mask; 20150 * to avoid out-of-bounds cpu speculation 20151 */ 20152 if (bpf_map_ptr_poisoned(aux)) { 20153 verbose(env, "tail_call abusing map_ptr\n"); 20154 return -EINVAL; 20155 } 20156 20157 map_ptr = aux->map_ptr_state.map_ptr; 20158 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 20159 map_ptr->max_entries, 2); 20160 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 20161 container_of(map_ptr, 20162 struct bpf_array, 20163 map)->index_mask); 20164 insn_buf[2] = *insn; 20165 cnt = 3; 20166 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20167 if (!new_prog) 20168 return -ENOMEM; 20169 20170 delta += cnt - 1; 20171 env->prog = prog = new_prog; 20172 insn = new_prog->insnsi + i + delta; 20173 goto next_insn; 20174 } 20175 20176 if (insn->imm == BPF_FUNC_timer_set_callback) { 20177 /* The verifier will process callback_fn as many times as necessary 20178 * with different maps and the register states prepared by 20179 * set_timer_callback_state will be accurate. 20180 * 20181 * The following use case is valid: 20182 * map1 is shared by prog1, prog2, prog3. 20183 * prog1 calls bpf_timer_init for some map1 elements 20184 * prog2 calls bpf_timer_set_callback for some map1 elements. 20185 * Those that were not bpf_timer_init-ed will return -EINVAL. 20186 * prog3 calls bpf_timer_start for some map1 elements. 20187 * Those that were not both bpf_timer_init-ed and 20188 * bpf_timer_set_callback-ed will return -EINVAL. 20189 */ 20190 struct bpf_insn ld_addrs[2] = { 20191 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 20192 }; 20193 20194 insn_buf[0] = ld_addrs[0]; 20195 insn_buf[1] = ld_addrs[1]; 20196 insn_buf[2] = *insn; 20197 cnt = 3; 20198 20199 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20200 if (!new_prog) 20201 return -ENOMEM; 20202 20203 delta += cnt - 1; 20204 env->prog = prog = new_prog; 20205 insn = new_prog->insnsi + i + delta; 20206 goto patch_call_imm; 20207 } 20208 20209 if (is_storage_get_function(insn->imm)) { 20210 if (!in_sleepable(env) || 20211 env->insn_aux_data[i + delta].storage_get_func_atomic) 20212 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 20213 else 20214 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 20215 insn_buf[1] = *insn; 20216 cnt = 2; 20217 20218 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20219 if (!new_prog) 20220 return -ENOMEM; 20221 20222 delta += cnt - 1; 20223 env->prog = prog = new_prog; 20224 insn = new_prog->insnsi + i + delta; 20225 goto patch_call_imm; 20226 } 20227 20228 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */ 20229 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) { 20230 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data, 20231 * bpf_mem_alloc() returns a ptr to the percpu data ptr. 20232 */ 20233 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0); 20234 insn_buf[1] = *insn; 20235 cnt = 2; 20236 20237 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20238 if (!new_prog) 20239 return -ENOMEM; 20240 20241 delta += cnt - 1; 20242 env->prog = prog = new_prog; 20243 insn = new_prog->insnsi + i + delta; 20244 goto patch_call_imm; 20245 } 20246 20247 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 20248 * and other inlining handlers are currently limited to 64 bit 20249 * only. 20250 */ 20251 if (prog->jit_requested && BITS_PER_LONG == 64 && 20252 (insn->imm == BPF_FUNC_map_lookup_elem || 20253 insn->imm == BPF_FUNC_map_update_elem || 20254 insn->imm == BPF_FUNC_map_delete_elem || 20255 insn->imm == BPF_FUNC_map_push_elem || 20256 insn->imm == BPF_FUNC_map_pop_elem || 20257 insn->imm == BPF_FUNC_map_peek_elem || 20258 insn->imm == BPF_FUNC_redirect_map || 20259 insn->imm == BPF_FUNC_for_each_map_elem || 20260 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 20261 aux = &env->insn_aux_data[i + delta]; 20262 if (bpf_map_ptr_poisoned(aux)) 20263 goto patch_call_imm; 20264 20265 map_ptr = aux->map_ptr_state.map_ptr; 20266 ops = map_ptr->ops; 20267 if (insn->imm == BPF_FUNC_map_lookup_elem && 20268 ops->map_gen_lookup) { 20269 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 20270 if (cnt == -EOPNOTSUPP) 20271 goto patch_map_ops_generic; 20272 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 20273 verbose(env, "bpf verifier is misconfigured\n"); 20274 return -EINVAL; 20275 } 20276 20277 new_prog = bpf_patch_insn_data(env, i + delta, 20278 insn_buf, cnt); 20279 if (!new_prog) 20280 return -ENOMEM; 20281 20282 delta += cnt - 1; 20283 env->prog = prog = new_prog; 20284 insn = new_prog->insnsi + i + delta; 20285 goto next_insn; 20286 } 20287 20288 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 20289 (void *(*)(struct bpf_map *map, void *key))NULL)); 20290 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 20291 (long (*)(struct bpf_map *map, void *key))NULL)); 20292 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 20293 (long (*)(struct bpf_map *map, void *key, void *value, 20294 u64 flags))NULL)); 20295 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 20296 (long (*)(struct bpf_map *map, void *value, 20297 u64 flags))NULL)); 20298 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 20299 (long (*)(struct bpf_map *map, void *value))NULL)); 20300 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 20301 (long (*)(struct bpf_map *map, void *value))NULL)); 20302 BUILD_BUG_ON(!__same_type(ops->map_redirect, 20303 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 20304 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 20305 (long (*)(struct bpf_map *map, 20306 bpf_callback_t callback_fn, 20307 void *callback_ctx, 20308 u64 flags))NULL)); 20309 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 20310 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 20311 20312 patch_map_ops_generic: 20313 switch (insn->imm) { 20314 case BPF_FUNC_map_lookup_elem: 20315 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 20316 goto next_insn; 20317 case BPF_FUNC_map_update_elem: 20318 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 20319 goto next_insn; 20320 case BPF_FUNC_map_delete_elem: 20321 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 20322 goto next_insn; 20323 case BPF_FUNC_map_push_elem: 20324 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 20325 goto next_insn; 20326 case BPF_FUNC_map_pop_elem: 20327 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 20328 goto next_insn; 20329 case BPF_FUNC_map_peek_elem: 20330 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 20331 goto next_insn; 20332 case BPF_FUNC_redirect_map: 20333 insn->imm = BPF_CALL_IMM(ops->map_redirect); 20334 goto next_insn; 20335 case BPF_FUNC_for_each_map_elem: 20336 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 20337 goto next_insn; 20338 case BPF_FUNC_map_lookup_percpu_elem: 20339 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 20340 goto next_insn; 20341 } 20342 20343 goto patch_call_imm; 20344 } 20345 20346 /* Implement bpf_jiffies64 inline. */ 20347 if (prog->jit_requested && BITS_PER_LONG == 64 && 20348 insn->imm == BPF_FUNC_jiffies64) { 20349 struct bpf_insn ld_jiffies_addr[2] = { 20350 BPF_LD_IMM64(BPF_REG_0, 20351 (unsigned long)&jiffies), 20352 }; 20353 20354 insn_buf[0] = ld_jiffies_addr[0]; 20355 insn_buf[1] = ld_jiffies_addr[1]; 20356 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 20357 BPF_REG_0, 0); 20358 cnt = 3; 20359 20360 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 20361 cnt); 20362 if (!new_prog) 20363 return -ENOMEM; 20364 20365 delta += cnt - 1; 20366 env->prog = prog = new_prog; 20367 insn = new_prog->insnsi + i + delta; 20368 goto next_insn; 20369 } 20370 20371 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML) 20372 /* Implement bpf_get_smp_processor_id() inline. */ 20373 if (insn->imm == BPF_FUNC_get_smp_processor_id && 20374 prog->jit_requested && bpf_jit_supports_percpu_insn()) { 20375 /* BPF_FUNC_get_smp_processor_id inlining is an 20376 * optimization, so if pcpu_hot.cpu_number is ever 20377 * changed in some incompatible and hard to support 20378 * way, it's fine to back out this inlining logic 20379 */ 20380 insn_buf[0] = BPF_MOV32_IMM(BPF_REG_0, (u32)(unsigned long)&pcpu_hot.cpu_number); 20381 insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0); 20382 insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0); 20383 cnt = 3; 20384 20385 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20386 if (!new_prog) 20387 return -ENOMEM; 20388 20389 delta += cnt - 1; 20390 env->prog = prog = new_prog; 20391 insn = new_prog->insnsi + i + delta; 20392 goto next_insn; 20393 } 20394 #endif 20395 /* Implement bpf_get_func_arg inline. */ 20396 if (prog_type == BPF_PROG_TYPE_TRACING && 20397 insn->imm == BPF_FUNC_get_func_arg) { 20398 /* Load nr_args from ctx - 8 */ 20399 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 20400 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 20401 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 20402 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 20403 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 20404 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 20405 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 20406 insn_buf[7] = BPF_JMP_A(1); 20407 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 20408 cnt = 9; 20409 20410 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20411 if (!new_prog) 20412 return -ENOMEM; 20413 20414 delta += cnt - 1; 20415 env->prog = prog = new_prog; 20416 insn = new_prog->insnsi + i + delta; 20417 goto next_insn; 20418 } 20419 20420 /* Implement bpf_get_func_ret inline. */ 20421 if (prog_type == BPF_PROG_TYPE_TRACING && 20422 insn->imm == BPF_FUNC_get_func_ret) { 20423 if (eatype == BPF_TRACE_FEXIT || 20424 eatype == BPF_MODIFY_RETURN) { 20425 /* Load nr_args from ctx - 8 */ 20426 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 20427 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 20428 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 20429 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 20430 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 20431 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 20432 cnt = 6; 20433 } else { 20434 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 20435 cnt = 1; 20436 } 20437 20438 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20439 if (!new_prog) 20440 return -ENOMEM; 20441 20442 delta += cnt - 1; 20443 env->prog = prog = new_prog; 20444 insn = new_prog->insnsi + i + delta; 20445 goto next_insn; 20446 } 20447 20448 /* Implement get_func_arg_cnt inline. */ 20449 if (prog_type == BPF_PROG_TYPE_TRACING && 20450 insn->imm == BPF_FUNC_get_func_arg_cnt) { 20451 /* Load nr_args from ctx - 8 */ 20452 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 20453 20454 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 20455 if (!new_prog) 20456 return -ENOMEM; 20457 20458 env->prog = prog = new_prog; 20459 insn = new_prog->insnsi + i + delta; 20460 goto next_insn; 20461 } 20462 20463 /* Implement bpf_get_func_ip inline. */ 20464 if (prog_type == BPF_PROG_TYPE_TRACING && 20465 insn->imm == BPF_FUNC_get_func_ip) { 20466 /* Load IP address from ctx - 16 */ 20467 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 20468 20469 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 20470 if (!new_prog) 20471 return -ENOMEM; 20472 20473 env->prog = prog = new_prog; 20474 insn = new_prog->insnsi + i + delta; 20475 goto next_insn; 20476 } 20477 20478 /* Implement bpf_get_branch_snapshot inline. */ 20479 if (IS_ENABLED(CONFIG_PERF_EVENTS) && 20480 prog->jit_requested && BITS_PER_LONG == 64 && 20481 insn->imm == BPF_FUNC_get_branch_snapshot) { 20482 /* We are dealing with the following func protos: 20483 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags); 20484 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt); 20485 */ 20486 const u32 br_entry_size = sizeof(struct perf_branch_entry); 20487 20488 /* struct perf_branch_entry is part of UAPI and is 20489 * used as an array element, so extremely unlikely to 20490 * ever grow or shrink 20491 */ 20492 BUILD_BUG_ON(br_entry_size != 24); 20493 20494 /* if (unlikely(flags)) return -EINVAL */ 20495 insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7); 20496 20497 /* Transform size (bytes) into number of entries (cnt = size / 24). 20498 * But to avoid expensive division instruction, we implement 20499 * divide-by-3 through multiplication, followed by further 20500 * division by 8 through 3-bit right shift. 20501 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr., 20502 * p. 227, chapter "Unsigned Division by 3" for details and proofs. 20503 * 20504 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab. 20505 */ 20506 insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab); 20507 insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0); 20508 insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36); 20509 20510 /* call perf_snapshot_branch_stack implementation */ 20511 insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack)); 20512 /* if (entry_cnt == 0) return -ENOENT */ 20513 insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4); 20514 /* return entry_cnt * sizeof(struct perf_branch_entry) */ 20515 insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size); 20516 insn_buf[7] = BPF_JMP_A(3); 20517 /* return -EINVAL; */ 20518 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 20519 insn_buf[9] = BPF_JMP_A(1); 20520 /* return -ENOENT; */ 20521 insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT); 20522 cnt = 11; 20523 20524 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20525 if (!new_prog) 20526 return -ENOMEM; 20527 20528 delta += cnt - 1; 20529 env->prog = prog = new_prog; 20530 insn = new_prog->insnsi + i + delta; 20531 continue; 20532 } 20533 20534 /* Implement bpf_kptr_xchg inline */ 20535 if (prog->jit_requested && BITS_PER_LONG == 64 && 20536 insn->imm == BPF_FUNC_kptr_xchg && 20537 bpf_jit_supports_ptr_xchg()) { 20538 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2); 20539 insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0); 20540 cnt = 2; 20541 20542 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20543 if (!new_prog) 20544 return -ENOMEM; 20545 20546 delta += cnt - 1; 20547 env->prog = prog = new_prog; 20548 insn = new_prog->insnsi + i + delta; 20549 goto next_insn; 20550 } 20551 patch_call_imm: 20552 fn = env->ops->get_func_proto(insn->imm, env->prog); 20553 /* all functions that have prototype and verifier allowed 20554 * programs to call them, must be real in-kernel functions 20555 */ 20556 if (!fn->func) { 20557 verbose(env, 20558 "kernel subsystem misconfigured func %s#%d\n", 20559 func_id_name(insn->imm), insn->imm); 20560 return -EFAULT; 20561 } 20562 insn->imm = fn->func - __bpf_call_base; 20563 next_insn: 20564 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 20565 subprogs[cur_subprog].stack_depth += stack_depth_extra; 20566 subprogs[cur_subprog].stack_extra = stack_depth_extra; 20567 cur_subprog++; 20568 stack_depth = subprogs[cur_subprog].stack_depth; 20569 stack_depth_extra = 0; 20570 } 20571 i++; 20572 insn++; 20573 } 20574 20575 env->prog->aux->stack_depth = subprogs[0].stack_depth; 20576 for (i = 0; i < env->subprog_cnt; i++) { 20577 int subprog_start = subprogs[i].start; 20578 int stack_slots = subprogs[i].stack_extra / 8; 20579 20580 if (!stack_slots) 20581 continue; 20582 if (stack_slots > 1) { 20583 verbose(env, "verifier bug: stack_slots supports may_goto only\n"); 20584 return -EFAULT; 20585 } 20586 20587 /* Add ST insn to subprog prologue to init extra stack */ 20588 insn_buf[0] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, 20589 -subprogs[i].stack_depth, BPF_MAX_LOOPS); 20590 /* Copy first actual insn to preserve it */ 20591 insn_buf[1] = env->prog->insnsi[subprog_start]; 20592 20593 new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, 2); 20594 if (!new_prog) 20595 return -ENOMEM; 20596 env->prog = prog = new_prog; 20597 /* 20598 * If may_goto is a first insn of a prog there could be a jmp 20599 * insn that points to it, hence adjust all such jmps to point 20600 * to insn after BPF_ST that inits may_goto count. 20601 * Adjustment will succeed because bpf_patch_insn_data() didn't fail. 20602 */ 20603 WARN_ON(adjust_jmp_off(env->prog, subprog_start, 1)); 20604 } 20605 20606 /* Since poke tab is now finalized, publish aux to tracker. */ 20607 for (i = 0; i < prog->aux->size_poke_tab; i++) { 20608 map_ptr = prog->aux->poke_tab[i].tail_call.map; 20609 if (!map_ptr->ops->map_poke_track || 20610 !map_ptr->ops->map_poke_untrack || 20611 !map_ptr->ops->map_poke_run) { 20612 verbose(env, "bpf verifier is misconfigured\n"); 20613 return -EINVAL; 20614 } 20615 20616 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 20617 if (ret < 0) { 20618 verbose(env, "tracking tail call prog failed\n"); 20619 return ret; 20620 } 20621 } 20622 20623 sort_kfunc_descs_by_imm_off(env->prog); 20624 20625 return 0; 20626 } 20627 20628 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 20629 int position, 20630 s32 stack_base, 20631 u32 callback_subprogno, 20632 u32 *cnt) 20633 { 20634 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 20635 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 20636 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 20637 int reg_loop_max = BPF_REG_6; 20638 int reg_loop_cnt = BPF_REG_7; 20639 int reg_loop_ctx = BPF_REG_8; 20640 20641 struct bpf_prog *new_prog; 20642 u32 callback_start; 20643 u32 call_insn_offset; 20644 s32 callback_offset; 20645 20646 /* This represents an inlined version of bpf_iter.c:bpf_loop, 20647 * be careful to modify this code in sync. 20648 */ 20649 struct bpf_insn insn_buf[] = { 20650 /* Return error and jump to the end of the patch if 20651 * expected number of iterations is too big. 20652 */ 20653 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 20654 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 20655 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 20656 /* spill R6, R7, R8 to use these as loop vars */ 20657 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 20658 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 20659 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 20660 /* initialize loop vars */ 20661 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 20662 BPF_MOV32_IMM(reg_loop_cnt, 0), 20663 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 20664 /* loop header, 20665 * if reg_loop_cnt >= reg_loop_max skip the loop body 20666 */ 20667 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 20668 /* callback call, 20669 * correct callback offset would be set after patching 20670 */ 20671 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 20672 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 20673 BPF_CALL_REL(0), 20674 /* increment loop counter */ 20675 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 20676 /* jump to loop header if callback returned 0 */ 20677 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 20678 /* return value of bpf_loop, 20679 * set R0 to the number of iterations 20680 */ 20681 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 20682 /* restore original values of R6, R7, R8 */ 20683 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 20684 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 20685 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 20686 }; 20687 20688 *cnt = ARRAY_SIZE(insn_buf); 20689 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 20690 if (!new_prog) 20691 return new_prog; 20692 20693 /* callback start is known only after patching */ 20694 callback_start = env->subprog_info[callback_subprogno].start; 20695 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 20696 call_insn_offset = position + 12; 20697 callback_offset = callback_start - call_insn_offset - 1; 20698 new_prog->insnsi[call_insn_offset].imm = callback_offset; 20699 20700 return new_prog; 20701 } 20702 20703 static bool is_bpf_loop_call(struct bpf_insn *insn) 20704 { 20705 return insn->code == (BPF_JMP | BPF_CALL) && 20706 insn->src_reg == 0 && 20707 insn->imm == BPF_FUNC_loop; 20708 } 20709 20710 /* For all sub-programs in the program (including main) check 20711 * insn_aux_data to see if there are bpf_loop calls that require 20712 * inlining. If such calls are found the calls are replaced with a 20713 * sequence of instructions produced by `inline_bpf_loop` function and 20714 * subprog stack_depth is increased by the size of 3 registers. 20715 * This stack space is used to spill values of the R6, R7, R8. These 20716 * registers are used to store the loop bound, counter and context 20717 * variables. 20718 */ 20719 static int optimize_bpf_loop(struct bpf_verifier_env *env) 20720 { 20721 struct bpf_subprog_info *subprogs = env->subprog_info; 20722 int i, cur_subprog = 0, cnt, delta = 0; 20723 struct bpf_insn *insn = env->prog->insnsi; 20724 int insn_cnt = env->prog->len; 20725 u16 stack_depth = subprogs[cur_subprog].stack_depth; 20726 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 20727 u16 stack_depth_extra = 0; 20728 20729 for (i = 0; i < insn_cnt; i++, insn++) { 20730 struct bpf_loop_inline_state *inline_state = 20731 &env->insn_aux_data[i + delta].loop_inline_state; 20732 20733 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 20734 struct bpf_prog *new_prog; 20735 20736 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 20737 new_prog = inline_bpf_loop(env, 20738 i + delta, 20739 -(stack_depth + stack_depth_extra), 20740 inline_state->callback_subprogno, 20741 &cnt); 20742 if (!new_prog) 20743 return -ENOMEM; 20744 20745 delta += cnt - 1; 20746 env->prog = new_prog; 20747 insn = new_prog->insnsi + i + delta; 20748 } 20749 20750 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 20751 subprogs[cur_subprog].stack_depth += stack_depth_extra; 20752 cur_subprog++; 20753 stack_depth = subprogs[cur_subprog].stack_depth; 20754 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 20755 stack_depth_extra = 0; 20756 } 20757 } 20758 20759 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 20760 20761 return 0; 20762 } 20763 20764 static void free_states(struct bpf_verifier_env *env) 20765 { 20766 struct bpf_verifier_state_list *sl, *sln; 20767 int i; 20768 20769 sl = env->free_list; 20770 while (sl) { 20771 sln = sl->next; 20772 free_verifier_state(&sl->state, false); 20773 kfree(sl); 20774 sl = sln; 20775 } 20776 env->free_list = NULL; 20777 20778 if (!env->explored_states) 20779 return; 20780 20781 for (i = 0; i < state_htab_size(env); i++) { 20782 sl = env->explored_states[i]; 20783 20784 while (sl) { 20785 sln = sl->next; 20786 free_verifier_state(&sl->state, false); 20787 kfree(sl); 20788 sl = sln; 20789 } 20790 env->explored_states[i] = NULL; 20791 } 20792 } 20793 20794 static int do_check_common(struct bpf_verifier_env *env, int subprog) 20795 { 20796 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 20797 struct bpf_subprog_info *sub = subprog_info(env, subprog); 20798 struct bpf_verifier_state *state; 20799 struct bpf_reg_state *regs; 20800 int ret, i; 20801 20802 env->prev_linfo = NULL; 20803 env->pass_cnt++; 20804 20805 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 20806 if (!state) 20807 return -ENOMEM; 20808 state->curframe = 0; 20809 state->speculative = false; 20810 state->branches = 1; 20811 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 20812 if (!state->frame[0]) { 20813 kfree(state); 20814 return -ENOMEM; 20815 } 20816 env->cur_state = state; 20817 init_func_state(env, state->frame[0], 20818 BPF_MAIN_FUNC /* callsite */, 20819 0 /* frameno */, 20820 subprog); 20821 state->first_insn_idx = env->subprog_info[subprog].start; 20822 state->last_insn_idx = -1; 20823 20824 regs = state->frame[state->curframe]->regs; 20825 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 20826 const char *sub_name = subprog_name(env, subprog); 20827 struct bpf_subprog_arg_info *arg; 20828 struct bpf_reg_state *reg; 20829 20830 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 20831 ret = btf_prepare_func_args(env, subprog); 20832 if (ret) 20833 goto out; 20834 20835 if (subprog_is_exc_cb(env, subprog)) { 20836 state->frame[0]->in_exception_callback_fn = true; 20837 /* We have already ensured that the callback returns an integer, just 20838 * like all global subprogs. We need to determine it only has a single 20839 * scalar argument. 20840 */ 20841 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 20842 verbose(env, "exception cb only supports single integer argument\n"); 20843 ret = -EINVAL; 20844 goto out; 20845 } 20846 } 20847 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) { 20848 arg = &sub->args[i - BPF_REG_1]; 20849 reg = ®s[i]; 20850 20851 if (arg->arg_type == ARG_PTR_TO_CTX) { 20852 reg->type = PTR_TO_CTX; 20853 mark_reg_known_zero(env, regs, i); 20854 } else if (arg->arg_type == ARG_ANYTHING) { 20855 reg->type = SCALAR_VALUE; 20856 mark_reg_unknown(env, regs, i); 20857 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 20858 /* assume unspecial LOCAL dynptr type */ 20859 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen); 20860 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 20861 reg->type = PTR_TO_MEM; 20862 if (arg->arg_type & PTR_MAYBE_NULL) 20863 reg->type |= PTR_MAYBE_NULL; 20864 mark_reg_known_zero(env, regs, i); 20865 reg->mem_size = arg->mem_size; 20866 reg->id = ++env->id_gen; 20867 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 20868 reg->type = PTR_TO_BTF_ID; 20869 if (arg->arg_type & PTR_MAYBE_NULL) 20870 reg->type |= PTR_MAYBE_NULL; 20871 if (arg->arg_type & PTR_UNTRUSTED) 20872 reg->type |= PTR_UNTRUSTED; 20873 if (arg->arg_type & PTR_TRUSTED) 20874 reg->type |= PTR_TRUSTED; 20875 mark_reg_known_zero(env, regs, i); 20876 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */ 20877 reg->btf_id = arg->btf_id; 20878 reg->id = ++env->id_gen; 20879 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 20880 /* caller can pass either PTR_TO_ARENA or SCALAR */ 20881 mark_reg_unknown(env, regs, i); 20882 } else { 20883 WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n", 20884 i - BPF_REG_1, arg->arg_type); 20885 ret = -EFAULT; 20886 goto out; 20887 } 20888 } 20889 } else { 20890 /* if main BPF program has associated BTF info, validate that 20891 * it's matching expected signature, and otherwise mark BTF 20892 * info for main program as unreliable 20893 */ 20894 if (env->prog->aux->func_info_aux) { 20895 ret = btf_prepare_func_args(env, 0); 20896 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) 20897 env->prog->aux->func_info_aux[0].unreliable = true; 20898 } 20899 20900 /* 1st arg to a function */ 20901 regs[BPF_REG_1].type = PTR_TO_CTX; 20902 mark_reg_known_zero(env, regs, BPF_REG_1); 20903 } 20904 20905 ret = do_check(env); 20906 out: 20907 /* check for NULL is necessary, since cur_state can be freed inside 20908 * do_check() under memory pressure. 20909 */ 20910 if (env->cur_state) { 20911 free_verifier_state(env->cur_state, true); 20912 env->cur_state = NULL; 20913 } 20914 while (!pop_stack(env, NULL, NULL, false)); 20915 if (!ret && pop_log) 20916 bpf_vlog_reset(&env->log, 0); 20917 free_states(env); 20918 return ret; 20919 } 20920 20921 /* Lazily verify all global functions based on their BTF, if they are called 20922 * from main BPF program or any of subprograms transitively. 20923 * BPF global subprogs called from dead code are not validated. 20924 * All callable global functions must pass verification. 20925 * Otherwise the whole program is rejected. 20926 * Consider: 20927 * int bar(int); 20928 * int foo(int f) 20929 * { 20930 * return bar(f); 20931 * } 20932 * int bar(int b) 20933 * { 20934 * ... 20935 * } 20936 * foo() will be verified first for R1=any_scalar_value. During verification it 20937 * will be assumed that bar() already verified successfully and call to bar() 20938 * from foo() will be checked for type match only. Later bar() will be verified 20939 * independently to check that it's safe for R1=any_scalar_value. 20940 */ 20941 static int do_check_subprogs(struct bpf_verifier_env *env) 20942 { 20943 struct bpf_prog_aux *aux = env->prog->aux; 20944 struct bpf_func_info_aux *sub_aux; 20945 int i, ret, new_cnt; 20946 20947 if (!aux->func_info) 20948 return 0; 20949 20950 /* exception callback is presumed to be always called */ 20951 if (env->exception_callback_subprog) 20952 subprog_aux(env, env->exception_callback_subprog)->called = true; 20953 20954 again: 20955 new_cnt = 0; 20956 for (i = 1; i < env->subprog_cnt; i++) { 20957 if (!subprog_is_global(env, i)) 20958 continue; 20959 20960 sub_aux = subprog_aux(env, i); 20961 if (!sub_aux->called || sub_aux->verified) 20962 continue; 20963 20964 env->insn_idx = env->subprog_info[i].start; 20965 WARN_ON_ONCE(env->insn_idx == 0); 20966 ret = do_check_common(env, i); 20967 if (ret) { 20968 return ret; 20969 } else if (env->log.level & BPF_LOG_LEVEL) { 20970 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 20971 i, subprog_name(env, i)); 20972 } 20973 20974 /* We verified new global subprog, it might have called some 20975 * more global subprogs that we haven't verified yet, so we 20976 * need to do another pass over subprogs to verify those. 20977 */ 20978 sub_aux->verified = true; 20979 new_cnt++; 20980 } 20981 20982 /* We can't loop forever as we verify at least one global subprog on 20983 * each pass. 20984 */ 20985 if (new_cnt) 20986 goto again; 20987 20988 return 0; 20989 } 20990 20991 static int do_check_main(struct bpf_verifier_env *env) 20992 { 20993 int ret; 20994 20995 env->insn_idx = 0; 20996 ret = do_check_common(env, 0); 20997 if (!ret) 20998 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 20999 return ret; 21000 } 21001 21002 21003 static void print_verification_stats(struct bpf_verifier_env *env) 21004 { 21005 int i; 21006 21007 if (env->log.level & BPF_LOG_STATS) { 21008 verbose(env, "verification time %lld usec\n", 21009 div_u64(env->verification_time, 1000)); 21010 verbose(env, "stack depth "); 21011 for (i = 0; i < env->subprog_cnt; i++) { 21012 u32 depth = env->subprog_info[i].stack_depth; 21013 21014 verbose(env, "%d", depth); 21015 if (i + 1 < env->subprog_cnt) 21016 verbose(env, "+"); 21017 } 21018 verbose(env, "\n"); 21019 } 21020 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 21021 "total_states %d peak_states %d mark_read %d\n", 21022 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 21023 env->max_states_per_insn, env->total_states, 21024 env->peak_states, env->longest_mark_read_walk); 21025 } 21026 21027 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 21028 { 21029 const struct btf_type *t, *func_proto; 21030 const struct bpf_struct_ops_desc *st_ops_desc; 21031 const struct bpf_struct_ops *st_ops; 21032 const struct btf_member *member; 21033 struct bpf_prog *prog = env->prog; 21034 u32 btf_id, member_idx; 21035 struct btf *btf; 21036 const char *mname; 21037 21038 if (!prog->gpl_compatible) { 21039 verbose(env, "struct ops programs must have a GPL compatible license\n"); 21040 return -EINVAL; 21041 } 21042 21043 if (!prog->aux->attach_btf_id) 21044 return -ENOTSUPP; 21045 21046 btf = prog->aux->attach_btf; 21047 if (btf_is_module(btf)) { 21048 /* Make sure st_ops is valid through the lifetime of env */ 21049 env->attach_btf_mod = btf_try_get_module(btf); 21050 if (!env->attach_btf_mod) { 21051 verbose(env, "struct_ops module %s is not found\n", 21052 btf_get_name(btf)); 21053 return -ENOTSUPP; 21054 } 21055 } 21056 21057 btf_id = prog->aux->attach_btf_id; 21058 st_ops_desc = bpf_struct_ops_find(btf, btf_id); 21059 if (!st_ops_desc) { 21060 verbose(env, "attach_btf_id %u is not a supported struct\n", 21061 btf_id); 21062 return -ENOTSUPP; 21063 } 21064 st_ops = st_ops_desc->st_ops; 21065 21066 t = st_ops_desc->type; 21067 member_idx = prog->expected_attach_type; 21068 if (member_idx >= btf_type_vlen(t)) { 21069 verbose(env, "attach to invalid member idx %u of struct %s\n", 21070 member_idx, st_ops->name); 21071 return -EINVAL; 21072 } 21073 21074 member = &btf_type_member(t)[member_idx]; 21075 mname = btf_name_by_offset(btf, member->name_off); 21076 func_proto = btf_type_resolve_func_ptr(btf, member->type, 21077 NULL); 21078 if (!func_proto) { 21079 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 21080 mname, member_idx, st_ops->name); 21081 return -EINVAL; 21082 } 21083 21084 if (st_ops->check_member) { 21085 int err = st_ops->check_member(t, member, prog); 21086 21087 if (err) { 21088 verbose(env, "attach to unsupported member %s of struct %s\n", 21089 mname, st_ops->name); 21090 return err; 21091 } 21092 } 21093 21094 /* btf_ctx_access() used this to provide argument type info */ 21095 prog->aux->ctx_arg_info = 21096 st_ops_desc->arg_info[member_idx].info; 21097 prog->aux->ctx_arg_info_size = 21098 st_ops_desc->arg_info[member_idx].cnt; 21099 21100 prog->aux->attach_func_proto = func_proto; 21101 prog->aux->attach_func_name = mname; 21102 env->ops = st_ops->verifier_ops; 21103 21104 return 0; 21105 } 21106 #define SECURITY_PREFIX "security_" 21107 21108 static int check_attach_modify_return(unsigned long addr, const char *func_name) 21109 { 21110 if (within_error_injection_list(addr) || 21111 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 21112 return 0; 21113 21114 return -EINVAL; 21115 } 21116 21117 /* list of non-sleepable functions that are otherwise on 21118 * ALLOW_ERROR_INJECTION list 21119 */ 21120 BTF_SET_START(btf_non_sleepable_error_inject) 21121 /* Three functions below can be called from sleepable and non-sleepable context. 21122 * Assume non-sleepable from bpf safety point of view. 21123 */ 21124 BTF_ID(func, __filemap_add_folio) 21125 BTF_ID(func, should_fail_alloc_page) 21126 BTF_ID(func, should_failslab) 21127 BTF_SET_END(btf_non_sleepable_error_inject) 21128 21129 static int check_non_sleepable_error_inject(u32 btf_id) 21130 { 21131 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 21132 } 21133 21134 int bpf_check_attach_target(struct bpf_verifier_log *log, 21135 const struct bpf_prog *prog, 21136 const struct bpf_prog *tgt_prog, 21137 u32 btf_id, 21138 struct bpf_attach_target_info *tgt_info) 21139 { 21140 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 21141 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 21142 const char prefix[] = "btf_trace_"; 21143 int ret = 0, subprog = -1, i; 21144 const struct btf_type *t; 21145 bool conservative = true; 21146 const char *tname; 21147 struct btf *btf; 21148 long addr = 0; 21149 struct module *mod = NULL; 21150 21151 if (!btf_id) { 21152 bpf_log(log, "Tracing programs must provide btf_id\n"); 21153 return -EINVAL; 21154 } 21155 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 21156 if (!btf) { 21157 bpf_log(log, 21158 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 21159 return -EINVAL; 21160 } 21161 t = btf_type_by_id(btf, btf_id); 21162 if (!t) { 21163 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 21164 return -EINVAL; 21165 } 21166 tname = btf_name_by_offset(btf, t->name_off); 21167 if (!tname) { 21168 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 21169 return -EINVAL; 21170 } 21171 if (tgt_prog) { 21172 struct bpf_prog_aux *aux = tgt_prog->aux; 21173 21174 if (bpf_prog_is_dev_bound(prog->aux) && 21175 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 21176 bpf_log(log, "Target program bound device mismatch"); 21177 return -EINVAL; 21178 } 21179 21180 for (i = 0; i < aux->func_info_cnt; i++) 21181 if (aux->func_info[i].type_id == btf_id) { 21182 subprog = i; 21183 break; 21184 } 21185 if (subprog == -1) { 21186 bpf_log(log, "Subprog %s doesn't exist\n", tname); 21187 return -EINVAL; 21188 } 21189 if (aux->func && aux->func[subprog]->aux->exception_cb) { 21190 bpf_log(log, 21191 "%s programs cannot attach to exception callback\n", 21192 prog_extension ? "Extension" : "FENTRY/FEXIT"); 21193 return -EINVAL; 21194 } 21195 conservative = aux->func_info_aux[subprog].unreliable; 21196 if (prog_extension) { 21197 if (conservative) { 21198 bpf_log(log, 21199 "Cannot replace static functions\n"); 21200 return -EINVAL; 21201 } 21202 if (!prog->jit_requested) { 21203 bpf_log(log, 21204 "Extension programs should be JITed\n"); 21205 return -EINVAL; 21206 } 21207 } 21208 if (!tgt_prog->jited) { 21209 bpf_log(log, "Can attach to only JITed progs\n"); 21210 return -EINVAL; 21211 } 21212 if (prog_tracing) { 21213 if (aux->attach_tracing_prog) { 21214 /* 21215 * Target program is an fentry/fexit which is already attached 21216 * to another tracing program. More levels of nesting 21217 * attachment are not allowed. 21218 */ 21219 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 21220 return -EINVAL; 21221 } 21222 } else if (tgt_prog->type == prog->type) { 21223 /* 21224 * To avoid potential call chain cycles, prevent attaching of a 21225 * program extension to another extension. It's ok to attach 21226 * fentry/fexit to extension program. 21227 */ 21228 bpf_log(log, "Cannot recursively attach\n"); 21229 return -EINVAL; 21230 } 21231 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 21232 prog_extension && 21233 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 21234 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 21235 /* Program extensions can extend all program types 21236 * except fentry/fexit. The reason is the following. 21237 * The fentry/fexit programs are used for performance 21238 * analysis, stats and can be attached to any program 21239 * type. When extension program is replacing XDP function 21240 * it is necessary to allow performance analysis of all 21241 * functions. Both original XDP program and its program 21242 * extension. Hence attaching fentry/fexit to 21243 * BPF_PROG_TYPE_EXT is allowed. If extending of 21244 * fentry/fexit was allowed it would be possible to create 21245 * long call chain fentry->extension->fentry->extension 21246 * beyond reasonable stack size. Hence extending fentry 21247 * is not allowed. 21248 */ 21249 bpf_log(log, "Cannot extend fentry/fexit\n"); 21250 return -EINVAL; 21251 } 21252 } else { 21253 if (prog_extension) { 21254 bpf_log(log, "Cannot replace kernel functions\n"); 21255 return -EINVAL; 21256 } 21257 } 21258 21259 switch (prog->expected_attach_type) { 21260 case BPF_TRACE_RAW_TP: 21261 if (tgt_prog) { 21262 bpf_log(log, 21263 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 21264 return -EINVAL; 21265 } 21266 if (!btf_type_is_typedef(t)) { 21267 bpf_log(log, "attach_btf_id %u is not a typedef\n", 21268 btf_id); 21269 return -EINVAL; 21270 } 21271 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 21272 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 21273 btf_id, tname); 21274 return -EINVAL; 21275 } 21276 tname += sizeof(prefix) - 1; 21277 t = btf_type_by_id(btf, t->type); 21278 if (!btf_type_is_ptr(t)) 21279 /* should never happen in valid vmlinux build */ 21280 return -EINVAL; 21281 t = btf_type_by_id(btf, t->type); 21282 if (!btf_type_is_func_proto(t)) 21283 /* should never happen in valid vmlinux build */ 21284 return -EINVAL; 21285 21286 break; 21287 case BPF_TRACE_ITER: 21288 if (!btf_type_is_func(t)) { 21289 bpf_log(log, "attach_btf_id %u is not a function\n", 21290 btf_id); 21291 return -EINVAL; 21292 } 21293 t = btf_type_by_id(btf, t->type); 21294 if (!btf_type_is_func_proto(t)) 21295 return -EINVAL; 21296 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 21297 if (ret) 21298 return ret; 21299 break; 21300 default: 21301 if (!prog_extension) 21302 return -EINVAL; 21303 fallthrough; 21304 case BPF_MODIFY_RETURN: 21305 case BPF_LSM_MAC: 21306 case BPF_LSM_CGROUP: 21307 case BPF_TRACE_FENTRY: 21308 case BPF_TRACE_FEXIT: 21309 if (!btf_type_is_func(t)) { 21310 bpf_log(log, "attach_btf_id %u is not a function\n", 21311 btf_id); 21312 return -EINVAL; 21313 } 21314 if (prog_extension && 21315 btf_check_type_match(log, prog, btf, t)) 21316 return -EINVAL; 21317 t = btf_type_by_id(btf, t->type); 21318 if (!btf_type_is_func_proto(t)) 21319 return -EINVAL; 21320 21321 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 21322 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 21323 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 21324 return -EINVAL; 21325 21326 if (tgt_prog && conservative) 21327 t = NULL; 21328 21329 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 21330 if (ret < 0) 21331 return ret; 21332 21333 if (tgt_prog) { 21334 if (subprog == 0) 21335 addr = (long) tgt_prog->bpf_func; 21336 else 21337 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 21338 } else { 21339 if (btf_is_module(btf)) { 21340 mod = btf_try_get_module(btf); 21341 if (mod) 21342 addr = find_kallsyms_symbol_value(mod, tname); 21343 else 21344 addr = 0; 21345 } else { 21346 addr = kallsyms_lookup_name(tname); 21347 } 21348 if (!addr) { 21349 module_put(mod); 21350 bpf_log(log, 21351 "The address of function %s cannot be found\n", 21352 tname); 21353 return -ENOENT; 21354 } 21355 } 21356 21357 if (prog->sleepable) { 21358 ret = -EINVAL; 21359 switch (prog->type) { 21360 case BPF_PROG_TYPE_TRACING: 21361 21362 /* fentry/fexit/fmod_ret progs can be sleepable if they are 21363 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 21364 */ 21365 if (!check_non_sleepable_error_inject(btf_id) && 21366 within_error_injection_list(addr)) 21367 ret = 0; 21368 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 21369 * in the fmodret id set with the KF_SLEEPABLE flag. 21370 */ 21371 else { 21372 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 21373 prog); 21374 21375 if (flags && (*flags & KF_SLEEPABLE)) 21376 ret = 0; 21377 } 21378 break; 21379 case BPF_PROG_TYPE_LSM: 21380 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 21381 * Only some of them are sleepable. 21382 */ 21383 if (bpf_lsm_is_sleepable_hook(btf_id)) 21384 ret = 0; 21385 break; 21386 default: 21387 break; 21388 } 21389 if (ret) { 21390 module_put(mod); 21391 bpf_log(log, "%s is not sleepable\n", tname); 21392 return ret; 21393 } 21394 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 21395 if (tgt_prog) { 21396 module_put(mod); 21397 bpf_log(log, "can't modify return codes of BPF programs\n"); 21398 return -EINVAL; 21399 } 21400 ret = -EINVAL; 21401 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 21402 !check_attach_modify_return(addr, tname)) 21403 ret = 0; 21404 if (ret) { 21405 module_put(mod); 21406 bpf_log(log, "%s() is not modifiable\n", tname); 21407 return ret; 21408 } 21409 } 21410 21411 break; 21412 } 21413 tgt_info->tgt_addr = addr; 21414 tgt_info->tgt_name = tname; 21415 tgt_info->tgt_type = t; 21416 tgt_info->tgt_mod = mod; 21417 return 0; 21418 } 21419 21420 BTF_SET_START(btf_id_deny) 21421 BTF_ID_UNUSED 21422 #ifdef CONFIG_SMP 21423 BTF_ID(func, migrate_disable) 21424 BTF_ID(func, migrate_enable) 21425 #endif 21426 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 21427 BTF_ID(func, rcu_read_unlock_strict) 21428 #endif 21429 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 21430 BTF_ID(func, preempt_count_add) 21431 BTF_ID(func, preempt_count_sub) 21432 #endif 21433 #ifdef CONFIG_PREEMPT_RCU 21434 BTF_ID(func, __rcu_read_lock) 21435 BTF_ID(func, __rcu_read_unlock) 21436 #endif 21437 BTF_SET_END(btf_id_deny) 21438 21439 static bool can_be_sleepable(struct bpf_prog *prog) 21440 { 21441 if (prog->type == BPF_PROG_TYPE_TRACING) { 21442 switch (prog->expected_attach_type) { 21443 case BPF_TRACE_FENTRY: 21444 case BPF_TRACE_FEXIT: 21445 case BPF_MODIFY_RETURN: 21446 case BPF_TRACE_ITER: 21447 return true; 21448 default: 21449 return false; 21450 } 21451 } 21452 return prog->type == BPF_PROG_TYPE_LSM || 21453 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 21454 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 21455 } 21456 21457 static int check_attach_btf_id(struct bpf_verifier_env *env) 21458 { 21459 struct bpf_prog *prog = env->prog; 21460 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 21461 struct bpf_attach_target_info tgt_info = {}; 21462 u32 btf_id = prog->aux->attach_btf_id; 21463 struct bpf_trampoline *tr; 21464 int ret; 21465 u64 key; 21466 21467 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 21468 if (prog->sleepable) 21469 /* attach_btf_id checked to be zero already */ 21470 return 0; 21471 verbose(env, "Syscall programs can only be sleepable\n"); 21472 return -EINVAL; 21473 } 21474 21475 if (prog->sleepable && !can_be_sleepable(prog)) { 21476 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 21477 return -EINVAL; 21478 } 21479 21480 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 21481 return check_struct_ops_btf_id(env); 21482 21483 if (prog->type != BPF_PROG_TYPE_TRACING && 21484 prog->type != BPF_PROG_TYPE_LSM && 21485 prog->type != BPF_PROG_TYPE_EXT) 21486 return 0; 21487 21488 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 21489 if (ret) 21490 return ret; 21491 21492 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 21493 /* to make freplace equivalent to their targets, they need to 21494 * inherit env->ops and expected_attach_type for the rest of the 21495 * verification 21496 */ 21497 env->ops = bpf_verifier_ops[tgt_prog->type]; 21498 prog->expected_attach_type = tgt_prog->expected_attach_type; 21499 } 21500 21501 /* store info about the attachment target that will be used later */ 21502 prog->aux->attach_func_proto = tgt_info.tgt_type; 21503 prog->aux->attach_func_name = tgt_info.tgt_name; 21504 prog->aux->mod = tgt_info.tgt_mod; 21505 21506 if (tgt_prog) { 21507 prog->aux->saved_dst_prog_type = tgt_prog->type; 21508 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 21509 } 21510 21511 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 21512 prog->aux->attach_btf_trace = true; 21513 return 0; 21514 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 21515 if (!bpf_iter_prog_supported(prog)) 21516 return -EINVAL; 21517 return 0; 21518 } 21519 21520 if (prog->type == BPF_PROG_TYPE_LSM) { 21521 ret = bpf_lsm_verify_prog(&env->log, prog); 21522 if (ret < 0) 21523 return ret; 21524 } else if (prog->type == BPF_PROG_TYPE_TRACING && 21525 btf_id_set_contains(&btf_id_deny, btf_id)) { 21526 return -EINVAL; 21527 } 21528 21529 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 21530 tr = bpf_trampoline_get(key, &tgt_info); 21531 if (!tr) 21532 return -ENOMEM; 21533 21534 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 21535 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 21536 21537 prog->aux->dst_trampoline = tr; 21538 return 0; 21539 } 21540 21541 struct btf *bpf_get_btf_vmlinux(void) 21542 { 21543 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 21544 mutex_lock(&bpf_verifier_lock); 21545 if (!btf_vmlinux) 21546 btf_vmlinux = btf_parse_vmlinux(); 21547 mutex_unlock(&bpf_verifier_lock); 21548 } 21549 return btf_vmlinux; 21550 } 21551 21552 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 21553 { 21554 u64 start_time = ktime_get_ns(); 21555 struct bpf_verifier_env *env; 21556 int i, len, ret = -EINVAL, err; 21557 u32 log_true_size; 21558 bool is_priv; 21559 21560 /* no program is valid */ 21561 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 21562 return -EINVAL; 21563 21564 /* 'struct bpf_verifier_env' can be global, but since it's not small, 21565 * allocate/free it every time bpf_check() is called 21566 */ 21567 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 21568 if (!env) 21569 return -ENOMEM; 21570 21571 env->bt.env = env; 21572 21573 len = (*prog)->len; 21574 env->insn_aux_data = 21575 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 21576 ret = -ENOMEM; 21577 if (!env->insn_aux_data) 21578 goto err_free_env; 21579 for (i = 0; i < len; i++) 21580 env->insn_aux_data[i].orig_idx = i; 21581 env->prog = *prog; 21582 env->ops = bpf_verifier_ops[env->prog->type]; 21583 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 21584 21585 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 21586 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 21587 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 21588 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 21589 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 21590 21591 bpf_get_btf_vmlinux(); 21592 21593 /* grab the mutex to protect few globals used by verifier */ 21594 if (!is_priv) 21595 mutex_lock(&bpf_verifier_lock); 21596 21597 /* user could have requested verbose verifier output 21598 * and supplied buffer to store the verification trace 21599 */ 21600 ret = bpf_vlog_init(&env->log, attr->log_level, 21601 (char __user *) (unsigned long) attr->log_buf, 21602 attr->log_size); 21603 if (ret) 21604 goto err_unlock; 21605 21606 mark_verifier_state_clean(env); 21607 21608 if (IS_ERR(btf_vmlinux)) { 21609 /* Either gcc or pahole or kernel are broken. */ 21610 verbose(env, "in-kernel BTF is malformed\n"); 21611 ret = PTR_ERR(btf_vmlinux); 21612 goto skip_full_check; 21613 } 21614 21615 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 21616 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 21617 env->strict_alignment = true; 21618 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 21619 env->strict_alignment = false; 21620 21621 if (is_priv) 21622 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 21623 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 21624 21625 env->explored_states = kvcalloc(state_htab_size(env), 21626 sizeof(struct bpf_verifier_state_list *), 21627 GFP_USER); 21628 ret = -ENOMEM; 21629 if (!env->explored_states) 21630 goto skip_full_check; 21631 21632 ret = check_btf_info_early(env, attr, uattr); 21633 if (ret < 0) 21634 goto skip_full_check; 21635 21636 ret = add_subprog_and_kfunc(env); 21637 if (ret < 0) 21638 goto skip_full_check; 21639 21640 ret = check_subprogs(env); 21641 if (ret < 0) 21642 goto skip_full_check; 21643 21644 ret = check_btf_info(env, attr, uattr); 21645 if (ret < 0) 21646 goto skip_full_check; 21647 21648 ret = check_attach_btf_id(env); 21649 if (ret) 21650 goto skip_full_check; 21651 21652 ret = resolve_pseudo_ldimm64(env); 21653 if (ret < 0) 21654 goto skip_full_check; 21655 21656 if (bpf_prog_is_offloaded(env->prog->aux)) { 21657 ret = bpf_prog_offload_verifier_prep(env->prog); 21658 if (ret) 21659 goto skip_full_check; 21660 } 21661 21662 ret = check_cfg(env); 21663 if (ret < 0) 21664 goto skip_full_check; 21665 21666 ret = do_check_main(env); 21667 ret = ret ?: do_check_subprogs(env); 21668 21669 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 21670 ret = bpf_prog_offload_finalize(env); 21671 21672 skip_full_check: 21673 kvfree(env->explored_states); 21674 21675 if (ret == 0) 21676 ret = check_max_stack_depth(env); 21677 21678 /* instruction rewrites happen after this point */ 21679 if (ret == 0) 21680 ret = optimize_bpf_loop(env); 21681 21682 if (is_priv) { 21683 if (ret == 0) 21684 opt_hard_wire_dead_code_branches(env); 21685 if (ret == 0) 21686 ret = opt_remove_dead_code(env); 21687 if (ret == 0) 21688 ret = opt_remove_nops(env); 21689 } else { 21690 if (ret == 0) 21691 sanitize_dead_code(env); 21692 } 21693 21694 if (ret == 0) 21695 /* program is valid, convert *(u32*)(ctx + off) accesses */ 21696 ret = convert_ctx_accesses(env); 21697 21698 if (ret == 0) 21699 ret = do_misc_fixups(env); 21700 21701 /* do 32-bit optimization after insn patching has done so those patched 21702 * insns could be handled correctly. 21703 */ 21704 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 21705 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 21706 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 21707 : false; 21708 } 21709 21710 if (ret == 0) 21711 ret = fixup_call_args(env); 21712 21713 env->verification_time = ktime_get_ns() - start_time; 21714 print_verification_stats(env); 21715 env->prog->aux->verified_insns = env->insn_processed; 21716 21717 /* preserve original error even if log finalization is successful */ 21718 err = bpf_vlog_finalize(&env->log, &log_true_size); 21719 if (err) 21720 ret = err; 21721 21722 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 21723 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 21724 &log_true_size, sizeof(log_true_size))) { 21725 ret = -EFAULT; 21726 goto err_release_maps; 21727 } 21728 21729 if (ret) 21730 goto err_release_maps; 21731 21732 if (env->used_map_cnt) { 21733 /* if program passed verifier, update used_maps in bpf_prog_info */ 21734 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 21735 sizeof(env->used_maps[0]), 21736 GFP_KERNEL); 21737 21738 if (!env->prog->aux->used_maps) { 21739 ret = -ENOMEM; 21740 goto err_release_maps; 21741 } 21742 21743 memcpy(env->prog->aux->used_maps, env->used_maps, 21744 sizeof(env->used_maps[0]) * env->used_map_cnt); 21745 env->prog->aux->used_map_cnt = env->used_map_cnt; 21746 } 21747 if (env->used_btf_cnt) { 21748 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 21749 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 21750 sizeof(env->used_btfs[0]), 21751 GFP_KERNEL); 21752 if (!env->prog->aux->used_btfs) { 21753 ret = -ENOMEM; 21754 goto err_release_maps; 21755 } 21756 21757 memcpy(env->prog->aux->used_btfs, env->used_btfs, 21758 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 21759 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 21760 } 21761 if (env->used_map_cnt || env->used_btf_cnt) { 21762 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 21763 * bpf_ld_imm64 instructions 21764 */ 21765 convert_pseudo_ld_imm64(env); 21766 } 21767 21768 adjust_btf_func(env); 21769 21770 err_release_maps: 21771 if (!env->prog->aux->used_maps) 21772 /* if we didn't copy map pointers into bpf_prog_info, release 21773 * them now. Otherwise free_used_maps() will release them. 21774 */ 21775 release_maps(env); 21776 if (!env->prog->aux->used_btfs) 21777 release_btfs(env); 21778 21779 /* extension progs temporarily inherit the attach_type of their targets 21780 for verification purposes, so set it back to zero before returning 21781 */ 21782 if (env->prog->type == BPF_PROG_TYPE_EXT) 21783 env->prog->expected_attach_type = 0; 21784 21785 *prog = env->prog; 21786 21787 module_put(env->attach_btf_mod); 21788 err_unlock: 21789 if (!is_priv) 21790 mutex_unlock(&bpf_verifier_lock); 21791 vfree(env->insn_aux_data); 21792 err_free_env: 21793 kfree(env); 21794 return ret; 21795 } 21796