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 /* verifer 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_MAP_PTR_UNPRIV 1UL 194 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \ 195 POISON_POINTER_DELTA)) 196 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV)) 197 198 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE 512 199 200 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx); 201 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id); 202 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 203 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 204 static int ref_set_non_owning(struct bpf_verifier_env *env, 205 struct bpf_reg_state *reg); 206 static void specialize_kfunc(struct bpf_verifier_env *env, 207 u32 func_id, u16 offset, unsigned long *addr); 208 static bool is_trusted_reg(const struct bpf_reg_state *reg); 209 210 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 211 { 212 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON; 213 } 214 215 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 216 { 217 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV; 218 } 219 220 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 221 const struct bpf_map *map, bool unpriv) 222 { 223 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV); 224 unpriv |= bpf_map_ptr_unpriv(aux); 225 aux->map_ptr_state = (unsigned long)map | 226 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL); 227 } 228 229 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 230 { 231 return aux->map_key_state & BPF_MAP_KEY_POISON; 232 } 233 234 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 235 { 236 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 237 } 238 239 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 240 { 241 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 242 } 243 244 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 245 { 246 bool poisoned = bpf_map_key_poisoned(aux); 247 248 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 249 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 250 } 251 252 static bool bpf_helper_call(const struct bpf_insn *insn) 253 { 254 return insn->code == (BPF_JMP | BPF_CALL) && 255 insn->src_reg == 0; 256 } 257 258 static bool bpf_pseudo_call(const struct bpf_insn *insn) 259 { 260 return insn->code == (BPF_JMP | BPF_CALL) && 261 insn->src_reg == BPF_PSEUDO_CALL; 262 } 263 264 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 265 { 266 return insn->code == (BPF_JMP | BPF_CALL) && 267 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 268 } 269 270 struct bpf_call_arg_meta { 271 struct bpf_map *map_ptr; 272 bool raw_mode; 273 bool pkt_access; 274 u8 release_regno; 275 int regno; 276 int access_size; 277 int mem_size; 278 u64 msize_max_value; 279 int ref_obj_id; 280 int dynptr_id; 281 int map_uid; 282 int func_id; 283 struct btf *btf; 284 u32 btf_id; 285 struct btf *ret_btf; 286 u32 ret_btf_id; 287 u32 subprogno; 288 struct btf_field *kptr_field; 289 }; 290 291 struct bpf_kfunc_call_arg_meta { 292 /* In parameters */ 293 struct btf *btf; 294 u32 func_id; 295 u32 kfunc_flags; 296 const struct btf_type *func_proto; 297 const char *func_name; 298 /* Out parameters */ 299 u32 ref_obj_id; 300 u8 release_regno; 301 bool r0_rdonly; 302 u32 ret_btf_id; 303 u64 r0_size; 304 u32 subprogno; 305 struct { 306 u64 value; 307 bool found; 308 } arg_constant; 309 310 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling, 311 * generally to pass info about user-defined local kptr types to later 312 * verification logic 313 * bpf_obj_drop/bpf_percpu_obj_drop 314 * Record the local kptr type to be drop'd 315 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type) 316 * Record the local kptr type to be refcount_incr'd and use 317 * arg_owning_ref to determine whether refcount_acquire should be 318 * fallible 319 */ 320 struct btf *arg_btf; 321 u32 arg_btf_id; 322 bool arg_owning_ref; 323 324 struct { 325 struct btf_field *field; 326 } arg_list_head; 327 struct { 328 struct btf_field *field; 329 } arg_rbtree_root; 330 struct { 331 enum bpf_dynptr_type type; 332 u32 id; 333 u32 ref_obj_id; 334 } initialized_dynptr; 335 struct { 336 u8 spi; 337 u8 frameno; 338 } iter; 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_bpf_throw_kfunc(struct bpf_insn *insn); 505 506 static bool is_sync_callback_calling_function(enum bpf_func_id func_id) 507 { 508 return func_id == BPF_FUNC_for_each_map_elem || 509 func_id == BPF_FUNC_find_vma || 510 func_id == BPF_FUNC_loop || 511 func_id == BPF_FUNC_user_ringbuf_drain; 512 } 513 514 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 515 { 516 return func_id == BPF_FUNC_timer_set_callback; 517 } 518 519 static bool is_callback_calling_function(enum bpf_func_id func_id) 520 { 521 return is_sync_callback_calling_function(func_id) || 522 is_async_callback_calling_function(func_id); 523 } 524 525 static bool is_sync_callback_calling_insn(struct bpf_insn *insn) 526 { 527 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) || 528 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm)); 529 } 530 531 static bool is_storage_get_function(enum bpf_func_id func_id) 532 { 533 return func_id == BPF_FUNC_sk_storage_get || 534 func_id == BPF_FUNC_inode_storage_get || 535 func_id == BPF_FUNC_task_storage_get || 536 func_id == BPF_FUNC_cgrp_storage_get; 537 } 538 539 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 540 const struct bpf_map *map) 541 { 542 int ref_obj_uses = 0; 543 544 if (is_ptr_cast_function(func_id)) 545 ref_obj_uses++; 546 if (is_acquire_function(func_id, map)) 547 ref_obj_uses++; 548 if (is_dynptr_ref_function(func_id)) 549 ref_obj_uses++; 550 551 return ref_obj_uses > 1; 552 } 553 554 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 555 { 556 return BPF_CLASS(insn->code) == BPF_STX && 557 BPF_MODE(insn->code) == BPF_ATOMIC && 558 insn->imm == BPF_CMPXCHG; 559 } 560 561 static int __get_spi(s32 off) 562 { 563 return (-off - 1) / BPF_REG_SIZE; 564 } 565 566 static struct bpf_func_state *func(struct bpf_verifier_env *env, 567 const struct bpf_reg_state *reg) 568 { 569 struct bpf_verifier_state *cur = env->cur_state; 570 571 return cur->frame[reg->frameno]; 572 } 573 574 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 575 { 576 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 577 578 /* We need to check that slots between [spi - nr_slots + 1, spi] are 579 * within [0, allocated_stack). 580 * 581 * Please note that the spi grows downwards. For example, a dynptr 582 * takes the size of two stack slots; the first slot will be at 583 * spi and the second slot will be at spi - 1. 584 */ 585 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 586 } 587 588 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 589 const char *obj_kind, int nr_slots) 590 { 591 int off, spi; 592 593 if (!tnum_is_const(reg->var_off)) { 594 verbose(env, "%s has to be at a constant offset\n", obj_kind); 595 return -EINVAL; 596 } 597 598 off = reg->off + reg->var_off.value; 599 if (off % BPF_REG_SIZE) { 600 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 601 return -EINVAL; 602 } 603 604 spi = __get_spi(off); 605 if (spi + 1 < nr_slots) { 606 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 607 return -EINVAL; 608 } 609 610 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots)) 611 return -ERANGE; 612 return spi; 613 } 614 615 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 616 { 617 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 618 } 619 620 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 621 { 622 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 623 } 624 625 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 626 { 627 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 628 case DYNPTR_TYPE_LOCAL: 629 return BPF_DYNPTR_TYPE_LOCAL; 630 case DYNPTR_TYPE_RINGBUF: 631 return BPF_DYNPTR_TYPE_RINGBUF; 632 case DYNPTR_TYPE_SKB: 633 return BPF_DYNPTR_TYPE_SKB; 634 case DYNPTR_TYPE_XDP: 635 return BPF_DYNPTR_TYPE_XDP; 636 default: 637 return BPF_DYNPTR_TYPE_INVALID; 638 } 639 } 640 641 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 642 { 643 switch (type) { 644 case BPF_DYNPTR_TYPE_LOCAL: 645 return DYNPTR_TYPE_LOCAL; 646 case BPF_DYNPTR_TYPE_RINGBUF: 647 return DYNPTR_TYPE_RINGBUF; 648 case BPF_DYNPTR_TYPE_SKB: 649 return DYNPTR_TYPE_SKB; 650 case BPF_DYNPTR_TYPE_XDP: 651 return DYNPTR_TYPE_XDP; 652 default: 653 return 0; 654 } 655 } 656 657 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 658 { 659 return type == BPF_DYNPTR_TYPE_RINGBUF; 660 } 661 662 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 663 enum bpf_dynptr_type type, 664 bool first_slot, int dynptr_id); 665 666 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 667 struct bpf_reg_state *reg); 668 669 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 670 struct bpf_reg_state *sreg1, 671 struct bpf_reg_state *sreg2, 672 enum bpf_dynptr_type type) 673 { 674 int id = ++env->id_gen; 675 676 __mark_dynptr_reg(sreg1, type, true, id); 677 __mark_dynptr_reg(sreg2, type, false, id); 678 } 679 680 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 681 struct bpf_reg_state *reg, 682 enum bpf_dynptr_type type) 683 { 684 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 685 } 686 687 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 688 struct bpf_func_state *state, int spi); 689 690 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 691 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id) 692 { 693 struct bpf_func_state *state = func(env, reg); 694 enum bpf_dynptr_type type; 695 int spi, i, err; 696 697 spi = dynptr_get_spi(env, reg); 698 if (spi < 0) 699 return spi; 700 701 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 702 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 703 * to ensure that for the following example: 704 * [d1][d1][d2][d2] 705 * spi 3 2 1 0 706 * So marking spi = 2 should lead to destruction of both d1 and d2. In 707 * case they do belong to same dynptr, second call won't see slot_type 708 * as STACK_DYNPTR and will simply skip destruction. 709 */ 710 err = destroy_if_dynptr_stack_slot(env, state, spi); 711 if (err) 712 return err; 713 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 714 if (err) 715 return err; 716 717 for (i = 0; i < BPF_REG_SIZE; i++) { 718 state->stack[spi].slot_type[i] = STACK_DYNPTR; 719 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 720 } 721 722 type = arg_to_dynptr_type(arg_type); 723 if (type == BPF_DYNPTR_TYPE_INVALID) 724 return -EINVAL; 725 726 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 727 &state->stack[spi - 1].spilled_ptr, type); 728 729 if (dynptr_type_refcounted(type)) { 730 /* The id is used to track proper releasing */ 731 int id; 732 733 if (clone_ref_obj_id) 734 id = clone_ref_obj_id; 735 else 736 id = acquire_reference_state(env, insn_idx); 737 738 if (id < 0) 739 return id; 740 741 state->stack[spi].spilled_ptr.ref_obj_id = id; 742 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 743 } 744 745 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 746 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 747 748 return 0; 749 } 750 751 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi) 752 { 753 int i; 754 755 for (i = 0; i < BPF_REG_SIZE; i++) { 756 state->stack[spi].slot_type[i] = STACK_INVALID; 757 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 758 } 759 760 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 761 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 762 763 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot? 764 * 765 * While we don't allow reading STACK_INVALID, it is still possible to 766 * do <8 byte writes marking some but not all slots as STACK_MISC. Then, 767 * helpers or insns can do partial read of that part without failing, 768 * but check_stack_range_initialized, check_stack_read_var_off, and 769 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of 770 * the slot conservatively. Hence we need to prevent those liveness 771 * marking walks. 772 * 773 * This was not a problem before because STACK_INVALID is only set by 774 * default (where the default reg state has its reg->parent as NULL), or 775 * in clean_live_states after REG_LIVE_DONE (at which point 776 * mark_reg_read won't walk reg->parent chain), but not randomly during 777 * verifier state exploration (like we did above). Hence, for our case 778 * parentage chain will still be live (i.e. reg->parent may be 779 * non-NULL), while earlier reg->parent was NULL, so we need 780 * REG_LIVE_WRITTEN to screen off read marker propagation when it is 781 * done later on reads or by mark_dynptr_read as well to unnecessary 782 * mark registers in verifier state. 783 */ 784 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 785 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 786 } 787 788 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 789 { 790 struct bpf_func_state *state = func(env, reg); 791 int spi, ref_obj_id, i; 792 793 spi = dynptr_get_spi(env, reg); 794 if (spi < 0) 795 return spi; 796 797 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 798 invalidate_dynptr(env, state, spi); 799 return 0; 800 } 801 802 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 803 804 /* If the dynptr has a ref_obj_id, then we need to invalidate 805 * two things: 806 * 807 * 1) Any dynptrs with a matching ref_obj_id (clones) 808 * 2) Any slices derived from this dynptr. 809 */ 810 811 /* Invalidate any slices associated with this dynptr */ 812 WARN_ON_ONCE(release_reference(env, ref_obj_id)); 813 814 /* Invalidate any dynptr clones */ 815 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) { 816 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id) 817 continue; 818 819 /* it should always be the case that if the ref obj id 820 * matches then the stack slot also belongs to a 821 * dynptr 822 */ 823 if (state->stack[i].slot_type[0] != STACK_DYNPTR) { 824 verbose(env, "verifier internal error: misconfigured ref_obj_id\n"); 825 return -EFAULT; 826 } 827 if (state->stack[i].spilled_ptr.dynptr.first_slot) 828 invalidate_dynptr(env, state, i); 829 } 830 831 return 0; 832 } 833 834 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 835 struct bpf_reg_state *reg); 836 837 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 838 { 839 if (!env->allow_ptr_leaks) 840 __mark_reg_not_init(env, reg); 841 else 842 __mark_reg_unknown(env, reg); 843 } 844 845 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 846 struct bpf_func_state *state, int spi) 847 { 848 struct bpf_func_state *fstate; 849 struct bpf_reg_state *dreg; 850 int i, dynptr_id; 851 852 /* We always ensure that STACK_DYNPTR is never set partially, 853 * hence just checking for slot_type[0] is enough. This is 854 * different for STACK_SPILL, where it may be only set for 855 * 1 byte, so code has to use is_spilled_reg. 856 */ 857 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 858 return 0; 859 860 /* Reposition spi to first slot */ 861 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 862 spi = spi + 1; 863 864 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 865 verbose(env, "cannot overwrite referenced dynptr\n"); 866 return -EINVAL; 867 } 868 869 mark_stack_slot_scratched(env, spi); 870 mark_stack_slot_scratched(env, spi - 1); 871 872 /* Writing partially to one dynptr stack slot destroys both. */ 873 for (i = 0; i < BPF_REG_SIZE; i++) { 874 state->stack[spi].slot_type[i] = STACK_INVALID; 875 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 876 } 877 878 dynptr_id = state->stack[spi].spilled_ptr.id; 879 /* Invalidate any slices associated with this dynptr */ 880 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 881 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 882 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 883 continue; 884 if (dreg->dynptr_id == dynptr_id) 885 mark_reg_invalid(env, dreg); 886 })); 887 888 /* Do not release reference state, we are destroying dynptr on stack, 889 * not using some helper to release it. Just reset register. 890 */ 891 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 892 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 893 894 /* Same reason as unmark_stack_slots_dynptr above */ 895 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 896 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 897 898 return 0; 899 } 900 901 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 902 { 903 int spi; 904 905 if (reg->type == CONST_PTR_TO_DYNPTR) 906 return false; 907 908 spi = dynptr_get_spi(env, reg); 909 910 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 911 * error because this just means the stack state hasn't been updated yet. 912 * We will do check_mem_access to check and update stack bounds later. 913 */ 914 if (spi < 0 && spi != -ERANGE) 915 return false; 916 917 /* We don't need to check if the stack slots are marked by previous 918 * dynptr initializations because we allow overwriting existing unreferenced 919 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 920 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 921 * touching are completely destructed before we reinitialize them for a new 922 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 923 * instead of delaying it until the end where the user will get "Unreleased 924 * reference" error. 925 */ 926 return true; 927 } 928 929 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 930 { 931 struct bpf_func_state *state = func(env, reg); 932 int i, spi; 933 934 /* This already represents first slot of initialized bpf_dynptr. 935 * 936 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 937 * check_func_arg_reg_off's logic, so we don't need to check its 938 * offset and alignment. 939 */ 940 if (reg->type == CONST_PTR_TO_DYNPTR) 941 return true; 942 943 spi = dynptr_get_spi(env, reg); 944 if (spi < 0) 945 return false; 946 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 947 return false; 948 949 for (i = 0; i < BPF_REG_SIZE; i++) { 950 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 951 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 952 return false; 953 } 954 955 return true; 956 } 957 958 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 959 enum bpf_arg_type arg_type) 960 { 961 struct bpf_func_state *state = func(env, reg); 962 enum bpf_dynptr_type dynptr_type; 963 int spi; 964 965 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 966 if (arg_type == ARG_PTR_TO_DYNPTR) 967 return true; 968 969 dynptr_type = arg_to_dynptr_type(arg_type); 970 if (reg->type == CONST_PTR_TO_DYNPTR) { 971 return reg->dynptr.type == dynptr_type; 972 } else { 973 spi = dynptr_get_spi(env, reg); 974 if (spi < 0) 975 return false; 976 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 977 } 978 } 979 980 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 981 982 static bool in_rcu_cs(struct bpf_verifier_env *env); 983 984 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta); 985 986 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 987 struct bpf_kfunc_call_arg_meta *meta, 988 struct bpf_reg_state *reg, int insn_idx, 989 struct btf *btf, u32 btf_id, int nr_slots) 990 { 991 struct bpf_func_state *state = func(env, reg); 992 int spi, i, j, id; 993 994 spi = iter_get_spi(env, reg, nr_slots); 995 if (spi < 0) 996 return spi; 997 998 id = acquire_reference_state(env, insn_idx); 999 if (id < 0) 1000 return id; 1001 1002 for (i = 0; i < nr_slots; i++) { 1003 struct bpf_stack_state *slot = &state->stack[spi - i]; 1004 struct bpf_reg_state *st = &slot->spilled_ptr; 1005 1006 __mark_reg_known_zero(st); 1007 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1008 if (is_kfunc_rcu_protected(meta)) { 1009 if (in_rcu_cs(env)) 1010 st->type |= MEM_RCU; 1011 else 1012 st->type |= PTR_UNTRUSTED; 1013 } 1014 st->live |= REG_LIVE_WRITTEN; 1015 st->ref_obj_id = i == 0 ? id : 0; 1016 st->iter.btf = btf; 1017 st->iter.btf_id = btf_id; 1018 st->iter.state = BPF_ITER_STATE_ACTIVE; 1019 st->iter.depth = 0; 1020 1021 for (j = 0; j < BPF_REG_SIZE; j++) 1022 slot->slot_type[j] = STACK_ITER; 1023 1024 mark_stack_slot_scratched(env, spi - i); 1025 } 1026 1027 return 0; 1028 } 1029 1030 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 1031 struct bpf_reg_state *reg, int nr_slots) 1032 { 1033 struct bpf_func_state *state = func(env, reg); 1034 int spi, i, j; 1035 1036 spi = iter_get_spi(env, reg, nr_slots); 1037 if (spi < 0) 1038 return spi; 1039 1040 for (i = 0; i < nr_slots; i++) { 1041 struct bpf_stack_state *slot = &state->stack[spi - i]; 1042 struct bpf_reg_state *st = &slot->spilled_ptr; 1043 1044 if (i == 0) 1045 WARN_ON_ONCE(release_reference(env, st->ref_obj_id)); 1046 1047 __mark_reg_not_init(env, st); 1048 1049 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1050 st->live |= REG_LIVE_WRITTEN; 1051 1052 for (j = 0; j < BPF_REG_SIZE; j++) 1053 slot->slot_type[j] = STACK_INVALID; 1054 1055 mark_stack_slot_scratched(env, spi - i); 1056 } 1057 1058 return 0; 1059 } 1060 1061 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1062 struct bpf_reg_state *reg, int nr_slots) 1063 { 1064 struct bpf_func_state *state = func(env, reg); 1065 int spi, i, j; 1066 1067 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1068 * will do check_mem_access to check and update stack bounds later, so 1069 * return true for that case. 1070 */ 1071 spi = iter_get_spi(env, reg, nr_slots); 1072 if (spi == -ERANGE) 1073 return true; 1074 if (spi < 0) 1075 return false; 1076 1077 for (i = 0; i < nr_slots; i++) { 1078 struct bpf_stack_state *slot = &state->stack[spi - i]; 1079 1080 for (j = 0; j < BPF_REG_SIZE; j++) 1081 if (slot->slot_type[j] == STACK_ITER) 1082 return false; 1083 } 1084 1085 return true; 1086 } 1087 1088 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1089 struct btf *btf, u32 btf_id, int nr_slots) 1090 { 1091 struct bpf_func_state *state = func(env, reg); 1092 int spi, i, j; 1093 1094 spi = iter_get_spi(env, reg, nr_slots); 1095 if (spi < 0) 1096 return -EINVAL; 1097 1098 for (i = 0; i < nr_slots; i++) { 1099 struct bpf_stack_state *slot = &state->stack[spi - i]; 1100 struct bpf_reg_state *st = &slot->spilled_ptr; 1101 1102 if (st->type & PTR_UNTRUSTED) 1103 return -EPROTO; 1104 /* only main (first) slot has ref_obj_id set */ 1105 if (i == 0 && !st->ref_obj_id) 1106 return -EINVAL; 1107 if (i != 0 && st->ref_obj_id) 1108 return -EINVAL; 1109 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1110 return -EINVAL; 1111 1112 for (j = 0; j < BPF_REG_SIZE; j++) 1113 if (slot->slot_type[j] != STACK_ITER) 1114 return -EINVAL; 1115 } 1116 1117 return 0; 1118 } 1119 1120 /* Check if given stack slot is "special": 1121 * - spilled register state (STACK_SPILL); 1122 * - dynptr state (STACK_DYNPTR); 1123 * - iter state (STACK_ITER). 1124 */ 1125 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1126 { 1127 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1128 1129 switch (type) { 1130 case STACK_SPILL: 1131 case STACK_DYNPTR: 1132 case STACK_ITER: 1133 return true; 1134 case STACK_INVALID: 1135 case STACK_MISC: 1136 case STACK_ZERO: 1137 return false; 1138 default: 1139 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1140 return true; 1141 } 1142 } 1143 1144 /* The reg state of a pointer or a bounded scalar was saved when 1145 * it was spilled to the stack. 1146 */ 1147 static bool is_spilled_reg(const struct bpf_stack_state *stack) 1148 { 1149 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1150 } 1151 1152 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack) 1153 { 1154 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL && 1155 stack->spilled_ptr.type == SCALAR_VALUE; 1156 } 1157 1158 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which 1159 * case they are equivalent, or it's STACK_ZERO, in which case we preserve 1160 * more precise STACK_ZERO. 1161 * Note, in uprivileged mode leaving STACK_INVALID is wrong, so we take 1162 * env->allow_ptr_leaks into account and force STACK_MISC, if necessary. 1163 */ 1164 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype) 1165 { 1166 if (*stype == STACK_ZERO) 1167 return; 1168 if (env->allow_ptr_leaks && *stype == STACK_INVALID) 1169 return; 1170 *stype = STACK_MISC; 1171 } 1172 1173 static void scrub_spilled_slot(u8 *stype) 1174 { 1175 if (*stype != STACK_INVALID) 1176 *stype = STACK_MISC; 1177 } 1178 1179 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1180 * small to hold src. This is different from krealloc since we don't want to preserve 1181 * the contents of dst. 1182 * 1183 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1184 * not be allocated. 1185 */ 1186 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1187 { 1188 size_t alloc_bytes; 1189 void *orig = dst; 1190 size_t bytes; 1191 1192 if (ZERO_OR_NULL_PTR(src)) 1193 goto out; 1194 1195 if (unlikely(check_mul_overflow(n, size, &bytes))) 1196 return NULL; 1197 1198 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1199 dst = krealloc(orig, alloc_bytes, flags); 1200 if (!dst) { 1201 kfree(orig); 1202 return NULL; 1203 } 1204 1205 memcpy(dst, src, bytes); 1206 out: 1207 return dst ? dst : ZERO_SIZE_PTR; 1208 } 1209 1210 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1211 * small to hold new_n items. new items are zeroed out if the array grows. 1212 * 1213 * Contrary to krealloc_array, does not free arr if new_n is zero. 1214 */ 1215 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1216 { 1217 size_t alloc_size; 1218 void *new_arr; 1219 1220 if (!new_n || old_n == new_n) 1221 goto out; 1222 1223 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1224 new_arr = krealloc(arr, alloc_size, GFP_KERNEL); 1225 if (!new_arr) { 1226 kfree(arr); 1227 return NULL; 1228 } 1229 arr = new_arr; 1230 1231 if (new_n > old_n) 1232 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1233 1234 out: 1235 return arr ? arr : ZERO_SIZE_PTR; 1236 } 1237 1238 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1239 { 1240 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1241 sizeof(struct bpf_reference_state), GFP_KERNEL); 1242 if (!dst->refs) 1243 return -ENOMEM; 1244 1245 dst->acquired_refs = src->acquired_refs; 1246 return 0; 1247 } 1248 1249 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1250 { 1251 size_t n = src->allocated_stack / BPF_REG_SIZE; 1252 1253 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1254 GFP_KERNEL); 1255 if (!dst->stack) 1256 return -ENOMEM; 1257 1258 dst->allocated_stack = src->allocated_stack; 1259 return 0; 1260 } 1261 1262 static int resize_reference_state(struct bpf_func_state *state, size_t n) 1263 { 1264 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1265 sizeof(struct bpf_reference_state)); 1266 if (!state->refs) 1267 return -ENOMEM; 1268 1269 state->acquired_refs = n; 1270 return 0; 1271 } 1272 1273 /* Possibly update state->allocated_stack to be at least size bytes. Also 1274 * possibly update the function's high-water mark in its bpf_subprog_info. 1275 */ 1276 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) 1277 { 1278 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n; 1279 1280 /* The stack size is always a multiple of BPF_REG_SIZE. */ 1281 size = round_up(size, BPF_REG_SIZE); 1282 n = size / BPF_REG_SIZE; 1283 1284 if (old_n >= n) 1285 return 0; 1286 1287 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1288 if (!state->stack) 1289 return -ENOMEM; 1290 1291 state->allocated_stack = size; 1292 1293 /* update known max for given subprogram */ 1294 if (env->subprog_info[state->subprogno].stack_depth < size) 1295 env->subprog_info[state->subprogno].stack_depth = size; 1296 1297 return 0; 1298 } 1299 1300 /* Acquire a pointer id from the env and update the state->refs to include 1301 * this new pointer reference. 1302 * On success, returns a valid pointer id to associate with the register 1303 * On failure, returns a negative errno. 1304 */ 1305 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1306 { 1307 struct bpf_func_state *state = cur_func(env); 1308 int new_ofs = state->acquired_refs; 1309 int id, err; 1310 1311 err = resize_reference_state(state, state->acquired_refs + 1); 1312 if (err) 1313 return err; 1314 id = ++env->id_gen; 1315 state->refs[new_ofs].id = id; 1316 state->refs[new_ofs].insn_idx = insn_idx; 1317 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0; 1318 1319 return id; 1320 } 1321 1322 /* release function corresponding to acquire_reference_state(). Idempotent. */ 1323 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 1324 { 1325 int i, last_idx; 1326 1327 last_idx = state->acquired_refs - 1; 1328 for (i = 0; i < state->acquired_refs; i++) { 1329 if (state->refs[i].id == ptr_id) { 1330 /* Cannot release caller references in callbacks */ 1331 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 1332 return -EINVAL; 1333 if (last_idx && i != last_idx) 1334 memcpy(&state->refs[i], &state->refs[last_idx], 1335 sizeof(*state->refs)); 1336 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1337 state->acquired_refs--; 1338 return 0; 1339 } 1340 } 1341 return -EINVAL; 1342 } 1343 1344 static void free_func_state(struct bpf_func_state *state) 1345 { 1346 if (!state) 1347 return; 1348 kfree(state->refs); 1349 kfree(state->stack); 1350 kfree(state); 1351 } 1352 1353 static void clear_jmp_history(struct bpf_verifier_state *state) 1354 { 1355 kfree(state->jmp_history); 1356 state->jmp_history = NULL; 1357 state->jmp_history_cnt = 0; 1358 } 1359 1360 static void free_verifier_state(struct bpf_verifier_state *state, 1361 bool free_self) 1362 { 1363 int i; 1364 1365 for (i = 0; i <= state->curframe; i++) { 1366 free_func_state(state->frame[i]); 1367 state->frame[i] = NULL; 1368 } 1369 clear_jmp_history(state); 1370 if (free_self) 1371 kfree(state); 1372 } 1373 1374 /* copy verifier state from src to dst growing dst stack space 1375 * when necessary to accommodate larger src stack 1376 */ 1377 static int copy_func_state(struct bpf_func_state *dst, 1378 const struct bpf_func_state *src) 1379 { 1380 int err; 1381 1382 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 1383 err = copy_reference_state(dst, src); 1384 if (err) 1385 return err; 1386 return copy_stack_state(dst, src); 1387 } 1388 1389 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1390 const struct bpf_verifier_state *src) 1391 { 1392 struct bpf_func_state *dst; 1393 int i, err; 1394 1395 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1396 src->jmp_history_cnt, sizeof(*dst_state->jmp_history), 1397 GFP_USER); 1398 if (!dst_state->jmp_history) 1399 return -ENOMEM; 1400 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1401 1402 /* if dst has more stack frames then src frame, free them, this is also 1403 * necessary in case of exceptional exits using bpf_throw. 1404 */ 1405 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1406 free_func_state(dst_state->frame[i]); 1407 dst_state->frame[i] = NULL; 1408 } 1409 dst_state->speculative = src->speculative; 1410 dst_state->active_rcu_lock = src->active_rcu_lock; 1411 dst_state->curframe = src->curframe; 1412 dst_state->active_lock.ptr = src->active_lock.ptr; 1413 dst_state->active_lock.id = src->active_lock.id; 1414 dst_state->branches = src->branches; 1415 dst_state->parent = src->parent; 1416 dst_state->first_insn_idx = src->first_insn_idx; 1417 dst_state->last_insn_idx = src->last_insn_idx; 1418 dst_state->dfs_depth = src->dfs_depth; 1419 dst_state->callback_unroll_depth = src->callback_unroll_depth; 1420 dst_state->used_as_loop_entry = src->used_as_loop_entry; 1421 for (i = 0; i <= src->curframe; i++) { 1422 dst = dst_state->frame[i]; 1423 if (!dst) { 1424 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1425 if (!dst) 1426 return -ENOMEM; 1427 dst_state->frame[i] = dst; 1428 } 1429 err = copy_func_state(dst, src->frame[i]); 1430 if (err) 1431 return err; 1432 } 1433 return 0; 1434 } 1435 1436 static u32 state_htab_size(struct bpf_verifier_env *env) 1437 { 1438 return env->prog->len; 1439 } 1440 1441 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx) 1442 { 1443 struct bpf_verifier_state *cur = env->cur_state; 1444 struct bpf_func_state *state = cur->frame[cur->curframe]; 1445 1446 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 1447 } 1448 1449 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b) 1450 { 1451 int fr; 1452 1453 if (a->curframe != b->curframe) 1454 return false; 1455 1456 for (fr = a->curframe; fr >= 0; fr--) 1457 if (a->frame[fr]->callsite != b->frame[fr]->callsite) 1458 return false; 1459 1460 return true; 1461 } 1462 1463 /* Open coded iterators allow back-edges in the state graph in order to 1464 * check unbounded loops that iterators. 1465 * 1466 * In is_state_visited() it is necessary to know if explored states are 1467 * part of some loops in order to decide whether non-exact states 1468 * comparison could be used: 1469 * - non-exact states comparison establishes sub-state relation and uses 1470 * read and precision marks to do so, these marks are propagated from 1471 * children states and thus are not guaranteed to be final in a loop; 1472 * - exact states comparison just checks if current and explored states 1473 * are identical (and thus form a back-edge). 1474 * 1475 * Paper "A New Algorithm for Identifying Loops in Decompilation" 1476 * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient 1477 * algorithm for loop structure detection and gives an overview of 1478 * relevant terminology. It also has helpful illustrations. 1479 * 1480 * [1] https://api.semanticscholar.org/CorpusID:15784067 1481 * 1482 * We use a similar algorithm but because loop nested structure is 1483 * irrelevant for verifier ours is significantly simpler and resembles 1484 * strongly connected components algorithm from Sedgewick's textbook. 1485 * 1486 * Define topmost loop entry as a first node of the loop traversed in a 1487 * depth first search starting from initial state. The goal of the loop 1488 * tracking algorithm is to associate topmost loop entries with states 1489 * derived from these entries. 1490 * 1491 * For each step in the DFS states traversal algorithm needs to identify 1492 * the following situations: 1493 * 1494 * initial initial initial 1495 * | | | 1496 * V V V 1497 * ... ... .---------> hdr 1498 * | | | | 1499 * V V | V 1500 * cur .-> succ | .------... 1501 * | | | | | | 1502 * V | V | V V 1503 * succ '-- cur | ... ... 1504 * | | | 1505 * | V V 1506 * | succ <- cur 1507 * | | 1508 * | V 1509 * | ... 1510 * | | 1511 * '----' 1512 * 1513 * (A) successor state of cur (B) successor state of cur or it's entry 1514 * not yet traversed are in current DFS path, thus cur and succ 1515 * are members of the same outermost loop 1516 * 1517 * initial initial 1518 * | | 1519 * V V 1520 * ... ... 1521 * | | 1522 * V V 1523 * .------... .------... 1524 * | | | | 1525 * V V V V 1526 * .-> hdr ... ... ... 1527 * | | | | | 1528 * | V V V V 1529 * | succ <- cur succ <- cur 1530 * | | | 1531 * | V V 1532 * | ... ... 1533 * | | | 1534 * '----' exit 1535 * 1536 * (C) successor state of cur is a part of some loop but this loop 1537 * does not include cur or successor state is not in a loop at all. 1538 * 1539 * Algorithm could be described as the following python code: 1540 * 1541 * traversed = set() # Set of traversed nodes 1542 * entries = {} # Mapping from node to loop entry 1543 * depths = {} # Depth level assigned to graph node 1544 * path = set() # Current DFS path 1545 * 1546 * # Find outermost loop entry known for n 1547 * def get_loop_entry(n): 1548 * h = entries.get(n, None) 1549 * while h in entries and entries[h] != h: 1550 * h = entries[h] 1551 * return h 1552 * 1553 * # Update n's loop entry if h's outermost entry comes 1554 * # before n's outermost entry in current DFS path. 1555 * def update_loop_entry(n, h): 1556 * n1 = get_loop_entry(n) or n 1557 * h1 = get_loop_entry(h) or h 1558 * if h1 in path and depths[h1] <= depths[n1]: 1559 * entries[n] = h1 1560 * 1561 * def dfs(n, depth): 1562 * traversed.add(n) 1563 * path.add(n) 1564 * depths[n] = depth 1565 * for succ in G.successors(n): 1566 * if succ not in traversed: 1567 * # Case A: explore succ and update cur's loop entry 1568 * # only if succ's entry is in current DFS path. 1569 * dfs(succ, depth + 1) 1570 * h = get_loop_entry(succ) 1571 * update_loop_entry(n, h) 1572 * else: 1573 * # Case B or C depending on `h1 in path` check in update_loop_entry(). 1574 * update_loop_entry(n, succ) 1575 * path.remove(n) 1576 * 1577 * To adapt this algorithm for use with verifier: 1578 * - use st->branch == 0 as a signal that DFS of succ had been finished 1579 * and cur's loop entry has to be updated (case A), handle this in 1580 * update_branch_counts(); 1581 * - use st->branch > 0 as a signal that st is in the current DFS path; 1582 * - handle cases B and C in is_state_visited(); 1583 * - update topmost loop entry for intermediate states in get_loop_entry(). 1584 */ 1585 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st) 1586 { 1587 struct bpf_verifier_state *topmost = st->loop_entry, *old; 1588 1589 while (topmost && topmost->loop_entry && topmost != topmost->loop_entry) 1590 topmost = topmost->loop_entry; 1591 /* Update loop entries for intermediate states to avoid this 1592 * traversal in future get_loop_entry() calls. 1593 */ 1594 while (st && st->loop_entry != topmost) { 1595 old = st->loop_entry; 1596 st->loop_entry = topmost; 1597 st = old; 1598 } 1599 return topmost; 1600 } 1601 1602 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr) 1603 { 1604 struct bpf_verifier_state *cur1, *hdr1; 1605 1606 cur1 = get_loop_entry(cur) ?: cur; 1607 hdr1 = get_loop_entry(hdr) ?: hdr; 1608 /* The head1->branches check decides between cases B and C in 1609 * comment for get_loop_entry(). If hdr1->branches == 0 then 1610 * head's topmost loop entry is not in current DFS path, 1611 * hence 'cur' and 'hdr' are not in the same loop and there is 1612 * no need to update cur->loop_entry. 1613 */ 1614 if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) { 1615 cur->loop_entry = hdr; 1616 hdr->used_as_loop_entry = true; 1617 } 1618 } 1619 1620 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1621 { 1622 while (st) { 1623 u32 br = --st->branches; 1624 1625 /* br == 0 signals that DFS exploration for 'st' is finished, 1626 * thus it is necessary to update parent's loop entry if it 1627 * turned out that st is a part of some loop. 1628 * This is a part of 'case A' in get_loop_entry() comment. 1629 */ 1630 if (br == 0 && st->parent && st->loop_entry) 1631 update_loop_entry(st->parent, st->loop_entry); 1632 1633 /* WARN_ON(br > 1) technically makes sense here, 1634 * but see comment in push_stack(), hence: 1635 */ 1636 WARN_ONCE((int)br < 0, 1637 "BUG update_branch_counts:branches_to_explore=%d\n", 1638 br); 1639 if (br) 1640 break; 1641 st = st->parent; 1642 } 1643 } 1644 1645 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1646 int *insn_idx, bool pop_log) 1647 { 1648 struct bpf_verifier_state *cur = env->cur_state; 1649 struct bpf_verifier_stack_elem *elem, *head = env->head; 1650 int err; 1651 1652 if (env->head == NULL) 1653 return -ENOENT; 1654 1655 if (cur) { 1656 err = copy_verifier_state(cur, &head->st); 1657 if (err) 1658 return err; 1659 } 1660 if (pop_log) 1661 bpf_vlog_reset(&env->log, head->log_pos); 1662 if (insn_idx) 1663 *insn_idx = head->insn_idx; 1664 if (prev_insn_idx) 1665 *prev_insn_idx = head->prev_insn_idx; 1666 elem = head->next; 1667 free_verifier_state(&head->st, false); 1668 kfree(head); 1669 env->head = elem; 1670 env->stack_size--; 1671 return 0; 1672 } 1673 1674 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1675 int insn_idx, int prev_insn_idx, 1676 bool speculative) 1677 { 1678 struct bpf_verifier_state *cur = env->cur_state; 1679 struct bpf_verifier_stack_elem *elem; 1680 int err; 1681 1682 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1683 if (!elem) 1684 goto err; 1685 1686 elem->insn_idx = insn_idx; 1687 elem->prev_insn_idx = prev_insn_idx; 1688 elem->next = env->head; 1689 elem->log_pos = env->log.end_pos; 1690 env->head = elem; 1691 env->stack_size++; 1692 err = copy_verifier_state(&elem->st, cur); 1693 if (err) 1694 goto err; 1695 elem->st.speculative |= speculative; 1696 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1697 verbose(env, "The sequence of %d jumps is too complex.\n", 1698 env->stack_size); 1699 goto err; 1700 } 1701 if (elem->st.parent) { 1702 ++elem->st.parent->branches; 1703 /* WARN_ON(branches > 2) technically makes sense here, 1704 * but 1705 * 1. speculative states will bump 'branches' for non-branch 1706 * instructions 1707 * 2. is_state_visited() heuristics may decide not to create 1708 * a new state for a sequence of branches and all such current 1709 * and cloned states will be pointing to a single parent state 1710 * which might have large 'branches' count. 1711 */ 1712 } 1713 return &elem->st; 1714 err: 1715 free_verifier_state(env->cur_state, true); 1716 env->cur_state = NULL; 1717 /* pop all elements and return */ 1718 while (!pop_stack(env, NULL, NULL, false)); 1719 return NULL; 1720 } 1721 1722 #define CALLER_SAVED_REGS 6 1723 static const int caller_saved[CALLER_SAVED_REGS] = { 1724 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1725 }; 1726 1727 /* This helper doesn't clear reg->id */ 1728 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1729 { 1730 reg->var_off = tnum_const(imm); 1731 reg->smin_value = (s64)imm; 1732 reg->smax_value = (s64)imm; 1733 reg->umin_value = imm; 1734 reg->umax_value = imm; 1735 1736 reg->s32_min_value = (s32)imm; 1737 reg->s32_max_value = (s32)imm; 1738 reg->u32_min_value = (u32)imm; 1739 reg->u32_max_value = (u32)imm; 1740 } 1741 1742 /* Mark the unknown part of a register (variable offset or scalar value) as 1743 * known to have the value @imm. 1744 */ 1745 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1746 { 1747 /* Clear off and union(map_ptr, range) */ 1748 memset(((u8 *)reg) + sizeof(reg->type), 0, 1749 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1750 reg->id = 0; 1751 reg->ref_obj_id = 0; 1752 ___mark_reg_known(reg, imm); 1753 } 1754 1755 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1756 { 1757 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1758 reg->s32_min_value = (s32)imm; 1759 reg->s32_max_value = (s32)imm; 1760 reg->u32_min_value = (u32)imm; 1761 reg->u32_max_value = (u32)imm; 1762 } 1763 1764 /* Mark the 'variable offset' part of a register as zero. This should be 1765 * used only on registers holding a pointer type. 1766 */ 1767 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1768 { 1769 __mark_reg_known(reg, 0); 1770 } 1771 1772 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1773 { 1774 __mark_reg_known(reg, 0); 1775 reg->type = SCALAR_VALUE; 1776 /* all scalars are assumed imprecise initially (unless unprivileged, 1777 * in which case everything is forced to be precise) 1778 */ 1779 reg->precise = !env->bpf_capable; 1780 } 1781 1782 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1783 struct bpf_reg_state *regs, u32 regno) 1784 { 1785 if (WARN_ON(regno >= MAX_BPF_REG)) { 1786 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1787 /* Something bad happened, let's kill all regs */ 1788 for (regno = 0; regno < MAX_BPF_REG; regno++) 1789 __mark_reg_not_init(env, regs + regno); 1790 return; 1791 } 1792 __mark_reg_known_zero(regs + regno); 1793 } 1794 1795 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1796 bool first_slot, int dynptr_id) 1797 { 1798 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1799 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1800 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1801 */ 1802 __mark_reg_known_zero(reg); 1803 reg->type = CONST_PTR_TO_DYNPTR; 1804 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1805 reg->id = dynptr_id; 1806 reg->dynptr.type = type; 1807 reg->dynptr.first_slot = first_slot; 1808 } 1809 1810 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1811 { 1812 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1813 const struct bpf_map *map = reg->map_ptr; 1814 1815 if (map->inner_map_meta) { 1816 reg->type = CONST_PTR_TO_MAP; 1817 reg->map_ptr = map->inner_map_meta; 1818 /* transfer reg's id which is unique for every map_lookup_elem 1819 * as UID of the inner map. 1820 */ 1821 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 1822 reg->map_uid = reg->id; 1823 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1824 reg->type = PTR_TO_XDP_SOCK; 1825 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1826 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1827 reg->type = PTR_TO_SOCKET; 1828 } else { 1829 reg->type = PTR_TO_MAP_VALUE; 1830 } 1831 return; 1832 } 1833 1834 reg->type &= ~PTR_MAYBE_NULL; 1835 } 1836 1837 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 1838 struct btf_field_graph_root *ds_head) 1839 { 1840 __mark_reg_known_zero(®s[regno]); 1841 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 1842 regs[regno].btf = ds_head->btf; 1843 regs[regno].btf_id = ds_head->value_btf_id; 1844 regs[regno].off = ds_head->node_offset; 1845 } 1846 1847 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1848 { 1849 return type_is_pkt_pointer(reg->type); 1850 } 1851 1852 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1853 { 1854 return reg_is_pkt_pointer(reg) || 1855 reg->type == PTR_TO_PACKET_END; 1856 } 1857 1858 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 1859 { 1860 return base_type(reg->type) == PTR_TO_MEM && 1861 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP); 1862 } 1863 1864 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1865 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1866 enum bpf_reg_type which) 1867 { 1868 /* The register can already have a range from prior markings. 1869 * This is fine as long as it hasn't been advanced from its 1870 * origin. 1871 */ 1872 return reg->type == which && 1873 reg->id == 0 && 1874 reg->off == 0 && 1875 tnum_equals_const(reg->var_off, 0); 1876 } 1877 1878 /* Reset the min/max bounds of a register */ 1879 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1880 { 1881 reg->smin_value = S64_MIN; 1882 reg->smax_value = S64_MAX; 1883 reg->umin_value = 0; 1884 reg->umax_value = U64_MAX; 1885 1886 reg->s32_min_value = S32_MIN; 1887 reg->s32_max_value = S32_MAX; 1888 reg->u32_min_value = 0; 1889 reg->u32_max_value = U32_MAX; 1890 } 1891 1892 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1893 { 1894 reg->smin_value = S64_MIN; 1895 reg->smax_value = S64_MAX; 1896 reg->umin_value = 0; 1897 reg->umax_value = U64_MAX; 1898 } 1899 1900 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1901 { 1902 reg->s32_min_value = S32_MIN; 1903 reg->s32_max_value = S32_MAX; 1904 reg->u32_min_value = 0; 1905 reg->u32_max_value = U32_MAX; 1906 } 1907 1908 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1909 { 1910 struct tnum var32_off = tnum_subreg(reg->var_off); 1911 1912 /* min signed is max(sign bit) | min(other bits) */ 1913 reg->s32_min_value = max_t(s32, reg->s32_min_value, 1914 var32_off.value | (var32_off.mask & S32_MIN)); 1915 /* max signed is min(sign bit) | max(other bits) */ 1916 reg->s32_max_value = min_t(s32, reg->s32_max_value, 1917 var32_off.value | (var32_off.mask & S32_MAX)); 1918 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 1919 reg->u32_max_value = min(reg->u32_max_value, 1920 (u32)(var32_off.value | var32_off.mask)); 1921 } 1922 1923 static void __update_reg64_bounds(struct bpf_reg_state *reg) 1924 { 1925 /* min signed is max(sign bit) | min(other bits) */ 1926 reg->smin_value = max_t(s64, reg->smin_value, 1927 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 1928 /* max signed is min(sign bit) | max(other bits) */ 1929 reg->smax_value = min_t(s64, reg->smax_value, 1930 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 1931 reg->umin_value = max(reg->umin_value, reg->var_off.value); 1932 reg->umax_value = min(reg->umax_value, 1933 reg->var_off.value | reg->var_off.mask); 1934 } 1935 1936 static void __update_reg_bounds(struct bpf_reg_state *reg) 1937 { 1938 __update_reg32_bounds(reg); 1939 __update_reg64_bounds(reg); 1940 } 1941 1942 /* Uses signed min/max values to inform unsigned, and vice-versa */ 1943 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 1944 { 1945 /* If upper 32 bits of u64/s64 range don't change, we can use lower 32 1946 * bits to improve our u32/s32 boundaries. 1947 * 1948 * E.g., the case where we have upper 32 bits as zero ([10, 20] in 1949 * u64) is pretty trivial, it's obvious that in u32 we'll also have 1950 * [10, 20] range. But this property holds for any 64-bit range as 1951 * long as upper 32 bits in that entire range of values stay the same. 1952 * 1953 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311] 1954 * in decimal) has the same upper 32 bits throughout all the values in 1955 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15]) 1956 * range. 1957 * 1958 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32, 1959 * following the rules outlined below about u64/s64 correspondence 1960 * (which equally applies to u32 vs s32 correspondence). In general it 1961 * depends on actual hexadecimal values of 32-bit range. They can form 1962 * only valid u32, or only valid s32 ranges in some cases. 1963 * 1964 * So we use all these insights to derive bounds for subregisters here. 1965 */ 1966 if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) { 1967 /* u64 to u32 casting preserves validity of low 32 bits as 1968 * a range, if upper 32 bits are the same 1969 */ 1970 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value); 1971 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value); 1972 1973 if ((s32)reg->umin_value <= (s32)reg->umax_value) { 1974 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 1975 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 1976 } 1977 } 1978 if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) { 1979 /* low 32 bits should form a proper u32 range */ 1980 if ((u32)reg->smin_value <= (u32)reg->smax_value) { 1981 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value); 1982 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value); 1983 } 1984 /* low 32 bits should form a proper s32 range */ 1985 if ((s32)reg->smin_value <= (s32)reg->smax_value) { 1986 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 1987 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 1988 } 1989 } 1990 /* Special case where upper bits form a small sequence of two 1991 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to 1992 * 0x00000000 is also valid), while lower bits form a proper s32 range 1993 * going from negative numbers to positive numbers. E.g., let's say we 1994 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]). 1995 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff, 1996 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits, 1997 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]). 1998 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in 1999 * upper 32 bits. As a random example, s64 range 2000 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range 2001 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister. 2002 */ 2003 if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) && 2004 (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) { 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 if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) && 2009 (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) { 2010 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 2011 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 2012 } 2013 /* if u32 range forms a valid s32 range (due to matching sign bit), 2014 * try to learn from that 2015 */ 2016 if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) { 2017 reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value); 2018 reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value); 2019 } 2020 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2021 * are the same, so combine. This works even in the negative case, e.g. 2022 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2023 */ 2024 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2025 reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value); 2026 reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value); 2027 } 2028 } 2029 2030 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 2031 { 2032 /* If u64 range forms a valid s64 range (due to matching sign bit), 2033 * try to learn from that. Let's do a bit of ASCII art to see when 2034 * this is happening. Let's take u64 range first: 2035 * 2036 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2037 * |-------------------------------|--------------------------------| 2038 * 2039 * Valid u64 range is formed when umin and umax are anywhere in the 2040 * range [0, U64_MAX], and umin <= umax. u64 case is simple and 2041 * straightforward. Let's see how s64 range maps onto the same range 2042 * of values, annotated below the line for comparison: 2043 * 2044 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2045 * |-------------------------------|--------------------------------| 2046 * 0 S64_MAX S64_MIN -1 2047 * 2048 * So s64 values basically start in the middle and they are logically 2049 * contiguous to the right of it, wrapping around from -1 to 0, and 2050 * then finishing as S64_MAX (0x7fffffffffffffff) right before 2051 * S64_MIN. We can try drawing the continuity of u64 vs s64 values 2052 * more visually as mapped to sign-agnostic range of hex values. 2053 * 2054 * u64 start u64 end 2055 * _______________________________________________________________ 2056 * / \ 2057 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2058 * |-------------------------------|--------------------------------| 2059 * 0 S64_MAX S64_MIN -1 2060 * / \ 2061 * >------------------------------ -------------------------------> 2062 * s64 continues... s64 end s64 start s64 "midpoint" 2063 * 2064 * What this means is that, in general, we can't always derive 2065 * something new about u64 from any random s64 range, and vice versa. 2066 * 2067 * But we can do that in two particular cases. One is when entire 2068 * u64/s64 range is *entirely* contained within left half of the above 2069 * diagram or when it is *entirely* contained in the right half. I.e.: 2070 * 2071 * |-------------------------------|--------------------------------| 2072 * ^ ^ ^ ^ 2073 * A B C D 2074 * 2075 * [A, B] and [C, D] are contained entirely in their respective halves 2076 * and form valid contiguous ranges as both u64 and s64 values. [A, B] 2077 * will be non-negative both as u64 and s64 (and in fact it will be 2078 * identical ranges no matter the signedness). [C, D] treated as s64 2079 * will be a range of negative values, while in u64 it will be 2080 * non-negative range of values larger than 0x8000000000000000. 2081 * 2082 * Now, any other range here can't be represented in both u64 and s64 2083 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid 2084 * contiguous u64 ranges, but they are discontinuous in s64. [B, C] 2085 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX], 2086 * for example. Similarly, valid s64 range [D, A] (going from negative 2087 * to positive values), would be two separate [D, U64_MAX] and [0, A] 2088 * ranges as u64. Currently reg_state can't represent two segments per 2089 * numeric domain, so in such situations we can only derive maximal 2090 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64). 2091 * 2092 * So we use these facts to derive umin/umax from smin/smax and vice 2093 * versa only if they stay within the same "half". This is equivalent 2094 * to checking sign bit: lower half will have sign bit as zero, upper 2095 * half have sign bit 1. Below in code we simplify this by just 2096 * casting umin/umax as smin/smax and checking if they form valid 2097 * range, and vice versa. Those are equivalent checks. 2098 */ 2099 if ((s64)reg->umin_value <= (s64)reg->umax_value) { 2100 reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value); 2101 reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value); 2102 } 2103 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2104 * are the same, so combine. This works even in the negative case, e.g. 2105 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2106 */ 2107 if ((u64)reg->smin_value <= (u64)reg->smax_value) { 2108 reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); 2109 reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); 2110 } 2111 } 2112 2113 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg) 2114 { 2115 /* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit 2116 * values on both sides of 64-bit range in hope to have tigher range. 2117 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from 2118 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff]. 2119 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound 2120 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of 2121 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a 2122 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff]. 2123 * We just need to make sure that derived bounds we are intersecting 2124 * with are well-formed ranges in respecitve s64 or u64 domain, just 2125 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments. 2126 */ 2127 __u64 new_umin, new_umax; 2128 __s64 new_smin, new_smax; 2129 2130 /* u32 -> u64 tightening, it's always well-formed */ 2131 new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value; 2132 new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value; 2133 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2134 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2135 /* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */ 2136 new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value; 2137 new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value; 2138 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2139 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2140 2141 /* if s32 can be treated as valid u32 range, we can use it as well */ 2142 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2143 /* s32 -> u64 tightening */ 2144 new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value; 2145 new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value; 2146 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2147 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2148 /* s32 -> s64 tightening */ 2149 new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value; 2150 new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value; 2151 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2152 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2153 } 2154 } 2155 2156 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2157 { 2158 __reg32_deduce_bounds(reg); 2159 __reg64_deduce_bounds(reg); 2160 __reg_deduce_mixed_bounds(reg); 2161 } 2162 2163 /* Attempts to improve var_off based on unsigned min/max information */ 2164 static void __reg_bound_offset(struct bpf_reg_state *reg) 2165 { 2166 struct tnum var64_off = tnum_intersect(reg->var_off, 2167 tnum_range(reg->umin_value, 2168 reg->umax_value)); 2169 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2170 tnum_range(reg->u32_min_value, 2171 reg->u32_max_value)); 2172 2173 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2174 } 2175 2176 static void reg_bounds_sync(struct bpf_reg_state *reg) 2177 { 2178 /* We might have learned new bounds from the var_off. */ 2179 __update_reg_bounds(reg); 2180 /* We might have learned something about the sign bit. */ 2181 __reg_deduce_bounds(reg); 2182 __reg_deduce_bounds(reg); 2183 /* We might have learned some bits from the bounds. */ 2184 __reg_bound_offset(reg); 2185 /* Intersecting with the old var_off might have improved our bounds 2186 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2187 * then new var_off is (0; 0x7f...fc) which improves our umax. 2188 */ 2189 __update_reg_bounds(reg); 2190 } 2191 2192 static int reg_bounds_sanity_check(struct bpf_verifier_env *env, 2193 struct bpf_reg_state *reg, const char *ctx) 2194 { 2195 const char *msg; 2196 2197 if (reg->umin_value > reg->umax_value || 2198 reg->smin_value > reg->smax_value || 2199 reg->u32_min_value > reg->u32_max_value || 2200 reg->s32_min_value > reg->s32_max_value) { 2201 msg = "range bounds violation"; 2202 goto out; 2203 } 2204 2205 if (tnum_is_const(reg->var_off)) { 2206 u64 uval = reg->var_off.value; 2207 s64 sval = (s64)uval; 2208 2209 if (reg->umin_value != uval || reg->umax_value != uval || 2210 reg->smin_value != sval || reg->smax_value != sval) { 2211 msg = "const tnum out of sync with range bounds"; 2212 goto out; 2213 } 2214 } 2215 2216 if (tnum_subreg_is_const(reg->var_off)) { 2217 u32 uval32 = tnum_subreg(reg->var_off).value; 2218 s32 sval32 = (s32)uval32; 2219 2220 if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 || 2221 reg->s32_min_value != sval32 || reg->s32_max_value != sval32) { 2222 msg = "const subreg tnum out of sync with range bounds"; 2223 goto out; 2224 } 2225 } 2226 2227 return 0; 2228 out: 2229 verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] " 2230 "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n", 2231 ctx, msg, reg->umin_value, reg->umax_value, 2232 reg->smin_value, reg->smax_value, 2233 reg->u32_min_value, reg->u32_max_value, 2234 reg->s32_min_value, reg->s32_max_value, 2235 reg->var_off.value, reg->var_off.mask); 2236 if (env->test_reg_invariants) 2237 return -EFAULT; 2238 __mark_reg_unbounded(reg); 2239 return 0; 2240 } 2241 2242 static bool __reg32_bound_s64(s32 a) 2243 { 2244 return a >= 0 && a <= S32_MAX; 2245 } 2246 2247 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 2248 { 2249 reg->umin_value = reg->u32_min_value; 2250 reg->umax_value = reg->u32_max_value; 2251 2252 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 2253 * be positive otherwise set to worse case bounds and refine later 2254 * from tnum. 2255 */ 2256 if (__reg32_bound_s64(reg->s32_min_value) && 2257 __reg32_bound_s64(reg->s32_max_value)) { 2258 reg->smin_value = reg->s32_min_value; 2259 reg->smax_value = reg->s32_max_value; 2260 } else { 2261 reg->smin_value = 0; 2262 reg->smax_value = U32_MAX; 2263 } 2264 } 2265 2266 /* Mark a register as having a completely unknown (scalar) value. */ 2267 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2268 struct bpf_reg_state *reg) 2269 { 2270 /* 2271 * Clear type, off, and union(map_ptr, range) and 2272 * padding between 'type' and union 2273 */ 2274 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2275 reg->type = SCALAR_VALUE; 2276 reg->id = 0; 2277 reg->ref_obj_id = 0; 2278 reg->var_off = tnum_unknown; 2279 reg->frameno = 0; 2280 reg->precise = !env->bpf_capable; 2281 __mark_reg_unbounded(reg); 2282 } 2283 2284 static void mark_reg_unknown(struct bpf_verifier_env *env, 2285 struct bpf_reg_state *regs, u32 regno) 2286 { 2287 if (WARN_ON(regno >= MAX_BPF_REG)) { 2288 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 2289 /* Something bad happened, let's kill all regs except FP */ 2290 for (regno = 0; regno < BPF_REG_FP; regno++) 2291 __mark_reg_not_init(env, regs + regno); 2292 return; 2293 } 2294 __mark_reg_unknown(env, regs + regno); 2295 } 2296 2297 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 2298 struct bpf_reg_state *reg) 2299 { 2300 __mark_reg_unknown(env, reg); 2301 reg->type = NOT_INIT; 2302 } 2303 2304 static void mark_reg_not_init(struct bpf_verifier_env *env, 2305 struct bpf_reg_state *regs, u32 regno) 2306 { 2307 if (WARN_ON(regno >= MAX_BPF_REG)) { 2308 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 2309 /* Something bad happened, let's kill all regs except FP */ 2310 for (regno = 0; regno < BPF_REG_FP; regno++) 2311 __mark_reg_not_init(env, regs + regno); 2312 return; 2313 } 2314 __mark_reg_not_init(env, regs + regno); 2315 } 2316 2317 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 2318 struct bpf_reg_state *regs, u32 regno, 2319 enum bpf_reg_type reg_type, 2320 struct btf *btf, u32 btf_id, 2321 enum bpf_type_flag flag) 2322 { 2323 if (reg_type == SCALAR_VALUE) { 2324 mark_reg_unknown(env, regs, regno); 2325 return; 2326 } 2327 mark_reg_known_zero(env, regs, regno); 2328 regs[regno].type = PTR_TO_BTF_ID | flag; 2329 regs[regno].btf = btf; 2330 regs[regno].btf_id = btf_id; 2331 } 2332 2333 #define DEF_NOT_SUBREG (0) 2334 static void init_reg_state(struct bpf_verifier_env *env, 2335 struct bpf_func_state *state) 2336 { 2337 struct bpf_reg_state *regs = state->regs; 2338 int i; 2339 2340 for (i = 0; i < MAX_BPF_REG; i++) { 2341 mark_reg_not_init(env, regs, i); 2342 regs[i].live = REG_LIVE_NONE; 2343 regs[i].parent = NULL; 2344 regs[i].subreg_def = DEF_NOT_SUBREG; 2345 } 2346 2347 /* frame pointer */ 2348 regs[BPF_REG_FP].type = PTR_TO_STACK; 2349 mark_reg_known_zero(env, regs, BPF_REG_FP); 2350 regs[BPF_REG_FP].frameno = state->frameno; 2351 } 2352 2353 static struct bpf_retval_range retval_range(s32 minval, s32 maxval) 2354 { 2355 return (struct bpf_retval_range){ minval, maxval }; 2356 } 2357 2358 #define BPF_MAIN_FUNC (-1) 2359 static void init_func_state(struct bpf_verifier_env *env, 2360 struct bpf_func_state *state, 2361 int callsite, int frameno, int subprogno) 2362 { 2363 state->callsite = callsite; 2364 state->frameno = frameno; 2365 state->subprogno = subprogno; 2366 state->callback_ret_range = retval_range(0, 0); 2367 init_reg_state(env, state); 2368 mark_verifier_state_scratched(env); 2369 } 2370 2371 /* Similar to push_stack(), but for async callbacks */ 2372 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2373 int insn_idx, int prev_insn_idx, 2374 int subprog) 2375 { 2376 struct bpf_verifier_stack_elem *elem; 2377 struct bpf_func_state *frame; 2378 2379 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2380 if (!elem) 2381 goto err; 2382 2383 elem->insn_idx = insn_idx; 2384 elem->prev_insn_idx = prev_insn_idx; 2385 elem->next = env->head; 2386 elem->log_pos = env->log.end_pos; 2387 env->head = elem; 2388 env->stack_size++; 2389 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2390 verbose(env, 2391 "The sequence of %d jumps is too complex for async cb.\n", 2392 env->stack_size); 2393 goto err; 2394 } 2395 /* Unlike push_stack() do not copy_verifier_state(). 2396 * The caller state doesn't matter. 2397 * This is async callback. It starts in a fresh stack. 2398 * Initialize it similar to do_check_common(). 2399 */ 2400 elem->st.branches = 1; 2401 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 2402 if (!frame) 2403 goto err; 2404 init_func_state(env, frame, 2405 BPF_MAIN_FUNC /* callsite */, 2406 0 /* frameno within this callchain */, 2407 subprog /* subprog number within this prog */); 2408 elem->st.frame[0] = frame; 2409 return &elem->st; 2410 err: 2411 free_verifier_state(env->cur_state, true); 2412 env->cur_state = NULL; 2413 /* pop all elements and return */ 2414 while (!pop_stack(env, NULL, NULL, false)); 2415 return NULL; 2416 } 2417 2418 2419 enum reg_arg_type { 2420 SRC_OP, /* register is used as source operand */ 2421 DST_OP, /* register is used as destination operand */ 2422 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2423 }; 2424 2425 static int cmp_subprogs(const void *a, const void *b) 2426 { 2427 return ((struct bpf_subprog_info *)a)->start - 2428 ((struct bpf_subprog_info *)b)->start; 2429 } 2430 2431 static int find_subprog(struct bpf_verifier_env *env, int off) 2432 { 2433 struct bpf_subprog_info *p; 2434 2435 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 2436 sizeof(env->subprog_info[0]), cmp_subprogs); 2437 if (!p) 2438 return -ENOENT; 2439 return p - env->subprog_info; 2440 2441 } 2442 2443 static int add_subprog(struct bpf_verifier_env *env, int off) 2444 { 2445 int insn_cnt = env->prog->len; 2446 int ret; 2447 2448 if (off >= insn_cnt || off < 0) { 2449 verbose(env, "call to invalid destination\n"); 2450 return -EINVAL; 2451 } 2452 ret = find_subprog(env, off); 2453 if (ret >= 0) 2454 return ret; 2455 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2456 verbose(env, "too many subprograms\n"); 2457 return -E2BIG; 2458 } 2459 /* determine subprog starts. The end is one before the next starts */ 2460 env->subprog_info[env->subprog_cnt++].start = off; 2461 sort(env->subprog_info, env->subprog_cnt, 2462 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2463 return env->subprog_cnt - 1; 2464 } 2465 2466 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env) 2467 { 2468 struct bpf_prog_aux *aux = env->prog->aux; 2469 struct btf *btf = aux->btf; 2470 const struct btf_type *t; 2471 u32 main_btf_id, id; 2472 const char *name; 2473 int ret, i; 2474 2475 /* Non-zero func_info_cnt implies valid btf */ 2476 if (!aux->func_info_cnt) 2477 return 0; 2478 main_btf_id = aux->func_info[0].type_id; 2479 2480 t = btf_type_by_id(btf, main_btf_id); 2481 if (!t) { 2482 verbose(env, "invalid btf id for main subprog in func_info\n"); 2483 return -EINVAL; 2484 } 2485 2486 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:"); 2487 if (IS_ERR(name)) { 2488 ret = PTR_ERR(name); 2489 /* If there is no tag present, there is no exception callback */ 2490 if (ret == -ENOENT) 2491 ret = 0; 2492 else if (ret == -EEXIST) 2493 verbose(env, "multiple exception callback tags for main subprog\n"); 2494 return ret; 2495 } 2496 2497 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC); 2498 if (ret < 0) { 2499 verbose(env, "exception callback '%s' could not be found in BTF\n", name); 2500 return ret; 2501 } 2502 id = ret; 2503 t = btf_type_by_id(btf, id); 2504 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) { 2505 verbose(env, "exception callback '%s' must have global linkage\n", name); 2506 return -EINVAL; 2507 } 2508 ret = 0; 2509 for (i = 0; i < aux->func_info_cnt; i++) { 2510 if (aux->func_info[i].type_id != id) 2511 continue; 2512 ret = aux->func_info[i].insn_off; 2513 /* Further func_info and subprog checks will also happen 2514 * later, so assume this is the right insn_off for now. 2515 */ 2516 if (!ret) { 2517 verbose(env, "invalid exception callback insn_off in func_info: 0\n"); 2518 ret = -EINVAL; 2519 } 2520 } 2521 if (!ret) { 2522 verbose(env, "exception callback type id not found in func_info\n"); 2523 ret = -EINVAL; 2524 } 2525 return ret; 2526 } 2527 2528 #define MAX_KFUNC_DESCS 256 2529 #define MAX_KFUNC_BTFS 256 2530 2531 struct bpf_kfunc_desc { 2532 struct btf_func_model func_model; 2533 u32 func_id; 2534 s32 imm; 2535 u16 offset; 2536 unsigned long addr; 2537 }; 2538 2539 struct bpf_kfunc_btf { 2540 struct btf *btf; 2541 struct module *module; 2542 u16 offset; 2543 }; 2544 2545 struct bpf_kfunc_desc_tab { 2546 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during 2547 * verification. JITs do lookups by bpf_insn, where func_id may not be 2548 * available, therefore at the end of verification do_misc_fixups() 2549 * sorts this by imm and offset. 2550 */ 2551 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 2552 u32 nr_descs; 2553 }; 2554 2555 struct bpf_kfunc_btf_tab { 2556 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2557 u32 nr_descs; 2558 }; 2559 2560 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2561 { 2562 const struct bpf_kfunc_desc *d0 = a; 2563 const struct bpf_kfunc_desc *d1 = b; 2564 2565 /* func_id is not greater than BTF_MAX_TYPE */ 2566 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2567 } 2568 2569 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2570 { 2571 const struct bpf_kfunc_btf *d0 = a; 2572 const struct bpf_kfunc_btf *d1 = b; 2573 2574 return d0->offset - d1->offset; 2575 } 2576 2577 static const struct bpf_kfunc_desc * 2578 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2579 { 2580 struct bpf_kfunc_desc desc = { 2581 .func_id = func_id, 2582 .offset = offset, 2583 }; 2584 struct bpf_kfunc_desc_tab *tab; 2585 2586 tab = prog->aux->kfunc_tab; 2587 return bsearch(&desc, tab->descs, tab->nr_descs, 2588 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2589 } 2590 2591 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2592 u16 btf_fd_idx, u8 **func_addr) 2593 { 2594 const struct bpf_kfunc_desc *desc; 2595 2596 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2597 if (!desc) 2598 return -EFAULT; 2599 2600 *func_addr = (u8 *)desc->addr; 2601 return 0; 2602 } 2603 2604 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2605 s16 offset) 2606 { 2607 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2608 struct bpf_kfunc_btf_tab *tab; 2609 struct bpf_kfunc_btf *b; 2610 struct module *mod; 2611 struct btf *btf; 2612 int btf_fd; 2613 2614 tab = env->prog->aux->kfunc_btf_tab; 2615 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2616 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2617 if (!b) { 2618 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2619 verbose(env, "too many different module BTFs\n"); 2620 return ERR_PTR(-E2BIG); 2621 } 2622 2623 if (bpfptr_is_null(env->fd_array)) { 2624 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2625 return ERR_PTR(-EPROTO); 2626 } 2627 2628 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2629 offset * sizeof(btf_fd), 2630 sizeof(btf_fd))) 2631 return ERR_PTR(-EFAULT); 2632 2633 btf = btf_get_by_fd(btf_fd); 2634 if (IS_ERR(btf)) { 2635 verbose(env, "invalid module BTF fd specified\n"); 2636 return btf; 2637 } 2638 2639 if (!btf_is_module(btf)) { 2640 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2641 btf_put(btf); 2642 return ERR_PTR(-EINVAL); 2643 } 2644 2645 mod = btf_try_get_module(btf); 2646 if (!mod) { 2647 btf_put(btf); 2648 return ERR_PTR(-ENXIO); 2649 } 2650 2651 b = &tab->descs[tab->nr_descs++]; 2652 b->btf = btf; 2653 b->module = mod; 2654 b->offset = offset; 2655 2656 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2657 kfunc_btf_cmp_by_off, NULL); 2658 } 2659 return b->btf; 2660 } 2661 2662 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2663 { 2664 if (!tab) 2665 return; 2666 2667 while (tab->nr_descs--) { 2668 module_put(tab->descs[tab->nr_descs].module); 2669 btf_put(tab->descs[tab->nr_descs].btf); 2670 } 2671 kfree(tab); 2672 } 2673 2674 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2675 { 2676 if (offset) { 2677 if (offset < 0) { 2678 /* In the future, this can be allowed to increase limit 2679 * of fd index into fd_array, interpreted as u16. 2680 */ 2681 verbose(env, "negative offset disallowed for kernel module function call\n"); 2682 return ERR_PTR(-EINVAL); 2683 } 2684 2685 return __find_kfunc_desc_btf(env, offset); 2686 } 2687 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2688 } 2689 2690 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 2691 { 2692 const struct btf_type *func, *func_proto; 2693 struct bpf_kfunc_btf_tab *btf_tab; 2694 struct bpf_kfunc_desc_tab *tab; 2695 struct bpf_prog_aux *prog_aux; 2696 struct bpf_kfunc_desc *desc; 2697 const char *func_name; 2698 struct btf *desc_btf; 2699 unsigned long call_imm; 2700 unsigned long addr; 2701 int err; 2702 2703 prog_aux = env->prog->aux; 2704 tab = prog_aux->kfunc_tab; 2705 btf_tab = prog_aux->kfunc_btf_tab; 2706 if (!tab) { 2707 if (!btf_vmlinux) { 2708 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2709 return -ENOTSUPP; 2710 } 2711 2712 if (!env->prog->jit_requested) { 2713 verbose(env, "JIT is required for calling kernel function\n"); 2714 return -ENOTSUPP; 2715 } 2716 2717 if (!bpf_jit_supports_kfunc_call()) { 2718 verbose(env, "JIT does not support calling kernel function\n"); 2719 return -ENOTSUPP; 2720 } 2721 2722 if (!env->prog->gpl_compatible) { 2723 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2724 return -EINVAL; 2725 } 2726 2727 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 2728 if (!tab) 2729 return -ENOMEM; 2730 prog_aux->kfunc_tab = tab; 2731 } 2732 2733 /* func_id == 0 is always invalid, but instead of returning an error, be 2734 * conservative and wait until the code elimination pass before returning 2735 * error, so that invalid calls that get pruned out can be in BPF programs 2736 * loaded from userspace. It is also required that offset be untouched 2737 * for such calls. 2738 */ 2739 if (!func_id && !offset) 2740 return 0; 2741 2742 if (!btf_tab && offset) { 2743 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 2744 if (!btf_tab) 2745 return -ENOMEM; 2746 prog_aux->kfunc_btf_tab = btf_tab; 2747 } 2748 2749 desc_btf = find_kfunc_desc_btf(env, offset); 2750 if (IS_ERR(desc_btf)) { 2751 verbose(env, "failed to find BTF for kernel function\n"); 2752 return PTR_ERR(desc_btf); 2753 } 2754 2755 if (find_kfunc_desc(env->prog, func_id, offset)) 2756 return 0; 2757 2758 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2759 verbose(env, "too many different kernel function calls\n"); 2760 return -E2BIG; 2761 } 2762 2763 func = btf_type_by_id(desc_btf, func_id); 2764 if (!func || !btf_type_is_func(func)) { 2765 verbose(env, "kernel btf_id %u is not a function\n", 2766 func_id); 2767 return -EINVAL; 2768 } 2769 func_proto = btf_type_by_id(desc_btf, func->type); 2770 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2771 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 2772 func_id); 2773 return -EINVAL; 2774 } 2775 2776 func_name = btf_name_by_offset(desc_btf, func->name_off); 2777 addr = kallsyms_lookup_name(func_name); 2778 if (!addr) { 2779 verbose(env, "cannot find address for kernel function %s\n", 2780 func_name); 2781 return -EINVAL; 2782 } 2783 specialize_kfunc(env, func_id, offset, &addr); 2784 2785 if (bpf_jit_supports_far_kfunc_call()) { 2786 call_imm = func_id; 2787 } else { 2788 call_imm = BPF_CALL_IMM(addr); 2789 /* Check whether the relative offset overflows desc->imm */ 2790 if ((unsigned long)(s32)call_imm != call_imm) { 2791 verbose(env, "address of kernel function %s is out of range\n", 2792 func_name); 2793 return -EINVAL; 2794 } 2795 } 2796 2797 if (bpf_dev_bound_kfunc_id(func_id)) { 2798 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2799 if (err) 2800 return err; 2801 } 2802 2803 desc = &tab->descs[tab->nr_descs++]; 2804 desc->func_id = func_id; 2805 desc->imm = call_imm; 2806 desc->offset = offset; 2807 desc->addr = addr; 2808 err = btf_distill_func_proto(&env->log, desc_btf, 2809 func_proto, func_name, 2810 &desc->func_model); 2811 if (!err) 2812 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2813 kfunc_desc_cmp_by_id_off, NULL); 2814 return err; 2815 } 2816 2817 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b) 2818 { 2819 const struct bpf_kfunc_desc *d0 = a; 2820 const struct bpf_kfunc_desc *d1 = b; 2821 2822 if (d0->imm != d1->imm) 2823 return d0->imm < d1->imm ? -1 : 1; 2824 if (d0->offset != d1->offset) 2825 return d0->offset < d1->offset ? -1 : 1; 2826 return 0; 2827 } 2828 2829 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog) 2830 { 2831 struct bpf_kfunc_desc_tab *tab; 2832 2833 tab = prog->aux->kfunc_tab; 2834 if (!tab) 2835 return; 2836 2837 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2838 kfunc_desc_cmp_by_imm_off, NULL); 2839 } 2840 2841 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2842 { 2843 return !!prog->aux->kfunc_tab; 2844 } 2845 2846 const struct btf_func_model * 2847 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 2848 const struct bpf_insn *insn) 2849 { 2850 const struct bpf_kfunc_desc desc = { 2851 .imm = insn->imm, 2852 .offset = insn->off, 2853 }; 2854 const struct bpf_kfunc_desc *res; 2855 struct bpf_kfunc_desc_tab *tab; 2856 2857 tab = prog->aux->kfunc_tab; 2858 res = bsearch(&desc, tab->descs, tab->nr_descs, 2859 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off); 2860 2861 return res ? &res->func_model : NULL; 2862 } 2863 2864 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 2865 { 2866 struct bpf_subprog_info *subprog = env->subprog_info; 2867 int i, ret, insn_cnt = env->prog->len, ex_cb_insn; 2868 struct bpf_insn *insn = env->prog->insnsi; 2869 2870 /* Add entry function. */ 2871 ret = add_subprog(env, 0); 2872 if (ret) 2873 return ret; 2874 2875 for (i = 0; i < insn_cnt; i++, insn++) { 2876 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 2877 !bpf_pseudo_kfunc_call(insn)) 2878 continue; 2879 2880 if (!env->bpf_capable) { 2881 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2882 return -EPERM; 2883 } 2884 2885 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 2886 ret = add_subprog(env, i + insn->imm + 1); 2887 else 2888 ret = add_kfunc_call(env, insn->imm, insn->off); 2889 2890 if (ret < 0) 2891 return ret; 2892 } 2893 2894 ret = bpf_find_exception_callback_insn_off(env); 2895 if (ret < 0) 2896 return ret; 2897 ex_cb_insn = ret; 2898 2899 /* If ex_cb_insn > 0, this means that the main program has a subprog 2900 * marked using BTF decl tag to serve as the exception callback. 2901 */ 2902 if (ex_cb_insn) { 2903 ret = add_subprog(env, ex_cb_insn); 2904 if (ret < 0) 2905 return ret; 2906 for (i = 1; i < env->subprog_cnt; i++) { 2907 if (env->subprog_info[i].start != ex_cb_insn) 2908 continue; 2909 env->exception_callback_subprog = i; 2910 mark_subprog_exc_cb(env, i); 2911 break; 2912 } 2913 } 2914 2915 /* Add a fake 'exit' subprog which could simplify subprog iteration 2916 * logic. 'subprog_cnt' should not be increased. 2917 */ 2918 subprog[env->subprog_cnt].start = insn_cnt; 2919 2920 if (env->log.level & BPF_LOG_LEVEL2) 2921 for (i = 0; i < env->subprog_cnt; i++) 2922 verbose(env, "func#%d @%d\n", i, subprog[i].start); 2923 2924 return 0; 2925 } 2926 2927 static int check_subprogs(struct bpf_verifier_env *env) 2928 { 2929 int i, subprog_start, subprog_end, off, cur_subprog = 0; 2930 struct bpf_subprog_info *subprog = env->subprog_info; 2931 struct bpf_insn *insn = env->prog->insnsi; 2932 int insn_cnt = env->prog->len; 2933 2934 /* now check that all jumps are within the same subprog */ 2935 subprog_start = subprog[cur_subprog].start; 2936 subprog_end = subprog[cur_subprog + 1].start; 2937 for (i = 0; i < insn_cnt; i++) { 2938 u8 code = insn[i].code; 2939 2940 if (code == (BPF_JMP | BPF_CALL) && 2941 insn[i].src_reg == 0 && 2942 insn[i].imm == BPF_FUNC_tail_call) 2943 subprog[cur_subprog].has_tail_call = true; 2944 if (BPF_CLASS(code) == BPF_LD && 2945 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 2946 subprog[cur_subprog].has_ld_abs = true; 2947 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 2948 goto next; 2949 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 2950 goto next; 2951 if (code == (BPF_JMP32 | BPF_JA)) 2952 off = i + insn[i].imm + 1; 2953 else 2954 off = i + insn[i].off + 1; 2955 if (off < subprog_start || off >= subprog_end) { 2956 verbose(env, "jump out of range from insn %d to %d\n", i, off); 2957 return -EINVAL; 2958 } 2959 next: 2960 if (i == subprog_end - 1) { 2961 /* to avoid fall-through from one subprog into another 2962 * the last insn of the subprog should be either exit 2963 * or unconditional jump back or bpf_throw call 2964 */ 2965 if (code != (BPF_JMP | BPF_EXIT) && 2966 code != (BPF_JMP32 | BPF_JA) && 2967 code != (BPF_JMP | BPF_JA)) { 2968 verbose(env, "last insn is not an exit or jmp\n"); 2969 return -EINVAL; 2970 } 2971 subprog_start = subprog_end; 2972 cur_subprog++; 2973 if (cur_subprog < env->subprog_cnt) 2974 subprog_end = subprog[cur_subprog + 1].start; 2975 } 2976 } 2977 return 0; 2978 } 2979 2980 /* Parentage chain of this register (or stack slot) should take care of all 2981 * issues like callee-saved registers, stack slot allocation time, etc. 2982 */ 2983 static int mark_reg_read(struct bpf_verifier_env *env, 2984 const struct bpf_reg_state *state, 2985 struct bpf_reg_state *parent, u8 flag) 2986 { 2987 bool writes = parent == state->parent; /* Observe write marks */ 2988 int cnt = 0; 2989 2990 while (parent) { 2991 /* if read wasn't screened by an earlier write ... */ 2992 if (writes && state->live & REG_LIVE_WRITTEN) 2993 break; 2994 if (parent->live & REG_LIVE_DONE) { 2995 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 2996 reg_type_str(env, parent->type), 2997 parent->var_off.value, parent->off); 2998 return -EFAULT; 2999 } 3000 /* The first condition is more likely to be true than the 3001 * second, checked it first. 3002 */ 3003 if ((parent->live & REG_LIVE_READ) == flag || 3004 parent->live & REG_LIVE_READ64) 3005 /* The parentage chain never changes and 3006 * this parent was already marked as LIVE_READ. 3007 * There is no need to keep walking the chain again and 3008 * keep re-marking all parents as LIVE_READ. 3009 * This case happens when the same register is read 3010 * multiple times without writes into it in-between. 3011 * Also, if parent has the stronger REG_LIVE_READ64 set, 3012 * then no need to set the weak REG_LIVE_READ32. 3013 */ 3014 break; 3015 /* ... then we depend on parent's value */ 3016 parent->live |= flag; 3017 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 3018 if (flag == REG_LIVE_READ64) 3019 parent->live &= ~REG_LIVE_READ32; 3020 state = parent; 3021 parent = state->parent; 3022 writes = true; 3023 cnt++; 3024 } 3025 3026 if (env->longest_mark_read_walk < cnt) 3027 env->longest_mark_read_walk = cnt; 3028 return 0; 3029 } 3030 3031 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3032 { 3033 struct bpf_func_state *state = func(env, reg); 3034 int spi, ret; 3035 3036 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 3037 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 3038 * check_kfunc_call. 3039 */ 3040 if (reg->type == CONST_PTR_TO_DYNPTR) 3041 return 0; 3042 spi = dynptr_get_spi(env, reg); 3043 if (spi < 0) 3044 return spi; 3045 /* Caller ensures dynptr is valid and initialized, which means spi is in 3046 * bounds and spi is the first dynptr slot. Simply mark stack slot as 3047 * read. 3048 */ 3049 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr, 3050 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64); 3051 if (ret) 3052 return ret; 3053 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr, 3054 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64); 3055 } 3056 3057 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3058 int spi, int nr_slots) 3059 { 3060 struct bpf_func_state *state = func(env, reg); 3061 int err, i; 3062 3063 for (i = 0; i < nr_slots; i++) { 3064 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr; 3065 3066 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64); 3067 if (err) 3068 return err; 3069 3070 mark_stack_slot_scratched(env, spi - i); 3071 } 3072 3073 return 0; 3074 } 3075 3076 /* This function is supposed to be used by the following 32-bit optimization 3077 * code only. It returns TRUE if the source or destination register operates 3078 * on 64-bit, otherwise return FALSE. 3079 */ 3080 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 3081 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 3082 { 3083 u8 code, class, op; 3084 3085 code = insn->code; 3086 class = BPF_CLASS(code); 3087 op = BPF_OP(code); 3088 if (class == BPF_JMP) { 3089 /* BPF_EXIT for "main" will reach here. Return TRUE 3090 * conservatively. 3091 */ 3092 if (op == BPF_EXIT) 3093 return true; 3094 if (op == BPF_CALL) { 3095 /* BPF to BPF call will reach here because of marking 3096 * caller saved clobber with DST_OP_NO_MARK for which we 3097 * don't care the register def because they are anyway 3098 * marked as NOT_INIT already. 3099 */ 3100 if (insn->src_reg == BPF_PSEUDO_CALL) 3101 return false; 3102 /* Helper call will reach here because of arg type 3103 * check, conservatively return TRUE. 3104 */ 3105 if (t == SRC_OP) 3106 return true; 3107 3108 return false; 3109 } 3110 } 3111 3112 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3113 return false; 3114 3115 if (class == BPF_ALU64 || class == BPF_JMP || 3116 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3117 return true; 3118 3119 if (class == BPF_ALU || class == BPF_JMP32) 3120 return false; 3121 3122 if (class == BPF_LDX) { 3123 if (t != SRC_OP) 3124 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX; 3125 /* LDX source must be ptr. */ 3126 return true; 3127 } 3128 3129 if (class == BPF_STX) { 3130 /* BPF_STX (including atomic variants) has multiple source 3131 * operands, one of which is a ptr. Check whether the caller is 3132 * asking about it. 3133 */ 3134 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3135 return true; 3136 return BPF_SIZE(code) == BPF_DW; 3137 } 3138 3139 if (class == BPF_LD) { 3140 u8 mode = BPF_MODE(code); 3141 3142 /* LD_IMM64 */ 3143 if (mode == BPF_IMM) 3144 return true; 3145 3146 /* Both LD_IND and LD_ABS return 32-bit data. */ 3147 if (t != SRC_OP) 3148 return false; 3149 3150 /* Implicit ctx ptr. */ 3151 if (regno == BPF_REG_6) 3152 return true; 3153 3154 /* Explicit source could be any width. */ 3155 return true; 3156 } 3157 3158 if (class == BPF_ST) 3159 /* The only source register for BPF_ST is a ptr. */ 3160 return true; 3161 3162 /* Conservatively return true at default. */ 3163 return true; 3164 } 3165 3166 /* Return the regno defined by the insn, or -1. */ 3167 static int insn_def_regno(const struct bpf_insn *insn) 3168 { 3169 switch (BPF_CLASS(insn->code)) { 3170 case BPF_JMP: 3171 case BPF_JMP32: 3172 case BPF_ST: 3173 return -1; 3174 case BPF_STX: 3175 if (BPF_MODE(insn->code) == BPF_ATOMIC && 3176 (insn->imm & BPF_FETCH)) { 3177 if (insn->imm == BPF_CMPXCHG) 3178 return BPF_REG_0; 3179 else 3180 return insn->src_reg; 3181 } else { 3182 return -1; 3183 } 3184 default: 3185 return insn->dst_reg; 3186 } 3187 } 3188 3189 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 3190 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 3191 { 3192 int dst_reg = insn_def_regno(insn); 3193 3194 if (dst_reg == -1) 3195 return false; 3196 3197 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 3198 } 3199 3200 static void mark_insn_zext(struct bpf_verifier_env *env, 3201 struct bpf_reg_state *reg) 3202 { 3203 s32 def_idx = reg->subreg_def; 3204 3205 if (def_idx == DEF_NOT_SUBREG) 3206 return; 3207 3208 env->insn_aux_data[def_idx - 1].zext_dst = true; 3209 /* The dst will be zero extended, so won't be sub-register anymore. */ 3210 reg->subreg_def = DEF_NOT_SUBREG; 3211 } 3212 3213 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno, 3214 enum reg_arg_type t) 3215 { 3216 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3217 struct bpf_reg_state *reg; 3218 bool rw64; 3219 3220 if (regno >= MAX_BPF_REG) { 3221 verbose(env, "R%d is invalid\n", regno); 3222 return -EINVAL; 3223 } 3224 3225 mark_reg_scratched(env, regno); 3226 3227 reg = ®s[regno]; 3228 rw64 = is_reg64(env, insn, regno, reg, t); 3229 if (t == SRC_OP) { 3230 /* check whether register used as source operand can be read */ 3231 if (reg->type == NOT_INIT) { 3232 verbose(env, "R%d !read_ok\n", regno); 3233 return -EACCES; 3234 } 3235 /* We don't need to worry about FP liveness because it's read-only */ 3236 if (regno == BPF_REG_FP) 3237 return 0; 3238 3239 if (rw64) 3240 mark_insn_zext(env, reg); 3241 3242 return mark_reg_read(env, reg, reg->parent, 3243 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 3244 } else { 3245 /* check whether register used as dest operand can be written to */ 3246 if (regno == BPF_REG_FP) { 3247 verbose(env, "frame pointer is read only\n"); 3248 return -EACCES; 3249 } 3250 reg->live |= REG_LIVE_WRITTEN; 3251 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3252 if (t == DST_OP) 3253 mark_reg_unknown(env, regs, regno); 3254 } 3255 return 0; 3256 } 3257 3258 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3259 enum reg_arg_type t) 3260 { 3261 struct bpf_verifier_state *vstate = env->cur_state; 3262 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3263 3264 return __check_reg_arg(env, state->regs, regno, t); 3265 } 3266 3267 static int insn_stack_access_flags(int frameno, int spi) 3268 { 3269 return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno; 3270 } 3271 3272 static int insn_stack_access_spi(int insn_flags) 3273 { 3274 return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK; 3275 } 3276 3277 static int insn_stack_access_frameno(int insn_flags) 3278 { 3279 return insn_flags & INSN_F_FRAMENO_MASK; 3280 } 3281 3282 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 3283 { 3284 env->insn_aux_data[idx].jmp_point = true; 3285 } 3286 3287 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 3288 { 3289 return env->insn_aux_data[insn_idx].jmp_point; 3290 } 3291 3292 /* for any branch, call, exit record the history of jmps in the given state */ 3293 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur, 3294 int insn_flags) 3295 { 3296 u32 cnt = cur->jmp_history_cnt; 3297 struct bpf_jmp_history_entry *p; 3298 size_t alloc_size; 3299 3300 /* combine instruction flags if we already recorded this instruction */ 3301 if (env->cur_hist_ent) { 3302 /* atomic instructions push insn_flags twice, for READ and 3303 * WRITE sides, but they should agree on stack slot 3304 */ 3305 WARN_ONCE((env->cur_hist_ent->flags & insn_flags) && 3306 (env->cur_hist_ent->flags & insn_flags) != insn_flags, 3307 "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n", 3308 env->insn_idx, env->cur_hist_ent->flags, insn_flags); 3309 env->cur_hist_ent->flags |= insn_flags; 3310 return 0; 3311 } 3312 3313 cnt++; 3314 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 3315 p = krealloc(cur->jmp_history, alloc_size, GFP_USER); 3316 if (!p) 3317 return -ENOMEM; 3318 cur->jmp_history = p; 3319 3320 p = &cur->jmp_history[cnt - 1]; 3321 p->idx = env->insn_idx; 3322 p->prev_idx = env->prev_insn_idx; 3323 p->flags = insn_flags; 3324 cur->jmp_history_cnt = cnt; 3325 env->cur_hist_ent = p; 3326 3327 return 0; 3328 } 3329 3330 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st, 3331 u32 hist_end, int insn_idx) 3332 { 3333 if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx) 3334 return &st->jmp_history[hist_end - 1]; 3335 return NULL; 3336 } 3337 3338 /* Backtrack one insn at a time. If idx is not at the top of recorded 3339 * history then previous instruction came from straight line execution. 3340 * Return -ENOENT if we exhausted all instructions within given state. 3341 * 3342 * It's legal to have a bit of a looping with the same starting and ending 3343 * insn index within the same state, e.g.: 3->4->5->3, so just because current 3344 * instruction index is the same as state's first_idx doesn't mean we are 3345 * done. If there is still some jump history left, we should keep going. We 3346 * need to take into account that we might have a jump history between given 3347 * state's parent and itself, due to checkpointing. In this case, we'll have 3348 * history entry recording a jump from last instruction of parent state and 3349 * first instruction of given state. 3350 */ 3351 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 3352 u32 *history) 3353 { 3354 u32 cnt = *history; 3355 3356 if (i == st->first_insn_idx) { 3357 if (cnt == 0) 3358 return -ENOENT; 3359 if (cnt == 1 && st->jmp_history[0].idx == i) 3360 return -ENOENT; 3361 } 3362 3363 if (cnt && st->jmp_history[cnt - 1].idx == i) { 3364 i = st->jmp_history[cnt - 1].prev_idx; 3365 (*history)--; 3366 } else { 3367 i--; 3368 } 3369 return i; 3370 } 3371 3372 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3373 { 3374 const struct btf_type *func; 3375 struct btf *desc_btf; 3376 3377 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3378 return NULL; 3379 3380 desc_btf = find_kfunc_desc_btf(data, insn->off); 3381 if (IS_ERR(desc_btf)) 3382 return "<error>"; 3383 3384 func = btf_type_by_id(desc_btf, insn->imm); 3385 return btf_name_by_offset(desc_btf, func->name_off); 3386 } 3387 3388 static inline void bt_init(struct backtrack_state *bt, u32 frame) 3389 { 3390 bt->frame = frame; 3391 } 3392 3393 static inline void bt_reset(struct backtrack_state *bt) 3394 { 3395 struct bpf_verifier_env *env = bt->env; 3396 3397 memset(bt, 0, sizeof(*bt)); 3398 bt->env = env; 3399 } 3400 3401 static inline u32 bt_empty(struct backtrack_state *bt) 3402 { 3403 u64 mask = 0; 3404 int i; 3405 3406 for (i = 0; i <= bt->frame; i++) 3407 mask |= bt->reg_masks[i] | bt->stack_masks[i]; 3408 3409 return mask == 0; 3410 } 3411 3412 static inline int bt_subprog_enter(struct backtrack_state *bt) 3413 { 3414 if (bt->frame == MAX_CALL_FRAMES - 1) { 3415 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame); 3416 WARN_ONCE(1, "verifier backtracking bug"); 3417 return -EFAULT; 3418 } 3419 bt->frame++; 3420 return 0; 3421 } 3422 3423 static inline int bt_subprog_exit(struct backtrack_state *bt) 3424 { 3425 if (bt->frame == 0) { 3426 verbose(bt->env, "BUG subprog exit from frame 0\n"); 3427 WARN_ONCE(1, "verifier backtracking bug"); 3428 return -EFAULT; 3429 } 3430 bt->frame--; 3431 return 0; 3432 } 3433 3434 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3435 { 3436 bt->reg_masks[frame] |= 1 << reg; 3437 } 3438 3439 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3440 { 3441 bt->reg_masks[frame] &= ~(1 << reg); 3442 } 3443 3444 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg) 3445 { 3446 bt_set_frame_reg(bt, bt->frame, reg); 3447 } 3448 3449 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg) 3450 { 3451 bt_clear_frame_reg(bt, bt->frame, reg); 3452 } 3453 3454 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3455 { 3456 bt->stack_masks[frame] |= 1ull << slot; 3457 } 3458 3459 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3460 { 3461 bt->stack_masks[frame] &= ~(1ull << slot); 3462 } 3463 3464 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame) 3465 { 3466 return bt->reg_masks[frame]; 3467 } 3468 3469 static inline u32 bt_reg_mask(struct backtrack_state *bt) 3470 { 3471 return bt->reg_masks[bt->frame]; 3472 } 3473 3474 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame) 3475 { 3476 return bt->stack_masks[frame]; 3477 } 3478 3479 static inline u64 bt_stack_mask(struct backtrack_state *bt) 3480 { 3481 return bt->stack_masks[bt->frame]; 3482 } 3483 3484 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg) 3485 { 3486 return bt->reg_masks[bt->frame] & (1 << reg); 3487 } 3488 3489 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot) 3490 { 3491 return bt->stack_masks[frame] & (1ull << slot); 3492 } 3493 3494 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */ 3495 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask) 3496 { 3497 DECLARE_BITMAP(mask, 64); 3498 bool first = true; 3499 int i, n; 3500 3501 buf[0] = '\0'; 3502 3503 bitmap_from_u64(mask, reg_mask); 3504 for_each_set_bit(i, mask, 32) { 3505 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i); 3506 first = false; 3507 buf += n; 3508 buf_sz -= n; 3509 if (buf_sz < 0) 3510 break; 3511 } 3512 } 3513 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */ 3514 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask) 3515 { 3516 DECLARE_BITMAP(mask, 64); 3517 bool first = true; 3518 int i, n; 3519 3520 buf[0] = '\0'; 3521 3522 bitmap_from_u64(mask, stack_mask); 3523 for_each_set_bit(i, mask, 64) { 3524 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8); 3525 first = false; 3526 buf += n; 3527 buf_sz -= n; 3528 if (buf_sz < 0) 3529 break; 3530 } 3531 } 3532 3533 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx); 3534 3535 /* For given verifier state backtrack_insn() is called from the last insn to 3536 * the first insn. Its purpose is to compute a bitmask of registers and 3537 * stack slots that needs precision in the parent verifier state. 3538 * 3539 * @idx is an index of the instruction we are currently processing; 3540 * @subseq_idx is an index of the subsequent instruction that: 3541 * - *would be* executed next, if jump history is viewed in forward order; 3542 * - *was* processed previously during backtracking. 3543 */ 3544 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx, 3545 struct bpf_jmp_history_entry *hist, struct backtrack_state *bt) 3546 { 3547 const struct bpf_insn_cbs cbs = { 3548 .cb_call = disasm_kfunc_name, 3549 .cb_print = verbose, 3550 .private_data = env, 3551 }; 3552 struct bpf_insn *insn = env->prog->insnsi + idx; 3553 u8 class = BPF_CLASS(insn->code); 3554 u8 opcode = BPF_OP(insn->code); 3555 u8 mode = BPF_MODE(insn->code); 3556 u32 dreg = insn->dst_reg; 3557 u32 sreg = insn->src_reg; 3558 u32 spi, i, fr; 3559 3560 if (insn->code == 0) 3561 return 0; 3562 if (env->log.level & BPF_LOG_LEVEL2) { 3563 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt)); 3564 verbose(env, "mark_precise: frame%d: regs=%s ", 3565 bt->frame, env->tmp_str_buf); 3566 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt)); 3567 verbose(env, "stack=%s before ", env->tmp_str_buf); 3568 verbose(env, "%d: ", idx); 3569 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3570 } 3571 3572 if (class == BPF_ALU || class == BPF_ALU64) { 3573 if (!bt_is_reg_set(bt, dreg)) 3574 return 0; 3575 if (opcode == BPF_END || opcode == BPF_NEG) { 3576 /* sreg is reserved and unused 3577 * dreg still need precision before this insn 3578 */ 3579 return 0; 3580 } else if (opcode == BPF_MOV) { 3581 if (BPF_SRC(insn->code) == BPF_X) { 3582 /* dreg = sreg or dreg = (s8, s16, s32)sreg 3583 * dreg needs precision after this insn 3584 * sreg needs precision before this insn 3585 */ 3586 bt_clear_reg(bt, dreg); 3587 bt_set_reg(bt, sreg); 3588 } else { 3589 /* dreg = K 3590 * dreg needs precision after this insn. 3591 * Corresponding register is already marked 3592 * as precise=true in this verifier state. 3593 * No further markings in parent are necessary 3594 */ 3595 bt_clear_reg(bt, dreg); 3596 } 3597 } else { 3598 if (BPF_SRC(insn->code) == BPF_X) { 3599 /* dreg += sreg 3600 * both dreg and sreg need precision 3601 * before this insn 3602 */ 3603 bt_set_reg(bt, sreg); 3604 } /* else dreg += K 3605 * dreg still needs precision before this insn 3606 */ 3607 } 3608 } else if (class == BPF_LDX) { 3609 if (!bt_is_reg_set(bt, dreg)) 3610 return 0; 3611 bt_clear_reg(bt, dreg); 3612 3613 /* scalars can only be spilled into stack w/o losing precision. 3614 * Load from any other memory can be zero extended. 3615 * The desire to keep that precision is already indicated 3616 * by 'precise' mark in corresponding register of this state. 3617 * No further tracking necessary. 3618 */ 3619 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 3620 return 0; 3621 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 3622 * that [fp - off] slot contains scalar that needs to be 3623 * tracked with precision 3624 */ 3625 spi = insn_stack_access_spi(hist->flags); 3626 fr = insn_stack_access_frameno(hist->flags); 3627 bt_set_frame_slot(bt, fr, spi); 3628 } else if (class == BPF_STX || class == BPF_ST) { 3629 if (bt_is_reg_set(bt, dreg)) 3630 /* stx & st shouldn't be using _scalar_ dst_reg 3631 * to access memory. It means backtracking 3632 * encountered a case of pointer subtraction. 3633 */ 3634 return -ENOTSUPP; 3635 /* scalars can only be spilled into stack */ 3636 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 3637 return 0; 3638 spi = insn_stack_access_spi(hist->flags); 3639 fr = insn_stack_access_frameno(hist->flags); 3640 if (!bt_is_frame_slot_set(bt, fr, spi)) 3641 return 0; 3642 bt_clear_frame_slot(bt, fr, spi); 3643 if (class == BPF_STX) 3644 bt_set_reg(bt, sreg); 3645 } else if (class == BPF_JMP || class == BPF_JMP32) { 3646 if (bpf_pseudo_call(insn)) { 3647 int subprog_insn_idx, subprog; 3648 3649 subprog_insn_idx = idx + insn->imm + 1; 3650 subprog = find_subprog(env, subprog_insn_idx); 3651 if (subprog < 0) 3652 return -EFAULT; 3653 3654 if (subprog_is_global(env, subprog)) { 3655 /* check that jump history doesn't have any 3656 * extra instructions from subprog; the next 3657 * instruction after call to global subprog 3658 * should be literally next instruction in 3659 * caller program 3660 */ 3661 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug"); 3662 /* r1-r5 are invalidated after subprog call, 3663 * so for global func call it shouldn't be set 3664 * anymore 3665 */ 3666 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3667 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3668 WARN_ONCE(1, "verifier backtracking bug"); 3669 return -EFAULT; 3670 } 3671 /* global subprog always sets R0 */ 3672 bt_clear_reg(bt, BPF_REG_0); 3673 return 0; 3674 } else { 3675 /* static subprog call instruction, which 3676 * means that we are exiting current subprog, 3677 * so only r1-r5 could be still requested as 3678 * precise, r0 and r6-r10 or any stack slot in 3679 * the current frame should be zero by now 3680 */ 3681 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3682 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3683 WARN_ONCE(1, "verifier backtracking bug"); 3684 return -EFAULT; 3685 } 3686 /* we are now tracking register spills correctly, 3687 * so any instance of leftover slots is a bug 3688 */ 3689 if (bt_stack_mask(bt) != 0) { 3690 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt)); 3691 WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)"); 3692 return -EFAULT; 3693 } 3694 /* propagate r1-r5 to the caller */ 3695 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 3696 if (bt_is_reg_set(bt, i)) { 3697 bt_clear_reg(bt, i); 3698 bt_set_frame_reg(bt, bt->frame - 1, i); 3699 } 3700 } 3701 if (bt_subprog_exit(bt)) 3702 return -EFAULT; 3703 return 0; 3704 } 3705 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) { 3706 /* exit from callback subprog to callback-calling helper or 3707 * kfunc call. Use idx/subseq_idx check to discern it from 3708 * straight line code backtracking. 3709 * Unlike the subprog call handling above, we shouldn't 3710 * propagate precision of r1-r5 (if any requested), as they are 3711 * not actually arguments passed directly to callback subprogs 3712 */ 3713 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3714 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3715 WARN_ONCE(1, "verifier backtracking bug"); 3716 return -EFAULT; 3717 } 3718 if (bt_stack_mask(bt) != 0) { 3719 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt)); 3720 WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)"); 3721 return -EFAULT; 3722 } 3723 /* clear r1-r5 in callback subprog's mask */ 3724 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3725 bt_clear_reg(bt, i); 3726 if (bt_subprog_exit(bt)) 3727 return -EFAULT; 3728 return 0; 3729 } else if (opcode == BPF_CALL) { 3730 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 3731 * catch this error later. Make backtracking conservative 3732 * with ENOTSUPP. 3733 */ 3734 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 3735 return -ENOTSUPP; 3736 /* regular helper call sets R0 */ 3737 bt_clear_reg(bt, BPF_REG_0); 3738 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3739 /* if backtracing was looking for registers R1-R5 3740 * they should have been found already. 3741 */ 3742 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3743 WARN_ONCE(1, "verifier backtracking bug"); 3744 return -EFAULT; 3745 } 3746 } else if (opcode == BPF_EXIT) { 3747 bool r0_precise; 3748 3749 /* Backtracking to a nested function call, 'idx' is a part of 3750 * the inner frame 'subseq_idx' is a part of the outer frame. 3751 * In case of a regular function call, instructions giving 3752 * precision to registers R1-R5 should have been found already. 3753 * In case of a callback, it is ok to have R1-R5 marked for 3754 * backtracking, as these registers are set by the function 3755 * invoking callback. 3756 */ 3757 if (subseq_idx >= 0 && calls_callback(env, subseq_idx)) 3758 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3759 bt_clear_reg(bt, i); 3760 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3761 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3762 WARN_ONCE(1, "verifier backtracking bug"); 3763 return -EFAULT; 3764 } 3765 3766 /* BPF_EXIT in subprog or callback always returns 3767 * right after the call instruction, so by checking 3768 * whether the instruction at subseq_idx-1 is subprog 3769 * call or not we can distinguish actual exit from 3770 * *subprog* from exit from *callback*. In the former 3771 * case, we need to propagate r0 precision, if 3772 * necessary. In the former we never do that. 3773 */ 3774 r0_precise = subseq_idx - 1 >= 0 && 3775 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) && 3776 bt_is_reg_set(bt, BPF_REG_0); 3777 3778 bt_clear_reg(bt, BPF_REG_0); 3779 if (bt_subprog_enter(bt)) 3780 return -EFAULT; 3781 3782 if (r0_precise) 3783 bt_set_reg(bt, BPF_REG_0); 3784 /* r6-r9 and stack slots will stay set in caller frame 3785 * bitmasks until we return back from callee(s) 3786 */ 3787 return 0; 3788 } else if (BPF_SRC(insn->code) == BPF_X) { 3789 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg)) 3790 return 0; 3791 /* dreg <cond> sreg 3792 * Both dreg and sreg need precision before 3793 * this insn. If only sreg was marked precise 3794 * before it would be equally necessary to 3795 * propagate it to dreg. 3796 */ 3797 bt_set_reg(bt, dreg); 3798 bt_set_reg(bt, sreg); 3799 /* else dreg <cond> K 3800 * Only dreg still needs precision before 3801 * this insn, so for the K-based conditional 3802 * there is nothing new to be marked. 3803 */ 3804 } 3805 } else if (class == BPF_LD) { 3806 if (!bt_is_reg_set(bt, dreg)) 3807 return 0; 3808 bt_clear_reg(bt, dreg); 3809 /* It's ld_imm64 or ld_abs or ld_ind. 3810 * For ld_imm64 no further tracking of precision 3811 * into parent is necessary 3812 */ 3813 if (mode == BPF_IND || mode == BPF_ABS) 3814 /* to be analyzed */ 3815 return -ENOTSUPP; 3816 } 3817 return 0; 3818 } 3819 3820 /* the scalar precision tracking algorithm: 3821 * . at the start all registers have precise=false. 3822 * . scalar ranges are tracked as normal through alu and jmp insns. 3823 * . once precise value of the scalar register is used in: 3824 * . ptr + scalar alu 3825 * . if (scalar cond K|scalar) 3826 * . helper_call(.., scalar, ...) where ARG_CONST is expected 3827 * backtrack through the verifier states and mark all registers and 3828 * stack slots with spilled constants that these scalar regisers 3829 * should be precise. 3830 * . during state pruning two registers (or spilled stack slots) 3831 * are equivalent if both are not precise. 3832 * 3833 * Note the verifier cannot simply walk register parentage chain, 3834 * since many different registers and stack slots could have been 3835 * used to compute single precise scalar. 3836 * 3837 * The approach of starting with precise=true for all registers and then 3838 * backtrack to mark a register as not precise when the verifier detects 3839 * that program doesn't care about specific value (e.g., when helper 3840 * takes register as ARG_ANYTHING parameter) is not safe. 3841 * 3842 * It's ok to walk single parentage chain of the verifier states. 3843 * It's possible that this backtracking will go all the way till 1st insn. 3844 * All other branches will be explored for needing precision later. 3845 * 3846 * The backtracking needs to deal with cases like: 3847 * 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) 3848 * r9 -= r8 3849 * r5 = r9 3850 * if r5 > 0x79f goto pc+7 3851 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 3852 * r5 += 1 3853 * ... 3854 * call bpf_perf_event_output#25 3855 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 3856 * 3857 * and this case: 3858 * r6 = 1 3859 * call foo // uses callee's r6 inside to compute r0 3860 * r0 += r6 3861 * if r0 == 0 goto 3862 * 3863 * to track above reg_mask/stack_mask needs to be independent for each frame. 3864 * 3865 * Also if parent's curframe > frame where backtracking started, 3866 * the verifier need to mark registers in both frames, otherwise callees 3867 * may incorrectly prune callers. This is similar to 3868 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 3869 * 3870 * For now backtracking falls back into conservative marking. 3871 */ 3872 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 3873 struct bpf_verifier_state *st) 3874 { 3875 struct bpf_func_state *func; 3876 struct bpf_reg_state *reg; 3877 int i, j; 3878 3879 if (env->log.level & BPF_LOG_LEVEL2) { 3880 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n", 3881 st->curframe); 3882 } 3883 3884 /* big hammer: mark all scalars precise in this path. 3885 * pop_stack may still get !precise scalars. 3886 * We also skip current state and go straight to first parent state, 3887 * because precision markings in current non-checkpointed state are 3888 * not needed. See why in the comment in __mark_chain_precision below. 3889 */ 3890 for (st = st->parent; st; st = st->parent) { 3891 for (i = 0; i <= st->curframe; i++) { 3892 func = st->frame[i]; 3893 for (j = 0; j < BPF_REG_FP; j++) { 3894 reg = &func->regs[j]; 3895 if (reg->type != SCALAR_VALUE || reg->precise) 3896 continue; 3897 reg->precise = true; 3898 if (env->log.level & BPF_LOG_LEVEL2) { 3899 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n", 3900 i, j); 3901 } 3902 } 3903 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3904 if (!is_spilled_reg(&func->stack[j])) 3905 continue; 3906 reg = &func->stack[j].spilled_ptr; 3907 if (reg->type != SCALAR_VALUE || reg->precise) 3908 continue; 3909 reg->precise = true; 3910 if (env->log.level & BPF_LOG_LEVEL2) { 3911 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n", 3912 i, -(j + 1) * 8); 3913 } 3914 } 3915 } 3916 } 3917 } 3918 3919 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 3920 { 3921 struct bpf_func_state *func; 3922 struct bpf_reg_state *reg; 3923 int i, j; 3924 3925 for (i = 0; i <= st->curframe; i++) { 3926 func = st->frame[i]; 3927 for (j = 0; j < BPF_REG_FP; j++) { 3928 reg = &func->regs[j]; 3929 if (reg->type != SCALAR_VALUE) 3930 continue; 3931 reg->precise = false; 3932 } 3933 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3934 if (!is_spilled_reg(&func->stack[j])) 3935 continue; 3936 reg = &func->stack[j].spilled_ptr; 3937 if (reg->type != SCALAR_VALUE) 3938 continue; 3939 reg->precise = false; 3940 } 3941 } 3942 } 3943 3944 static bool idset_contains(struct bpf_idset *s, u32 id) 3945 { 3946 u32 i; 3947 3948 for (i = 0; i < s->count; ++i) 3949 if (s->ids[i] == id) 3950 return true; 3951 3952 return false; 3953 } 3954 3955 static int idset_push(struct bpf_idset *s, u32 id) 3956 { 3957 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids))) 3958 return -EFAULT; 3959 s->ids[s->count++] = id; 3960 return 0; 3961 } 3962 3963 static void idset_reset(struct bpf_idset *s) 3964 { 3965 s->count = 0; 3966 } 3967 3968 /* Collect a set of IDs for all registers currently marked as precise in env->bt. 3969 * Mark all registers with these IDs as precise. 3970 */ 3971 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 3972 { 3973 struct bpf_idset *precise_ids = &env->idset_scratch; 3974 struct backtrack_state *bt = &env->bt; 3975 struct bpf_func_state *func; 3976 struct bpf_reg_state *reg; 3977 DECLARE_BITMAP(mask, 64); 3978 int i, fr; 3979 3980 idset_reset(precise_ids); 3981 3982 for (fr = bt->frame; fr >= 0; fr--) { 3983 func = st->frame[fr]; 3984 3985 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 3986 for_each_set_bit(i, mask, 32) { 3987 reg = &func->regs[i]; 3988 if (!reg->id || reg->type != SCALAR_VALUE) 3989 continue; 3990 if (idset_push(precise_ids, reg->id)) 3991 return -EFAULT; 3992 } 3993 3994 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 3995 for_each_set_bit(i, mask, 64) { 3996 if (i >= func->allocated_stack / BPF_REG_SIZE) 3997 break; 3998 if (!is_spilled_scalar_reg(&func->stack[i])) 3999 continue; 4000 reg = &func->stack[i].spilled_ptr; 4001 if (!reg->id) 4002 continue; 4003 if (idset_push(precise_ids, reg->id)) 4004 return -EFAULT; 4005 } 4006 } 4007 4008 for (fr = 0; fr <= st->curframe; ++fr) { 4009 func = st->frame[fr]; 4010 4011 for (i = BPF_REG_0; i < BPF_REG_10; ++i) { 4012 reg = &func->regs[i]; 4013 if (!reg->id) 4014 continue; 4015 if (!idset_contains(precise_ids, reg->id)) 4016 continue; 4017 bt_set_frame_reg(bt, fr, i); 4018 } 4019 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) { 4020 if (!is_spilled_scalar_reg(&func->stack[i])) 4021 continue; 4022 reg = &func->stack[i].spilled_ptr; 4023 if (!reg->id) 4024 continue; 4025 if (!idset_contains(precise_ids, reg->id)) 4026 continue; 4027 bt_set_frame_slot(bt, fr, i); 4028 } 4029 } 4030 4031 return 0; 4032 } 4033 4034 /* 4035 * __mark_chain_precision() backtracks BPF program instruction sequence and 4036 * chain of verifier states making sure that register *regno* (if regno >= 0) 4037 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 4038 * SCALARS, as well as any other registers and slots that contribute to 4039 * a tracked state of given registers/stack slots, depending on specific BPF 4040 * assembly instructions (see backtrack_insns() for exact instruction handling 4041 * logic). This backtracking relies on recorded jmp_history and is able to 4042 * traverse entire chain of parent states. This process ends only when all the 4043 * necessary registers/slots and their transitive dependencies are marked as 4044 * precise. 4045 * 4046 * One important and subtle aspect is that precise marks *do not matter* in 4047 * the currently verified state (current state). It is important to understand 4048 * why this is the case. 4049 * 4050 * First, note that current state is the state that is not yet "checkpointed", 4051 * i.e., it is not yet put into env->explored_states, and it has no children 4052 * states as well. It's ephemeral, and can end up either a) being discarded if 4053 * compatible explored state is found at some point or BPF_EXIT instruction is 4054 * reached or b) checkpointed and put into env->explored_states, branching out 4055 * into one or more children states. 4056 * 4057 * In the former case, precise markings in current state are completely 4058 * ignored by state comparison code (see regsafe() for details). Only 4059 * checkpointed ("old") state precise markings are important, and if old 4060 * state's register/slot is precise, regsafe() assumes current state's 4061 * register/slot as precise and checks value ranges exactly and precisely. If 4062 * states turn out to be compatible, current state's necessary precise 4063 * markings and any required parent states' precise markings are enforced 4064 * after the fact with propagate_precision() logic, after the fact. But it's 4065 * important to realize that in this case, even after marking current state 4066 * registers/slots as precise, we immediately discard current state. So what 4067 * actually matters is any of the precise markings propagated into current 4068 * state's parent states, which are always checkpointed (due to b) case above). 4069 * As such, for scenario a) it doesn't matter if current state has precise 4070 * markings set or not. 4071 * 4072 * Now, for the scenario b), checkpointing and forking into child(ren) 4073 * state(s). Note that before current state gets to checkpointing step, any 4074 * processed instruction always assumes precise SCALAR register/slot 4075 * knowledge: if precise value or range is useful to prune jump branch, BPF 4076 * verifier takes this opportunity enthusiastically. Similarly, when 4077 * register's value is used to calculate offset or memory address, exact 4078 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 4079 * what we mentioned above about state comparison ignoring precise markings 4080 * during state comparison, BPF verifier ignores and also assumes precise 4081 * markings *at will* during instruction verification process. But as verifier 4082 * assumes precision, it also propagates any precision dependencies across 4083 * parent states, which are not yet finalized, so can be further restricted 4084 * based on new knowledge gained from restrictions enforced by their children 4085 * states. This is so that once those parent states are finalized, i.e., when 4086 * they have no more active children state, state comparison logic in 4087 * is_state_visited() would enforce strict and precise SCALAR ranges, if 4088 * required for correctness. 4089 * 4090 * To build a bit more intuition, note also that once a state is checkpointed, 4091 * the path we took to get to that state is not important. This is crucial 4092 * property for state pruning. When state is checkpointed and finalized at 4093 * some instruction index, it can be correctly and safely used to "short 4094 * circuit" any *compatible* state that reaches exactly the same instruction 4095 * index. I.e., if we jumped to that instruction from a completely different 4096 * code path than original finalized state was derived from, it doesn't 4097 * matter, current state can be discarded because from that instruction 4098 * forward having a compatible state will ensure we will safely reach the 4099 * exit. States describe preconditions for further exploration, but completely 4100 * forget the history of how we got here. 4101 * 4102 * This also means that even if we needed precise SCALAR range to get to 4103 * finalized state, but from that point forward *that same* SCALAR register is 4104 * never used in a precise context (i.e., it's precise value is not needed for 4105 * correctness), it's correct and safe to mark such register as "imprecise" 4106 * (i.e., precise marking set to false). This is what we rely on when we do 4107 * not set precise marking in current state. If no child state requires 4108 * precision for any given SCALAR register, it's safe to dictate that it can 4109 * be imprecise. If any child state does require this register to be precise, 4110 * we'll mark it precise later retroactively during precise markings 4111 * propagation from child state to parent states. 4112 * 4113 * Skipping precise marking setting in current state is a mild version of 4114 * relying on the above observation. But we can utilize this property even 4115 * more aggressively by proactively forgetting any precise marking in the 4116 * current state (which we inherited from the parent state), right before we 4117 * checkpoint it and branch off into new child state. This is done by 4118 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 4119 * finalized states which help in short circuiting more future states. 4120 */ 4121 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno) 4122 { 4123 struct backtrack_state *bt = &env->bt; 4124 struct bpf_verifier_state *st = env->cur_state; 4125 int first_idx = st->first_insn_idx; 4126 int last_idx = env->insn_idx; 4127 int subseq_idx = -1; 4128 struct bpf_func_state *func; 4129 struct bpf_reg_state *reg; 4130 bool skip_first = true; 4131 int i, fr, err; 4132 4133 if (!env->bpf_capable) 4134 return 0; 4135 4136 /* set frame number from which we are starting to backtrack */ 4137 bt_init(bt, env->cur_state->curframe); 4138 4139 /* Do sanity checks against current state of register and/or stack 4140 * slot, but don't set precise flag in current state, as precision 4141 * tracking in the current state is unnecessary. 4142 */ 4143 func = st->frame[bt->frame]; 4144 if (regno >= 0) { 4145 reg = &func->regs[regno]; 4146 if (reg->type != SCALAR_VALUE) { 4147 WARN_ONCE(1, "backtracing misuse"); 4148 return -EFAULT; 4149 } 4150 bt_set_reg(bt, regno); 4151 } 4152 4153 if (bt_empty(bt)) 4154 return 0; 4155 4156 for (;;) { 4157 DECLARE_BITMAP(mask, 64); 4158 u32 history = st->jmp_history_cnt; 4159 struct bpf_jmp_history_entry *hist; 4160 4161 if (env->log.level & BPF_LOG_LEVEL2) { 4162 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n", 4163 bt->frame, last_idx, first_idx, subseq_idx); 4164 } 4165 4166 /* If some register with scalar ID is marked as precise, 4167 * make sure that all registers sharing this ID are also precise. 4168 * This is needed to estimate effect of find_equal_scalars(). 4169 * Do this at the last instruction of each state, 4170 * bpf_reg_state::id fields are valid for these instructions. 4171 * 4172 * Allows to track precision in situation like below: 4173 * 4174 * r2 = unknown value 4175 * ... 4176 * --- state #0 --- 4177 * ... 4178 * r1 = r2 // r1 and r2 now share the same ID 4179 * ... 4180 * --- state #1 {r1.id = A, r2.id = A} --- 4181 * ... 4182 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1 4183 * ... 4184 * --- state #2 {r1.id = A, r2.id = A} --- 4185 * r3 = r10 4186 * r3 += r1 // need to mark both r1 and r2 4187 */ 4188 if (mark_precise_scalar_ids(env, st)) 4189 return -EFAULT; 4190 4191 if (last_idx < 0) { 4192 /* we are at the entry into subprog, which 4193 * is expected for global funcs, but only if 4194 * requested precise registers are R1-R5 4195 * (which are global func's input arguments) 4196 */ 4197 if (st->curframe == 0 && 4198 st->frame[0]->subprogno > 0 && 4199 st->frame[0]->callsite == BPF_MAIN_FUNC && 4200 bt_stack_mask(bt) == 0 && 4201 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) { 4202 bitmap_from_u64(mask, bt_reg_mask(bt)); 4203 for_each_set_bit(i, mask, 32) { 4204 reg = &st->frame[0]->regs[i]; 4205 bt_clear_reg(bt, i); 4206 if (reg->type == SCALAR_VALUE) 4207 reg->precise = true; 4208 } 4209 return 0; 4210 } 4211 4212 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n", 4213 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt)); 4214 WARN_ONCE(1, "verifier backtracking bug"); 4215 return -EFAULT; 4216 } 4217 4218 for (i = last_idx;;) { 4219 if (skip_first) { 4220 err = 0; 4221 skip_first = false; 4222 } else { 4223 hist = get_jmp_hist_entry(st, history, i); 4224 err = backtrack_insn(env, i, subseq_idx, hist, bt); 4225 } 4226 if (err == -ENOTSUPP) { 4227 mark_all_scalars_precise(env, env->cur_state); 4228 bt_reset(bt); 4229 return 0; 4230 } else if (err) { 4231 return err; 4232 } 4233 if (bt_empty(bt)) 4234 /* Found assignment(s) into tracked register in this state. 4235 * Since this state is already marked, just return. 4236 * Nothing to be tracked further in the parent state. 4237 */ 4238 return 0; 4239 subseq_idx = i; 4240 i = get_prev_insn_idx(st, i, &history); 4241 if (i == -ENOENT) 4242 break; 4243 if (i >= env->prog->len) { 4244 /* This can happen if backtracking reached insn 0 4245 * and there are still reg_mask or stack_mask 4246 * to backtrack. 4247 * It means the backtracking missed the spot where 4248 * particular register was initialized with a constant. 4249 */ 4250 verbose(env, "BUG backtracking idx %d\n", i); 4251 WARN_ONCE(1, "verifier backtracking bug"); 4252 return -EFAULT; 4253 } 4254 } 4255 st = st->parent; 4256 if (!st) 4257 break; 4258 4259 for (fr = bt->frame; fr >= 0; fr--) { 4260 func = st->frame[fr]; 4261 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4262 for_each_set_bit(i, mask, 32) { 4263 reg = &func->regs[i]; 4264 if (reg->type != SCALAR_VALUE) { 4265 bt_clear_frame_reg(bt, fr, i); 4266 continue; 4267 } 4268 if (reg->precise) 4269 bt_clear_frame_reg(bt, fr, i); 4270 else 4271 reg->precise = true; 4272 } 4273 4274 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4275 for_each_set_bit(i, mask, 64) { 4276 if (i >= func->allocated_stack / BPF_REG_SIZE) { 4277 verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n", 4278 i, func->allocated_stack / BPF_REG_SIZE); 4279 WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)"); 4280 return -EFAULT; 4281 } 4282 4283 if (!is_spilled_scalar_reg(&func->stack[i])) { 4284 bt_clear_frame_slot(bt, fr, i); 4285 continue; 4286 } 4287 reg = &func->stack[i].spilled_ptr; 4288 if (reg->precise) 4289 bt_clear_frame_slot(bt, fr, i); 4290 else 4291 reg->precise = true; 4292 } 4293 if (env->log.level & BPF_LOG_LEVEL2) { 4294 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4295 bt_frame_reg_mask(bt, fr)); 4296 verbose(env, "mark_precise: frame%d: parent state regs=%s ", 4297 fr, env->tmp_str_buf); 4298 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4299 bt_frame_stack_mask(bt, fr)); 4300 verbose(env, "stack=%s: ", env->tmp_str_buf); 4301 print_verifier_state(env, func, true); 4302 } 4303 } 4304 4305 if (bt_empty(bt)) 4306 return 0; 4307 4308 subseq_idx = first_idx; 4309 last_idx = st->last_insn_idx; 4310 first_idx = st->first_insn_idx; 4311 } 4312 4313 /* if we still have requested precise regs or slots, we missed 4314 * something (e.g., stack access through non-r10 register), so 4315 * fallback to marking all precise 4316 */ 4317 if (!bt_empty(bt)) { 4318 mark_all_scalars_precise(env, env->cur_state); 4319 bt_reset(bt); 4320 } 4321 4322 return 0; 4323 } 4324 4325 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 4326 { 4327 return __mark_chain_precision(env, regno); 4328 } 4329 4330 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 4331 * desired reg and stack masks across all relevant frames 4332 */ 4333 static int mark_chain_precision_batch(struct bpf_verifier_env *env) 4334 { 4335 return __mark_chain_precision(env, -1); 4336 } 4337 4338 static bool is_spillable_regtype(enum bpf_reg_type type) 4339 { 4340 switch (base_type(type)) { 4341 case PTR_TO_MAP_VALUE: 4342 case PTR_TO_STACK: 4343 case PTR_TO_CTX: 4344 case PTR_TO_PACKET: 4345 case PTR_TO_PACKET_META: 4346 case PTR_TO_PACKET_END: 4347 case PTR_TO_FLOW_KEYS: 4348 case CONST_PTR_TO_MAP: 4349 case PTR_TO_SOCKET: 4350 case PTR_TO_SOCK_COMMON: 4351 case PTR_TO_TCP_SOCK: 4352 case PTR_TO_XDP_SOCK: 4353 case PTR_TO_BTF_ID: 4354 case PTR_TO_BUF: 4355 case PTR_TO_MEM: 4356 case PTR_TO_FUNC: 4357 case PTR_TO_MAP_KEY: 4358 return true; 4359 default: 4360 return false; 4361 } 4362 } 4363 4364 /* Does this register contain a constant zero? */ 4365 static bool register_is_null(struct bpf_reg_state *reg) 4366 { 4367 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 4368 } 4369 4370 /* check if register is a constant scalar value */ 4371 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32) 4372 { 4373 return reg->type == SCALAR_VALUE && 4374 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off); 4375 } 4376 4377 /* assuming is_reg_const() is true, return constant value of a register */ 4378 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32) 4379 { 4380 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value; 4381 } 4382 4383 static bool __is_scalar_unbounded(struct bpf_reg_state *reg) 4384 { 4385 return tnum_is_unknown(reg->var_off) && 4386 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX && 4387 reg->umin_value == 0 && reg->umax_value == U64_MAX && 4388 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX && 4389 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX; 4390 } 4391 4392 static bool register_is_bounded(struct bpf_reg_state *reg) 4393 { 4394 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg); 4395 } 4396 4397 static bool __is_pointer_value(bool allow_ptr_leaks, 4398 const struct bpf_reg_state *reg) 4399 { 4400 if (allow_ptr_leaks) 4401 return false; 4402 4403 return reg->type != SCALAR_VALUE; 4404 } 4405 4406 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env, 4407 struct bpf_reg_state *src_reg) 4408 { 4409 if (src_reg->type == SCALAR_VALUE && !src_reg->id && 4410 !tnum_is_const(src_reg->var_off)) 4411 /* Ensure that src_reg has a valid ID that will be copied to 4412 * dst_reg and then will be used by find_equal_scalars() to 4413 * propagate min/max range. 4414 */ 4415 src_reg->id = ++env->id_gen; 4416 } 4417 4418 /* Copy src state preserving dst->parent and dst->live fields */ 4419 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 4420 { 4421 struct bpf_reg_state *parent = dst->parent; 4422 enum bpf_reg_liveness live = dst->live; 4423 4424 *dst = *src; 4425 dst->parent = parent; 4426 dst->live = live; 4427 } 4428 4429 static void save_register_state(struct bpf_verifier_env *env, 4430 struct bpf_func_state *state, 4431 int spi, struct bpf_reg_state *reg, 4432 int size) 4433 { 4434 int i; 4435 4436 copy_register_state(&state->stack[spi].spilled_ptr, reg); 4437 if (size == BPF_REG_SIZE) 4438 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4439 4440 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 4441 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 4442 4443 /* size < 8 bytes spill */ 4444 for (; i; i--) 4445 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]); 4446 } 4447 4448 static bool is_bpf_st_mem(struct bpf_insn *insn) 4449 { 4450 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 4451 } 4452 4453 static int get_reg_width(struct bpf_reg_state *reg) 4454 { 4455 return fls64(reg->umax_value); 4456 } 4457 4458 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 4459 * stack boundary and alignment are checked in check_mem_access() 4460 */ 4461 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 4462 /* stack frame we're writing to */ 4463 struct bpf_func_state *state, 4464 int off, int size, int value_regno, 4465 int insn_idx) 4466 { 4467 struct bpf_func_state *cur; /* state of the current function */ 4468 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 4469 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4470 struct bpf_reg_state *reg = NULL; 4471 int insn_flags = insn_stack_access_flags(state->frameno, spi); 4472 4473 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 4474 * so it's aligned access and [off, off + size) are within stack limits 4475 */ 4476 if (!env->allow_ptr_leaks && 4477 is_spilled_reg(&state->stack[spi]) && 4478 size != BPF_REG_SIZE) { 4479 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 4480 return -EACCES; 4481 } 4482 4483 cur = env->cur_state->frame[env->cur_state->curframe]; 4484 if (value_regno >= 0) 4485 reg = &cur->regs[value_regno]; 4486 if (!env->bypass_spec_v4) { 4487 bool sanitize = reg && is_spillable_regtype(reg->type); 4488 4489 for (i = 0; i < size; i++) { 4490 u8 type = state->stack[spi].slot_type[i]; 4491 4492 if (type != STACK_MISC && type != STACK_ZERO) { 4493 sanitize = true; 4494 break; 4495 } 4496 } 4497 4498 if (sanitize) 4499 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 4500 } 4501 4502 err = destroy_if_dynptr_stack_slot(env, state, spi); 4503 if (err) 4504 return err; 4505 4506 mark_stack_slot_scratched(env, spi); 4507 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && env->bpf_capable) { 4508 bool reg_value_fits; 4509 4510 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size; 4511 /* Make sure that reg had an ID to build a relation on spill. */ 4512 if (reg_value_fits) 4513 assign_scalar_id_before_mov(env, reg); 4514 save_register_state(env, state, spi, reg, size); 4515 /* Break the relation on a narrowing spill. */ 4516 if (!reg_value_fits) 4517 state->stack[spi].spilled_ptr.id = 0; 4518 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 4519 insn->imm != 0 && env->bpf_capable) { 4520 struct bpf_reg_state fake_reg = {}; 4521 4522 __mark_reg_known(&fake_reg, insn->imm); 4523 fake_reg.type = SCALAR_VALUE; 4524 save_register_state(env, state, spi, &fake_reg, size); 4525 } else if (reg && is_spillable_regtype(reg->type)) { 4526 /* register containing pointer is being spilled into stack */ 4527 if (size != BPF_REG_SIZE) { 4528 verbose_linfo(env, insn_idx, "; "); 4529 verbose(env, "invalid size of register spill\n"); 4530 return -EACCES; 4531 } 4532 if (state != cur && reg->type == PTR_TO_STACK) { 4533 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4534 return -EINVAL; 4535 } 4536 save_register_state(env, state, spi, reg, size); 4537 } else { 4538 u8 type = STACK_MISC; 4539 4540 /* regular write of data into stack destroys any spilled ptr */ 4541 state->stack[spi].spilled_ptr.type = NOT_INIT; 4542 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 4543 if (is_stack_slot_special(&state->stack[spi])) 4544 for (i = 0; i < BPF_REG_SIZE; i++) 4545 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 4546 4547 /* only mark the slot as written if all 8 bytes were written 4548 * otherwise read propagation may incorrectly stop too soon 4549 * when stack slots are partially written. 4550 * This heuristic means that read propagation will be 4551 * conservative, since it will add reg_live_read marks 4552 * to stack slots all the way to first state when programs 4553 * writes+reads less than 8 bytes 4554 */ 4555 if (size == BPF_REG_SIZE) 4556 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4557 4558 /* when we zero initialize stack slots mark them as such */ 4559 if ((reg && register_is_null(reg)) || 4560 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4561 /* STACK_ZERO case happened because register spill 4562 * wasn't properly aligned at the stack slot boundary, 4563 * so it's not a register spill anymore; force 4564 * originating register to be precise to make 4565 * STACK_ZERO correct for subsequent states 4566 */ 4567 err = mark_chain_precision(env, value_regno); 4568 if (err) 4569 return err; 4570 type = STACK_ZERO; 4571 } 4572 4573 /* Mark slots affected by this stack write. */ 4574 for (i = 0; i < size; i++) 4575 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 4576 insn_flags = 0; /* not a register spill */ 4577 } 4578 4579 if (insn_flags) 4580 return push_jmp_history(env, env->cur_state, insn_flags); 4581 return 0; 4582 } 4583 4584 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 4585 * known to contain a variable offset. 4586 * This function checks whether the write is permitted and conservatively 4587 * tracks the effects of the write, considering that each stack slot in the 4588 * dynamic range is potentially written to. 4589 * 4590 * 'off' includes 'regno->off'. 4591 * 'value_regno' can be -1, meaning that an unknown value is being written to 4592 * the stack. 4593 * 4594 * Spilled pointers in range are not marked as written because we don't know 4595 * what's going to be actually written. This means that read propagation for 4596 * future reads cannot be terminated by this write. 4597 * 4598 * For privileged programs, uninitialized stack slots are considered 4599 * initialized by this write (even though we don't know exactly what offsets 4600 * are going to be written to). The idea is that we don't want the verifier to 4601 * reject future reads that access slots written to through variable offsets. 4602 */ 4603 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4604 /* func where register points to */ 4605 struct bpf_func_state *state, 4606 int ptr_regno, int off, int size, 4607 int value_regno, int insn_idx) 4608 { 4609 struct bpf_func_state *cur; /* state of the current function */ 4610 int min_off, max_off; 4611 int i, err; 4612 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 4613 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4614 bool writing_zero = false; 4615 /* set if the fact that we're writing a zero is used to let any 4616 * stack slots remain STACK_ZERO 4617 */ 4618 bool zero_used = false; 4619 4620 cur = env->cur_state->frame[env->cur_state->curframe]; 4621 ptr_reg = &cur->regs[ptr_regno]; 4622 min_off = ptr_reg->smin_value + off; 4623 max_off = ptr_reg->smax_value + off + size; 4624 if (value_regno >= 0) 4625 value_reg = &cur->regs[value_regno]; 4626 if ((value_reg && register_is_null(value_reg)) || 4627 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4628 writing_zero = true; 4629 4630 for (i = min_off; i < max_off; i++) { 4631 int spi; 4632 4633 spi = __get_spi(i); 4634 err = destroy_if_dynptr_stack_slot(env, state, spi); 4635 if (err) 4636 return err; 4637 } 4638 4639 /* Variable offset writes destroy any spilled pointers in range. */ 4640 for (i = min_off; i < max_off; i++) { 4641 u8 new_type, *stype; 4642 int slot, spi; 4643 4644 slot = -i - 1; 4645 spi = slot / BPF_REG_SIZE; 4646 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4647 mark_stack_slot_scratched(env, spi); 4648 4649 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4650 /* Reject the write if range we may write to has not 4651 * been initialized beforehand. If we didn't reject 4652 * here, the ptr status would be erased below (even 4653 * though not all slots are actually overwritten), 4654 * possibly opening the door to leaks. 4655 * 4656 * We do however catch STACK_INVALID case below, and 4657 * only allow reading possibly uninitialized memory 4658 * later for CAP_PERFMON, as the write may not happen to 4659 * that slot. 4660 */ 4661 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4662 insn_idx, i); 4663 return -EINVAL; 4664 } 4665 4666 /* Erase all spilled pointers. */ 4667 state->stack[spi].spilled_ptr.type = NOT_INIT; 4668 4669 /* Update the slot type. */ 4670 new_type = STACK_MISC; 4671 if (writing_zero && *stype == STACK_ZERO) { 4672 new_type = STACK_ZERO; 4673 zero_used = true; 4674 } 4675 /* If the slot is STACK_INVALID, we check whether it's OK to 4676 * pretend that it will be initialized by this write. The slot 4677 * might not actually be written to, and so if we mark it as 4678 * initialized future reads might leak uninitialized memory. 4679 * For privileged programs, we will accept such reads to slots 4680 * that may or may not be written because, if we're reject 4681 * them, the error would be too confusing. 4682 */ 4683 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4684 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4685 insn_idx, i); 4686 return -EINVAL; 4687 } 4688 *stype = new_type; 4689 } 4690 if (zero_used) { 4691 /* backtracking doesn't work for STACK_ZERO yet. */ 4692 err = mark_chain_precision(env, value_regno); 4693 if (err) 4694 return err; 4695 } 4696 return 0; 4697 } 4698 4699 /* When register 'dst_regno' is assigned some values from stack[min_off, 4700 * max_off), we set the register's type according to the types of the 4701 * respective stack slots. If all the stack values are known to be zeros, then 4702 * so is the destination reg. Otherwise, the register is considered to be 4703 * SCALAR. This function does not deal with register filling; the caller must 4704 * ensure that all spilled registers in the stack range have been marked as 4705 * read. 4706 */ 4707 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4708 /* func where src register points to */ 4709 struct bpf_func_state *ptr_state, 4710 int min_off, int max_off, int dst_regno) 4711 { 4712 struct bpf_verifier_state *vstate = env->cur_state; 4713 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4714 int i, slot, spi; 4715 u8 *stype; 4716 int zeros = 0; 4717 4718 for (i = min_off; i < max_off; i++) { 4719 slot = -i - 1; 4720 spi = slot / BPF_REG_SIZE; 4721 mark_stack_slot_scratched(env, spi); 4722 stype = ptr_state->stack[spi].slot_type; 4723 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4724 break; 4725 zeros++; 4726 } 4727 if (zeros == max_off - min_off) { 4728 /* Any access_size read into register is zero extended, 4729 * so the whole register == const_zero. 4730 */ 4731 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4732 } else { 4733 /* have read misc data from the stack */ 4734 mark_reg_unknown(env, state->regs, dst_regno); 4735 } 4736 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4737 } 4738 4739 /* Read the stack at 'off' and put the results into the register indicated by 4740 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4741 * spilled reg. 4742 * 4743 * 'dst_regno' can be -1, meaning that the read value is not going to a 4744 * register. 4745 * 4746 * The access is assumed to be within the current stack bounds. 4747 */ 4748 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4749 /* func where src register points to */ 4750 struct bpf_func_state *reg_state, 4751 int off, int size, int dst_regno) 4752 { 4753 struct bpf_verifier_state *vstate = env->cur_state; 4754 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4755 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4756 struct bpf_reg_state *reg; 4757 u8 *stype, type; 4758 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi); 4759 4760 stype = reg_state->stack[spi].slot_type; 4761 reg = ®_state->stack[spi].spilled_ptr; 4762 4763 mark_stack_slot_scratched(env, spi); 4764 4765 if (is_spilled_reg(®_state->stack[spi])) { 4766 u8 spill_size = 1; 4767 4768 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4769 spill_size++; 4770 4771 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4772 if (reg->type != SCALAR_VALUE) { 4773 verbose_linfo(env, env->insn_idx, "; "); 4774 verbose(env, "invalid size of register fill\n"); 4775 return -EACCES; 4776 } 4777 4778 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4779 if (dst_regno < 0) 4780 return 0; 4781 4782 if (!(off % BPF_REG_SIZE) && size == spill_size) { 4783 /* The earlier check_reg_arg() has decided the 4784 * subreg_def for this insn. Save it first. 4785 */ 4786 s32 subreg_def = state->regs[dst_regno].subreg_def; 4787 4788 copy_register_state(&state->regs[dst_regno], reg); 4789 state->regs[dst_regno].subreg_def = subreg_def; 4790 } else { 4791 int spill_cnt = 0, zero_cnt = 0; 4792 4793 for (i = 0; i < size; i++) { 4794 type = stype[(slot - i) % BPF_REG_SIZE]; 4795 if (type == STACK_SPILL) { 4796 spill_cnt++; 4797 continue; 4798 } 4799 if (type == STACK_MISC) 4800 continue; 4801 if (type == STACK_ZERO) { 4802 zero_cnt++; 4803 continue; 4804 } 4805 if (type == STACK_INVALID && env->allow_uninit_stack) 4806 continue; 4807 verbose(env, "invalid read from stack off %d+%d size %d\n", 4808 off, i, size); 4809 return -EACCES; 4810 } 4811 4812 if (spill_cnt == size && 4813 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 4814 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4815 /* this IS register fill, so keep insn_flags */ 4816 } else if (zero_cnt == size) { 4817 /* similarly to mark_reg_stack_read(), preserve zeroes */ 4818 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4819 insn_flags = 0; /* not restoring original register state */ 4820 } else { 4821 mark_reg_unknown(env, state->regs, dst_regno); 4822 insn_flags = 0; /* not restoring original register state */ 4823 } 4824 } 4825 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4826 } else if (dst_regno >= 0) { 4827 /* restore register state from stack */ 4828 copy_register_state(&state->regs[dst_regno], reg); 4829 /* mark reg as written since spilled pointer state likely 4830 * has its liveness marks cleared by is_state_visited() 4831 * which resets stack/reg liveness for state transitions 4832 */ 4833 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4834 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 4835 /* If dst_regno==-1, the caller is asking us whether 4836 * it is acceptable to use this value as a SCALAR_VALUE 4837 * (e.g. for XADD). 4838 * We must not allow unprivileged callers to do that 4839 * with spilled pointers. 4840 */ 4841 verbose(env, "leaking pointer from stack off %d\n", 4842 off); 4843 return -EACCES; 4844 } 4845 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4846 } else { 4847 for (i = 0; i < size; i++) { 4848 type = stype[(slot - i) % BPF_REG_SIZE]; 4849 if (type == STACK_MISC) 4850 continue; 4851 if (type == STACK_ZERO) 4852 continue; 4853 if (type == STACK_INVALID && env->allow_uninit_stack) 4854 continue; 4855 verbose(env, "invalid read from stack off %d+%d size %d\n", 4856 off, i, size); 4857 return -EACCES; 4858 } 4859 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4860 if (dst_regno >= 0) 4861 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 4862 insn_flags = 0; /* we are not restoring spilled register */ 4863 } 4864 if (insn_flags) 4865 return push_jmp_history(env, env->cur_state, insn_flags); 4866 return 0; 4867 } 4868 4869 enum bpf_access_src { 4870 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 4871 ACCESS_HELPER = 2, /* the access is performed by a helper */ 4872 }; 4873 4874 static int check_stack_range_initialized(struct bpf_verifier_env *env, 4875 int regno, int off, int access_size, 4876 bool zero_size_allowed, 4877 enum bpf_access_src type, 4878 struct bpf_call_arg_meta *meta); 4879 4880 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 4881 { 4882 return cur_regs(env) + regno; 4883 } 4884 4885 /* Read the stack at 'ptr_regno + off' and put the result into the register 4886 * 'dst_regno'. 4887 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 4888 * but not its variable offset. 4889 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 4890 * 4891 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 4892 * filling registers (i.e. reads of spilled register cannot be detected when 4893 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 4894 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 4895 * offset; for a fixed offset check_stack_read_fixed_off should be used 4896 * instead. 4897 */ 4898 static int check_stack_read_var_off(struct bpf_verifier_env *env, 4899 int ptr_regno, int off, int size, int dst_regno) 4900 { 4901 /* The state of the source register. */ 4902 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4903 struct bpf_func_state *ptr_state = func(env, reg); 4904 int err; 4905 int min_off, max_off; 4906 4907 /* Note that we pass a NULL meta, so raw access will not be permitted. 4908 */ 4909 err = check_stack_range_initialized(env, ptr_regno, off, size, 4910 false, ACCESS_DIRECT, NULL); 4911 if (err) 4912 return err; 4913 4914 min_off = reg->smin_value + off; 4915 max_off = reg->smax_value + off; 4916 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 4917 return 0; 4918 } 4919 4920 /* check_stack_read dispatches to check_stack_read_fixed_off or 4921 * check_stack_read_var_off. 4922 * 4923 * The caller must ensure that the offset falls within the allocated stack 4924 * bounds. 4925 * 4926 * 'dst_regno' is a register which will receive the value from the stack. It 4927 * can be -1, meaning that the read value is not going to a register. 4928 */ 4929 static int check_stack_read(struct bpf_verifier_env *env, 4930 int ptr_regno, int off, int size, 4931 int dst_regno) 4932 { 4933 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4934 struct bpf_func_state *state = func(env, reg); 4935 int err; 4936 /* Some accesses are only permitted with a static offset. */ 4937 bool var_off = !tnum_is_const(reg->var_off); 4938 4939 /* The offset is required to be static when reads don't go to a 4940 * register, in order to not leak pointers (see 4941 * check_stack_read_fixed_off). 4942 */ 4943 if (dst_regno < 0 && var_off) { 4944 char tn_buf[48]; 4945 4946 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4947 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 4948 tn_buf, off, size); 4949 return -EACCES; 4950 } 4951 /* Variable offset is prohibited for unprivileged mode for simplicity 4952 * since it requires corresponding support in Spectre masking for stack 4953 * ALU. See also retrieve_ptr_limit(). The check in 4954 * check_stack_access_for_ptr_arithmetic() called by 4955 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 4956 * with variable offsets, therefore no check is required here. Further, 4957 * just checking it here would be insufficient as speculative stack 4958 * writes could still lead to unsafe speculative behaviour. 4959 */ 4960 if (!var_off) { 4961 off += reg->var_off.value; 4962 err = check_stack_read_fixed_off(env, state, off, size, 4963 dst_regno); 4964 } else { 4965 /* Variable offset stack reads need more conservative handling 4966 * than fixed offset ones. Note that dst_regno >= 0 on this 4967 * branch. 4968 */ 4969 err = check_stack_read_var_off(env, ptr_regno, off, size, 4970 dst_regno); 4971 } 4972 return err; 4973 } 4974 4975 4976 /* check_stack_write dispatches to check_stack_write_fixed_off or 4977 * check_stack_write_var_off. 4978 * 4979 * 'ptr_regno' is the register used as a pointer into the stack. 4980 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 4981 * 'value_regno' is the register whose value we're writing to the stack. It can 4982 * be -1, meaning that we're not writing from a register. 4983 * 4984 * The caller must ensure that the offset falls within the maximum stack size. 4985 */ 4986 static int check_stack_write(struct bpf_verifier_env *env, 4987 int ptr_regno, int off, int size, 4988 int value_regno, int insn_idx) 4989 { 4990 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4991 struct bpf_func_state *state = func(env, reg); 4992 int err; 4993 4994 if (tnum_is_const(reg->var_off)) { 4995 off += reg->var_off.value; 4996 err = check_stack_write_fixed_off(env, state, off, size, 4997 value_regno, insn_idx); 4998 } else { 4999 /* Variable offset stack reads need more conservative handling 5000 * than fixed offset ones. 5001 */ 5002 err = check_stack_write_var_off(env, state, 5003 ptr_regno, off, size, 5004 value_regno, insn_idx); 5005 } 5006 return err; 5007 } 5008 5009 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 5010 int off, int size, enum bpf_access_type type) 5011 { 5012 struct bpf_reg_state *regs = cur_regs(env); 5013 struct bpf_map *map = regs[regno].map_ptr; 5014 u32 cap = bpf_map_flags_to_cap(map); 5015 5016 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 5017 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 5018 map->value_size, off, size); 5019 return -EACCES; 5020 } 5021 5022 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 5023 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 5024 map->value_size, off, size); 5025 return -EACCES; 5026 } 5027 5028 return 0; 5029 } 5030 5031 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 5032 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 5033 int off, int size, u32 mem_size, 5034 bool zero_size_allowed) 5035 { 5036 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 5037 struct bpf_reg_state *reg; 5038 5039 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 5040 return 0; 5041 5042 reg = &cur_regs(env)[regno]; 5043 switch (reg->type) { 5044 case PTR_TO_MAP_KEY: 5045 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 5046 mem_size, off, size); 5047 break; 5048 case PTR_TO_MAP_VALUE: 5049 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 5050 mem_size, off, size); 5051 break; 5052 case PTR_TO_PACKET: 5053 case PTR_TO_PACKET_META: 5054 case PTR_TO_PACKET_END: 5055 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 5056 off, size, regno, reg->id, off, mem_size); 5057 break; 5058 case PTR_TO_MEM: 5059 default: 5060 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 5061 mem_size, off, size); 5062 } 5063 5064 return -EACCES; 5065 } 5066 5067 /* check read/write into a memory region with possible variable offset */ 5068 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 5069 int off, int size, u32 mem_size, 5070 bool zero_size_allowed) 5071 { 5072 struct bpf_verifier_state *vstate = env->cur_state; 5073 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5074 struct bpf_reg_state *reg = &state->regs[regno]; 5075 int err; 5076 5077 /* We may have adjusted the register pointing to memory region, so we 5078 * need to try adding each of min_value and max_value to off 5079 * to make sure our theoretical access will be safe. 5080 * 5081 * The minimum value is only important with signed 5082 * comparisons where we can't assume the floor of a 5083 * value is 0. If we are using signed variables for our 5084 * index'es we need to make sure that whatever we use 5085 * will have a set floor within our range. 5086 */ 5087 if (reg->smin_value < 0 && 5088 (reg->smin_value == S64_MIN || 5089 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5090 reg->smin_value + off < 0)) { 5091 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5092 regno); 5093 return -EACCES; 5094 } 5095 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5096 mem_size, zero_size_allowed); 5097 if (err) { 5098 verbose(env, "R%d min value is outside of the allowed memory range\n", 5099 regno); 5100 return err; 5101 } 5102 5103 /* If we haven't set a max value then we need to bail since we can't be 5104 * sure we won't do bad things. 5105 * If reg->umax_value + off could overflow, treat that as unbounded too. 5106 */ 5107 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5108 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5109 regno); 5110 return -EACCES; 5111 } 5112 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5113 mem_size, zero_size_allowed); 5114 if (err) { 5115 verbose(env, "R%d max value is outside of the allowed memory range\n", 5116 regno); 5117 return err; 5118 } 5119 5120 return 0; 5121 } 5122 5123 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5124 const struct bpf_reg_state *reg, int regno, 5125 bool fixed_off_ok) 5126 { 5127 /* Access to this pointer-typed register or passing it to a helper 5128 * is only allowed in its original, unmodified form. 5129 */ 5130 5131 if (reg->off < 0) { 5132 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5133 reg_type_str(env, reg->type), regno, reg->off); 5134 return -EACCES; 5135 } 5136 5137 if (!fixed_off_ok && reg->off) { 5138 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5139 reg_type_str(env, reg->type), regno, reg->off); 5140 return -EACCES; 5141 } 5142 5143 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5144 char tn_buf[48]; 5145 5146 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5147 verbose(env, "variable %s access var_off=%s disallowed\n", 5148 reg_type_str(env, reg->type), tn_buf); 5149 return -EACCES; 5150 } 5151 5152 return 0; 5153 } 5154 5155 static int check_ptr_off_reg(struct bpf_verifier_env *env, 5156 const struct bpf_reg_state *reg, int regno) 5157 { 5158 return __check_ptr_off_reg(env, reg, regno, false); 5159 } 5160 5161 static int map_kptr_match_type(struct bpf_verifier_env *env, 5162 struct btf_field *kptr_field, 5163 struct bpf_reg_state *reg, u32 regno) 5164 { 5165 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5166 int perm_flags; 5167 const char *reg_name = ""; 5168 5169 if (btf_is_kernel(reg->btf)) { 5170 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5171 5172 /* Only unreferenced case accepts untrusted pointers */ 5173 if (kptr_field->type == BPF_KPTR_UNREF) 5174 perm_flags |= PTR_UNTRUSTED; 5175 } else { 5176 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5177 if (kptr_field->type == BPF_KPTR_PERCPU) 5178 perm_flags |= MEM_PERCPU; 5179 } 5180 5181 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5182 goto bad_type; 5183 5184 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5185 reg_name = btf_type_name(reg->btf, reg->btf_id); 5186 5187 /* For ref_ptr case, release function check should ensure we get one 5188 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5189 * normal store of unreferenced kptr, we must ensure var_off is zero. 5190 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5191 * reg->off and reg->ref_obj_id are not needed here. 5192 */ 5193 if (__check_ptr_off_reg(env, reg, regno, true)) 5194 return -EACCES; 5195 5196 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5197 * we also need to take into account the reg->off. 5198 * 5199 * We want to support cases like: 5200 * 5201 * struct foo { 5202 * struct bar br; 5203 * struct baz bz; 5204 * }; 5205 * 5206 * struct foo *v; 5207 * v = func(); // PTR_TO_BTF_ID 5208 * val->foo = v; // reg->off is zero, btf and btf_id match type 5209 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5210 * // first member type of struct after comparison fails 5211 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5212 * // to match type 5213 * 5214 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5215 * is zero. We must also ensure that btf_struct_ids_match does not walk 5216 * the struct to match type against first member of struct, i.e. reject 5217 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5218 * strict mode to true for type match. 5219 */ 5220 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5221 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5222 kptr_field->type != BPF_KPTR_UNREF)) 5223 goto bad_type; 5224 return 0; 5225 bad_type: 5226 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5227 reg_type_str(env, reg->type), reg_name); 5228 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5229 if (kptr_field->type == BPF_KPTR_UNREF) 5230 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5231 targ_name); 5232 else 5233 verbose(env, "\n"); 5234 return -EINVAL; 5235 } 5236 5237 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5238 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5239 */ 5240 static bool in_rcu_cs(struct bpf_verifier_env *env) 5241 { 5242 return env->cur_state->active_rcu_lock || 5243 env->cur_state->active_lock.ptr || 5244 !env->prog->aux->sleepable; 5245 } 5246 5247 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5248 BTF_SET_START(rcu_protected_types) 5249 BTF_ID(struct, prog_test_ref_kfunc) 5250 #ifdef CONFIG_CGROUPS 5251 BTF_ID(struct, cgroup) 5252 #endif 5253 BTF_ID(struct, bpf_cpumask) 5254 BTF_ID(struct, task_struct) 5255 BTF_SET_END(rcu_protected_types) 5256 5257 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5258 { 5259 if (!btf_is_kernel(btf)) 5260 return true; 5261 return btf_id_set_contains(&rcu_protected_types, btf_id); 5262 } 5263 5264 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 5265 { 5266 struct btf_struct_meta *meta; 5267 5268 if (btf_is_kernel(kptr_field->kptr.btf)) 5269 return NULL; 5270 5271 meta = btf_find_struct_meta(kptr_field->kptr.btf, 5272 kptr_field->kptr.btf_id); 5273 5274 return meta ? meta->record : NULL; 5275 } 5276 5277 static bool rcu_safe_kptr(const struct btf_field *field) 5278 { 5279 const struct btf_field_kptr *kptr = &field->kptr; 5280 5281 return field->type == BPF_KPTR_PERCPU || 5282 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 5283 } 5284 5285 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 5286 { 5287 struct btf_record *rec; 5288 u32 ret; 5289 5290 ret = PTR_MAYBE_NULL; 5291 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 5292 ret |= MEM_RCU; 5293 if (kptr_field->type == BPF_KPTR_PERCPU) 5294 ret |= MEM_PERCPU; 5295 else if (!btf_is_kernel(kptr_field->kptr.btf)) 5296 ret |= MEM_ALLOC; 5297 5298 rec = kptr_pointee_btf_record(kptr_field); 5299 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 5300 ret |= NON_OWN_REF; 5301 } else { 5302 ret |= PTR_UNTRUSTED; 5303 } 5304 5305 return ret; 5306 } 5307 5308 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5309 int value_regno, int insn_idx, 5310 struct btf_field *kptr_field) 5311 { 5312 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5313 int class = BPF_CLASS(insn->code); 5314 struct bpf_reg_state *val_reg; 5315 5316 /* Things we already checked for in check_map_access and caller: 5317 * - Reject cases where variable offset may touch kptr 5318 * - size of access (must be BPF_DW) 5319 * - tnum_is_const(reg->var_off) 5320 * - kptr_field->offset == off + reg->var_off.value 5321 */ 5322 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5323 if (BPF_MODE(insn->code) != BPF_MEM) { 5324 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5325 return -EACCES; 5326 } 5327 5328 /* We only allow loading referenced kptr, since it will be marked as 5329 * untrusted, similar to unreferenced kptr. 5330 */ 5331 if (class != BPF_LDX && 5332 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 5333 verbose(env, "store to referenced kptr disallowed\n"); 5334 return -EACCES; 5335 } 5336 5337 if (class == BPF_LDX) { 5338 val_reg = reg_state(env, value_regno); 5339 /* We can simply mark the value_regno receiving the pointer 5340 * value from map as PTR_TO_BTF_ID, with the correct type. 5341 */ 5342 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5343 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field)); 5344 /* For mark_ptr_or_null_reg */ 5345 val_reg->id = ++env->id_gen; 5346 } else if (class == BPF_STX) { 5347 val_reg = reg_state(env, value_regno); 5348 if (!register_is_null(val_reg) && 5349 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5350 return -EACCES; 5351 } else if (class == BPF_ST) { 5352 if (insn->imm) { 5353 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5354 kptr_field->offset); 5355 return -EACCES; 5356 } 5357 } else { 5358 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5359 return -EACCES; 5360 } 5361 return 0; 5362 } 5363 5364 /* check read/write into a map element with possible variable offset */ 5365 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5366 int off, int size, bool zero_size_allowed, 5367 enum bpf_access_src src) 5368 { 5369 struct bpf_verifier_state *vstate = env->cur_state; 5370 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5371 struct bpf_reg_state *reg = &state->regs[regno]; 5372 struct bpf_map *map = reg->map_ptr; 5373 struct btf_record *rec; 5374 int err, i; 5375 5376 err = check_mem_region_access(env, regno, off, size, map->value_size, 5377 zero_size_allowed); 5378 if (err) 5379 return err; 5380 5381 if (IS_ERR_OR_NULL(map->record)) 5382 return 0; 5383 rec = map->record; 5384 for (i = 0; i < rec->cnt; i++) { 5385 struct btf_field *field = &rec->fields[i]; 5386 u32 p = field->offset; 5387 5388 /* If any part of a field can be touched by load/store, reject 5389 * this program. To check that [x1, x2) overlaps with [y1, y2), 5390 * it is sufficient to check x1 < y2 && y1 < x2. 5391 */ 5392 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 5393 p < reg->umax_value + off + size) { 5394 switch (field->type) { 5395 case BPF_KPTR_UNREF: 5396 case BPF_KPTR_REF: 5397 case BPF_KPTR_PERCPU: 5398 if (src != ACCESS_DIRECT) { 5399 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 5400 return -EACCES; 5401 } 5402 if (!tnum_is_const(reg->var_off)) { 5403 verbose(env, "kptr access cannot have variable offset\n"); 5404 return -EACCES; 5405 } 5406 if (p != off + reg->var_off.value) { 5407 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 5408 p, off + reg->var_off.value); 5409 return -EACCES; 5410 } 5411 if (size != bpf_size_to_bytes(BPF_DW)) { 5412 verbose(env, "kptr access size must be BPF_DW\n"); 5413 return -EACCES; 5414 } 5415 break; 5416 default: 5417 verbose(env, "%s cannot be accessed directly by load/store\n", 5418 btf_field_type_name(field->type)); 5419 return -EACCES; 5420 } 5421 } 5422 } 5423 return 0; 5424 } 5425 5426 #define MAX_PACKET_OFF 0xffff 5427 5428 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5429 const struct bpf_call_arg_meta *meta, 5430 enum bpf_access_type t) 5431 { 5432 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5433 5434 switch (prog_type) { 5435 /* Program types only with direct read access go here! */ 5436 case BPF_PROG_TYPE_LWT_IN: 5437 case BPF_PROG_TYPE_LWT_OUT: 5438 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5439 case BPF_PROG_TYPE_SK_REUSEPORT: 5440 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5441 case BPF_PROG_TYPE_CGROUP_SKB: 5442 if (t == BPF_WRITE) 5443 return false; 5444 fallthrough; 5445 5446 /* Program types with direct read + write access go here! */ 5447 case BPF_PROG_TYPE_SCHED_CLS: 5448 case BPF_PROG_TYPE_SCHED_ACT: 5449 case BPF_PROG_TYPE_XDP: 5450 case BPF_PROG_TYPE_LWT_XMIT: 5451 case BPF_PROG_TYPE_SK_SKB: 5452 case BPF_PROG_TYPE_SK_MSG: 5453 if (meta) 5454 return meta->pkt_access; 5455 5456 env->seen_direct_write = true; 5457 return true; 5458 5459 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5460 if (t == BPF_WRITE) 5461 env->seen_direct_write = true; 5462 5463 return true; 5464 5465 default: 5466 return false; 5467 } 5468 } 5469 5470 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5471 int size, bool zero_size_allowed) 5472 { 5473 struct bpf_reg_state *regs = cur_regs(env); 5474 struct bpf_reg_state *reg = ®s[regno]; 5475 int err; 5476 5477 /* We may have added a variable offset to the packet pointer; but any 5478 * reg->range we have comes after that. We are only checking the fixed 5479 * offset. 5480 */ 5481 5482 /* We don't allow negative numbers, because we aren't tracking enough 5483 * detail to prove they're safe. 5484 */ 5485 if (reg->smin_value < 0) { 5486 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5487 regno); 5488 return -EACCES; 5489 } 5490 5491 err = reg->range < 0 ? -EINVAL : 5492 __check_mem_access(env, regno, off, size, reg->range, 5493 zero_size_allowed); 5494 if (err) { 5495 verbose(env, "R%d offset is outside of the packet\n", regno); 5496 return err; 5497 } 5498 5499 /* __check_mem_access has made sure "off + size - 1" is within u16. 5500 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5501 * otherwise find_good_pkt_pointers would have refused to set range info 5502 * that __check_mem_access would have rejected this pkt access. 5503 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5504 */ 5505 env->prog->aux->max_pkt_offset = 5506 max_t(u32, env->prog->aux->max_pkt_offset, 5507 off + reg->umax_value + size - 1); 5508 5509 return err; 5510 } 5511 5512 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5513 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5514 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5515 struct btf **btf, u32 *btf_id) 5516 { 5517 struct bpf_insn_access_aux info = { 5518 .reg_type = *reg_type, 5519 .log = &env->log, 5520 }; 5521 5522 if (env->ops->is_valid_access && 5523 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5524 /* A non zero info.ctx_field_size indicates that this field is a 5525 * candidate for later verifier transformation to load the whole 5526 * field and then apply a mask when accessed with a narrower 5527 * access than actual ctx access size. A zero info.ctx_field_size 5528 * will only allow for whole field access and rejects any other 5529 * type of narrower access. 5530 */ 5531 *reg_type = info.reg_type; 5532 5533 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5534 *btf = info.btf; 5535 *btf_id = info.btf_id; 5536 } else { 5537 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5538 } 5539 /* remember the offset of last byte accessed in ctx */ 5540 if (env->prog->aux->max_ctx_offset < off + size) 5541 env->prog->aux->max_ctx_offset = off + size; 5542 return 0; 5543 } 5544 5545 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5546 return -EACCES; 5547 } 5548 5549 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5550 int size) 5551 { 5552 if (size < 0 || off < 0 || 5553 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5554 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5555 off, size); 5556 return -EACCES; 5557 } 5558 return 0; 5559 } 5560 5561 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5562 u32 regno, int off, int size, 5563 enum bpf_access_type t) 5564 { 5565 struct bpf_reg_state *regs = cur_regs(env); 5566 struct bpf_reg_state *reg = ®s[regno]; 5567 struct bpf_insn_access_aux info = {}; 5568 bool valid; 5569 5570 if (reg->smin_value < 0) { 5571 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5572 regno); 5573 return -EACCES; 5574 } 5575 5576 switch (reg->type) { 5577 case PTR_TO_SOCK_COMMON: 5578 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5579 break; 5580 case PTR_TO_SOCKET: 5581 valid = bpf_sock_is_valid_access(off, size, t, &info); 5582 break; 5583 case PTR_TO_TCP_SOCK: 5584 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5585 break; 5586 case PTR_TO_XDP_SOCK: 5587 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5588 break; 5589 default: 5590 valid = false; 5591 } 5592 5593 5594 if (valid) { 5595 env->insn_aux_data[insn_idx].ctx_field_size = 5596 info.ctx_field_size; 5597 return 0; 5598 } 5599 5600 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5601 regno, reg_type_str(env, reg->type), off, size); 5602 5603 return -EACCES; 5604 } 5605 5606 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5607 { 5608 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5609 } 5610 5611 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5612 { 5613 const struct bpf_reg_state *reg = reg_state(env, regno); 5614 5615 return reg->type == PTR_TO_CTX; 5616 } 5617 5618 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5619 { 5620 const struct bpf_reg_state *reg = reg_state(env, regno); 5621 5622 return type_is_sk_pointer(reg->type); 5623 } 5624 5625 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5626 { 5627 const struct bpf_reg_state *reg = reg_state(env, regno); 5628 5629 return type_is_pkt_pointer(reg->type); 5630 } 5631 5632 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5633 { 5634 const struct bpf_reg_state *reg = reg_state(env, regno); 5635 5636 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5637 return reg->type == PTR_TO_FLOW_KEYS; 5638 } 5639 5640 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5641 #ifdef CONFIG_NET 5642 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5643 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5644 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5645 #endif 5646 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5647 }; 5648 5649 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5650 { 5651 /* A referenced register is always trusted. */ 5652 if (reg->ref_obj_id) 5653 return true; 5654 5655 /* Types listed in the reg2btf_ids are always trusted */ 5656 if (reg2btf_ids[base_type(reg->type)]) 5657 return true; 5658 5659 /* If a register is not referenced, it is trusted if it has the 5660 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5661 * other type modifiers may be safe, but we elect to take an opt-in 5662 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5663 * not. 5664 * 5665 * Eventually, we should make PTR_TRUSTED the single source of truth 5666 * for whether a register is trusted. 5667 */ 5668 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5669 !bpf_type_has_unsafe_modifiers(reg->type); 5670 } 5671 5672 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5673 { 5674 return reg->type & MEM_RCU; 5675 } 5676 5677 static void clear_trusted_flags(enum bpf_type_flag *flag) 5678 { 5679 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5680 } 5681 5682 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5683 const struct bpf_reg_state *reg, 5684 int off, int size, bool strict) 5685 { 5686 struct tnum reg_off; 5687 int ip_align; 5688 5689 /* Byte size accesses are always allowed. */ 5690 if (!strict || size == 1) 5691 return 0; 5692 5693 /* For platforms that do not have a Kconfig enabling 5694 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5695 * NET_IP_ALIGN is universally set to '2'. And on platforms 5696 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5697 * to this code only in strict mode where we want to emulate 5698 * the NET_IP_ALIGN==2 checking. Therefore use an 5699 * unconditional IP align value of '2'. 5700 */ 5701 ip_align = 2; 5702 5703 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5704 if (!tnum_is_aligned(reg_off, size)) { 5705 char tn_buf[48]; 5706 5707 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5708 verbose(env, 5709 "misaligned packet access off %d+%s+%d+%d size %d\n", 5710 ip_align, tn_buf, reg->off, off, size); 5711 return -EACCES; 5712 } 5713 5714 return 0; 5715 } 5716 5717 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5718 const struct bpf_reg_state *reg, 5719 const char *pointer_desc, 5720 int off, int size, bool strict) 5721 { 5722 struct tnum reg_off; 5723 5724 /* Byte size accesses are always allowed. */ 5725 if (!strict || size == 1) 5726 return 0; 5727 5728 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5729 if (!tnum_is_aligned(reg_off, size)) { 5730 char tn_buf[48]; 5731 5732 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5733 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5734 pointer_desc, tn_buf, reg->off, off, size); 5735 return -EACCES; 5736 } 5737 5738 return 0; 5739 } 5740 5741 static int check_ptr_alignment(struct bpf_verifier_env *env, 5742 const struct bpf_reg_state *reg, int off, 5743 int size, bool strict_alignment_once) 5744 { 5745 bool strict = env->strict_alignment || strict_alignment_once; 5746 const char *pointer_desc = ""; 5747 5748 switch (reg->type) { 5749 case PTR_TO_PACKET: 5750 case PTR_TO_PACKET_META: 5751 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5752 * right in front, treat it the very same way. 5753 */ 5754 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5755 case PTR_TO_FLOW_KEYS: 5756 pointer_desc = "flow keys "; 5757 break; 5758 case PTR_TO_MAP_KEY: 5759 pointer_desc = "key "; 5760 break; 5761 case PTR_TO_MAP_VALUE: 5762 pointer_desc = "value "; 5763 break; 5764 case PTR_TO_CTX: 5765 pointer_desc = "context "; 5766 break; 5767 case PTR_TO_STACK: 5768 pointer_desc = "stack "; 5769 /* The stack spill tracking logic in check_stack_write_fixed_off() 5770 * and check_stack_read_fixed_off() relies on stack accesses being 5771 * aligned. 5772 */ 5773 strict = true; 5774 break; 5775 case PTR_TO_SOCKET: 5776 pointer_desc = "sock "; 5777 break; 5778 case PTR_TO_SOCK_COMMON: 5779 pointer_desc = "sock_common "; 5780 break; 5781 case PTR_TO_TCP_SOCK: 5782 pointer_desc = "tcp_sock "; 5783 break; 5784 case PTR_TO_XDP_SOCK: 5785 pointer_desc = "xdp_sock "; 5786 break; 5787 default: 5788 break; 5789 } 5790 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5791 strict); 5792 } 5793 5794 /* starting from main bpf function walk all instructions of the function 5795 * and recursively walk all callees that given function can call. 5796 * Ignore jump and exit insns. 5797 * Since recursion is prevented by check_cfg() this algorithm 5798 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 5799 */ 5800 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx) 5801 { 5802 struct bpf_subprog_info *subprog = env->subprog_info; 5803 struct bpf_insn *insn = env->prog->insnsi; 5804 int depth = 0, frame = 0, i, subprog_end; 5805 bool tail_call_reachable = false; 5806 int ret_insn[MAX_CALL_FRAMES]; 5807 int ret_prog[MAX_CALL_FRAMES]; 5808 int j; 5809 5810 i = subprog[idx].start; 5811 process_func: 5812 /* protect against potential stack overflow that might happen when 5813 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5814 * depth for such case down to 256 so that the worst case scenario 5815 * would result in 8k stack size (32 which is tailcall limit * 256 = 5816 * 8k). 5817 * 5818 * To get the idea what might happen, see an example: 5819 * func1 -> sub rsp, 128 5820 * subfunc1 -> sub rsp, 256 5821 * tailcall1 -> add rsp, 256 5822 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5823 * subfunc2 -> sub rsp, 64 5824 * subfunc22 -> sub rsp, 128 5825 * tailcall2 -> add rsp, 128 5826 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5827 * 5828 * tailcall will unwind the current stack frame but it will not get rid 5829 * of caller's stack as shown on the example above. 5830 */ 5831 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5832 verbose(env, 5833 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5834 depth); 5835 return -EACCES; 5836 } 5837 /* round up to 32-bytes, since this is granularity 5838 * of interpreter stack size 5839 */ 5840 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5841 if (depth > MAX_BPF_STACK) { 5842 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5843 frame + 1, depth); 5844 return -EACCES; 5845 } 5846 continue_func: 5847 subprog_end = subprog[idx + 1].start; 5848 for (; i < subprog_end; i++) { 5849 int next_insn, sidx; 5850 5851 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 5852 bool err = false; 5853 5854 if (!is_bpf_throw_kfunc(insn + i)) 5855 continue; 5856 if (subprog[idx].is_cb) 5857 err = true; 5858 for (int c = 0; c < frame && !err; c++) { 5859 if (subprog[ret_prog[c]].is_cb) { 5860 err = true; 5861 break; 5862 } 5863 } 5864 if (!err) 5865 continue; 5866 verbose(env, 5867 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 5868 i, idx); 5869 return -EINVAL; 5870 } 5871 5872 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5873 continue; 5874 /* remember insn and function to return to */ 5875 ret_insn[frame] = i + 1; 5876 ret_prog[frame] = idx; 5877 5878 /* find the callee */ 5879 next_insn = i + insn[i].imm + 1; 5880 sidx = find_subprog(env, next_insn); 5881 if (sidx < 0) { 5882 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5883 next_insn); 5884 return -EFAULT; 5885 } 5886 if (subprog[sidx].is_async_cb) { 5887 if (subprog[sidx].has_tail_call) { 5888 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 5889 return -EFAULT; 5890 } 5891 /* async callbacks don't increase bpf prog stack size unless called directly */ 5892 if (!bpf_pseudo_call(insn + i)) 5893 continue; 5894 if (subprog[sidx].is_exception_cb) { 5895 verbose(env, "insn %d cannot call exception cb directly\n", i); 5896 return -EINVAL; 5897 } 5898 } 5899 i = next_insn; 5900 idx = sidx; 5901 5902 if (subprog[idx].has_tail_call) 5903 tail_call_reachable = true; 5904 5905 frame++; 5906 if (frame >= MAX_CALL_FRAMES) { 5907 verbose(env, "the call stack of %d frames is too deep !\n", 5908 frame); 5909 return -E2BIG; 5910 } 5911 goto process_func; 5912 } 5913 /* if tail call got detected across bpf2bpf calls then mark each of the 5914 * currently present subprog frames as tail call reachable subprogs; 5915 * this info will be utilized by JIT so that we will be preserving the 5916 * tail call counter throughout bpf2bpf calls combined with tailcalls 5917 */ 5918 if (tail_call_reachable) 5919 for (j = 0; j < frame; j++) { 5920 if (subprog[ret_prog[j]].is_exception_cb) { 5921 verbose(env, "cannot tail call within exception cb\n"); 5922 return -EINVAL; 5923 } 5924 subprog[ret_prog[j]].tail_call_reachable = true; 5925 } 5926 if (subprog[0].tail_call_reachable) 5927 env->prog->aux->tail_call_reachable = true; 5928 5929 /* end of for() loop means the last insn of the 'subprog' 5930 * was reached. Doesn't matter whether it was JA or EXIT 5931 */ 5932 if (frame == 0) 5933 return 0; 5934 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5935 frame--; 5936 i = ret_insn[frame]; 5937 idx = ret_prog[frame]; 5938 goto continue_func; 5939 } 5940 5941 static int check_max_stack_depth(struct bpf_verifier_env *env) 5942 { 5943 struct bpf_subprog_info *si = env->subprog_info; 5944 int ret; 5945 5946 for (int i = 0; i < env->subprog_cnt; i++) { 5947 if (!i || si[i].is_async_cb) { 5948 ret = check_max_stack_depth_subprog(env, i); 5949 if (ret < 0) 5950 return ret; 5951 } 5952 continue; 5953 } 5954 return 0; 5955 } 5956 5957 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 5958 static int get_callee_stack_depth(struct bpf_verifier_env *env, 5959 const struct bpf_insn *insn, int idx) 5960 { 5961 int start = idx + insn->imm + 1, subprog; 5962 5963 subprog = find_subprog(env, start); 5964 if (subprog < 0) { 5965 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5966 start); 5967 return -EFAULT; 5968 } 5969 return env->subprog_info[subprog].stack_depth; 5970 } 5971 #endif 5972 5973 static int __check_buffer_access(struct bpf_verifier_env *env, 5974 const char *buf_info, 5975 const struct bpf_reg_state *reg, 5976 int regno, int off, int size) 5977 { 5978 if (off < 0) { 5979 verbose(env, 5980 "R%d invalid %s buffer access: off=%d, size=%d\n", 5981 regno, buf_info, off, size); 5982 return -EACCES; 5983 } 5984 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5985 char tn_buf[48]; 5986 5987 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5988 verbose(env, 5989 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 5990 regno, off, tn_buf); 5991 return -EACCES; 5992 } 5993 5994 return 0; 5995 } 5996 5997 static int check_tp_buffer_access(struct bpf_verifier_env *env, 5998 const struct bpf_reg_state *reg, 5999 int regno, int off, int size) 6000 { 6001 int err; 6002 6003 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 6004 if (err) 6005 return err; 6006 6007 if (off + size > env->prog->aux->max_tp_access) 6008 env->prog->aux->max_tp_access = off + size; 6009 6010 return 0; 6011 } 6012 6013 static int check_buffer_access(struct bpf_verifier_env *env, 6014 const struct bpf_reg_state *reg, 6015 int regno, int off, int size, 6016 bool zero_size_allowed, 6017 u32 *max_access) 6018 { 6019 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 6020 int err; 6021 6022 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 6023 if (err) 6024 return err; 6025 6026 if (off + size > *max_access) 6027 *max_access = off + size; 6028 6029 return 0; 6030 } 6031 6032 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 6033 static void zext_32_to_64(struct bpf_reg_state *reg) 6034 { 6035 reg->var_off = tnum_subreg(reg->var_off); 6036 __reg_assign_32_into_64(reg); 6037 } 6038 6039 /* truncate register to smaller size (in bytes) 6040 * must be called with size < BPF_REG_SIZE 6041 */ 6042 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 6043 { 6044 u64 mask; 6045 6046 /* clear high bits in bit representation */ 6047 reg->var_off = tnum_cast(reg->var_off, size); 6048 6049 /* fix arithmetic bounds */ 6050 mask = ((u64)1 << (size * 8)) - 1; 6051 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 6052 reg->umin_value &= mask; 6053 reg->umax_value &= mask; 6054 } else { 6055 reg->umin_value = 0; 6056 reg->umax_value = mask; 6057 } 6058 reg->smin_value = reg->umin_value; 6059 reg->smax_value = reg->umax_value; 6060 6061 /* If size is smaller than 32bit register the 32bit register 6062 * values are also truncated so we push 64-bit bounds into 6063 * 32-bit bounds. Above were truncated < 32-bits already. 6064 */ 6065 if (size < 4) { 6066 __mark_reg32_unbounded(reg); 6067 reg_bounds_sync(reg); 6068 } 6069 } 6070 6071 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 6072 { 6073 if (size == 1) { 6074 reg->smin_value = reg->s32_min_value = S8_MIN; 6075 reg->smax_value = reg->s32_max_value = S8_MAX; 6076 } else if (size == 2) { 6077 reg->smin_value = reg->s32_min_value = S16_MIN; 6078 reg->smax_value = reg->s32_max_value = S16_MAX; 6079 } else { 6080 /* size == 4 */ 6081 reg->smin_value = reg->s32_min_value = S32_MIN; 6082 reg->smax_value = reg->s32_max_value = S32_MAX; 6083 } 6084 reg->umin_value = reg->u32_min_value = 0; 6085 reg->umax_value = U64_MAX; 6086 reg->u32_max_value = U32_MAX; 6087 reg->var_off = tnum_unknown; 6088 } 6089 6090 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6091 { 6092 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6093 u64 top_smax_value, top_smin_value; 6094 u64 num_bits = size * 8; 6095 6096 if (tnum_is_const(reg->var_off)) { 6097 u64_cval = reg->var_off.value; 6098 if (size == 1) 6099 reg->var_off = tnum_const((s8)u64_cval); 6100 else if (size == 2) 6101 reg->var_off = tnum_const((s16)u64_cval); 6102 else 6103 /* size == 4 */ 6104 reg->var_off = tnum_const((s32)u64_cval); 6105 6106 u64_cval = reg->var_off.value; 6107 reg->smax_value = reg->smin_value = u64_cval; 6108 reg->umax_value = reg->umin_value = u64_cval; 6109 reg->s32_max_value = reg->s32_min_value = u64_cval; 6110 reg->u32_max_value = reg->u32_min_value = u64_cval; 6111 return; 6112 } 6113 6114 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6115 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6116 6117 if (top_smax_value != top_smin_value) 6118 goto out; 6119 6120 /* find the s64_min and s64_min after sign extension */ 6121 if (size == 1) { 6122 init_s64_max = (s8)reg->smax_value; 6123 init_s64_min = (s8)reg->smin_value; 6124 } else if (size == 2) { 6125 init_s64_max = (s16)reg->smax_value; 6126 init_s64_min = (s16)reg->smin_value; 6127 } else { 6128 init_s64_max = (s32)reg->smax_value; 6129 init_s64_min = (s32)reg->smin_value; 6130 } 6131 6132 s64_max = max(init_s64_max, init_s64_min); 6133 s64_min = min(init_s64_max, init_s64_min); 6134 6135 /* both of s64_max/s64_min positive or negative */ 6136 if ((s64_max >= 0) == (s64_min >= 0)) { 6137 reg->smin_value = reg->s32_min_value = s64_min; 6138 reg->smax_value = reg->s32_max_value = s64_max; 6139 reg->umin_value = reg->u32_min_value = s64_min; 6140 reg->umax_value = reg->u32_max_value = s64_max; 6141 reg->var_off = tnum_range(s64_min, s64_max); 6142 return; 6143 } 6144 6145 out: 6146 set_sext64_default_val(reg, size); 6147 } 6148 6149 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6150 { 6151 if (size == 1) { 6152 reg->s32_min_value = S8_MIN; 6153 reg->s32_max_value = S8_MAX; 6154 } else { 6155 /* size == 2 */ 6156 reg->s32_min_value = S16_MIN; 6157 reg->s32_max_value = S16_MAX; 6158 } 6159 reg->u32_min_value = 0; 6160 reg->u32_max_value = U32_MAX; 6161 } 6162 6163 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6164 { 6165 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6166 u32 top_smax_value, top_smin_value; 6167 u32 num_bits = size * 8; 6168 6169 if (tnum_is_const(reg->var_off)) { 6170 u32_val = reg->var_off.value; 6171 if (size == 1) 6172 reg->var_off = tnum_const((s8)u32_val); 6173 else 6174 reg->var_off = tnum_const((s16)u32_val); 6175 6176 u32_val = reg->var_off.value; 6177 reg->s32_min_value = reg->s32_max_value = u32_val; 6178 reg->u32_min_value = reg->u32_max_value = u32_val; 6179 return; 6180 } 6181 6182 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 6183 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 6184 6185 if (top_smax_value != top_smin_value) 6186 goto out; 6187 6188 /* find the s32_min and s32_min after sign extension */ 6189 if (size == 1) { 6190 init_s32_max = (s8)reg->s32_max_value; 6191 init_s32_min = (s8)reg->s32_min_value; 6192 } else { 6193 /* size == 2 */ 6194 init_s32_max = (s16)reg->s32_max_value; 6195 init_s32_min = (s16)reg->s32_min_value; 6196 } 6197 s32_max = max(init_s32_max, init_s32_min); 6198 s32_min = min(init_s32_max, init_s32_min); 6199 6200 if ((s32_min >= 0) == (s32_max >= 0)) { 6201 reg->s32_min_value = s32_min; 6202 reg->s32_max_value = s32_max; 6203 reg->u32_min_value = (u32)s32_min; 6204 reg->u32_max_value = (u32)s32_max; 6205 return; 6206 } 6207 6208 out: 6209 set_sext32_default_val(reg, size); 6210 } 6211 6212 static bool bpf_map_is_rdonly(const struct bpf_map *map) 6213 { 6214 /* A map is considered read-only if the following condition are true: 6215 * 6216 * 1) BPF program side cannot change any of the map content. The 6217 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6218 * and was set at map creation time. 6219 * 2) The map value(s) have been initialized from user space by a 6220 * loader and then "frozen", such that no new map update/delete 6221 * operations from syscall side are possible for the rest of 6222 * the map's lifetime from that point onwards. 6223 * 3) Any parallel/pending map update/delete operations from syscall 6224 * side have been completed. Only after that point, it's safe to 6225 * assume that map value(s) are immutable. 6226 */ 6227 return (map->map_flags & BPF_F_RDONLY_PROG) && 6228 READ_ONCE(map->frozen) && 6229 !bpf_map_write_active(map); 6230 } 6231 6232 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6233 bool is_ldsx) 6234 { 6235 void *ptr; 6236 u64 addr; 6237 int err; 6238 6239 err = map->ops->map_direct_value_addr(map, &addr, off); 6240 if (err) 6241 return err; 6242 ptr = (void *)(long)addr + off; 6243 6244 switch (size) { 6245 case sizeof(u8): 6246 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6247 break; 6248 case sizeof(u16): 6249 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6250 break; 6251 case sizeof(u32): 6252 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6253 break; 6254 case sizeof(u64): 6255 *val = *(u64 *)ptr; 6256 break; 6257 default: 6258 return -EINVAL; 6259 } 6260 return 0; 6261 } 6262 6263 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6264 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6265 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6266 6267 /* 6268 * Allow list few fields as RCU trusted or full trusted. 6269 * This logic doesn't allow mix tagging and will be removed once GCC supports 6270 * btf_type_tag. 6271 */ 6272 6273 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6274 BTF_TYPE_SAFE_RCU(struct task_struct) { 6275 const cpumask_t *cpus_ptr; 6276 struct css_set __rcu *cgroups; 6277 struct task_struct __rcu *real_parent; 6278 struct task_struct *group_leader; 6279 }; 6280 6281 BTF_TYPE_SAFE_RCU(struct cgroup) { 6282 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6283 struct kernfs_node *kn; 6284 }; 6285 6286 BTF_TYPE_SAFE_RCU(struct css_set) { 6287 struct cgroup *dfl_cgrp; 6288 }; 6289 6290 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6291 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6292 struct file __rcu *exe_file; 6293 }; 6294 6295 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6296 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6297 */ 6298 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6299 struct sock *sk; 6300 }; 6301 6302 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6303 struct sock *sk; 6304 }; 6305 6306 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6307 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6308 struct seq_file *seq; 6309 }; 6310 6311 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6312 struct bpf_iter_meta *meta; 6313 struct task_struct *task; 6314 }; 6315 6316 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6317 struct file *file; 6318 }; 6319 6320 BTF_TYPE_SAFE_TRUSTED(struct file) { 6321 struct inode *f_inode; 6322 }; 6323 6324 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 6325 /* no negative dentry-s in places where bpf can see it */ 6326 struct inode *d_inode; 6327 }; 6328 6329 BTF_TYPE_SAFE_TRUSTED(struct socket) { 6330 struct sock *sk; 6331 }; 6332 6333 static bool type_is_rcu(struct bpf_verifier_env *env, 6334 struct bpf_reg_state *reg, 6335 const char *field_name, u32 btf_id) 6336 { 6337 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6338 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6339 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6340 6341 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6342 } 6343 6344 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6345 struct bpf_reg_state *reg, 6346 const char *field_name, u32 btf_id) 6347 { 6348 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6349 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6350 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6351 6352 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6353 } 6354 6355 static bool type_is_trusted(struct bpf_verifier_env *env, 6356 struct bpf_reg_state *reg, 6357 const char *field_name, u32 btf_id) 6358 { 6359 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 6360 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6361 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6362 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6363 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 6364 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket)); 6365 6366 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6367 } 6368 6369 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6370 struct bpf_reg_state *regs, 6371 int regno, int off, int size, 6372 enum bpf_access_type atype, 6373 int value_regno) 6374 { 6375 struct bpf_reg_state *reg = regs + regno; 6376 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6377 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6378 const char *field_name = NULL; 6379 enum bpf_type_flag flag = 0; 6380 u32 btf_id = 0; 6381 int ret; 6382 6383 if (!env->allow_ptr_leaks) { 6384 verbose(env, 6385 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6386 tname); 6387 return -EPERM; 6388 } 6389 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6390 verbose(env, 6391 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6392 tname); 6393 return -EINVAL; 6394 } 6395 if (off < 0) { 6396 verbose(env, 6397 "R%d is ptr_%s invalid negative access: off=%d\n", 6398 regno, tname, off); 6399 return -EACCES; 6400 } 6401 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6402 char tn_buf[48]; 6403 6404 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6405 verbose(env, 6406 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6407 regno, tname, off, tn_buf); 6408 return -EACCES; 6409 } 6410 6411 if (reg->type & MEM_USER) { 6412 verbose(env, 6413 "R%d is ptr_%s access user memory: off=%d\n", 6414 regno, tname, off); 6415 return -EACCES; 6416 } 6417 6418 if (reg->type & MEM_PERCPU) { 6419 verbose(env, 6420 "R%d is ptr_%s access percpu memory: off=%d\n", 6421 regno, tname, off); 6422 return -EACCES; 6423 } 6424 6425 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6426 if (!btf_is_kernel(reg->btf)) { 6427 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 6428 return -EFAULT; 6429 } 6430 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6431 } else { 6432 /* Writes are permitted with default btf_struct_access for 6433 * program allocated objects (which always have ref_obj_id > 0), 6434 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6435 */ 6436 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6437 verbose(env, "only read is supported\n"); 6438 return -EACCES; 6439 } 6440 6441 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6442 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 6443 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 6444 return -EFAULT; 6445 } 6446 6447 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6448 } 6449 6450 if (ret < 0) 6451 return ret; 6452 6453 if (ret != PTR_TO_BTF_ID) { 6454 /* just mark; */ 6455 6456 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6457 /* If this is an untrusted pointer, all pointers formed by walking it 6458 * also inherit the untrusted flag. 6459 */ 6460 flag = PTR_UNTRUSTED; 6461 6462 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6463 /* By default any pointer obtained from walking a trusted pointer is no 6464 * longer trusted, unless the field being accessed has explicitly been 6465 * marked as inheriting its parent's state of trust (either full or RCU). 6466 * For example: 6467 * 'cgroups' pointer is untrusted if task->cgroups dereference 6468 * happened in a sleepable program outside of bpf_rcu_read_lock() 6469 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6470 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6471 * 6472 * A regular RCU-protected pointer with __rcu tag can also be deemed 6473 * trusted if we are in an RCU CS. Such pointer can be NULL. 6474 */ 6475 if (type_is_trusted(env, reg, field_name, btf_id)) { 6476 flag |= PTR_TRUSTED; 6477 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6478 if (type_is_rcu(env, reg, field_name, btf_id)) { 6479 /* ignore __rcu tag and mark it MEM_RCU */ 6480 flag |= MEM_RCU; 6481 } else if (flag & MEM_RCU || 6482 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6483 /* __rcu tagged pointers can be NULL */ 6484 flag |= MEM_RCU | PTR_MAYBE_NULL; 6485 6486 /* We always trust them */ 6487 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6488 flag & PTR_UNTRUSTED) 6489 flag &= ~PTR_UNTRUSTED; 6490 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6491 /* keep as-is */ 6492 } else { 6493 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6494 clear_trusted_flags(&flag); 6495 } 6496 } else { 6497 /* 6498 * If not in RCU CS or MEM_RCU pointer can be NULL then 6499 * aggressively mark as untrusted otherwise such 6500 * pointers will be plain PTR_TO_BTF_ID without flags 6501 * and will be allowed to be passed into helpers for 6502 * compat reasons. 6503 */ 6504 flag = PTR_UNTRUSTED; 6505 } 6506 } else { 6507 /* Old compat. Deprecated */ 6508 clear_trusted_flags(&flag); 6509 } 6510 6511 if (atype == BPF_READ && value_regno >= 0) 6512 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6513 6514 return 0; 6515 } 6516 6517 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6518 struct bpf_reg_state *regs, 6519 int regno, int off, int size, 6520 enum bpf_access_type atype, 6521 int value_regno) 6522 { 6523 struct bpf_reg_state *reg = regs + regno; 6524 struct bpf_map *map = reg->map_ptr; 6525 struct bpf_reg_state map_reg; 6526 enum bpf_type_flag flag = 0; 6527 const struct btf_type *t; 6528 const char *tname; 6529 u32 btf_id; 6530 int ret; 6531 6532 if (!btf_vmlinux) { 6533 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6534 return -ENOTSUPP; 6535 } 6536 6537 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6538 verbose(env, "map_ptr access not supported for map type %d\n", 6539 map->map_type); 6540 return -ENOTSUPP; 6541 } 6542 6543 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6544 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6545 6546 if (!env->allow_ptr_leaks) { 6547 verbose(env, 6548 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6549 tname); 6550 return -EPERM; 6551 } 6552 6553 if (off < 0) { 6554 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6555 regno, tname, off); 6556 return -EACCES; 6557 } 6558 6559 if (atype != BPF_READ) { 6560 verbose(env, "only read from %s is supported\n", tname); 6561 return -EACCES; 6562 } 6563 6564 /* Simulate access to a PTR_TO_BTF_ID */ 6565 memset(&map_reg, 0, sizeof(map_reg)); 6566 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6567 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6568 if (ret < 0) 6569 return ret; 6570 6571 if (value_regno >= 0) 6572 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6573 6574 return 0; 6575 } 6576 6577 /* Check that the stack access at the given offset is within bounds. The 6578 * maximum valid offset is -1. 6579 * 6580 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6581 * -state->allocated_stack for reads. 6582 */ 6583 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 6584 s64 off, 6585 struct bpf_func_state *state, 6586 enum bpf_access_type t) 6587 { 6588 int min_valid_off; 6589 6590 if (t == BPF_WRITE || env->allow_uninit_stack) 6591 min_valid_off = -MAX_BPF_STACK; 6592 else 6593 min_valid_off = -state->allocated_stack; 6594 6595 if (off < min_valid_off || off > -1) 6596 return -EACCES; 6597 return 0; 6598 } 6599 6600 /* Check that the stack access at 'regno + off' falls within the maximum stack 6601 * bounds. 6602 * 6603 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6604 */ 6605 static int check_stack_access_within_bounds( 6606 struct bpf_verifier_env *env, 6607 int regno, int off, int access_size, 6608 enum bpf_access_src src, enum bpf_access_type type) 6609 { 6610 struct bpf_reg_state *regs = cur_regs(env); 6611 struct bpf_reg_state *reg = regs + regno; 6612 struct bpf_func_state *state = func(env, reg); 6613 s64 min_off, max_off; 6614 int err; 6615 char *err_extra; 6616 6617 if (src == ACCESS_HELPER) 6618 /* We don't know if helpers are reading or writing (or both). */ 6619 err_extra = " indirect access to"; 6620 else if (type == BPF_READ) 6621 err_extra = " read from"; 6622 else 6623 err_extra = " write to"; 6624 6625 if (tnum_is_const(reg->var_off)) { 6626 min_off = (s64)reg->var_off.value + off; 6627 max_off = min_off + access_size; 6628 } else { 6629 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6630 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6631 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6632 err_extra, regno); 6633 return -EACCES; 6634 } 6635 min_off = reg->smin_value + off; 6636 max_off = reg->smax_value + off + access_size; 6637 } 6638 6639 err = check_stack_slot_within_bounds(env, min_off, state, type); 6640 if (!err && max_off > 0) 6641 err = -EINVAL; /* out of stack access into non-negative offsets */ 6642 6643 if (err) { 6644 if (tnum_is_const(reg->var_off)) { 6645 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 6646 err_extra, regno, off, access_size); 6647 } else { 6648 char tn_buf[48]; 6649 6650 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6651 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n", 6652 err_extra, regno, tn_buf, off, access_size); 6653 } 6654 return err; 6655 } 6656 6657 /* Note that there is no stack access with offset zero, so the needed stack 6658 * size is -min_off, not -min_off+1. 6659 */ 6660 return grow_stack_state(env, state, -min_off /* size */); 6661 } 6662 6663 /* check whether memory at (regno + off) is accessible for t = (read | write) 6664 * if t==write, value_regno is a register which value is stored into memory 6665 * if t==read, value_regno is a register which will receive the value from memory 6666 * if t==write && value_regno==-1, some unknown value is stored into memory 6667 * if t==read && value_regno==-1, don't care what we read from memory 6668 */ 6669 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6670 int off, int bpf_size, enum bpf_access_type t, 6671 int value_regno, bool strict_alignment_once, bool is_ldsx) 6672 { 6673 struct bpf_reg_state *regs = cur_regs(env); 6674 struct bpf_reg_state *reg = regs + regno; 6675 int size, err = 0; 6676 6677 size = bpf_size_to_bytes(bpf_size); 6678 if (size < 0) 6679 return size; 6680 6681 /* alignment checks will add in reg->off themselves */ 6682 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6683 if (err) 6684 return err; 6685 6686 /* for access checks, reg->off is just part of off */ 6687 off += reg->off; 6688 6689 if (reg->type == PTR_TO_MAP_KEY) { 6690 if (t == BPF_WRITE) { 6691 verbose(env, "write to change key R%d not allowed\n", regno); 6692 return -EACCES; 6693 } 6694 6695 err = check_mem_region_access(env, regno, off, size, 6696 reg->map_ptr->key_size, false); 6697 if (err) 6698 return err; 6699 if (value_regno >= 0) 6700 mark_reg_unknown(env, regs, value_regno); 6701 } else if (reg->type == PTR_TO_MAP_VALUE) { 6702 struct btf_field *kptr_field = NULL; 6703 6704 if (t == BPF_WRITE && value_regno >= 0 && 6705 is_pointer_value(env, value_regno)) { 6706 verbose(env, "R%d leaks addr into map\n", value_regno); 6707 return -EACCES; 6708 } 6709 err = check_map_access_type(env, regno, off, size, t); 6710 if (err) 6711 return err; 6712 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6713 if (err) 6714 return err; 6715 if (tnum_is_const(reg->var_off)) 6716 kptr_field = btf_record_find(reg->map_ptr->record, 6717 off + reg->var_off.value, BPF_KPTR); 6718 if (kptr_field) { 6719 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6720 } else if (t == BPF_READ && value_regno >= 0) { 6721 struct bpf_map *map = reg->map_ptr; 6722 6723 /* if map is read-only, track its contents as scalars */ 6724 if (tnum_is_const(reg->var_off) && 6725 bpf_map_is_rdonly(map) && 6726 map->ops->map_direct_value_addr) { 6727 int map_off = off + reg->var_off.value; 6728 u64 val = 0; 6729 6730 err = bpf_map_direct_read(map, map_off, size, 6731 &val, is_ldsx); 6732 if (err) 6733 return err; 6734 6735 regs[value_regno].type = SCALAR_VALUE; 6736 __mark_reg_known(®s[value_regno], val); 6737 } else { 6738 mark_reg_unknown(env, regs, value_regno); 6739 } 6740 } 6741 } else if (base_type(reg->type) == PTR_TO_MEM) { 6742 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6743 6744 if (type_may_be_null(reg->type)) { 6745 verbose(env, "R%d invalid mem access '%s'\n", regno, 6746 reg_type_str(env, reg->type)); 6747 return -EACCES; 6748 } 6749 6750 if (t == BPF_WRITE && rdonly_mem) { 6751 verbose(env, "R%d cannot write into %s\n", 6752 regno, reg_type_str(env, reg->type)); 6753 return -EACCES; 6754 } 6755 6756 if (t == BPF_WRITE && value_regno >= 0 && 6757 is_pointer_value(env, value_regno)) { 6758 verbose(env, "R%d leaks addr into mem\n", value_regno); 6759 return -EACCES; 6760 } 6761 6762 err = check_mem_region_access(env, regno, off, size, 6763 reg->mem_size, false); 6764 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6765 mark_reg_unknown(env, regs, value_regno); 6766 } else if (reg->type == PTR_TO_CTX) { 6767 enum bpf_reg_type reg_type = SCALAR_VALUE; 6768 struct btf *btf = NULL; 6769 u32 btf_id = 0; 6770 6771 if (t == BPF_WRITE && value_regno >= 0 && 6772 is_pointer_value(env, value_regno)) { 6773 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6774 return -EACCES; 6775 } 6776 6777 err = check_ptr_off_reg(env, reg, regno); 6778 if (err < 0) 6779 return err; 6780 6781 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 6782 &btf_id); 6783 if (err) 6784 verbose_linfo(env, insn_idx, "; "); 6785 if (!err && t == BPF_READ && value_regno >= 0) { 6786 /* ctx access returns either a scalar, or a 6787 * PTR_TO_PACKET[_META,_END]. In the latter 6788 * case, we know the offset is zero. 6789 */ 6790 if (reg_type == SCALAR_VALUE) { 6791 mark_reg_unknown(env, regs, value_regno); 6792 } else { 6793 mark_reg_known_zero(env, regs, 6794 value_regno); 6795 if (type_may_be_null(reg_type)) 6796 regs[value_regno].id = ++env->id_gen; 6797 /* A load of ctx field could have different 6798 * actual load size with the one encoded in the 6799 * insn. When the dst is PTR, it is for sure not 6800 * a sub-register. 6801 */ 6802 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6803 if (base_type(reg_type) == PTR_TO_BTF_ID) { 6804 regs[value_regno].btf = btf; 6805 regs[value_regno].btf_id = btf_id; 6806 } 6807 } 6808 regs[value_regno].type = reg_type; 6809 } 6810 6811 } else if (reg->type == PTR_TO_STACK) { 6812 /* Basic bounds checks. */ 6813 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 6814 if (err) 6815 return err; 6816 6817 if (t == BPF_READ) 6818 err = check_stack_read(env, regno, off, size, 6819 value_regno); 6820 else 6821 err = check_stack_write(env, regno, off, size, 6822 value_regno, insn_idx); 6823 } else if (reg_is_pkt_pointer(reg)) { 6824 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6825 verbose(env, "cannot write into packet\n"); 6826 return -EACCES; 6827 } 6828 if (t == BPF_WRITE && value_regno >= 0 && 6829 is_pointer_value(env, value_regno)) { 6830 verbose(env, "R%d leaks addr into packet\n", 6831 value_regno); 6832 return -EACCES; 6833 } 6834 err = check_packet_access(env, regno, off, size, false); 6835 if (!err && t == BPF_READ && value_regno >= 0) 6836 mark_reg_unknown(env, regs, value_regno); 6837 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6838 if (t == BPF_WRITE && value_regno >= 0 && 6839 is_pointer_value(env, value_regno)) { 6840 verbose(env, "R%d leaks addr into flow keys\n", 6841 value_regno); 6842 return -EACCES; 6843 } 6844 6845 err = check_flow_keys_access(env, off, size); 6846 if (!err && t == BPF_READ && value_regno >= 0) 6847 mark_reg_unknown(env, regs, value_regno); 6848 } else if (type_is_sk_pointer(reg->type)) { 6849 if (t == BPF_WRITE) { 6850 verbose(env, "R%d cannot write into %s\n", 6851 regno, reg_type_str(env, reg->type)); 6852 return -EACCES; 6853 } 6854 err = check_sock_access(env, insn_idx, regno, off, size, t); 6855 if (!err && value_regno >= 0) 6856 mark_reg_unknown(env, regs, value_regno); 6857 } else if (reg->type == PTR_TO_TP_BUFFER) { 6858 err = check_tp_buffer_access(env, reg, regno, off, size); 6859 if (!err && t == BPF_READ && value_regno >= 0) 6860 mark_reg_unknown(env, regs, value_regno); 6861 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6862 !type_may_be_null(reg->type)) { 6863 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 6864 value_regno); 6865 } else if (reg->type == CONST_PTR_TO_MAP) { 6866 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 6867 value_regno); 6868 } else if (base_type(reg->type) == PTR_TO_BUF) { 6869 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6870 u32 *max_access; 6871 6872 if (rdonly_mem) { 6873 if (t == BPF_WRITE) { 6874 verbose(env, "R%d cannot write into %s\n", 6875 regno, reg_type_str(env, reg->type)); 6876 return -EACCES; 6877 } 6878 max_access = &env->prog->aux->max_rdonly_access; 6879 } else { 6880 max_access = &env->prog->aux->max_rdwr_access; 6881 } 6882 6883 err = check_buffer_access(env, reg, regno, off, size, false, 6884 max_access); 6885 6886 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6887 mark_reg_unknown(env, regs, value_regno); 6888 } else { 6889 verbose(env, "R%d invalid mem access '%s'\n", regno, 6890 reg_type_str(env, reg->type)); 6891 return -EACCES; 6892 } 6893 6894 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6895 regs[value_regno].type == SCALAR_VALUE) { 6896 if (!is_ldsx) 6897 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6898 coerce_reg_to_size(®s[value_regno], size); 6899 else 6900 coerce_reg_to_size_sx(®s[value_regno], size); 6901 } 6902 return err; 6903 } 6904 6905 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 6906 { 6907 int load_reg; 6908 int err; 6909 6910 switch (insn->imm) { 6911 case BPF_ADD: 6912 case BPF_ADD | BPF_FETCH: 6913 case BPF_AND: 6914 case BPF_AND | BPF_FETCH: 6915 case BPF_OR: 6916 case BPF_OR | BPF_FETCH: 6917 case BPF_XOR: 6918 case BPF_XOR | BPF_FETCH: 6919 case BPF_XCHG: 6920 case BPF_CMPXCHG: 6921 break; 6922 default: 6923 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 6924 return -EINVAL; 6925 } 6926 6927 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6928 verbose(env, "invalid atomic operand size\n"); 6929 return -EINVAL; 6930 } 6931 6932 /* check src1 operand */ 6933 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6934 if (err) 6935 return err; 6936 6937 /* check src2 operand */ 6938 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6939 if (err) 6940 return err; 6941 6942 if (insn->imm == BPF_CMPXCHG) { 6943 /* Check comparison of R0 with memory location */ 6944 const u32 aux_reg = BPF_REG_0; 6945 6946 err = check_reg_arg(env, aux_reg, SRC_OP); 6947 if (err) 6948 return err; 6949 6950 if (is_pointer_value(env, aux_reg)) { 6951 verbose(env, "R%d leaks addr into mem\n", aux_reg); 6952 return -EACCES; 6953 } 6954 } 6955 6956 if (is_pointer_value(env, insn->src_reg)) { 6957 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 6958 return -EACCES; 6959 } 6960 6961 if (is_ctx_reg(env, insn->dst_reg) || 6962 is_pkt_reg(env, insn->dst_reg) || 6963 is_flow_key_reg(env, insn->dst_reg) || 6964 is_sk_reg(env, insn->dst_reg)) { 6965 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6966 insn->dst_reg, 6967 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6968 return -EACCES; 6969 } 6970 6971 if (insn->imm & BPF_FETCH) { 6972 if (insn->imm == BPF_CMPXCHG) 6973 load_reg = BPF_REG_0; 6974 else 6975 load_reg = insn->src_reg; 6976 6977 /* check and record load of old value */ 6978 err = check_reg_arg(env, load_reg, DST_OP); 6979 if (err) 6980 return err; 6981 } else { 6982 /* This instruction accesses a memory location but doesn't 6983 * actually load it into a register. 6984 */ 6985 load_reg = -1; 6986 } 6987 6988 /* Check whether we can read the memory, with second call for fetch 6989 * case to simulate the register fill. 6990 */ 6991 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6992 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 6993 if (!err && load_reg >= 0) 6994 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6995 BPF_SIZE(insn->code), BPF_READ, load_reg, 6996 true, false); 6997 if (err) 6998 return err; 6999 7000 /* Check whether we can write into the same memory. */ 7001 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7002 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 7003 if (err) 7004 return err; 7005 return 0; 7006 } 7007 7008 /* When register 'regno' is used to read the stack (either directly or through 7009 * a helper function) make sure that it's within stack boundary and, depending 7010 * on the access type and privileges, that all elements of the stack are 7011 * initialized. 7012 * 7013 * 'off' includes 'regno->off', but not its dynamic part (if any). 7014 * 7015 * All registers that have been spilled on the stack in the slots within the 7016 * read offsets are marked as read. 7017 */ 7018 static int check_stack_range_initialized( 7019 struct bpf_verifier_env *env, int regno, int off, 7020 int access_size, bool zero_size_allowed, 7021 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 7022 { 7023 struct bpf_reg_state *reg = reg_state(env, regno); 7024 struct bpf_func_state *state = func(env, reg); 7025 int err, min_off, max_off, i, j, slot, spi; 7026 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 7027 enum bpf_access_type bounds_check_type; 7028 /* Some accesses can write anything into the stack, others are 7029 * read-only. 7030 */ 7031 bool clobber = false; 7032 7033 if (access_size == 0 && !zero_size_allowed) { 7034 verbose(env, "invalid zero-sized read\n"); 7035 return -EACCES; 7036 } 7037 7038 if (type == ACCESS_HELPER) { 7039 /* The bounds checks for writes are more permissive than for 7040 * reads. However, if raw_mode is not set, we'll do extra 7041 * checks below. 7042 */ 7043 bounds_check_type = BPF_WRITE; 7044 clobber = true; 7045 } else { 7046 bounds_check_type = BPF_READ; 7047 } 7048 err = check_stack_access_within_bounds(env, regno, off, access_size, 7049 type, bounds_check_type); 7050 if (err) 7051 return err; 7052 7053 7054 if (tnum_is_const(reg->var_off)) { 7055 min_off = max_off = reg->var_off.value + off; 7056 } else { 7057 /* Variable offset is prohibited for unprivileged mode for 7058 * simplicity since it requires corresponding support in 7059 * Spectre masking for stack ALU. 7060 * See also retrieve_ptr_limit(). 7061 */ 7062 if (!env->bypass_spec_v1) { 7063 char tn_buf[48]; 7064 7065 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7066 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 7067 regno, err_extra, tn_buf); 7068 return -EACCES; 7069 } 7070 /* Only initialized buffer on stack is allowed to be accessed 7071 * with variable offset. With uninitialized buffer it's hard to 7072 * guarantee that whole memory is marked as initialized on 7073 * helper return since specific bounds are unknown what may 7074 * cause uninitialized stack leaking. 7075 */ 7076 if (meta && meta->raw_mode) 7077 meta = NULL; 7078 7079 min_off = reg->smin_value + off; 7080 max_off = reg->smax_value + off; 7081 } 7082 7083 if (meta && meta->raw_mode) { 7084 /* Ensure we won't be overwriting dynptrs when simulating byte 7085 * by byte access in check_helper_call using meta.access_size. 7086 * This would be a problem if we have a helper in the future 7087 * which takes: 7088 * 7089 * helper(uninit_mem, len, dynptr) 7090 * 7091 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 7092 * may end up writing to dynptr itself when touching memory from 7093 * arg 1. This can be relaxed on a case by case basis for known 7094 * safe cases, but reject due to the possibilitiy of aliasing by 7095 * default. 7096 */ 7097 for (i = min_off; i < max_off + access_size; i++) { 7098 int stack_off = -i - 1; 7099 7100 spi = __get_spi(i); 7101 /* raw_mode may write past allocated_stack */ 7102 if (state->allocated_stack <= stack_off) 7103 continue; 7104 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 7105 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 7106 return -EACCES; 7107 } 7108 } 7109 meta->access_size = access_size; 7110 meta->regno = regno; 7111 return 0; 7112 } 7113 7114 for (i = min_off; i < max_off + access_size; i++) { 7115 u8 *stype; 7116 7117 slot = -i - 1; 7118 spi = slot / BPF_REG_SIZE; 7119 if (state->allocated_stack <= slot) { 7120 verbose(env, "verifier bug: allocated_stack too small"); 7121 return -EFAULT; 7122 } 7123 7124 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 7125 if (*stype == STACK_MISC) 7126 goto mark; 7127 if ((*stype == STACK_ZERO) || 7128 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 7129 if (clobber) { 7130 /* helper can write anything into the stack */ 7131 *stype = STACK_MISC; 7132 } 7133 goto mark; 7134 } 7135 7136 if (is_spilled_reg(&state->stack[spi]) && 7137 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 7138 env->allow_ptr_leaks)) { 7139 if (clobber) { 7140 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 7141 for (j = 0; j < BPF_REG_SIZE; j++) 7142 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 7143 } 7144 goto mark; 7145 } 7146 7147 if (tnum_is_const(reg->var_off)) { 7148 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 7149 err_extra, regno, min_off, i - min_off, access_size); 7150 } else { 7151 char tn_buf[48]; 7152 7153 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7154 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 7155 err_extra, regno, tn_buf, i - min_off, access_size); 7156 } 7157 return -EACCES; 7158 mark: 7159 /* reading any byte out of 8-byte 'spill_slot' will cause 7160 * the whole slot to be marked as 'read' 7161 */ 7162 mark_reg_read(env, &state->stack[spi].spilled_ptr, 7163 state->stack[spi].spilled_ptr.parent, 7164 REG_LIVE_READ64); 7165 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 7166 * be sure that whether stack slot is written to or not. Hence, 7167 * we must still conservatively propagate reads upwards even if 7168 * helper may write to the entire memory range. 7169 */ 7170 } 7171 return 0; 7172 } 7173 7174 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 7175 int access_size, bool zero_size_allowed, 7176 struct bpf_call_arg_meta *meta) 7177 { 7178 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7179 u32 *max_access; 7180 7181 switch (base_type(reg->type)) { 7182 case PTR_TO_PACKET: 7183 case PTR_TO_PACKET_META: 7184 return check_packet_access(env, regno, reg->off, access_size, 7185 zero_size_allowed); 7186 case PTR_TO_MAP_KEY: 7187 if (meta && meta->raw_mode) { 7188 verbose(env, "R%d cannot write into %s\n", regno, 7189 reg_type_str(env, reg->type)); 7190 return -EACCES; 7191 } 7192 return check_mem_region_access(env, regno, reg->off, access_size, 7193 reg->map_ptr->key_size, false); 7194 case PTR_TO_MAP_VALUE: 7195 if (check_map_access_type(env, regno, reg->off, access_size, 7196 meta && meta->raw_mode ? BPF_WRITE : 7197 BPF_READ)) 7198 return -EACCES; 7199 return check_map_access(env, regno, reg->off, access_size, 7200 zero_size_allowed, ACCESS_HELPER); 7201 case PTR_TO_MEM: 7202 if (type_is_rdonly_mem(reg->type)) { 7203 if (meta && meta->raw_mode) { 7204 verbose(env, "R%d cannot write into %s\n", regno, 7205 reg_type_str(env, reg->type)); 7206 return -EACCES; 7207 } 7208 } 7209 return check_mem_region_access(env, regno, reg->off, 7210 access_size, reg->mem_size, 7211 zero_size_allowed); 7212 case PTR_TO_BUF: 7213 if (type_is_rdonly_mem(reg->type)) { 7214 if (meta && meta->raw_mode) { 7215 verbose(env, "R%d cannot write into %s\n", regno, 7216 reg_type_str(env, reg->type)); 7217 return -EACCES; 7218 } 7219 7220 max_access = &env->prog->aux->max_rdonly_access; 7221 } else { 7222 max_access = &env->prog->aux->max_rdwr_access; 7223 } 7224 return check_buffer_access(env, reg, regno, reg->off, 7225 access_size, zero_size_allowed, 7226 max_access); 7227 case PTR_TO_STACK: 7228 return check_stack_range_initialized( 7229 env, 7230 regno, reg->off, access_size, 7231 zero_size_allowed, ACCESS_HELPER, meta); 7232 case PTR_TO_BTF_ID: 7233 return check_ptr_to_btf_access(env, regs, regno, reg->off, 7234 access_size, BPF_READ, -1); 7235 case PTR_TO_CTX: 7236 /* in case the function doesn't know how to access the context, 7237 * (because we are in a program of type SYSCALL for example), we 7238 * can not statically check its size. 7239 * Dynamically check it now. 7240 */ 7241 if (!env->ops->convert_ctx_access) { 7242 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 7243 int offset = access_size - 1; 7244 7245 /* Allow zero-byte read from PTR_TO_CTX */ 7246 if (access_size == 0) 7247 return zero_size_allowed ? 0 : -EACCES; 7248 7249 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 7250 atype, -1, false, false); 7251 } 7252 7253 fallthrough; 7254 default: /* scalar_value or invalid ptr */ 7255 /* Allow zero-byte read from NULL, regardless of pointer type */ 7256 if (zero_size_allowed && access_size == 0 && 7257 register_is_null(reg)) 7258 return 0; 7259 7260 verbose(env, "R%d type=%s ", regno, 7261 reg_type_str(env, reg->type)); 7262 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7263 return -EACCES; 7264 } 7265 } 7266 7267 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 7268 * size. 7269 * 7270 * @regno is the register containing the access size. regno-1 is the register 7271 * containing the pointer. 7272 */ 7273 static int check_mem_size_reg(struct bpf_verifier_env *env, 7274 struct bpf_reg_state *reg, u32 regno, 7275 bool zero_size_allowed, 7276 struct bpf_call_arg_meta *meta) 7277 { 7278 int err; 7279 7280 /* This is used to refine r0 return value bounds for helpers 7281 * that enforce this value as an upper bound on return values. 7282 * See do_refine_retval_range() for helpers that can refine 7283 * the return value. C type of helper is u32 so we pull register 7284 * bound from umax_value however, if negative verifier errors 7285 * out. Only upper bounds can be learned because retval is an 7286 * int type and negative retvals are allowed. 7287 */ 7288 meta->msize_max_value = reg->umax_value; 7289 7290 /* The register is SCALAR_VALUE; the access check 7291 * happens using its boundaries. 7292 */ 7293 if (!tnum_is_const(reg->var_off)) 7294 /* For unprivileged variable accesses, disable raw 7295 * mode so that the program is required to 7296 * initialize all the memory that the helper could 7297 * just partially fill up. 7298 */ 7299 meta = NULL; 7300 7301 if (reg->smin_value < 0) { 7302 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7303 regno); 7304 return -EACCES; 7305 } 7306 7307 if (reg->umin_value == 0 && !zero_size_allowed) { 7308 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n", 7309 regno, reg->umin_value, reg->umax_value); 7310 return -EACCES; 7311 } 7312 7313 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7314 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7315 regno); 7316 return -EACCES; 7317 } 7318 err = check_helper_mem_access(env, regno - 1, 7319 reg->umax_value, 7320 zero_size_allowed, meta); 7321 if (!err) 7322 err = mark_chain_precision(env, regno); 7323 return err; 7324 } 7325 7326 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7327 u32 regno, u32 mem_size) 7328 { 7329 bool may_be_null = type_may_be_null(reg->type); 7330 struct bpf_reg_state saved_reg; 7331 struct bpf_call_arg_meta meta; 7332 int err; 7333 7334 if (register_is_null(reg)) 7335 return 0; 7336 7337 memset(&meta, 0, sizeof(meta)); 7338 /* Assuming that the register contains a value check if the memory 7339 * access is safe. Temporarily save and restore the register's state as 7340 * the conversion shouldn't be visible to a caller. 7341 */ 7342 if (may_be_null) { 7343 saved_reg = *reg; 7344 mark_ptr_not_null_reg(reg); 7345 } 7346 7347 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 7348 /* Check access for BPF_WRITE */ 7349 meta.raw_mode = true; 7350 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 7351 7352 if (may_be_null) 7353 *reg = saved_reg; 7354 7355 return err; 7356 } 7357 7358 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7359 u32 regno) 7360 { 7361 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7362 bool may_be_null = type_may_be_null(mem_reg->type); 7363 struct bpf_reg_state saved_reg; 7364 struct bpf_call_arg_meta meta; 7365 int err; 7366 7367 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7368 7369 memset(&meta, 0, sizeof(meta)); 7370 7371 if (may_be_null) { 7372 saved_reg = *mem_reg; 7373 mark_ptr_not_null_reg(mem_reg); 7374 } 7375 7376 err = check_mem_size_reg(env, reg, regno, true, &meta); 7377 /* Check access for BPF_WRITE */ 7378 meta.raw_mode = true; 7379 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 7380 7381 if (may_be_null) 7382 *mem_reg = saved_reg; 7383 return err; 7384 } 7385 7386 /* Implementation details: 7387 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7388 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7389 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7390 * Two separate bpf_obj_new will also have different reg->id. 7391 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7392 * clears reg->id after value_or_null->value transition, since the verifier only 7393 * cares about the range of access to valid map value pointer and doesn't care 7394 * about actual address of the map element. 7395 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7396 * reg->id > 0 after value_or_null->value transition. By doing so 7397 * two bpf_map_lookups will be considered two different pointers that 7398 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7399 * returned from bpf_obj_new. 7400 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7401 * dead-locks. 7402 * Since only one bpf_spin_lock is allowed the checks are simpler than 7403 * reg_is_refcounted() logic. The verifier needs to remember only 7404 * one spin_lock instead of array of acquired_refs. 7405 * cur_state->active_lock remembers which map value element or allocated 7406 * object got locked and clears it after bpf_spin_unlock. 7407 */ 7408 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 7409 bool is_lock) 7410 { 7411 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7412 struct bpf_verifier_state *cur = env->cur_state; 7413 bool is_const = tnum_is_const(reg->var_off); 7414 u64 val = reg->var_off.value; 7415 struct bpf_map *map = NULL; 7416 struct btf *btf = NULL; 7417 struct btf_record *rec; 7418 7419 if (!is_const) { 7420 verbose(env, 7421 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 7422 regno); 7423 return -EINVAL; 7424 } 7425 if (reg->type == PTR_TO_MAP_VALUE) { 7426 map = reg->map_ptr; 7427 if (!map->btf) { 7428 verbose(env, 7429 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 7430 map->name); 7431 return -EINVAL; 7432 } 7433 } else { 7434 btf = reg->btf; 7435 } 7436 7437 rec = reg_btf_record(reg); 7438 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 7439 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 7440 map ? map->name : "kptr"); 7441 return -EINVAL; 7442 } 7443 if (rec->spin_lock_off != val + reg->off) { 7444 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 7445 val + reg->off, rec->spin_lock_off); 7446 return -EINVAL; 7447 } 7448 if (is_lock) { 7449 if (cur->active_lock.ptr) { 7450 verbose(env, 7451 "Locking two bpf_spin_locks are not allowed\n"); 7452 return -EINVAL; 7453 } 7454 if (map) 7455 cur->active_lock.ptr = map; 7456 else 7457 cur->active_lock.ptr = btf; 7458 cur->active_lock.id = reg->id; 7459 } else { 7460 void *ptr; 7461 7462 if (map) 7463 ptr = map; 7464 else 7465 ptr = btf; 7466 7467 if (!cur->active_lock.ptr) { 7468 verbose(env, "bpf_spin_unlock without taking a lock\n"); 7469 return -EINVAL; 7470 } 7471 if (cur->active_lock.ptr != ptr || 7472 cur->active_lock.id != reg->id) { 7473 verbose(env, "bpf_spin_unlock of different lock\n"); 7474 return -EINVAL; 7475 } 7476 7477 invalidate_non_owning_refs(env); 7478 7479 cur->active_lock.ptr = NULL; 7480 cur->active_lock.id = 0; 7481 } 7482 return 0; 7483 } 7484 7485 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7486 struct bpf_call_arg_meta *meta) 7487 { 7488 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7489 bool is_const = tnum_is_const(reg->var_off); 7490 struct bpf_map *map = reg->map_ptr; 7491 u64 val = reg->var_off.value; 7492 7493 if (!is_const) { 7494 verbose(env, 7495 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 7496 regno); 7497 return -EINVAL; 7498 } 7499 if (!map->btf) { 7500 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 7501 map->name); 7502 return -EINVAL; 7503 } 7504 if (!btf_record_has_field(map->record, BPF_TIMER)) { 7505 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 7506 return -EINVAL; 7507 } 7508 if (map->record->timer_off != val + reg->off) { 7509 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 7510 val + reg->off, map->record->timer_off); 7511 return -EINVAL; 7512 } 7513 if (meta->map_ptr) { 7514 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 7515 return -EFAULT; 7516 } 7517 meta->map_uid = reg->map_uid; 7518 meta->map_ptr = map; 7519 return 0; 7520 } 7521 7522 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7523 struct bpf_call_arg_meta *meta) 7524 { 7525 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7526 struct bpf_map *map_ptr = reg->map_ptr; 7527 struct btf_field *kptr_field; 7528 u32 kptr_off; 7529 7530 if (!tnum_is_const(reg->var_off)) { 7531 verbose(env, 7532 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7533 regno); 7534 return -EINVAL; 7535 } 7536 if (!map_ptr->btf) { 7537 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7538 map_ptr->name); 7539 return -EINVAL; 7540 } 7541 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 7542 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 7543 return -EINVAL; 7544 } 7545 7546 meta->map_ptr = map_ptr; 7547 kptr_off = reg->off + reg->var_off.value; 7548 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 7549 if (!kptr_field) { 7550 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7551 return -EACCES; 7552 } 7553 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7554 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7555 return -EACCES; 7556 } 7557 meta->kptr_field = kptr_field; 7558 return 0; 7559 } 7560 7561 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7562 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7563 * 7564 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7565 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7566 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7567 * 7568 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7569 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7570 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7571 * mutate the view of the dynptr and also possibly destroy it. In the latter 7572 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7573 * memory that dynptr points to. 7574 * 7575 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7576 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7577 * readonly dynptr view yet, hence only the first case is tracked and checked. 7578 * 7579 * This is consistent with how C applies the const modifier to a struct object, 7580 * where the pointer itself inside bpf_dynptr becomes const but not what it 7581 * points to. 7582 * 7583 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7584 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7585 */ 7586 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7587 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7588 { 7589 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7590 int err; 7591 7592 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7593 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7594 */ 7595 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7596 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 7597 return -EFAULT; 7598 } 7599 7600 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7601 * constructing a mutable bpf_dynptr object. 7602 * 7603 * Currently, this is only possible with PTR_TO_STACK 7604 * pointing to a region of at least 16 bytes which doesn't 7605 * contain an existing bpf_dynptr. 7606 * 7607 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7608 * mutated or destroyed. However, the memory it points to 7609 * may be mutated. 7610 * 7611 * None - Points to a initialized dynptr that can be mutated and 7612 * destroyed, including mutation of the memory it points 7613 * to. 7614 */ 7615 if (arg_type & MEM_UNINIT) { 7616 int i; 7617 7618 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7619 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7620 return -EINVAL; 7621 } 7622 7623 /* we write BPF_DW bits (8 bytes) at a time */ 7624 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7625 err = check_mem_access(env, insn_idx, regno, 7626 i, BPF_DW, BPF_WRITE, -1, false, false); 7627 if (err) 7628 return err; 7629 } 7630 7631 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7632 } else /* MEM_RDONLY and None case from above */ { 7633 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7634 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7635 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7636 return -EINVAL; 7637 } 7638 7639 if (!is_dynptr_reg_valid_init(env, reg)) { 7640 verbose(env, 7641 "Expected an initialized dynptr as arg #%d\n", 7642 regno); 7643 return -EINVAL; 7644 } 7645 7646 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7647 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7648 verbose(env, 7649 "Expected a dynptr of type %s as arg #%d\n", 7650 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 7651 return -EINVAL; 7652 } 7653 7654 err = mark_dynptr_read(env, reg); 7655 } 7656 return err; 7657 } 7658 7659 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7660 { 7661 struct bpf_func_state *state = func(env, reg); 7662 7663 return state->stack[spi].spilled_ptr.ref_obj_id; 7664 } 7665 7666 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7667 { 7668 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7669 } 7670 7671 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7672 { 7673 return meta->kfunc_flags & KF_ITER_NEW; 7674 } 7675 7676 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7677 { 7678 return meta->kfunc_flags & KF_ITER_NEXT; 7679 } 7680 7681 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7682 { 7683 return meta->kfunc_flags & KF_ITER_DESTROY; 7684 } 7685 7686 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg) 7687 { 7688 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7689 * kfunc is iter state pointer 7690 */ 7691 return arg == 0 && is_iter_kfunc(meta); 7692 } 7693 7694 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7695 struct bpf_kfunc_call_arg_meta *meta) 7696 { 7697 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7698 const struct btf_type *t; 7699 const struct btf_param *arg; 7700 int spi, err, i, nr_slots; 7701 u32 btf_id; 7702 7703 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */ 7704 arg = &btf_params(meta->func_proto)[0]; 7705 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */ 7706 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */ 7707 nr_slots = t->size / BPF_REG_SIZE; 7708 7709 if (is_iter_new_kfunc(meta)) { 7710 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7711 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7712 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 7713 iter_type_str(meta->btf, btf_id), regno); 7714 return -EINVAL; 7715 } 7716 7717 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7718 err = check_mem_access(env, insn_idx, regno, 7719 i, BPF_DW, BPF_WRITE, -1, false, false); 7720 if (err) 7721 return err; 7722 } 7723 7724 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 7725 if (err) 7726 return err; 7727 } else { 7728 /* iter_next() or iter_destroy() expect initialized iter state*/ 7729 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 7730 switch (err) { 7731 case 0: 7732 break; 7733 case -EINVAL: 7734 verbose(env, "expected an initialized iter_%s as arg #%d\n", 7735 iter_type_str(meta->btf, btf_id), regno); 7736 return err; 7737 case -EPROTO: 7738 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 7739 return err; 7740 default: 7741 return err; 7742 } 7743 7744 spi = iter_get_spi(env, reg, nr_slots); 7745 if (spi < 0) 7746 return spi; 7747 7748 err = mark_iter_read(env, reg, spi, nr_slots); 7749 if (err) 7750 return err; 7751 7752 /* remember meta->iter info for process_iter_next_call() */ 7753 meta->iter.spi = spi; 7754 meta->iter.frameno = reg->frameno; 7755 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 7756 7757 if (is_iter_destroy_kfunc(meta)) { 7758 err = unmark_stack_slots_iter(env, reg, nr_slots); 7759 if (err) 7760 return err; 7761 } 7762 } 7763 7764 return 0; 7765 } 7766 7767 /* Look for a previous loop entry at insn_idx: nearest parent state 7768 * stopped at insn_idx with callsites matching those in cur->frame. 7769 */ 7770 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 7771 struct bpf_verifier_state *cur, 7772 int insn_idx) 7773 { 7774 struct bpf_verifier_state_list *sl; 7775 struct bpf_verifier_state *st; 7776 7777 /* Explored states are pushed in stack order, most recent states come first */ 7778 sl = *explored_state(env, insn_idx); 7779 for (; sl; sl = sl->next) { 7780 /* If st->branches != 0 state is a part of current DFS verification path, 7781 * hence cur & st for a loop. 7782 */ 7783 st = &sl->state; 7784 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 7785 st->dfs_depth < cur->dfs_depth) 7786 return st; 7787 } 7788 7789 return NULL; 7790 } 7791 7792 static void reset_idmap_scratch(struct bpf_verifier_env *env); 7793 static bool regs_exact(const struct bpf_reg_state *rold, 7794 const struct bpf_reg_state *rcur, 7795 struct bpf_idmap *idmap); 7796 7797 static void maybe_widen_reg(struct bpf_verifier_env *env, 7798 struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 7799 struct bpf_idmap *idmap) 7800 { 7801 if (rold->type != SCALAR_VALUE) 7802 return; 7803 if (rold->type != rcur->type) 7804 return; 7805 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap)) 7806 return; 7807 __mark_reg_unknown(env, rcur); 7808 } 7809 7810 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 7811 struct bpf_verifier_state *old, 7812 struct bpf_verifier_state *cur) 7813 { 7814 struct bpf_func_state *fold, *fcur; 7815 int i, fr; 7816 7817 reset_idmap_scratch(env); 7818 for (fr = old->curframe; fr >= 0; fr--) { 7819 fold = old->frame[fr]; 7820 fcur = cur->frame[fr]; 7821 7822 for (i = 0; i < MAX_BPF_REG; i++) 7823 maybe_widen_reg(env, 7824 &fold->regs[i], 7825 &fcur->regs[i], 7826 &env->idmap_scratch); 7827 7828 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) { 7829 if (!is_spilled_reg(&fold->stack[i]) || 7830 !is_spilled_reg(&fcur->stack[i])) 7831 continue; 7832 7833 maybe_widen_reg(env, 7834 &fold->stack[i].spilled_ptr, 7835 &fcur->stack[i].spilled_ptr, 7836 &env->idmap_scratch); 7837 } 7838 } 7839 return 0; 7840 } 7841 7842 /* process_iter_next_call() is called when verifier gets to iterator's next 7843 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7844 * to it as just "iter_next()" in comments below. 7845 * 7846 * BPF verifier relies on a crucial contract for any iter_next() 7847 * implementation: it should *eventually* return NULL, and once that happens 7848 * it should keep returning NULL. That is, once iterator exhausts elements to 7849 * iterate, it should never reset or spuriously return new elements. 7850 * 7851 * With the assumption of such contract, process_iter_next_call() simulates 7852 * a fork in the verifier state to validate loop logic correctness and safety 7853 * without having to simulate infinite amount of iterations. 7854 * 7855 * In current state, we first assume that iter_next() returned NULL and 7856 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7857 * conditions we should not form an infinite loop and should eventually reach 7858 * exit. 7859 * 7860 * Besides that, we also fork current state and enqueue it for later 7861 * verification. In a forked state we keep iterator state as ACTIVE 7862 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7863 * also bump iteration depth to prevent erroneous infinite loop detection 7864 * later on (see iter_active_depths_differ() comment for details). In this 7865 * state we assume that we'll eventually loop back to another iter_next() 7866 * calls (it could be in exactly same location or in some other instruction, 7867 * it doesn't matter, we don't make any unnecessary assumptions about this, 7868 * everything revolves around iterator state in a stack slot, not which 7869 * instruction is calling iter_next()). When that happens, we either will come 7870 * to iter_next() with equivalent state and can conclude that next iteration 7871 * will proceed in exactly the same way as we just verified, so it's safe to 7872 * assume that loop converges. If not, we'll go on another iteration 7873 * simulation with a different input state, until all possible starting states 7874 * are validated or we reach maximum number of instructions limit. 7875 * 7876 * This way, we will either exhaustively discover all possible input states 7877 * that iterator loop can start with and eventually will converge, or we'll 7878 * effectively regress into bounded loop simulation logic and either reach 7879 * maximum number of instructions if loop is not provably convergent, or there 7880 * is some statically known limit on number of iterations (e.g., if there is 7881 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7882 * 7883 * Iteration convergence logic in is_state_visited() relies on exact 7884 * states comparison, which ignores read and precision marks. 7885 * This is necessary because read and precision marks are not finalized 7886 * while in the loop. Exact comparison might preclude convergence for 7887 * simple programs like below: 7888 * 7889 * i = 0; 7890 * while(iter_next(&it)) 7891 * i++; 7892 * 7893 * At each iteration step i++ would produce a new distinct state and 7894 * eventually instruction processing limit would be reached. 7895 * 7896 * To avoid such behavior speculatively forget (widen) range for 7897 * imprecise scalar registers, if those registers were not precise at the 7898 * end of the previous iteration and do not match exactly. 7899 * 7900 * This is a conservative heuristic that allows to verify wide range of programs, 7901 * however it precludes verification of programs that conjure an 7902 * imprecise value on the first loop iteration and use it as precise on a second. 7903 * For example, the following safe program would fail to verify: 7904 * 7905 * struct bpf_num_iter it; 7906 * int arr[10]; 7907 * int i = 0, a = 0; 7908 * bpf_iter_num_new(&it, 0, 10); 7909 * while (bpf_iter_num_next(&it)) { 7910 * if (a == 0) { 7911 * a = 1; 7912 * i = 7; // Because i changed verifier would forget 7913 * // it's range on second loop entry. 7914 * } else { 7915 * arr[i] = 42; // This would fail to verify. 7916 * } 7917 * } 7918 * bpf_iter_num_destroy(&it); 7919 */ 7920 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7921 struct bpf_kfunc_call_arg_meta *meta) 7922 { 7923 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 7924 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7925 struct bpf_reg_state *cur_iter, *queued_iter; 7926 int iter_frameno = meta->iter.frameno; 7927 int iter_spi = meta->iter.spi; 7928 7929 BTF_TYPE_EMIT(struct bpf_iter); 7930 7931 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7932 7933 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 7934 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 7935 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 7936 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 7937 return -EFAULT; 7938 } 7939 7940 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 7941 /* Because iter_next() call is a checkpoint is_state_visitied() 7942 * should guarantee parent state with same call sites and insn_idx. 7943 */ 7944 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 7945 !same_callsites(cur_st->parent, cur_st)) { 7946 verbose(env, "bug: bad parent state for iter next call"); 7947 return -EFAULT; 7948 } 7949 /* Note cur_st->parent in the call below, it is necessary to skip 7950 * checkpoint created for cur_st by is_state_visited() 7951 * right at this instruction. 7952 */ 7953 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 7954 /* branch out active iter state */ 7955 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 7956 if (!queued_st) 7957 return -ENOMEM; 7958 7959 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7960 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 7961 queued_iter->iter.depth++; 7962 if (prev_st) 7963 widen_imprecise_scalars(env, prev_st, queued_st); 7964 7965 queued_fr = queued_st->frame[queued_st->curframe]; 7966 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 7967 } 7968 7969 /* switch to DRAINED state, but keep the depth unchanged */ 7970 /* mark current iter state as drained and assume returned NULL */ 7971 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 7972 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 7973 7974 return 0; 7975 } 7976 7977 static bool arg_type_is_mem_size(enum bpf_arg_type type) 7978 { 7979 return type == ARG_CONST_SIZE || 7980 type == ARG_CONST_SIZE_OR_ZERO; 7981 } 7982 7983 static bool arg_type_is_release(enum bpf_arg_type type) 7984 { 7985 return type & OBJ_RELEASE; 7986 } 7987 7988 static bool arg_type_is_dynptr(enum bpf_arg_type type) 7989 { 7990 return base_type(type) == ARG_PTR_TO_DYNPTR; 7991 } 7992 7993 static int int_ptr_type_to_size(enum bpf_arg_type type) 7994 { 7995 if (type == ARG_PTR_TO_INT) 7996 return sizeof(u32); 7997 else if (type == ARG_PTR_TO_LONG) 7998 return sizeof(u64); 7999 8000 return -EINVAL; 8001 } 8002 8003 static int resolve_map_arg_type(struct bpf_verifier_env *env, 8004 const struct bpf_call_arg_meta *meta, 8005 enum bpf_arg_type *arg_type) 8006 { 8007 if (!meta->map_ptr) { 8008 /* kernel subsystem misconfigured verifier */ 8009 verbose(env, "invalid map_ptr to access map->type\n"); 8010 return -EACCES; 8011 } 8012 8013 switch (meta->map_ptr->map_type) { 8014 case BPF_MAP_TYPE_SOCKMAP: 8015 case BPF_MAP_TYPE_SOCKHASH: 8016 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 8017 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 8018 } else { 8019 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 8020 return -EINVAL; 8021 } 8022 break; 8023 case BPF_MAP_TYPE_BLOOM_FILTER: 8024 if (meta->func_id == BPF_FUNC_map_peek_elem) 8025 *arg_type = ARG_PTR_TO_MAP_VALUE; 8026 break; 8027 default: 8028 break; 8029 } 8030 return 0; 8031 } 8032 8033 struct bpf_reg_types { 8034 const enum bpf_reg_type types[10]; 8035 u32 *btf_id; 8036 }; 8037 8038 static const struct bpf_reg_types sock_types = { 8039 .types = { 8040 PTR_TO_SOCK_COMMON, 8041 PTR_TO_SOCKET, 8042 PTR_TO_TCP_SOCK, 8043 PTR_TO_XDP_SOCK, 8044 }, 8045 }; 8046 8047 #ifdef CONFIG_NET 8048 static const struct bpf_reg_types btf_id_sock_common_types = { 8049 .types = { 8050 PTR_TO_SOCK_COMMON, 8051 PTR_TO_SOCKET, 8052 PTR_TO_TCP_SOCK, 8053 PTR_TO_XDP_SOCK, 8054 PTR_TO_BTF_ID, 8055 PTR_TO_BTF_ID | PTR_TRUSTED, 8056 }, 8057 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 8058 }; 8059 #endif 8060 8061 static const struct bpf_reg_types mem_types = { 8062 .types = { 8063 PTR_TO_STACK, 8064 PTR_TO_PACKET, 8065 PTR_TO_PACKET_META, 8066 PTR_TO_MAP_KEY, 8067 PTR_TO_MAP_VALUE, 8068 PTR_TO_MEM, 8069 PTR_TO_MEM | MEM_RINGBUF, 8070 PTR_TO_BUF, 8071 PTR_TO_BTF_ID | PTR_TRUSTED, 8072 }, 8073 }; 8074 8075 static const struct bpf_reg_types int_ptr_types = { 8076 .types = { 8077 PTR_TO_STACK, 8078 PTR_TO_PACKET, 8079 PTR_TO_PACKET_META, 8080 PTR_TO_MAP_KEY, 8081 PTR_TO_MAP_VALUE, 8082 }, 8083 }; 8084 8085 static const struct bpf_reg_types spin_lock_types = { 8086 .types = { 8087 PTR_TO_MAP_VALUE, 8088 PTR_TO_BTF_ID | MEM_ALLOC, 8089 } 8090 }; 8091 8092 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 8093 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 8094 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 8095 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 8096 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 8097 static const struct bpf_reg_types btf_ptr_types = { 8098 .types = { 8099 PTR_TO_BTF_ID, 8100 PTR_TO_BTF_ID | PTR_TRUSTED, 8101 PTR_TO_BTF_ID | MEM_RCU, 8102 }, 8103 }; 8104 static const struct bpf_reg_types percpu_btf_ptr_types = { 8105 .types = { 8106 PTR_TO_BTF_ID | MEM_PERCPU, 8107 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 8108 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 8109 } 8110 }; 8111 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 8112 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 8113 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8114 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 8115 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8116 static const struct bpf_reg_types dynptr_types = { 8117 .types = { 8118 PTR_TO_STACK, 8119 CONST_PTR_TO_DYNPTR, 8120 } 8121 }; 8122 8123 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 8124 [ARG_PTR_TO_MAP_KEY] = &mem_types, 8125 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 8126 [ARG_CONST_SIZE] = &scalar_types, 8127 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 8128 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 8129 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 8130 [ARG_PTR_TO_CTX] = &context_types, 8131 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 8132 #ifdef CONFIG_NET 8133 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 8134 #endif 8135 [ARG_PTR_TO_SOCKET] = &fullsock_types, 8136 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 8137 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 8138 [ARG_PTR_TO_MEM] = &mem_types, 8139 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 8140 [ARG_PTR_TO_INT] = &int_ptr_types, 8141 [ARG_PTR_TO_LONG] = &int_ptr_types, 8142 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 8143 [ARG_PTR_TO_FUNC] = &func_ptr_types, 8144 [ARG_PTR_TO_STACK] = &stack_ptr_types, 8145 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 8146 [ARG_PTR_TO_TIMER] = &timer_types, 8147 [ARG_PTR_TO_KPTR] = &kptr_types, 8148 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 8149 }; 8150 8151 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 8152 enum bpf_arg_type arg_type, 8153 const u32 *arg_btf_id, 8154 struct bpf_call_arg_meta *meta) 8155 { 8156 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8157 enum bpf_reg_type expected, type = reg->type; 8158 const struct bpf_reg_types *compatible; 8159 int i, j; 8160 8161 compatible = compatible_reg_types[base_type(arg_type)]; 8162 if (!compatible) { 8163 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 8164 return -EFAULT; 8165 } 8166 8167 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 8168 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 8169 * 8170 * Same for MAYBE_NULL: 8171 * 8172 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 8173 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 8174 * 8175 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 8176 * 8177 * Therefore we fold these flags depending on the arg_type before comparison. 8178 */ 8179 if (arg_type & MEM_RDONLY) 8180 type &= ~MEM_RDONLY; 8181 if (arg_type & PTR_MAYBE_NULL) 8182 type &= ~PTR_MAYBE_NULL; 8183 if (base_type(arg_type) == ARG_PTR_TO_MEM) 8184 type &= ~DYNPTR_TYPE_FLAG_MASK; 8185 8186 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) { 8187 type &= ~MEM_ALLOC; 8188 type &= ~MEM_PERCPU; 8189 } 8190 8191 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 8192 expected = compatible->types[i]; 8193 if (expected == NOT_INIT) 8194 break; 8195 8196 if (type == expected) 8197 goto found; 8198 } 8199 8200 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 8201 for (j = 0; j + 1 < i; j++) 8202 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 8203 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 8204 return -EACCES; 8205 8206 found: 8207 if (base_type(reg->type) != PTR_TO_BTF_ID) 8208 return 0; 8209 8210 if (compatible == &mem_types) { 8211 if (!(arg_type & MEM_RDONLY)) { 8212 verbose(env, 8213 "%s() may write into memory pointed by R%d type=%s\n", 8214 func_id_name(meta->func_id), 8215 regno, reg_type_str(env, reg->type)); 8216 return -EACCES; 8217 } 8218 return 0; 8219 } 8220 8221 switch ((int)reg->type) { 8222 case PTR_TO_BTF_ID: 8223 case PTR_TO_BTF_ID | PTR_TRUSTED: 8224 case PTR_TO_BTF_ID | MEM_RCU: 8225 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 8226 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 8227 { 8228 /* For bpf_sk_release, it needs to match against first member 8229 * 'struct sock_common', hence make an exception for it. This 8230 * allows bpf_sk_release to work for multiple socket types. 8231 */ 8232 bool strict_type_match = arg_type_is_release(arg_type) && 8233 meta->func_id != BPF_FUNC_sk_release; 8234 8235 if (type_may_be_null(reg->type) && 8236 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 8237 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 8238 return -EACCES; 8239 } 8240 8241 if (!arg_btf_id) { 8242 if (!compatible->btf_id) { 8243 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 8244 return -EFAULT; 8245 } 8246 arg_btf_id = compatible->btf_id; 8247 } 8248 8249 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8250 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8251 return -EACCES; 8252 } else { 8253 if (arg_btf_id == BPF_PTR_POISON) { 8254 verbose(env, "verifier internal error:"); 8255 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 8256 regno); 8257 return -EACCES; 8258 } 8259 8260 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 8261 btf_vmlinux, *arg_btf_id, 8262 strict_type_match)) { 8263 verbose(env, "R%d is of type %s but %s is expected\n", 8264 regno, btf_type_name(reg->btf, reg->btf_id), 8265 btf_type_name(btf_vmlinux, *arg_btf_id)); 8266 return -EACCES; 8267 } 8268 } 8269 break; 8270 } 8271 case PTR_TO_BTF_ID | MEM_ALLOC: 8272 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 8273 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8274 meta->func_id != BPF_FUNC_kptr_xchg) { 8275 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 8276 return -EFAULT; 8277 } 8278 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8279 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8280 return -EACCES; 8281 } 8282 break; 8283 case PTR_TO_BTF_ID | MEM_PERCPU: 8284 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 8285 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8286 /* Handled by helper specific checks */ 8287 break; 8288 default: 8289 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 8290 return -EFAULT; 8291 } 8292 return 0; 8293 } 8294 8295 static struct btf_field * 8296 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8297 { 8298 struct btf_field *field; 8299 struct btf_record *rec; 8300 8301 rec = reg_btf_record(reg); 8302 if (!rec) 8303 return NULL; 8304 8305 field = btf_record_find(rec, off, fields); 8306 if (!field) 8307 return NULL; 8308 8309 return field; 8310 } 8311 8312 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 8313 const struct bpf_reg_state *reg, int regno, 8314 enum bpf_arg_type arg_type) 8315 { 8316 u32 type = reg->type; 8317 8318 /* When referenced register is passed to release function, its fixed 8319 * offset must be 0. 8320 * 8321 * We will check arg_type_is_release reg has ref_obj_id when storing 8322 * meta->release_regno. 8323 */ 8324 if (arg_type_is_release(arg_type)) { 8325 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8326 * may not directly point to the object being released, but to 8327 * dynptr pointing to such object, which might be at some offset 8328 * on the stack. In that case, we simply to fallback to the 8329 * default handling. 8330 */ 8331 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8332 return 0; 8333 8334 /* Doing check_ptr_off_reg check for the offset will catch this 8335 * because fixed_off_ok is false, but checking here allows us 8336 * to give the user a better error message. 8337 */ 8338 if (reg->off) { 8339 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 8340 regno); 8341 return -EINVAL; 8342 } 8343 return __check_ptr_off_reg(env, reg, regno, false); 8344 } 8345 8346 switch (type) { 8347 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8348 case PTR_TO_STACK: 8349 case PTR_TO_PACKET: 8350 case PTR_TO_PACKET_META: 8351 case PTR_TO_MAP_KEY: 8352 case PTR_TO_MAP_VALUE: 8353 case PTR_TO_MEM: 8354 case PTR_TO_MEM | MEM_RDONLY: 8355 case PTR_TO_MEM | MEM_RINGBUF: 8356 case PTR_TO_BUF: 8357 case PTR_TO_BUF | MEM_RDONLY: 8358 case SCALAR_VALUE: 8359 return 0; 8360 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8361 * fixed offset. 8362 */ 8363 case PTR_TO_BTF_ID: 8364 case PTR_TO_BTF_ID | MEM_ALLOC: 8365 case PTR_TO_BTF_ID | PTR_TRUSTED: 8366 case PTR_TO_BTF_ID | MEM_RCU: 8367 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8368 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8369 /* When referenced PTR_TO_BTF_ID is passed to release function, 8370 * its fixed offset must be 0. In the other cases, fixed offset 8371 * can be non-zero. This was already checked above. So pass 8372 * fixed_off_ok as true to allow fixed offset for all other 8373 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8374 * still need to do checks instead of returning. 8375 */ 8376 return __check_ptr_off_reg(env, reg, regno, true); 8377 default: 8378 return __check_ptr_off_reg(env, reg, regno, false); 8379 } 8380 } 8381 8382 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8383 const struct bpf_func_proto *fn, 8384 struct bpf_reg_state *regs) 8385 { 8386 struct bpf_reg_state *state = NULL; 8387 int i; 8388 8389 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8390 if (arg_type_is_dynptr(fn->arg_type[i])) { 8391 if (state) { 8392 verbose(env, "verifier internal error: multiple dynptr args\n"); 8393 return NULL; 8394 } 8395 state = ®s[BPF_REG_1 + i]; 8396 } 8397 8398 if (!state) 8399 verbose(env, "verifier internal error: no dynptr arg found\n"); 8400 8401 return state; 8402 } 8403 8404 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8405 { 8406 struct bpf_func_state *state = func(env, reg); 8407 int spi; 8408 8409 if (reg->type == CONST_PTR_TO_DYNPTR) 8410 return reg->id; 8411 spi = dynptr_get_spi(env, reg); 8412 if (spi < 0) 8413 return spi; 8414 return state->stack[spi].spilled_ptr.id; 8415 } 8416 8417 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8418 { 8419 struct bpf_func_state *state = func(env, reg); 8420 int spi; 8421 8422 if (reg->type == CONST_PTR_TO_DYNPTR) 8423 return reg->ref_obj_id; 8424 spi = dynptr_get_spi(env, reg); 8425 if (spi < 0) 8426 return spi; 8427 return state->stack[spi].spilled_ptr.ref_obj_id; 8428 } 8429 8430 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8431 struct bpf_reg_state *reg) 8432 { 8433 struct bpf_func_state *state = func(env, reg); 8434 int spi; 8435 8436 if (reg->type == CONST_PTR_TO_DYNPTR) 8437 return reg->dynptr.type; 8438 8439 spi = __get_spi(reg->off); 8440 if (spi < 0) { 8441 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8442 return BPF_DYNPTR_TYPE_INVALID; 8443 } 8444 8445 return state->stack[spi].spilled_ptr.dynptr.type; 8446 } 8447 8448 static int check_reg_const_str(struct bpf_verifier_env *env, 8449 struct bpf_reg_state *reg, u32 regno) 8450 { 8451 struct bpf_map *map = reg->map_ptr; 8452 int err; 8453 int map_off; 8454 u64 map_addr; 8455 char *str_ptr; 8456 8457 if (reg->type != PTR_TO_MAP_VALUE) 8458 return -EINVAL; 8459 8460 if (!bpf_map_is_rdonly(map)) { 8461 verbose(env, "R%d does not point to a readonly map'\n", regno); 8462 return -EACCES; 8463 } 8464 8465 if (!tnum_is_const(reg->var_off)) { 8466 verbose(env, "R%d is not a constant address'\n", regno); 8467 return -EACCES; 8468 } 8469 8470 if (!map->ops->map_direct_value_addr) { 8471 verbose(env, "no direct value access support for this map type\n"); 8472 return -EACCES; 8473 } 8474 8475 err = check_map_access(env, regno, reg->off, 8476 map->value_size - reg->off, false, 8477 ACCESS_HELPER); 8478 if (err) 8479 return err; 8480 8481 map_off = reg->off + reg->var_off.value; 8482 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8483 if (err) { 8484 verbose(env, "direct value access on string failed\n"); 8485 return err; 8486 } 8487 8488 str_ptr = (char *)(long)(map_addr); 8489 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8490 verbose(env, "string is not zero-terminated\n"); 8491 return -EINVAL; 8492 } 8493 return 0; 8494 } 8495 8496 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8497 struct bpf_call_arg_meta *meta, 8498 const struct bpf_func_proto *fn, 8499 int insn_idx) 8500 { 8501 u32 regno = BPF_REG_1 + arg; 8502 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8503 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8504 enum bpf_reg_type type = reg->type; 8505 u32 *arg_btf_id = NULL; 8506 int err = 0; 8507 8508 if (arg_type == ARG_DONTCARE) 8509 return 0; 8510 8511 err = check_reg_arg(env, regno, SRC_OP); 8512 if (err) 8513 return err; 8514 8515 if (arg_type == ARG_ANYTHING) { 8516 if (is_pointer_value(env, regno)) { 8517 verbose(env, "R%d leaks addr into helper function\n", 8518 regno); 8519 return -EACCES; 8520 } 8521 return 0; 8522 } 8523 8524 if (type_is_pkt_pointer(type) && 8525 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8526 verbose(env, "helper access to the packet is not allowed\n"); 8527 return -EACCES; 8528 } 8529 8530 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8531 err = resolve_map_arg_type(env, meta, &arg_type); 8532 if (err) 8533 return err; 8534 } 8535 8536 if (register_is_null(reg) && type_may_be_null(arg_type)) 8537 /* A NULL register has a SCALAR_VALUE type, so skip 8538 * type checking. 8539 */ 8540 goto skip_type_check; 8541 8542 /* arg_btf_id and arg_size are in a union. */ 8543 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8544 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8545 arg_btf_id = fn->arg_btf_id[arg]; 8546 8547 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 8548 if (err) 8549 return err; 8550 8551 err = check_func_arg_reg_off(env, reg, regno, arg_type); 8552 if (err) 8553 return err; 8554 8555 skip_type_check: 8556 if (arg_type_is_release(arg_type)) { 8557 if (arg_type_is_dynptr(arg_type)) { 8558 struct bpf_func_state *state = func(env, reg); 8559 int spi; 8560 8561 /* Only dynptr created on stack can be released, thus 8562 * the get_spi and stack state checks for spilled_ptr 8563 * should only be done before process_dynptr_func for 8564 * PTR_TO_STACK. 8565 */ 8566 if (reg->type == PTR_TO_STACK) { 8567 spi = dynptr_get_spi(env, reg); 8568 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8569 verbose(env, "arg %d is an unacquired reference\n", regno); 8570 return -EINVAL; 8571 } 8572 } else { 8573 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8574 return -EINVAL; 8575 } 8576 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 8577 verbose(env, "R%d must be referenced when passed to release function\n", 8578 regno); 8579 return -EINVAL; 8580 } 8581 if (meta->release_regno) { 8582 verbose(env, "verifier internal error: more than one release argument\n"); 8583 return -EFAULT; 8584 } 8585 meta->release_regno = regno; 8586 } 8587 8588 if (reg->ref_obj_id) { 8589 if (meta->ref_obj_id) { 8590 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 8591 regno, reg->ref_obj_id, 8592 meta->ref_obj_id); 8593 return -EFAULT; 8594 } 8595 meta->ref_obj_id = reg->ref_obj_id; 8596 } 8597 8598 switch (base_type(arg_type)) { 8599 case ARG_CONST_MAP_PTR: 8600 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8601 if (meta->map_ptr) { 8602 /* Use map_uid (which is unique id of inner map) to reject: 8603 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8604 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8605 * if (inner_map1 && inner_map2) { 8606 * timer = bpf_map_lookup_elem(inner_map1); 8607 * if (timer) 8608 * // mismatch would have been allowed 8609 * bpf_timer_init(timer, inner_map2); 8610 * } 8611 * 8612 * Comparing map_ptr is enough to distinguish normal and outer maps. 8613 */ 8614 if (meta->map_ptr != reg->map_ptr || 8615 meta->map_uid != reg->map_uid) { 8616 verbose(env, 8617 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8618 meta->map_uid, reg->map_uid); 8619 return -EINVAL; 8620 } 8621 } 8622 meta->map_ptr = reg->map_ptr; 8623 meta->map_uid = reg->map_uid; 8624 break; 8625 case ARG_PTR_TO_MAP_KEY: 8626 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8627 * check that [key, key + map->key_size) are within 8628 * stack limits and initialized 8629 */ 8630 if (!meta->map_ptr) { 8631 /* in function declaration map_ptr must come before 8632 * map_key, so that it's verified and known before 8633 * we have to check map_key here. Otherwise it means 8634 * that kernel subsystem misconfigured verifier 8635 */ 8636 verbose(env, "invalid map_ptr to access map->key\n"); 8637 return -EACCES; 8638 } 8639 err = check_helper_mem_access(env, regno, 8640 meta->map_ptr->key_size, false, 8641 NULL); 8642 break; 8643 case ARG_PTR_TO_MAP_VALUE: 8644 if (type_may_be_null(arg_type) && register_is_null(reg)) 8645 return 0; 8646 8647 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8648 * check [value, value + map->value_size) validity 8649 */ 8650 if (!meta->map_ptr) { 8651 /* kernel subsystem misconfigured verifier */ 8652 verbose(env, "invalid map_ptr to access map->value\n"); 8653 return -EACCES; 8654 } 8655 meta->raw_mode = arg_type & MEM_UNINIT; 8656 err = check_helper_mem_access(env, regno, 8657 meta->map_ptr->value_size, false, 8658 meta); 8659 break; 8660 case ARG_PTR_TO_PERCPU_BTF_ID: 8661 if (!reg->btf_id) { 8662 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8663 return -EACCES; 8664 } 8665 meta->ret_btf = reg->btf; 8666 meta->ret_btf_id = reg->btf_id; 8667 break; 8668 case ARG_PTR_TO_SPIN_LOCK: 8669 if (in_rbtree_lock_required_cb(env)) { 8670 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8671 return -EACCES; 8672 } 8673 if (meta->func_id == BPF_FUNC_spin_lock) { 8674 err = process_spin_lock(env, regno, true); 8675 if (err) 8676 return err; 8677 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8678 err = process_spin_lock(env, regno, false); 8679 if (err) 8680 return err; 8681 } else { 8682 verbose(env, "verifier internal error\n"); 8683 return -EFAULT; 8684 } 8685 break; 8686 case ARG_PTR_TO_TIMER: 8687 err = process_timer_func(env, regno, meta); 8688 if (err) 8689 return err; 8690 break; 8691 case ARG_PTR_TO_FUNC: 8692 meta->subprogno = reg->subprogno; 8693 break; 8694 case ARG_PTR_TO_MEM: 8695 /* The access to this pointer is only checked when we hit the 8696 * next is_mem_size argument below. 8697 */ 8698 meta->raw_mode = arg_type & MEM_UNINIT; 8699 if (arg_type & MEM_FIXED_SIZE) { 8700 err = check_helper_mem_access(env, regno, 8701 fn->arg_size[arg], false, 8702 meta); 8703 } 8704 break; 8705 case ARG_CONST_SIZE: 8706 err = check_mem_size_reg(env, reg, regno, false, meta); 8707 break; 8708 case ARG_CONST_SIZE_OR_ZERO: 8709 err = check_mem_size_reg(env, reg, regno, true, meta); 8710 break; 8711 case ARG_PTR_TO_DYNPTR: 8712 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 8713 if (err) 8714 return err; 8715 break; 8716 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8717 if (!tnum_is_const(reg->var_off)) { 8718 verbose(env, "R%d is not a known constant'\n", 8719 regno); 8720 return -EACCES; 8721 } 8722 meta->mem_size = reg->var_off.value; 8723 err = mark_chain_precision(env, regno); 8724 if (err) 8725 return err; 8726 break; 8727 case ARG_PTR_TO_INT: 8728 case ARG_PTR_TO_LONG: 8729 { 8730 int size = int_ptr_type_to_size(arg_type); 8731 8732 err = check_helper_mem_access(env, regno, size, false, meta); 8733 if (err) 8734 return err; 8735 err = check_ptr_alignment(env, reg, 0, size, true); 8736 break; 8737 } 8738 case ARG_PTR_TO_CONST_STR: 8739 { 8740 err = check_reg_const_str(env, reg, regno); 8741 if (err) 8742 return err; 8743 break; 8744 } 8745 case ARG_PTR_TO_KPTR: 8746 err = process_kptr_func(env, regno, meta); 8747 if (err) 8748 return err; 8749 break; 8750 } 8751 8752 return err; 8753 } 8754 8755 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8756 { 8757 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8758 enum bpf_prog_type type = resolve_prog_type(env->prog); 8759 8760 if (func_id != BPF_FUNC_map_update_elem) 8761 return false; 8762 8763 /* It's not possible to get access to a locked struct sock in these 8764 * contexts, so updating is safe. 8765 */ 8766 switch (type) { 8767 case BPF_PROG_TYPE_TRACING: 8768 if (eatype == BPF_TRACE_ITER) 8769 return true; 8770 break; 8771 case BPF_PROG_TYPE_SOCKET_FILTER: 8772 case BPF_PROG_TYPE_SCHED_CLS: 8773 case BPF_PROG_TYPE_SCHED_ACT: 8774 case BPF_PROG_TYPE_XDP: 8775 case BPF_PROG_TYPE_SK_REUSEPORT: 8776 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8777 case BPF_PROG_TYPE_SK_LOOKUP: 8778 return true; 8779 default: 8780 break; 8781 } 8782 8783 verbose(env, "cannot update sockmap in this context\n"); 8784 return false; 8785 } 8786 8787 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8788 { 8789 return env->prog->jit_requested && 8790 bpf_jit_supports_subprog_tailcalls(); 8791 } 8792 8793 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8794 struct bpf_map *map, int func_id) 8795 { 8796 if (!map) 8797 return 0; 8798 8799 /* We need a two way check, first is from map perspective ... */ 8800 switch (map->map_type) { 8801 case BPF_MAP_TYPE_PROG_ARRAY: 8802 if (func_id != BPF_FUNC_tail_call) 8803 goto error; 8804 break; 8805 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8806 if (func_id != BPF_FUNC_perf_event_read && 8807 func_id != BPF_FUNC_perf_event_output && 8808 func_id != BPF_FUNC_skb_output && 8809 func_id != BPF_FUNC_perf_event_read_value && 8810 func_id != BPF_FUNC_xdp_output) 8811 goto error; 8812 break; 8813 case BPF_MAP_TYPE_RINGBUF: 8814 if (func_id != BPF_FUNC_ringbuf_output && 8815 func_id != BPF_FUNC_ringbuf_reserve && 8816 func_id != BPF_FUNC_ringbuf_query && 8817 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8818 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8819 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8820 goto error; 8821 break; 8822 case BPF_MAP_TYPE_USER_RINGBUF: 8823 if (func_id != BPF_FUNC_user_ringbuf_drain) 8824 goto error; 8825 break; 8826 case BPF_MAP_TYPE_STACK_TRACE: 8827 if (func_id != BPF_FUNC_get_stackid) 8828 goto error; 8829 break; 8830 case BPF_MAP_TYPE_CGROUP_ARRAY: 8831 if (func_id != BPF_FUNC_skb_under_cgroup && 8832 func_id != BPF_FUNC_current_task_under_cgroup) 8833 goto error; 8834 break; 8835 case BPF_MAP_TYPE_CGROUP_STORAGE: 8836 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8837 if (func_id != BPF_FUNC_get_local_storage) 8838 goto error; 8839 break; 8840 case BPF_MAP_TYPE_DEVMAP: 8841 case BPF_MAP_TYPE_DEVMAP_HASH: 8842 if (func_id != BPF_FUNC_redirect_map && 8843 func_id != BPF_FUNC_map_lookup_elem) 8844 goto error; 8845 break; 8846 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8847 * appear. 8848 */ 8849 case BPF_MAP_TYPE_CPUMAP: 8850 if (func_id != BPF_FUNC_redirect_map) 8851 goto error; 8852 break; 8853 case BPF_MAP_TYPE_XSKMAP: 8854 if (func_id != BPF_FUNC_redirect_map && 8855 func_id != BPF_FUNC_map_lookup_elem) 8856 goto error; 8857 break; 8858 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8859 case BPF_MAP_TYPE_HASH_OF_MAPS: 8860 if (func_id != BPF_FUNC_map_lookup_elem) 8861 goto error; 8862 break; 8863 case BPF_MAP_TYPE_SOCKMAP: 8864 if (func_id != BPF_FUNC_sk_redirect_map && 8865 func_id != BPF_FUNC_sock_map_update && 8866 func_id != BPF_FUNC_map_delete_elem && 8867 func_id != BPF_FUNC_msg_redirect_map && 8868 func_id != BPF_FUNC_sk_select_reuseport && 8869 func_id != BPF_FUNC_map_lookup_elem && 8870 !may_update_sockmap(env, func_id)) 8871 goto error; 8872 break; 8873 case BPF_MAP_TYPE_SOCKHASH: 8874 if (func_id != BPF_FUNC_sk_redirect_hash && 8875 func_id != BPF_FUNC_sock_hash_update && 8876 func_id != BPF_FUNC_map_delete_elem && 8877 func_id != BPF_FUNC_msg_redirect_hash && 8878 func_id != BPF_FUNC_sk_select_reuseport && 8879 func_id != BPF_FUNC_map_lookup_elem && 8880 !may_update_sockmap(env, func_id)) 8881 goto error; 8882 break; 8883 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8884 if (func_id != BPF_FUNC_sk_select_reuseport) 8885 goto error; 8886 break; 8887 case BPF_MAP_TYPE_QUEUE: 8888 case BPF_MAP_TYPE_STACK: 8889 if (func_id != BPF_FUNC_map_peek_elem && 8890 func_id != BPF_FUNC_map_pop_elem && 8891 func_id != BPF_FUNC_map_push_elem) 8892 goto error; 8893 break; 8894 case BPF_MAP_TYPE_SK_STORAGE: 8895 if (func_id != BPF_FUNC_sk_storage_get && 8896 func_id != BPF_FUNC_sk_storage_delete && 8897 func_id != BPF_FUNC_kptr_xchg) 8898 goto error; 8899 break; 8900 case BPF_MAP_TYPE_INODE_STORAGE: 8901 if (func_id != BPF_FUNC_inode_storage_get && 8902 func_id != BPF_FUNC_inode_storage_delete && 8903 func_id != BPF_FUNC_kptr_xchg) 8904 goto error; 8905 break; 8906 case BPF_MAP_TYPE_TASK_STORAGE: 8907 if (func_id != BPF_FUNC_task_storage_get && 8908 func_id != BPF_FUNC_task_storage_delete && 8909 func_id != BPF_FUNC_kptr_xchg) 8910 goto error; 8911 break; 8912 case BPF_MAP_TYPE_CGRP_STORAGE: 8913 if (func_id != BPF_FUNC_cgrp_storage_get && 8914 func_id != BPF_FUNC_cgrp_storage_delete && 8915 func_id != BPF_FUNC_kptr_xchg) 8916 goto error; 8917 break; 8918 case BPF_MAP_TYPE_BLOOM_FILTER: 8919 if (func_id != BPF_FUNC_map_peek_elem && 8920 func_id != BPF_FUNC_map_push_elem) 8921 goto error; 8922 break; 8923 default: 8924 break; 8925 } 8926 8927 /* ... and second from the function itself. */ 8928 switch (func_id) { 8929 case BPF_FUNC_tail_call: 8930 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8931 goto error; 8932 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 8933 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 8934 return -EINVAL; 8935 } 8936 break; 8937 case BPF_FUNC_perf_event_read: 8938 case BPF_FUNC_perf_event_output: 8939 case BPF_FUNC_perf_event_read_value: 8940 case BPF_FUNC_skb_output: 8941 case BPF_FUNC_xdp_output: 8942 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 8943 goto error; 8944 break; 8945 case BPF_FUNC_ringbuf_output: 8946 case BPF_FUNC_ringbuf_reserve: 8947 case BPF_FUNC_ringbuf_query: 8948 case BPF_FUNC_ringbuf_reserve_dynptr: 8949 case BPF_FUNC_ringbuf_submit_dynptr: 8950 case BPF_FUNC_ringbuf_discard_dynptr: 8951 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 8952 goto error; 8953 break; 8954 case BPF_FUNC_user_ringbuf_drain: 8955 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 8956 goto error; 8957 break; 8958 case BPF_FUNC_get_stackid: 8959 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 8960 goto error; 8961 break; 8962 case BPF_FUNC_current_task_under_cgroup: 8963 case BPF_FUNC_skb_under_cgroup: 8964 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 8965 goto error; 8966 break; 8967 case BPF_FUNC_redirect_map: 8968 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 8969 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 8970 map->map_type != BPF_MAP_TYPE_CPUMAP && 8971 map->map_type != BPF_MAP_TYPE_XSKMAP) 8972 goto error; 8973 break; 8974 case BPF_FUNC_sk_redirect_map: 8975 case BPF_FUNC_msg_redirect_map: 8976 case BPF_FUNC_sock_map_update: 8977 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 8978 goto error; 8979 break; 8980 case BPF_FUNC_sk_redirect_hash: 8981 case BPF_FUNC_msg_redirect_hash: 8982 case BPF_FUNC_sock_hash_update: 8983 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 8984 goto error; 8985 break; 8986 case BPF_FUNC_get_local_storage: 8987 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 8988 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 8989 goto error; 8990 break; 8991 case BPF_FUNC_sk_select_reuseport: 8992 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 8993 map->map_type != BPF_MAP_TYPE_SOCKMAP && 8994 map->map_type != BPF_MAP_TYPE_SOCKHASH) 8995 goto error; 8996 break; 8997 case BPF_FUNC_map_pop_elem: 8998 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8999 map->map_type != BPF_MAP_TYPE_STACK) 9000 goto error; 9001 break; 9002 case BPF_FUNC_map_peek_elem: 9003 case BPF_FUNC_map_push_elem: 9004 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9005 map->map_type != BPF_MAP_TYPE_STACK && 9006 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 9007 goto error; 9008 break; 9009 case BPF_FUNC_map_lookup_percpu_elem: 9010 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 9011 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 9012 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 9013 goto error; 9014 break; 9015 case BPF_FUNC_sk_storage_get: 9016 case BPF_FUNC_sk_storage_delete: 9017 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 9018 goto error; 9019 break; 9020 case BPF_FUNC_inode_storage_get: 9021 case BPF_FUNC_inode_storage_delete: 9022 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 9023 goto error; 9024 break; 9025 case BPF_FUNC_task_storage_get: 9026 case BPF_FUNC_task_storage_delete: 9027 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 9028 goto error; 9029 break; 9030 case BPF_FUNC_cgrp_storage_get: 9031 case BPF_FUNC_cgrp_storage_delete: 9032 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 9033 goto error; 9034 break; 9035 default: 9036 break; 9037 } 9038 9039 return 0; 9040 error: 9041 verbose(env, "cannot pass map_type %d into func %s#%d\n", 9042 map->map_type, func_id_name(func_id), func_id); 9043 return -EINVAL; 9044 } 9045 9046 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 9047 { 9048 int count = 0; 9049 9050 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 9051 count++; 9052 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 9053 count++; 9054 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 9055 count++; 9056 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 9057 count++; 9058 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 9059 count++; 9060 9061 /* We only support one arg being in raw mode at the moment, 9062 * which is sufficient for the helper functions we have 9063 * right now. 9064 */ 9065 return count <= 1; 9066 } 9067 9068 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 9069 { 9070 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 9071 bool has_size = fn->arg_size[arg] != 0; 9072 bool is_next_size = false; 9073 9074 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 9075 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 9076 9077 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 9078 return is_next_size; 9079 9080 return has_size == is_next_size || is_next_size == is_fixed; 9081 } 9082 9083 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 9084 { 9085 /* bpf_xxx(..., buf, len) call will access 'len' 9086 * bytes from memory 'buf'. Both arg types need 9087 * to be paired, so make sure there's no buggy 9088 * helper function specification. 9089 */ 9090 if (arg_type_is_mem_size(fn->arg1_type) || 9091 check_args_pair_invalid(fn, 0) || 9092 check_args_pair_invalid(fn, 1) || 9093 check_args_pair_invalid(fn, 2) || 9094 check_args_pair_invalid(fn, 3) || 9095 check_args_pair_invalid(fn, 4)) 9096 return false; 9097 9098 return true; 9099 } 9100 9101 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 9102 { 9103 int i; 9104 9105 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 9106 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 9107 return !!fn->arg_btf_id[i]; 9108 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 9109 return fn->arg_btf_id[i] == BPF_PTR_POISON; 9110 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 9111 /* arg_btf_id and arg_size are in a union. */ 9112 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 9113 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 9114 return false; 9115 } 9116 9117 return true; 9118 } 9119 9120 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 9121 { 9122 return check_raw_mode_ok(fn) && 9123 check_arg_pair_ok(fn) && 9124 check_btf_id_ok(fn) ? 0 : -EINVAL; 9125 } 9126 9127 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 9128 * are now invalid, so turn them into unknown SCALAR_VALUE. 9129 * 9130 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 9131 * since these slices point to packet data. 9132 */ 9133 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 9134 { 9135 struct bpf_func_state *state; 9136 struct bpf_reg_state *reg; 9137 9138 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9139 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 9140 mark_reg_invalid(env, reg); 9141 })); 9142 } 9143 9144 enum { 9145 AT_PKT_END = -1, 9146 BEYOND_PKT_END = -2, 9147 }; 9148 9149 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 9150 { 9151 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9152 struct bpf_reg_state *reg = &state->regs[regn]; 9153 9154 if (reg->type != PTR_TO_PACKET) 9155 /* PTR_TO_PACKET_META is not supported yet */ 9156 return; 9157 9158 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 9159 * How far beyond pkt_end it goes is unknown. 9160 * if (!range_open) it's the case of pkt >= pkt_end 9161 * if (range_open) it's the case of pkt > pkt_end 9162 * hence this pointer is at least 1 byte bigger than pkt_end 9163 */ 9164 if (range_open) 9165 reg->range = BEYOND_PKT_END; 9166 else 9167 reg->range = AT_PKT_END; 9168 } 9169 9170 /* The pointer with the specified id has released its reference to kernel 9171 * resources. Identify all copies of the same pointer and clear the reference. 9172 */ 9173 static int release_reference(struct bpf_verifier_env *env, 9174 int ref_obj_id) 9175 { 9176 struct bpf_func_state *state; 9177 struct bpf_reg_state *reg; 9178 int err; 9179 9180 err = release_reference_state(cur_func(env), ref_obj_id); 9181 if (err) 9182 return err; 9183 9184 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9185 if (reg->ref_obj_id == ref_obj_id) 9186 mark_reg_invalid(env, reg); 9187 })); 9188 9189 return 0; 9190 } 9191 9192 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9193 { 9194 struct bpf_func_state *unused; 9195 struct bpf_reg_state *reg; 9196 9197 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9198 if (type_is_non_owning_ref(reg->type)) 9199 mark_reg_invalid(env, reg); 9200 })); 9201 } 9202 9203 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9204 struct bpf_reg_state *regs) 9205 { 9206 int i; 9207 9208 /* after the call registers r0 - r5 were scratched */ 9209 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9210 mark_reg_not_init(env, regs, caller_saved[i]); 9211 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9212 } 9213 } 9214 9215 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9216 struct bpf_func_state *caller, 9217 struct bpf_func_state *callee, 9218 int insn_idx); 9219 9220 static int set_callee_state(struct bpf_verifier_env *env, 9221 struct bpf_func_state *caller, 9222 struct bpf_func_state *callee, int insn_idx); 9223 9224 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9225 set_callee_state_fn set_callee_state_cb, 9226 struct bpf_verifier_state *state) 9227 { 9228 struct bpf_func_state *caller, *callee; 9229 int err; 9230 9231 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9232 verbose(env, "the call stack of %d frames is too deep\n", 9233 state->curframe + 2); 9234 return -E2BIG; 9235 } 9236 9237 if (state->frame[state->curframe + 1]) { 9238 verbose(env, "verifier bug. Frame %d already allocated\n", 9239 state->curframe + 1); 9240 return -EFAULT; 9241 } 9242 9243 caller = state->frame[state->curframe]; 9244 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 9245 if (!callee) 9246 return -ENOMEM; 9247 state->frame[state->curframe + 1] = callee; 9248 9249 /* callee cannot access r0, r6 - r9 for reading and has to write 9250 * into its own stack before reading from it. 9251 * callee can read/write into caller's stack 9252 */ 9253 init_func_state(env, callee, 9254 /* remember the callsite, it will be used by bpf_exit */ 9255 callsite, 9256 state->curframe + 1 /* frameno within this callchain */, 9257 subprog /* subprog number within this prog */); 9258 /* Transfer references to the callee */ 9259 err = copy_reference_state(callee, caller); 9260 err = err ?: set_callee_state_cb(env, caller, callee, callsite); 9261 if (err) 9262 goto err_out; 9263 9264 /* only increment it after check_reg_arg() finished */ 9265 state->curframe++; 9266 9267 return 0; 9268 9269 err_out: 9270 free_func_state(callee); 9271 state->frame[state->curframe + 1] = NULL; 9272 return err; 9273 } 9274 9275 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, 9276 const struct btf *btf, 9277 struct bpf_reg_state *regs) 9278 { 9279 struct bpf_subprog_info *sub = subprog_info(env, subprog); 9280 struct bpf_verifier_log *log = &env->log; 9281 u32 i; 9282 int ret; 9283 9284 ret = btf_prepare_func_args(env, subprog); 9285 if (ret) 9286 return ret; 9287 9288 /* check that BTF function arguments match actual types that the 9289 * verifier sees. 9290 */ 9291 for (i = 0; i < sub->arg_cnt; i++) { 9292 u32 regno = i + 1; 9293 struct bpf_reg_state *reg = ®s[regno]; 9294 struct bpf_subprog_arg_info *arg = &sub->args[i]; 9295 9296 if (arg->arg_type == ARG_ANYTHING) { 9297 if (reg->type != SCALAR_VALUE) { 9298 bpf_log(log, "R%d is not a scalar\n", regno); 9299 return -EINVAL; 9300 } 9301 } else if (arg->arg_type == ARG_PTR_TO_CTX) { 9302 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9303 if (ret < 0) 9304 return ret; 9305 /* If function expects ctx type in BTF check that caller 9306 * is passing PTR_TO_CTX. 9307 */ 9308 if (reg->type != PTR_TO_CTX) { 9309 bpf_log(log, "arg#%d expects pointer to ctx\n", i); 9310 return -EINVAL; 9311 } 9312 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 9313 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9314 if (ret < 0) 9315 return ret; 9316 if (check_mem_reg(env, reg, regno, arg->mem_size)) 9317 return -EINVAL; 9318 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) { 9319 bpf_log(log, "arg#%d is expected to be non-NULL\n", i); 9320 return -EINVAL; 9321 } 9322 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 9323 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0); 9324 if (ret) 9325 return ret; 9326 } else { 9327 bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n", 9328 i, arg->arg_type); 9329 return -EFAULT; 9330 } 9331 } 9332 9333 return 0; 9334 } 9335 9336 /* Compare BTF of a function call with given bpf_reg_state. 9337 * Returns: 9338 * EFAULT - there is a verifier bug. Abort verification. 9339 * EINVAL - there is a type mismatch or BTF is not available. 9340 * 0 - BTF matches with what bpf_reg_state expects. 9341 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized. 9342 */ 9343 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog, 9344 struct bpf_reg_state *regs) 9345 { 9346 struct bpf_prog *prog = env->prog; 9347 struct btf *btf = prog->aux->btf; 9348 u32 btf_id; 9349 int err; 9350 9351 if (!prog->aux->func_info) 9352 return -EINVAL; 9353 9354 btf_id = prog->aux->func_info[subprog].type_id; 9355 if (!btf_id) 9356 return -EFAULT; 9357 9358 if (prog->aux->func_info_aux[subprog].unreliable) 9359 return -EINVAL; 9360 9361 err = btf_check_func_arg_match(env, subprog, btf, regs); 9362 /* Compiler optimizations can remove arguments from static functions 9363 * or mismatched type can be passed into a global function. 9364 * In such cases mark the function as unreliable from BTF point of view. 9365 */ 9366 if (err) 9367 prog->aux->func_info_aux[subprog].unreliable = true; 9368 return err; 9369 } 9370 9371 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9372 int insn_idx, int subprog, 9373 set_callee_state_fn set_callee_state_cb) 9374 { 9375 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9376 struct bpf_func_state *caller, *callee; 9377 int err; 9378 9379 caller = state->frame[state->curframe]; 9380 err = btf_check_subprog_call(env, subprog, caller->regs); 9381 if (err == -EFAULT) 9382 return err; 9383 9384 /* set_callee_state is used for direct subprog calls, but we are 9385 * interested in validating only BPF helpers that can call subprogs as 9386 * callbacks 9387 */ 9388 env->subprog_info[subprog].is_cb = true; 9389 if (bpf_pseudo_kfunc_call(insn) && 9390 !is_sync_callback_calling_kfunc(insn->imm)) { 9391 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 9392 func_id_name(insn->imm), insn->imm); 9393 return -EFAULT; 9394 } else if (!bpf_pseudo_kfunc_call(insn) && 9395 !is_callback_calling_function(insn->imm)) { /* helper */ 9396 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 9397 func_id_name(insn->imm), insn->imm); 9398 return -EFAULT; 9399 } 9400 9401 if (insn->code == (BPF_JMP | BPF_CALL) && 9402 insn->src_reg == 0 && 9403 insn->imm == BPF_FUNC_timer_set_callback) { 9404 struct bpf_verifier_state *async_cb; 9405 9406 /* there is no real recursion here. timer callbacks are async */ 9407 env->subprog_info[subprog].is_async_cb = true; 9408 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9409 insn_idx, subprog); 9410 if (!async_cb) 9411 return -EFAULT; 9412 callee = async_cb->frame[0]; 9413 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9414 9415 /* Convert bpf_timer_set_callback() args into timer callback args */ 9416 err = set_callee_state_cb(env, caller, callee, insn_idx); 9417 if (err) 9418 return err; 9419 9420 return 0; 9421 } 9422 9423 /* for callback functions enqueue entry to callback and 9424 * proceed with next instruction within current frame. 9425 */ 9426 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9427 if (!callback_state) 9428 return -ENOMEM; 9429 9430 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9431 callback_state); 9432 if (err) 9433 return err; 9434 9435 callback_state->callback_unroll_depth++; 9436 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9437 caller->callback_depth = 0; 9438 return 0; 9439 } 9440 9441 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9442 int *insn_idx) 9443 { 9444 struct bpf_verifier_state *state = env->cur_state; 9445 struct bpf_func_state *caller; 9446 int err, subprog, target_insn; 9447 9448 target_insn = *insn_idx + insn->imm + 1; 9449 subprog = find_subprog(env, target_insn); 9450 if (subprog < 0) { 9451 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn); 9452 return -EFAULT; 9453 } 9454 9455 caller = state->frame[state->curframe]; 9456 err = btf_check_subprog_call(env, subprog, caller->regs); 9457 if (err == -EFAULT) 9458 return err; 9459 if (subprog_is_global(env, subprog)) { 9460 const char *sub_name = subprog_name(env, subprog); 9461 9462 if (err) { 9463 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 9464 subprog, sub_name); 9465 return err; 9466 } 9467 9468 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 9469 subprog, sub_name); 9470 /* mark global subprog for verifying after main prog */ 9471 subprog_aux(env, subprog)->called = true; 9472 clear_caller_saved_regs(env, caller->regs); 9473 9474 /* All global functions return a 64-bit SCALAR_VALUE */ 9475 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9476 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9477 9478 /* continue with next insn after call */ 9479 return 0; 9480 } 9481 9482 /* for regular function entry setup new frame and continue 9483 * from that frame. 9484 */ 9485 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9486 if (err) 9487 return err; 9488 9489 clear_caller_saved_regs(env, caller->regs); 9490 9491 /* and go analyze first insn of the callee */ 9492 *insn_idx = env->subprog_info[subprog].start - 1; 9493 9494 if (env->log.level & BPF_LOG_LEVEL) { 9495 verbose(env, "caller:\n"); 9496 print_verifier_state(env, caller, true); 9497 verbose(env, "callee:\n"); 9498 print_verifier_state(env, state->frame[state->curframe], true); 9499 } 9500 9501 return 0; 9502 } 9503 9504 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9505 struct bpf_func_state *caller, 9506 struct bpf_func_state *callee) 9507 { 9508 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9509 * void *callback_ctx, u64 flags); 9510 * callback_fn(struct bpf_map *map, void *key, void *value, 9511 * void *callback_ctx); 9512 */ 9513 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9514 9515 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9516 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9517 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9518 9519 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9520 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9521 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9522 9523 /* pointer to stack or null */ 9524 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9525 9526 /* unused */ 9527 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9528 return 0; 9529 } 9530 9531 static int set_callee_state(struct bpf_verifier_env *env, 9532 struct bpf_func_state *caller, 9533 struct bpf_func_state *callee, int insn_idx) 9534 { 9535 int i; 9536 9537 /* copy r1 - r5 args that callee can access. The copy includes parent 9538 * pointers, which connects us up to the liveness chain 9539 */ 9540 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9541 callee->regs[i] = caller->regs[i]; 9542 return 0; 9543 } 9544 9545 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9546 struct bpf_func_state *caller, 9547 struct bpf_func_state *callee, 9548 int insn_idx) 9549 { 9550 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9551 struct bpf_map *map; 9552 int err; 9553 9554 if (bpf_map_ptr_poisoned(insn_aux)) { 9555 verbose(env, "tail_call abusing map_ptr\n"); 9556 return -EINVAL; 9557 } 9558 9559 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 9560 if (!map->ops->map_set_for_each_callback_args || 9561 !map->ops->map_for_each_callback) { 9562 verbose(env, "callback function not allowed for map\n"); 9563 return -ENOTSUPP; 9564 } 9565 9566 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9567 if (err) 9568 return err; 9569 9570 callee->in_callback_fn = true; 9571 callee->callback_ret_range = retval_range(0, 1); 9572 return 0; 9573 } 9574 9575 static int set_loop_callback_state(struct bpf_verifier_env *env, 9576 struct bpf_func_state *caller, 9577 struct bpf_func_state *callee, 9578 int insn_idx) 9579 { 9580 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9581 * u64 flags); 9582 * callback_fn(u32 index, void *callback_ctx); 9583 */ 9584 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9585 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9586 9587 /* unused */ 9588 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9589 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9590 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9591 9592 callee->in_callback_fn = true; 9593 callee->callback_ret_range = retval_range(0, 1); 9594 return 0; 9595 } 9596 9597 static int set_timer_callback_state(struct bpf_verifier_env *env, 9598 struct bpf_func_state *caller, 9599 struct bpf_func_state *callee, 9600 int insn_idx) 9601 { 9602 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9603 9604 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9605 * callback_fn(struct bpf_map *map, void *key, void *value); 9606 */ 9607 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9608 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9609 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9610 9611 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9612 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9613 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9614 9615 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9616 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9617 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9618 9619 /* unused */ 9620 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9621 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9622 callee->in_async_callback_fn = true; 9623 callee->callback_ret_range = retval_range(0, 1); 9624 return 0; 9625 } 9626 9627 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9628 struct bpf_func_state *caller, 9629 struct bpf_func_state *callee, 9630 int insn_idx) 9631 { 9632 /* bpf_find_vma(struct task_struct *task, u64 addr, 9633 * void *callback_fn, void *callback_ctx, u64 flags) 9634 * (callback_fn)(struct task_struct *task, 9635 * struct vm_area_struct *vma, void *callback_ctx); 9636 */ 9637 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9638 9639 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9640 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9641 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9642 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 9643 9644 /* pointer to stack or null */ 9645 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9646 9647 /* unused */ 9648 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9649 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9650 callee->in_callback_fn = true; 9651 callee->callback_ret_range = retval_range(0, 1); 9652 return 0; 9653 } 9654 9655 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9656 struct bpf_func_state *caller, 9657 struct bpf_func_state *callee, 9658 int insn_idx) 9659 { 9660 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9661 * callback_ctx, u64 flags); 9662 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9663 */ 9664 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9665 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9666 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9667 9668 /* unused */ 9669 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9670 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9671 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9672 9673 callee->in_callback_fn = true; 9674 callee->callback_ret_range = retval_range(0, 1); 9675 return 0; 9676 } 9677 9678 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9679 struct bpf_func_state *caller, 9680 struct bpf_func_state *callee, 9681 int insn_idx) 9682 { 9683 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9684 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9685 * 9686 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9687 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9688 * by this point, so look at 'root' 9689 */ 9690 struct btf_field *field; 9691 9692 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 9693 BPF_RB_ROOT); 9694 if (!field || !field->graph_root.value_btf_id) 9695 return -EFAULT; 9696 9697 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9698 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9699 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9700 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9701 9702 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9703 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9704 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9705 callee->in_callback_fn = true; 9706 callee->callback_ret_range = retval_range(0, 1); 9707 return 0; 9708 } 9709 9710 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9711 9712 /* Are we currently verifying the callback for a rbtree helper that must 9713 * be called with lock held? If so, no need to complain about unreleased 9714 * lock 9715 */ 9716 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9717 { 9718 struct bpf_verifier_state *state = env->cur_state; 9719 struct bpf_insn *insn = env->prog->insnsi; 9720 struct bpf_func_state *callee; 9721 int kfunc_btf_id; 9722 9723 if (!state->curframe) 9724 return false; 9725 9726 callee = state->frame[state->curframe]; 9727 9728 if (!callee->in_callback_fn) 9729 return false; 9730 9731 kfunc_btf_id = insn[callee->callsite].imm; 9732 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9733 } 9734 9735 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg) 9736 { 9737 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval; 9738 } 9739 9740 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9741 { 9742 struct bpf_verifier_state *state = env->cur_state, *prev_st; 9743 struct bpf_func_state *caller, *callee; 9744 struct bpf_reg_state *r0; 9745 bool in_callback_fn; 9746 int err; 9747 9748 callee = state->frame[state->curframe]; 9749 r0 = &callee->regs[BPF_REG_0]; 9750 if (r0->type == PTR_TO_STACK) { 9751 /* technically it's ok to return caller's stack pointer 9752 * (or caller's caller's pointer) back to the caller, 9753 * since these pointers are valid. Only current stack 9754 * pointer will be invalid as soon as function exits, 9755 * but let's be conservative 9756 */ 9757 verbose(env, "cannot return stack pointer to the caller\n"); 9758 return -EINVAL; 9759 } 9760 9761 caller = state->frame[state->curframe - 1]; 9762 if (callee->in_callback_fn) { 9763 if (r0->type != SCALAR_VALUE) { 9764 verbose(env, "R0 not a scalar value\n"); 9765 return -EACCES; 9766 } 9767 9768 /* we are going to rely on register's precise value */ 9769 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64); 9770 err = err ?: mark_chain_precision(env, BPF_REG_0); 9771 if (err) 9772 return err; 9773 9774 /* enforce R0 return value range */ 9775 if (!retval_range_within(callee->callback_ret_range, r0)) { 9776 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 9777 "At callback return", "R0"); 9778 return -EINVAL; 9779 } 9780 if (!calls_callback(env, callee->callsite)) { 9781 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n", 9782 *insn_idx, callee->callsite); 9783 return -EFAULT; 9784 } 9785 } else { 9786 /* return to the caller whatever r0 had in the callee */ 9787 caller->regs[BPF_REG_0] = *r0; 9788 } 9789 9790 /* callback_fn frame should have released its own additions to parent's 9791 * reference state at this point, or check_reference_leak would 9792 * complain, hence it must be the same as the caller. There is no need 9793 * to copy it back. 9794 */ 9795 if (!callee->in_callback_fn) { 9796 /* Transfer references to the caller */ 9797 err = copy_reference_state(caller, callee); 9798 if (err) 9799 return err; 9800 } 9801 9802 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 9803 * there function call logic would reschedule callback visit. If iteration 9804 * converges is_state_visited() would prune that visit eventually. 9805 */ 9806 in_callback_fn = callee->in_callback_fn; 9807 if (in_callback_fn) 9808 *insn_idx = callee->callsite; 9809 else 9810 *insn_idx = callee->callsite + 1; 9811 9812 if (env->log.level & BPF_LOG_LEVEL) { 9813 verbose(env, "returning from callee:\n"); 9814 print_verifier_state(env, callee, true); 9815 verbose(env, "to caller at %d:\n", *insn_idx); 9816 print_verifier_state(env, caller, true); 9817 } 9818 /* clear everything in the callee. In case of exceptional exits using 9819 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 9820 free_func_state(callee); 9821 state->frame[state->curframe--] = NULL; 9822 9823 /* for callbacks widen imprecise scalars to make programs like below verify: 9824 * 9825 * struct ctx { int i; } 9826 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 9827 * ... 9828 * struct ctx = { .i = 0; } 9829 * bpf_loop(100, cb, &ctx, 0); 9830 * 9831 * This is similar to what is done in process_iter_next_call() for open 9832 * coded iterators. 9833 */ 9834 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 9835 if (prev_st) { 9836 err = widen_imprecise_scalars(env, prev_st, state); 9837 if (err) 9838 return err; 9839 } 9840 return 0; 9841 } 9842 9843 static int do_refine_retval_range(struct bpf_verifier_env *env, 9844 struct bpf_reg_state *regs, int ret_type, 9845 int func_id, 9846 struct bpf_call_arg_meta *meta) 9847 { 9848 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 9849 9850 if (ret_type != RET_INTEGER) 9851 return 0; 9852 9853 switch (func_id) { 9854 case BPF_FUNC_get_stack: 9855 case BPF_FUNC_get_task_stack: 9856 case BPF_FUNC_probe_read_str: 9857 case BPF_FUNC_probe_read_kernel_str: 9858 case BPF_FUNC_probe_read_user_str: 9859 ret_reg->smax_value = meta->msize_max_value; 9860 ret_reg->s32_max_value = meta->msize_max_value; 9861 ret_reg->smin_value = -MAX_ERRNO; 9862 ret_reg->s32_min_value = -MAX_ERRNO; 9863 reg_bounds_sync(ret_reg); 9864 break; 9865 case BPF_FUNC_get_smp_processor_id: 9866 ret_reg->umax_value = nr_cpu_ids - 1; 9867 ret_reg->u32_max_value = nr_cpu_ids - 1; 9868 ret_reg->smax_value = nr_cpu_ids - 1; 9869 ret_reg->s32_max_value = nr_cpu_ids - 1; 9870 ret_reg->umin_value = 0; 9871 ret_reg->u32_min_value = 0; 9872 ret_reg->smin_value = 0; 9873 ret_reg->s32_min_value = 0; 9874 reg_bounds_sync(ret_reg); 9875 break; 9876 } 9877 9878 return reg_bounds_sanity_check(env, ret_reg, "retval"); 9879 } 9880 9881 static int 9882 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9883 int func_id, int insn_idx) 9884 { 9885 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9886 struct bpf_map *map = meta->map_ptr; 9887 9888 if (func_id != BPF_FUNC_tail_call && 9889 func_id != BPF_FUNC_map_lookup_elem && 9890 func_id != BPF_FUNC_map_update_elem && 9891 func_id != BPF_FUNC_map_delete_elem && 9892 func_id != BPF_FUNC_map_push_elem && 9893 func_id != BPF_FUNC_map_pop_elem && 9894 func_id != BPF_FUNC_map_peek_elem && 9895 func_id != BPF_FUNC_for_each_map_elem && 9896 func_id != BPF_FUNC_redirect_map && 9897 func_id != BPF_FUNC_map_lookup_percpu_elem) 9898 return 0; 9899 9900 if (map == NULL) { 9901 verbose(env, "kernel subsystem misconfigured verifier\n"); 9902 return -EINVAL; 9903 } 9904 9905 /* In case of read-only, some additional restrictions 9906 * need to be applied in order to prevent altering the 9907 * state of the map from program side. 9908 */ 9909 if ((map->map_flags & BPF_F_RDONLY_PROG) && 9910 (func_id == BPF_FUNC_map_delete_elem || 9911 func_id == BPF_FUNC_map_update_elem || 9912 func_id == BPF_FUNC_map_push_elem || 9913 func_id == BPF_FUNC_map_pop_elem)) { 9914 verbose(env, "write into map forbidden\n"); 9915 return -EACCES; 9916 } 9917 9918 if (!BPF_MAP_PTR(aux->map_ptr_state)) 9919 bpf_map_ptr_store(aux, meta->map_ptr, 9920 !meta->map_ptr->bypass_spec_v1); 9921 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 9922 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 9923 !meta->map_ptr->bypass_spec_v1); 9924 return 0; 9925 } 9926 9927 static int 9928 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9929 int func_id, int insn_idx) 9930 { 9931 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9932 struct bpf_reg_state *regs = cur_regs(env), *reg; 9933 struct bpf_map *map = meta->map_ptr; 9934 u64 val, max; 9935 int err; 9936 9937 if (func_id != BPF_FUNC_tail_call) 9938 return 0; 9939 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 9940 verbose(env, "kernel subsystem misconfigured verifier\n"); 9941 return -EINVAL; 9942 } 9943 9944 reg = ®s[BPF_REG_3]; 9945 val = reg->var_off.value; 9946 max = map->max_entries; 9947 9948 if (!(is_reg_const(reg, false) && val < max)) { 9949 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9950 return 0; 9951 } 9952 9953 err = mark_chain_precision(env, BPF_REG_3); 9954 if (err) 9955 return err; 9956 if (bpf_map_key_unseen(aux)) 9957 bpf_map_key_store(aux, val); 9958 else if (!bpf_map_key_poisoned(aux) && 9959 bpf_map_key_immediate(aux) != val) 9960 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9961 return 0; 9962 } 9963 9964 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 9965 { 9966 struct bpf_func_state *state = cur_func(env); 9967 bool refs_lingering = false; 9968 int i; 9969 9970 if (!exception_exit && state->frameno && !state->in_callback_fn) 9971 return 0; 9972 9973 for (i = 0; i < state->acquired_refs; i++) { 9974 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 9975 continue; 9976 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 9977 state->refs[i].id, state->refs[i].insn_idx); 9978 refs_lingering = true; 9979 } 9980 return refs_lingering ? -EINVAL : 0; 9981 } 9982 9983 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 9984 struct bpf_reg_state *regs) 9985 { 9986 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 9987 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 9988 struct bpf_map *fmt_map = fmt_reg->map_ptr; 9989 struct bpf_bprintf_data data = {}; 9990 int err, fmt_map_off, num_args; 9991 u64 fmt_addr; 9992 char *fmt; 9993 9994 /* data must be an array of u64 */ 9995 if (data_len_reg->var_off.value % 8) 9996 return -EINVAL; 9997 num_args = data_len_reg->var_off.value / 8; 9998 9999 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 10000 * and map_direct_value_addr is set. 10001 */ 10002 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 10003 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 10004 fmt_map_off); 10005 if (err) { 10006 verbose(env, "verifier bug\n"); 10007 return -EFAULT; 10008 } 10009 fmt = (char *)(long)fmt_addr + fmt_map_off; 10010 10011 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 10012 * can focus on validating the format specifiers. 10013 */ 10014 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 10015 if (err < 0) 10016 verbose(env, "Invalid format string\n"); 10017 10018 return err; 10019 } 10020 10021 static int check_get_func_ip(struct bpf_verifier_env *env) 10022 { 10023 enum bpf_prog_type type = resolve_prog_type(env->prog); 10024 int func_id = BPF_FUNC_get_func_ip; 10025 10026 if (type == BPF_PROG_TYPE_TRACING) { 10027 if (!bpf_prog_has_trampoline(env->prog)) { 10028 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 10029 func_id_name(func_id), func_id); 10030 return -ENOTSUPP; 10031 } 10032 return 0; 10033 } else if (type == BPF_PROG_TYPE_KPROBE) { 10034 return 0; 10035 } 10036 10037 verbose(env, "func %s#%d not supported for program type %d\n", 10038 func_id_name(func_id), func_id, type); 10039 return -ENOTSUPP; 10040 } 10041 10042 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 10043 { 10044 return &env->insn_aux_data[env->insn_idx]; 10045 } 10046 10047 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 10048 { 10049 struct bpf_reg_state *regs = cur_regs(env); 10050 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 10051 bool reg_is_null = register_is_null(reg); 10052 10053 if (reg_is_null) 10054 mark_chain_precision(env, BPF_REG_4); 10055 10056 return reg_is_null; 10057 } 10058 10059 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 10060 { 10061 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 10062 10063 if (!state->initialized) { 10064 state->initialized = 1; 10065 state->fit_for_inline = loop_flag_is_zero(env); 10066 state->callback_subprogno = subprogno; 10067 return; 10068 } 10069 10070 if (!state->fit_for_inline) 10071 return; 10072 10073 state->fit_for_inline = (loop_flag_is_zero(env) && 10074 state->callback_subprogno == subprogno); 10075 } 10076 10077 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10078 int *insn_idx_p) 10079 { 10080 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 10081 bool returns_cpu_specific_alloc_ptr = false; 10082 const struct bpf_func_proto *fn = NULL; 10083 enum bpf_return_type ret_type; 10084 enum bpf_type_flag ret_flag; 10085 struct bpf_reg_state *regs; 10086 struct bpf_call_arg_meta meta; 10087 int insn_idx = *insn_idx_p; 10088 bool changes_data; 10089 int i, err, func_id; 10090 10091 /* find function prototype */ 10092 func_id = insn->imm; 10093 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 10094 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 10095 func_id); 10096 return -EINVAL; 10097 } 10098 10099 if (env->ops->get_func_proto) 10100 fn = env->ops->get_func_proto(func_id, env->prog); 10101 if (!fn) { 10102 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 10103 func_id); 10104 return -EINVAL; 10105 } 10106 10107 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 10108 if (!env->prog->gpl_compatible && fn->gpl_only) { 10109 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10110 return -EINVAL; 10111 } 10112 10113 if (fn->allowed && !fn->allowed(env->prog)) { 10114 verbose(env, "helper call is not allowed in probe\n"); 10115 return -EINVAL; 10116 } 10117 10118 if (!env->prog->aux->sleepable && fn->might_sleep) { 10119 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 10120 return -EINVAL; 10121 } 10122 10123 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10124 changes_data = bpf_helper_changes_pkt_data(fn->func); 10125 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10126 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 10127 func_id_name(func_id), func_id); 10128 return -EINVAL; 10129 } 10130 10131 memset(&meta, 0, sizeof(meta)); 10132 meta.pkt_access = fn->pkt_access; 10133 10134 err = check_func_proto(fn, func_id); 10135 if (err) { 10136 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 10137 func_id_name(func_id), func_id); 10138 return err; 10139 } 10140 10141 if (env->cur_state->active_rcu_lock) { 10142 if (fn->might_sleep) { 10143 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 10144 func_id_name(func_id), func_id); 10145 return -EINVAL; 10146 } 10147 10148 if (env->prog->aux->sleepable && is_storage_get_function(func_id)) 10149 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10150 } 10151 10152 meta.func_id = func_id; 10153 /* check args */ 10154 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10155 err = check_func_arg(env, i, &meta, fn, insn_idx); 10156 if (err) 10157 return err; 10158 } 10159 10160 err = record_func_map(env, &meta, func_id, insn_idx); 10161 if (err) 10162 return err; 10163 10164 err = record_func_key(env, &meta, func_id, insn_idx); 10165 if (err) 10166 return err; 10167 10168 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10169 * is inferred from register state. 10170 */ 10171 for (i = 0; i < meta.access_size; i++) { 10172 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 10173 BPF_WRITE, -1, false, false); 10174 if (err) 10175 return err; 10176 } 10177 10178 regs = cur_regs(env); 10179 10180 if (meta.release_regno) { 10181 err = -EINVAL; 10182 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 10183 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 10184 * is safe to do directly. 10185 */ 10186 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 10187 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 10188 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 10189 return -EFAULT; 10190 } 10191 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 10192 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 10193 u32 ref_obj_id = meta.ref_obj_id; 10194 bool in_rcu = in_rcu_cs(env); 10195 struct bpf_func_state *state; 10196 struct bpf_reg_state *reg; 10197 10198 err = release_reference_state(cur_func(env), ref_obj_id); 10199 if (!err) { 10200 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10201 if (reg->ref_obj_id == ref_obj_id) { 10202 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 10203 reg->ref_obj_id = 0; 10204 reg->type &= ~MEM_ALLOC; 10205 reg->type |= MEM_RCU; 10206 } else { 10207 mark_reg_invalid(env, reg); 10208 } 10209 } 10210 })); 10211 } 10212 } else if (meta.ref_obj_id) { 10213 err = release_reference(env, meta.ref_obj_id); 10214 } else if (register_is_null(®s[meta.release_regno])) { 10215 /* meta.ref_obj_id can only be 0 if register that is meant to be 10216 * released is NULL, which must be > R0. 10217 */ 10218 err = 0; 10219 } 10220 if (err) { 10221 verbose(env, "func %s#%d reference has not been acquired before\n", 10222 func_id_name(func_id), func_id); 10223 return err; 10224 } 10225 } 10226 10227 switch (func_id) { 10228 case BPF_FUNC_tail_call: 10229 err = check_reference_leak(env, false); 10230 if (err) { 10231 verbose(env, "tail_call would lead to reference leak\n"); 10232 return err; 10233 } 10234 break; 10235 case BPF_FUNC_get_local_storage: 10236 /* check that flags argument in get_local_storage(map, flags) is 0, 10237 * this is required because get_local_storage() can't return an error. 10238 */ 10239 if (!register_is_null(®s[BPF_REG_2])) { 10240 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10241 return -EINVAL; 10242 } 10243 break; 10244 case BPF_FUNC_for_each_map_elem: 10245 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10246 set_map_elem_callback_state); 10247 break; 10248 case BPF_FUNC_timer_set_callback: 10249 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10250 set_timer_callback_state); 10251 break; 10252 case BPF_FUNC_find_vma: 10253 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10254 set_find_vma_callback_state); 10255 break; 10256 case BPF_FUNC_snprintf: 10257 err = check_bpf_snprintf_call(env, regs); 10258 break; 10259 case BPF_FUNC_loop: 10260 update_loop_inline_state(env, meta.subprogno); 10261 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10262 * is finished, thus mark it precise. 10263 */ 10264 err = mark_chain_precision(env, BPF_REG_1); 10265 if (err) 10266 return err; 10267 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) { 10268 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10269 set_loop_callback_state); 10270 } else { 10271 cur_func(env)->callback_depth = 0; 10272 if (env->log.level & BPF_LOG_LEVEL2) 10273 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10274 env->cur_state->curframe); 10275 } 10276 break; 10277 case BPF_FUNC_dynptr_from_mem: 10278 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10279 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10280 reg_type_str(env, regs[BPF_REG_1].type)); 10281 return -EACCES; 10282 } 10283 break; 10284 case BPF_FUNC_set_retval: 10285 if (prog_type == BPF_PROG_TYPE_LSM && 10286 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10287 if (!env->prog->aux->attach_func_proto->type) { 10288 /* Make sure programs that attach to void 10289 * hooks don't try to modify return value. 10290 */ 10291 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10292 return -EINVAL; 10293 } 10294 } 10295 break; 10296 case BPF_FUNC_dynptr_data: 10297 { 10298 struct bpf_reg_state *reg; 10299 int id, ref_obj_id; 10300 10301 reg = get_dynptr_arg_reg(env, fn, regs); 10302 if (!reg) 10303 return -EFAULT; 10304 10305 10306 if (meta.dynptr_id) { 10307 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 10308 return -EFAULT; 10309 } 10310 if (meta.ref_obj_id) { 10311 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 10312 return -EFAULT; 10313 } 10314 10315 id = dynptr_id(env, reg); 10316 if (id < 0) { 10317 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 10318 return id; 10319 } 10320 10321 ref_obj_id = dynptr_ref_obj_id(env, reg); 10322 if (ref_obj_id < 0) { 10323 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 10324 return ref_obj_id; 10325 } 10326 10327 meta.dynptr_id = id; 10328 meta.ref_obj_id = ref_obj_id; 10329 10330 break; 10331 } 10332 case BPF_FUNC_dynptr_write: 10333 { 10334 enum bpf_dynptr_type dynptr_type; 10335 struct bpf_reg_state *reg; 10336 10337 reg = get_dynptr_arg_reg(env, fn, regs); 10338 if (!reg) 10339 return -EFAULT; 10340 10341 dynptr_type = dynptr_get_type(env, reg); 10342 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10343 return -EFAULT; 10344 10345 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 10346 /* this will trigger clear_all_pkt_pointers(), which will 10347 * invalidate all dynptr slices associated with the skb 10348 */ 10349 changes_data = true; 10350 10351 break; 10352 } 10353 case BPF_FUNC_per_cpu_ptr: 10354 case BPF_FUNC_this_cpu_ptr: 10355 { 10356 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 10357 const struct btf_type *type; 10358 10359 if (reg->type & MEM_RCU) { 10360 type = btf_type_by_id(reg->btf, reg->btf_id); 10361 if (!type || !btf_type_is_struct(type)) { 10362 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 10363 return -EFAULT; 10364 } 10365 returns_cpu_specific_alloc_ptr = true; 10366 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 10367 } 10368 break; 10369 } 10370 case BPF_FUNC_user_ringbuf_drain: 10371 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10372 set_user_ringbuf_callback_state); 10373 break; 10374 } 10375 10376 if (err) 10377 return err; 10378 10379 /* reset caller saved regs */ 10380 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10381 mark_reg_not_init(env, regs, caller_saved[i]); 10382 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10383 } 10384 10385 /* helper call returns 64-bit value. */ 10386 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10387 10388 /* update return register (already marked as written above) */ 10389 ret_type = fn->ret_type; 10390 ret_flag = type_flag(ret_type); 10391 10392 switch (base_type(ret_type)) { 10393 case RET_INTEGER: 10394 /* sets type to SCALAR_VALUE */ 10395 mark_reg_unknown(env, regs, BPF_REG_0); 10396 break; 10397 case RET_VOID: 10398 regs[BPF_REG_0].type = NOT_INIT; 10399 break; 10400 case RET_PTR_TO_MAP_VALUE: 10401 /* There is no offset yet applied, variable or fixed */ 10402 mark_reg_known_zero(env, regs, BPF_REG_0); 10403 /* remember map_ptr, so that check_map_access() 10404 * can check 'value_size' boundary of memory access 10405 * to map element returned from bpf_map_lookup_elem() 10406 */ 10407 if (meta.map_ptr == NULL) { 10408 verbose(env, 10409 "kernel subsystem misconfigured verifier\n"); 10410 return -EINVAL; 10411 } 10412 regs[BPF_REG_0].map_ptr = meta.map_ptr; 10413 regs[BPF_REG_0].map_uid = meta.map_uid; 10414 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10415 if (!type_may_be_null(ret_type) && 10416 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 10417 regs[BPF_REG_0].id = ++env->id_gen; 10418 } 10419 break; 10420 case RET_PTR_TO_SOCKET: 10421 mark_reg_known_zero(env, regs, BPF_REG_0); 10422 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10423 break; 10424 case RET_PTR_TO_SOCK_COMMON: 10425 mark_reg_known_zero(env, regs, BPF_REG_0); 10426 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10427 break; 10428 case RET_PTR_TO_TCP_SOCK: 10429 mark_reg_known_zero(env, regs, BPF_REG_0); 10430 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10431 break; 10432 case RET_PTR_TO_MEM: 10433 mark_reg_known_zero(env, regs, BPF_REG_0); 10434 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10435 regs[BPF_REG_0].mem_size = meta.mem_size; 10436 break; 10437 case RET_PTR_TO_MEM_OR_BTF_ID: 10438 { 10439 const struct btf_type *t; 10440 10441 mark_reg_known_zero(env, regs, BPF_REG_0); 10442 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10443 if (!btf_type_is_struct(t)) { 10444 u32 tsize; 10445 const struct btf_type *ret; 10446 const char *tname; 10447 10448 /* resolve the type size of ksym. */ 10449 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10450 if (IS_ERR(ret)) { 10451 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10452 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10453 tname, PTR_ERR(ret)); 10454 return -EINVAL; 10455 } 10456 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10457 regs[BPF_REG_0].mem_size = tsize; 10458 } else { 10459 if (returns_cpu_specific_alloc_ptr) { 10460 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10461 } else { 10462 /* MEM_RDONLY may be carried from ret_flag, but it 10463 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10464 * it will confuse the check of PTR_TO_BTF_ID in 10465 * check_mem_access(). 10466 */ 10467 ret_flag &= ~MEM_RDONLY; 10468 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10469 } 10470 10471 regs[BPF_REG_0].btf = meta.ret_btf; 10472 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10473 } 10474 break; 10475 } 10476 case RET_PTR_TO_BTF_ID: 10477 { 10478 struct btf *ret_btf; 10479 int ret_btf_id; 10480 10481 mark_reg_known_zero(env, regs, BPF_REG_0); 10482 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10483 if (func_id == BPF_FUNC_kptr_xchg) { 10484 ret_btf = meta.kptr_field->kptr.btf; 10485 ret_btf_id = meta.kptr_field->kptr.btf_id; 10486 if (!btf_is_kernel(ret_btf)) { 10487 regs[BPF_REG_0].type |= MEM_ALLOC; 10488 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10489 regs[BPF_REG_0].type |= MEM_PERCPU; 10490 } 10491 } else { 10492 if (fn->ret_btf_id == BPF_PTR_POISON) { 10493 verbose(env, "verifier internal error:"); 10494 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 10495 func_id_name(func_id)); 10496 return -EINVAL; 10497 } 10498 ret_btf = btf_vmlinux; 10499 ret_btf_id = *fn->ret_btf_id; 10500 } 10501 if (ret_btf_id == 0) { 10502 verbose(env, "invalid return type %u of func %s#%d\n", 10503 base_type(ret_type), func_id_name(func_id), 10504 func_id); 10505 return -EINVAL; 10506 } 10507 regs[BPF_REG_0].btf = ret_btf; 10508 regs[BPF_REG_0].btf_id = ret_btf_id; 10509 break; 10510 } 10511 default: 10512 verbose(env, "unknown return type %u of func %s#%d\n", 10513 base_type(ret_type), func_id_name(func_id), func_id); 10514 return -EINVAL; 10515 } 10516 10517 if (type_may_be_null(regs[BPF_REG_0].type)) 10518 regs[BPF_REG_0].id = ++env->id_gen; 10519 10520 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 10521 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 10522 func_id_name(func_id), func_id); 10523 return -EFAULT; 10524 } 10525 10526 if (is_dynptr_ref_function(func_id)) 10527 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 10528 10529 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 10530 /* For release_reference() */ 10531 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10532 } else if (is_acquire_function(func_id, meta.map_ptr)) { 10533 int id = acquire_reference_state(env, insn_idx); 10534 10535 if (id < 0) 10536 return id; 10537 /* For mark_ptr_or_null_reg() */ 10538 regs[BPF_REG_0].id = id; 10539 /* For release_reference() */ 10540 regs[BPF_REG_0].ref_obj_id = id; 10541 } 10542 10543 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 10544 if (err) 10545 return err; 10546 10547 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 10548 if (err) 10549 return err; 10550 10551 if ((func_id == BPF_FUNC_get_stack || 10552 func_id == BPF_FUNC_get_task_stack) && 10553 !env->prog->has_callchain_buf) { 10554 const char *err_str; 10555 10556 #ifdef CONFIG_PERF_EVENTS 10557 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10558 err_str = "cannot get callchain buffer for func %s#%d\n"; 10559 #else 10560 err = -ENOTSUPP; 10561 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10562 #endif 10563 if (err) { 10564 verbose(env, err_str, func_id_name(func_id), func_id); 10565 return err; 10566 } 10567 10568 env->prog->has_callchain_buf = true; 10569 } 10570 10571 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10572 env->prog->call_get_stack = true; 10573 10574 if (func_id == BPF_FUNC_get_func_ip) { 10575 if (check_get_func_ip(env)) 10576 return -ENOTSUPP; 10577 env->prog->call_get_func_ip = true; 10578 } 10579 10580 if (changes_data) 10581 clear_all_pkt_pointers(env); 10582 return 0; 10583 } 10584 10585 /* mark_btf_func_reg_size() is used when the reg size is determined by 10586 * the BTF func_proto's return value size and argument. 10587 */ 10588 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10589 size_t reg_size) 10590 { 10591 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 10592 10593 if (regno == BPF_REG_0) { 10594 /* Function return value */ 10595 reg->live |= REG_LIVE_WRITTEN; 10596 reg->subreg_def = reg_size == sizeof(u64) ? 10597 DEF_NOT_SUBREG : env->insn_idx + 1; 10598 } else { 10599 /* Function argument */ 10600 if (reg_size == sizeof(u64)) { 10601 mark_insn_zext(env, reg); 10602 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 10603 } else { 10604 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 10605 } 10606 } 10607 } 10608 10609 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10610 { 10611 return meta->kfunc_flags & KF_ACQUIRE; 10612 } 10613 10614 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10615 { 10616 return meta->kfunc_flags & KF_RELEASE; 10617 } 10618 10619 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 10620 { 10621 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 10622 } 10623 10624 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 10625 { 10626 return meta->kfunc_flags & KF_SLEEPABLE; 10627 } 10628 10629 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10630 { 10631 return meta->kfunc_flags & KF_DESTRUCTIVE; 10632 } 10633 10634 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10635 { 10636 return meta->kfunc_flags & KF_RCU; 10637 } 10638 10639 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 10640 { 10641 return meta->kfunc_flags & KF_RCU_PROTECTED; 10642 } 10643 10644 static bool __kfunc_param_match_suffix(const struct btf *btf, 10645 const struct btf_param *arg, 10646 const char *suffix) 10647 { 10648 int suffix_len = strlen(suffix), len; 10649 const char *param_name; 10650 10651 /* In the future, this can be ported to use BTF tagging */ 10652 param_name = btf_name_by_offset(btf, arg->name_off); 10653 if (str_is_empty(param_name)) 10654 return false; 10655 len = strlen(param_name); 10656 if (len < suffix_len) 10657 return false; 10658 param_name += len - suffix_len; 10659 return !strncmp(param_name, suffix, suffix_len); 10660 } 10661 10662 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10663 const struct btf_param *arg, 10664 const struct bpf_reg_state *reg) 10665 { 10666 const struct btf_type *t; 10667 10668 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10669 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10670 return false; 10671 10672 return __kfunc_param_match_suffix(btf, arg, "__sz"); 10673 } 10674 10675 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10676 const struct btf_param *arg, 10677 const struct bpf_reg_state *reg) 10678 { 10679 const struct btf_type *t; 10680 10681 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10682 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10683 return false; 10684 10685 return __kfunc_param_match_suffix(btf, arg, "__szk"); 10686 } 10687 10688 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 10689 { 10690 return __kfunc_param_match_suffix(btf, arg, "__opt"); 10691 } 10692 10693 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10694 { 10695 return __kfunc_param_match_suffix(btf, arg, "__k"); 10696 } 10697 10698 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10699 { 10700 return __kfunc_param_match_suffix(btf, arg, "__ign"); 10701 } 10702 10703 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10704 { 10705 return __kfunc_param_match_suffix(btf, arg, "__alloc"); 10706 } 10707 10708 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10709 { 10710 return __kfunc_param_match_suffix(btf, arg, "__uninit"); 10711 } 10712 10713 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10714 { 10715 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr"); 10716 } 10717 10718 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 10719 { 10720 return __kfunc_param_match_suffix(btf, arg, "__nullable"); 10721 } 10722 10723 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 10724 { 10725 return __kfunc_param_match_suffix(btf, arg, "__str"); 10726 } 10727 10728 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10729 const struct btf_param *arg, 10730 const char *name) 10731 { 10732 int len, target_len = strlen(name); 10733 const char *param_name; 10734 10735 param_name = btf_name_by_offset(btf, arg->name_off); 10736 if (str_is_empty(param_name)) 10737 return false; 10738 len = strlen(param_name); 10739 if (len != target_len) 10740 return false; 10741 if (strcmp(param_name, name)) 10742 return false; 10743 10744 return true; 10745 } 10746 10747 enum { 10748 KF_ARG_DYNPTR_ID, 10749 KF_ARG_LIST_HEAD_ID, 10750 KF_ARG_LIST_NODE_ID, 10751 KF_ARG_RB_ROOT_ID, 10752 KF_ARG_RB_NODE_ID, 10753 }; 10754 10755 BTF_ID_LIST(kf_arg_btf_ids) 10756 BTF_ID(struct, bpf_dynptr_kern) 10757 BTF_ID(struct, bpf_list_head) 10758 BTF_ID(struct, bpf_list_node) 10759 BTF_ID(struct, bpf_rb_root) 10760 BTF_ID(struct, bpf_rb_node) 10761 10762 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10763 const struct btf_param *arg, int type) 10764 { 10765 const struct btf_type *t; 10766 u32 res_id; 10767 10768 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10769 if (!t) 10770 return false; 10771 if (!btf_type_is_ptr(t)) 10772 return false; 10773 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10774 if (!t) 10775 return false; 10776 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10777 } 10778 10779 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10780 { 10781 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10782 } 10783 10784 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10785 { 10786 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10787 } 10788 10789 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10790 { 10791 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10792 } 10793 10794 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10795 { 10796 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10797 } 10798 10799 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10800 { 10801 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10802 } 10803 10804 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10805 const struct btf_param *arg) 10806 { 10807 const struct btf_type *t; 10808 10809 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10810 if (!t) 10811 return false; 10812 10813 return true; 10814 } 10815 10816 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10817 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10818 const struct btf *btf, 10819 const struct btf_type *t, int rec) 10820 { 10821 const struct btf_type *member_type; 10822 const struct btf_member *member; 10823 u32 i; 10824 10825 if (!btf_type_is_struct(t)) 10826 return false; 10827 10828 for_each_member(i, t, member) { 10829 const struct btf_array *array; 10830 10831 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 10832 if (btf_type_is_struct(member_type)) { 10833 if (rec >= 3) { 10834 verbose(env, "max struct nesting depth exceeded\n"); 10835 return false; 10836 } 10837 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 10838 return false; 10839 continue; 10840 } 10841 if (btf_type_is_array(member_type)) { 10842 array = btf_array(member_type); 10843 if (!array->nelems) 10844 return false; 10845 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 10846 if (!btf_type_is_scalar(member_type)) 10847 return false; 10848 continue; 10849 } 10850 if (!btf_type_is_scalar(member_type)) 10851 return false; 10852 } 10853 return true; 10854 } 10855 10856 enum kfunc_ptr_arg_type { 10857 KF_ARG_PTR_TO_CTX, 10858 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 10859 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 10860 KF_ARG_PTR_TO_DYNPTR, 10861 KF_ARG_PTR_TO_ITER, 10862 KF_ARG_PTR_TO_LIST_HEAD, 10863 KF_ARG_PTR_TO_LIST_NODE, 10864 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 10865 KF_ARG_PTR_TO_MEM, 10866 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 10867 KF_ARG_PTR_TO_CALLBACK, 10868 KF_ARG_PTR_TO_RB_ROOT, 10869 KF_ARG_PTR_TO_RB_NODE, 10870 KF_ARG_PTR_TO_NULL, 10871 KF_ARG_PTR_TO_CONST_STR, 10872 }; 10873 10874 enum special_kfunc_type { 10875 KF_bpf_obj_new_impl, 10876 KF_bpf_obj_drop_impl, 10877 KF_bpf_refcount_acquire_impl, 10878 KF_bpf_list_push_front_impl, 10879 KF_bpf_list_push_back_impl, 10880 KF_bpf_list_pop_front, 10881 KF_bpf_list_pop_back, 10882 KF_bpf_cast_to_kern_ctx, 10883 KF_bpf_rdonly_cast, 10884 KF_bpf_rcu_read_lock, 10885 KF_bpf_rcu_read_unlock, 10886 KF_bpf_rbtree_remove, 10887 KF_bpf_rbtree_add_impl, 10888 KF_bpf_rbtree_first, 10889 KF_bpf_dynptr_from_skb, 10890 KF_bpf_dynptr_from_xdp, 10891 KF_bpf_dynptr_slice, 10892 KF_bpf_dynptr_slice_rdwr, 10893 KF_bpf_dynptr_clone, 10894 KF_bpf_percpu_obj_new_impl, 10895 KF_bpf_percpu_obj_drop_impl, 10896 KF_bpf_throw, 10897 KF_bpf_iter_css_task_new, 10898 }; 10899 10900 BTF_SET_START(special_kfunc_set) 10901 BTF_ID(func, bpf_obj_new_impl) 10902 BTF_ID(func, bpf_obj_drop_impl) 10903 BTF_ID(func, bpf_refcount_acquire_impl) 10904 BTF_ID(func, bpf_list_push_front_impl) 10905 BTF_ID(func, bpf_list_push_back_impl) 10906 BTF_ID(func, bpf_list_pop_front) 10907 BTF_ID(func, bpf_list_pop_back) 10908 BTF_ID(func, bpf_cast_to_kern_ctx) 10909 BTF_ID(func, bpf_rdonly_cast) 10910 BTF_ID(func, bpf_rbtree_remove) 10911 BTF_ID(func, bpf_rbtree_add_impl) 10912 BTF_ID(func, bpf_rbtree_first) 10913 BTF_ID(func, bpf_dynptr_from_skb) 10914 BTF_ID(func, bpf_dynptr_from_xdp) 10915 BTF_ID(func, bpf_dynptr_slice) 10916 BTF_ID(func, bpf_dynptr_slice_rdwr) 10917 BTF_ID(func, bpf_dynptr_clone) 10918 BTF_ID(func, bpf_percpu_obj_new_impl) 10919 BTF_ID(func, bpf_percpu_obj_drop_impl) 10920 BTF_ID(func, bpf_throw) 10921 #ifdef CONFIG_CGROUPS 10922 BTF_ID(func, bpf_iter_css_task_new) 10923 #endif 10924 BTF_SET_END(special_kfunc_set) 10925 10926 BTF_ID_LIST(special_kfunc_list) 10927 BTF_ID(func, bpf_obj_new_impl) 10928 BTF_ID(func, bpf_obj_drop_impl) 10929 BTF_ID(func, bpf_refcount_acquire_impl) 10930 BTF_ID(func, bpf_list_push_front_impl) 10931 BTF_ID(func, bpf_list_push_back_impl) 10932 BTF_ID(func, bpf_list_pop_front) 10933 BTF_ID(func, bpf_list_pop_back) 10934 BTF_ID(func, bpf_cast_to_kern_ctx) 10935 BTF_ID(func, bpf_rdonly_cast) 10936 BTF_ID(func, bpf_rcu_read_lock) 10937 BTF_ID(func, bpf_rcu_read_unlock) 10938 BTF_ID(func, bpf_rbtree_remove) 10939 BTF_ID(func, bpf_rbtree_add_impl) 10940 BTF_ID(func, bpf_rbtree_first) 10941 BTF_ID(func, bpf_dynptr_from_skb) 10942 BTF_ID(func, bpf_dynptr_from_xdp) 10943 BTF_ID(func, bpf_dynptr_slice) 10944 BTF_ID(func, bpf_dynptr_slice_rdwr) 10945 BTF_ID(func, bpf_dynptr_clone) 10946 BTF_ID(func, bpf_percpu_obj_new_impl) 10947 BTF_ID(func, bpf_percpu_obj_drop_impl) 10948 BTF_ID(func, bpf_throw) 10949 #ifdef CONFIG_CGROUPS 10950 BTF_ID(func, bpf_iter_css_task_new) 10951 #else 10952 BTF_ID_UNUSED 10953 #endif 10954 10955 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 10956 { 10957 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 10958 meta->arg_owning_ref) { 10959 return false; 10960 } 10961 10962 return meta->kfunc_flags & KF_RET_NULL; 10963 } 10964 10965 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 10966 { 10967 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 10968 } 10969 10970 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 10971 { 10972 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 10973 } 10974 10975 static enum kfunc_ptr_arg_type 10976 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 10977 struct bpf_kfunc_call_arg_meta *meta, 10978 const struct btf_type *t, const struct btf_type *ref_t, 10979 const char *ref_tname, const struct btf_param *args, 10980 int argno, int nargs) 10981 { 10982 u32 regno = argno + 1; 10983 struct bpf_reg_state *regs = cur_regs(env); 10984 struct bpf_reg_state *reg = ®s[regno]; 10985 bool arg_mem_size = false; 10986 10987 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 10988 return KF_ARG_PTR_TO_CTX; 10989 10990 /* In this function, we verify the kfunc's BTF as per the argument type, 10991 * leaving the rest of the verification with respect to the register 10992 * type to our caller. When a set of conditions hold in the BTF type of 10993 * arguments, we resolve it to a known kfunc_ptr_arg_type. 10994 */ 10995 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 10996 return KF_ARG_PTR_TO_CTX; 10997 10998 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 10999 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 11000 11001 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 11002 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 11003 11004 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 11005 return KF_ARG_PTR_TO_DYNPTR; 11006 11007 if (is_kfunc_arg_iter(meta, argno)) 11008 return KF_ARG_PTR_TO_ITER; 11009 11010 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 11011 return KF_ARG_PTR_TO_LIST_HEAD; 11012 11013 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 11014 return KF_ARG_PTR_TO_LIST_NODE; 11015 11016 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 11017 return KF_ARG_PTR_TO_RB_ROOT; 11018 11019 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 11020 return KF_ARG_PTR_TO_RB_NODE; 11021 11022 if (is_kfunc_arg_const_str(meta->btf, &args[argno])) 11023 return KF_ARG_PTR_TO_CONST_STR; 11024 11025 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 11026 if (!btf_type_is_struct(ref_t)) { 11027 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 11028 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 11029 return -EINVAL; 11030 } 11031 return KF_ARG_PTR_TO_BTF_ID; 11032 } 11033 11034 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 11035 return KF_ARG_PTR_TO_CALLBACK; 11036 11037 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg)) 11038 return KF_ARG_PTR_TO_NULL; 11039 11040 if (argno + 1 < nargs && 11041 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 11042 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 11043 arg_mem_size = true; 11044 11045 /* This is the catch all argument type of register types supported by 11046 * check_helper_mem_access. However, we only allow when argument type is 11047 * pointer to scalar, or struct composed (recursively) of scalars. When 11048 * arg_mem_size is true, the pointer can be void *. 11049 */ 11050 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 11051 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 11052 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 11053 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 11054 return -EINVAL; 11055 } 11056 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 11057 } 11058 11059 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 11060 struct bpf_reg_state *reg, 11061 const struct btf_type *ref_t, 11062 const char *ref_tname, u32 ref_id, 11063 struct bpf_kfunc_call_arg_meta *meta, 11064 int argno) 11065 { 11066 const struct btf_type *reg_ref_t; 11067 bool strict_type_match = false; 11068 const struct btf *reg_btf; 11069 const char *reg_ref_tname; 11070 u32 reg_ref_id; 11071 11072 if (base_type(reg->type) == PTR_TO_BTF_ID) { 11073 reg_btf = reg->btf; 11074 reg_ref_id = reg->btf_id; 11075 } else { 11076 reg_btf = btf_vmlinux; 11077 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 11078 } 11079 11080 /* Enforce strict type matching for calls to kfuncs that are acquiring 11081 * or releasing a reference, or are no-cast aliases. We do _not_ 11082 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 11083 * as we want to enable BPF programs to pass types that are bitwise 11084 * equivalent without forcing them to explicitly cast with something 11085 * like bpf_cast_to_kern_ctx(). 11086 * 11087 * For example, say we had a type like the following: 11088 * 11089 * struct bpf_cpumask { 11090 * cpumask_t cpumask; 11091 * refcount_t usage; 11092 * }; 11093 * 11094 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 11095 * to a struct cpumask, so it would be safe to pass a struct 11096 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 11097 * 11098 * The philosophy here is similar to how we allow scalars of different 11099 * types to be passed to kfuncs as long as the size is the same. The 11100 * only difference here is that we're simply allowing 11101 * btf_struct_ids_match() to walk the struct at the 0th offset, and 11102 * resolve types. 11103 */ 11104 if (is_kfunc_acquire(meta) || 11105 (is_kfunc_release(meta) && reg->ref_obj_id) || 11106 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 11107 strict_type_match = true; 11108 11109 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 11110 11111 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 11112 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 11113 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 11114 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 11115 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 11116 btf_type_str(reg_ref_t), reg_ref_tname); 11117 return -EINVAL; 11118 } 11119 return 0; 11120 } 11121 11122 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11123 { 11124 struct bpf_verifier_state *state = env->cur_state; 11125 struct btf_record *rec = reg_btf_record(reg); 11126 11127 if (!state->active_lock.ptr) { 11128 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 11129 return -EFAULT; 11130 } 11131 11132 if (type_flag(reg->type) & NON_OWN_REF) { 11133 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 11134 return -EFAULT; 11135 } 11136 11137 reg->type |= NON_OWN_REF; 11138 if (rec->refcount_off >= 0) 11139 reg->type |= MEM_RCU; 11140 11141 return 0; 11142 } 11143 11144 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 11145 { 11146 struct bpf_func_state *state, *unused; 11147 struct bpf_reg_state *reg; 11148 int i; 11149 11150 state = cur_func(env); 11151 11152 if (!ref_obj_id) { 11153 verbose(env, "verifier internal error: ref_obj_id is zero for " 11154 "owning -> non-owning conversion\n"); 11155 return -EFAULT; 11156 } 11157 11158 for (i = 0; i < state->acquired_refs; i++) { 11159 if (state->refs[i].id != ref_obj_id) 11160 continue; 11161 11162 /* Clear ref_obj_id here so release_reference doesn't clobber 11163 * the whole reg 11164 */ 11165 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11166 if (reg->ref_obj_id == ref_obj_id) { 11167 reg->ref_obj_id = 0; 11168 ref_set_non_owning(env, reg); 11169 } 11170 })); 11171 return 0; 11172 } 11173 11174 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 11175 return -EFAULT; 11176 } 11177 11178 /* Implementation details: 11179 * 11180 * Each register points to some region of memory, which we define as an 11181 * allocation. Each allocation may embed a bpf_spin_lock which protects any 11182 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 11183 * allocation. The lock and the data it protects are colocated in the same 11184 * memory region. 11185 * 11186 * Hence, everytime a register holds a pointer value pointing to such 11187 * allocation, the verifier preserves a unique reg->id for it. 11188 * 11189 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 11190 * bpf_spin_lock is called. 11191 * 11192 * To enable this, lock state in the verifier captures two values: 11193 * active_lock.ptr = Register's type specific pointer 11194 * active_lock.id = A unique ID for each register pointer value 11195 * 11196 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11197 * supported register types. 11198 * 11199 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11200 * allocated objects is the reg->btf pointer. 11201 * 11202 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11203 * can establish the provenance of the map value statically for each distinct 11204 * lookup into such maps. They always contain a single map value hence unique 11205 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11206 * 11207 * So, in case of global variables, they use array maps with max_entries = 1, 11208 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11209 * into the same map value as max_entries is 1, as described above). 11210 * 11211 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11212 * outer map pointer (in verifier context), but each lookup into an inner map 11213 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11214 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11215 * will get different reg->id assigned to each lookup, hence different 11216 * active_lock.id. 11217 * 11218 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11219 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11220 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11221 */ 11222 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11223 { 11224 void *ptr; 11225 u32 id; 11226 11227 switch ((int)reg->type) { 11228 case PTR_TO_MAP_VALUE: 11229 ptr = reg->map_ptr; 11230 break; 11231 case PTR_TO_BTF_ID | MEM_ALLOC: 11232 ptr = reg->btf; 11233 break; 11234 default: 11235 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 11236 return -EFAULT; 11237 } 11238 id = reg->id; 11239 11240 if (!env->cur_state->active_lock.ptr) 11241 return -EINVAL; 11242 if (env->cur_state->active_lock.ptr != ptr || 11243 env->cur_state->active_lock.id != id) { 11244 verbose(env, "held lock and object are not in the same allocation\n"); 11245 return -EINVAL; 11246 } 11247 return 0; 11248 } 11249 11250 static bool is_bpf_list_api_kfunc(u32 btf_id) 11251 { 11252 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11253 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11254 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11255 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 11256 } 11257 11258 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11259 { 11260 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 11261 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11262 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 11263 } 11264 11265 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11266 { 11267 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 11268 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11269 } 11270 11271 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11272 { 11273 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11274 } 11275 11276 static bool is_bpf_throw_kfunc(struct bpf_insn *insn) 11277 { 11278 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 11279 insn->imm == special_kfunc_list[KF_bpf_throw]; 11280 } 11281 11282 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11283 { 11284 return is_bpf_rbtree_api_kfunc(btf_id); 11285 } 11286 11287 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11288 enum btf_field_type head_field_type, 11289 u32 kfunc_btf_id) 11290 { 11291 bool ret; 11292 11293 switch (head_field_type) { 11294 case BPF_LIST_HEAD: 11295 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11296 break; 11297 case BPF_RB_ROOT: 11298 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11299 break; 11300 default: 11301 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11302 btf_field_type_name(head_field_type)); 11303 return false; 11304 } 11305 11306 if (!ret) 11307 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11308 btf_field_type_name(head_field_type)); 11309 return ret; 11310 } 11311 11312 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11313 enum btf_field_type node_field_type, 11314 u32 kfunc_btf_id) 11315 { 11316 bool ret; 11317 11318 switch (node_field_type) { 11319 case BPF_LIST_NODE: 11320 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11321 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 11322 break; 11323 case BPF_RB_NODE: 11324 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11325 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 11326 break; 11327 default: 11328 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11329 btf_field_type_name(node_field_type)); 11330 return false; 11331 } 11332 11333 if (!ret) 11334 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11335 btf_field_type_name(node_field_type)); 11336 return ret; 11337 } 11338 11339 static int 11340 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11341 struct bpf_reg_state *reg, u32 regno, 11342 struct bpf_kfunc_call_arg_meta *meta, 11343 enum btf_field_type head_field_type, 11344 struct btf_field **head_field) 11345 { 11346 const char *head_type_name; 11347 struct btf_field *field; 11348 struct btf_record *rec; 11349 u32 head_off; 11350 11351 if (meta->btf != btf_vmlinux) { 11352 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11353 return -EFAULT; 11354 } 11355 11356 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11357 return -EFAULT; 11358 11359 head_type_name = btf_field_type_name(head_field_type); 11360 if (!tnum_is_const(reg->var_off)) { 11361 verbose(env, 11362 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11363 regno, head_type_name); 11364 return -EINVAL; 11365 } 11366 11367 rec = reg_btf_record(reg); 11368 head_off = reg->off + reg->var_off.value; 11369 field = btf_record_find(rec, head_off, head_field_type); 11370 if (!field) { 11371 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11372 return -EINVAL; 11373 } 11374 11375 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11376 if (check_reg_allocation_locked(env, reg)) { 11377 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11378 rec->spin_lock_off, head_type_name); 11379 return -EINVAL; 11380 } 11381 11382 if (*head_field) { 11383 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 11384 return -EFAULT; 11385 } 11386 *head_field = field; 11387 return 0; 11388 } 11389 11390 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11391 struct bpf_reg_state *reg, u32 regno, 11392 struct bpf_kfunc_call_arg_meta *meta) 11393 { 11394 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 11395 &meta->arg_list_head.field); 11396 } 11397 11398 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11399 struct bpf_reg_state *reg, u32 regno, 11400 struct bpf_kfunc_call_arg_meta *meta) 11401 { 11402 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 11403 &meta->arg_rbtree_root.field); 11404 } 11405 11406 static int 11407 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11408 struct bpf_reg_state *reg, u32 regno, 11409 struct bpf_kfunc_call_arg_meta *meta, 11410 enum btf_field_type head_field_type, 11411 enum btf_field_type node_field_type, 11412 struct btf_field **node_field) 11413 { 11414 const char *node_type_name; 11415 const struct btf_type *et, *t; 11416 struct btf_field *field; 11417 u32 node_off; 11418 11419 if (meta->btf != btf_vmlinux) { 11420 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11421 return -EFAULT; 11422 } 11423 11424 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11425 return -EFAULT; 11426 11427 node_type_name = btf_field_type_name(node_field_type); 11428 if (!tnum_is_const(reg->var_off)) { 11429 verbose(env, 11430 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11431 regno, node_type_name); 11432 return -EINVAL; 11433 } 11434 11435 node_off = reg->off + reg->var_off.value; 11436 field = reg_find_field_offset(reg, node_off, node_field_type); 11437 if (!field || field->offset != node_off) { 11438 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11439 return -EINVAL; 11440 } 11441 11442 field = *node_field; 11443 11444 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11445 t = btf_type_by_id(reg->btf, reg->btf_id); 11446 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11447 field->graph_root.value_btf_id, true)) { 11448 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11449 "in struct %s, but arg is at offset=%d in struct %s\n", 11450 btf_field_type_name(head_field_type), 11451 btf_field_type_name(node_field_type), 11452 field->graph_root.node_offset, 11453 btf_name_by_offset(field->graph_root.btf, et->name_off), 11454 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11455 return -EINVAL; 11456 } 11457 meta->arg_btf = reg->btf; 11458 meta->arg_btf_id = reg->btf_id; 11459 11460 if (node_off != field->graph_root.node_offset) { 11461 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11462 node_off, btf_field_type_name(node_field_type), 11463 field->graph_root.node_offset, 11464 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11465 return -EINVAL; 11466 } 11467 11468 return 0; 11469 } 11470 11471 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11472 struct bpf_reg_state *reg, u32 regno, 11473 struct bpf_kfunc_call_arg_meta *meta) 11474 { 11475 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11476 BPF_LIST_HEAD, BPF_LIST_NODE, 11477 &meta->arg_list_head.field); 11478 } 11479 11480 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11481 struct bpf_reg_state *reg, u32 regno, 11482 struct bpf_kfunc_call_arg_meta *meta) 11483 { 11484 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11485 BPF_RB_ROOT, BPF_RB_NODE, 11486 &meta->arg_rbtree_root.field); 11487 } 11488 11489 /* 11490 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 11491 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 11492 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 11493 * them can only be attached to some specific hook points. 11494 */ 11495 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 11496 { 11497 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11498 11499 switch (prog_type) { 11500 case BPF_PROG_TYPE_LSM: 11501 return true; 11502 case BPF_PROG_TYPE_TRACING: 11503 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 11504 return true; 11505 fallthrough; 11506 default: 11507 return env->prog->aux->sleepable; 11508 } 11509 } 11510 11511 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11512 int insn_idx) 11513 { 11514 const char *func_name = meta->func_name, *ref_tname; 11515 const struct btf *btf = meta->btf; 11516 const struct btf_param *args; 11517 struct btf_record *rec; 11518 u32 i, nargs; 11519 int ret; 11520 11521 args = (const struct btf_param *)(meta->func_proto + 1); 11522 nargs = btf_type_vlen(meta->func_proto); 11523 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 11524 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11525 MAX_BPF_FUNC_REG_ARGS); 11526 return -EINVAL; 11527 } 11528 11529 /* Check that BTF function arguments match actual types that the 11530 * verifier sees. 11531 */ 11532 for (i = 0; i < nargs; i++) { 11533 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 11534 const struct btf_type *t, *ref_t, *resolve_ret; 11535 enum bpf_arg_type arg_type = ARG_DONTCARE; 11536 u32 regno = i + 1, ref_id, type_size; 11537 bool is_ret_buf_sz = false; 11538 int kf_arg_type; 11539 11540 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11541 11542 if (is_kfunc_arg_ignore(btf, &args[i])) 11543 continue; 11544 11545 if (btf_type_is_scalar(t)) { 11546 if (reg->type != SCALAR_VALUE) { 11547 verbose(env, "R%d is not a scalar\n", regno); 11548 return -EINVAL; 11549 } 11550 11551 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11552 if (meta->arg_constant.found) { 11553 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11554 return -EFAULT; 11555 } 11556 if (!tnum_is_const(reg->var_off)) { 11557 verbose(env, "R%d must be a known constant\n", regno); 11558 return -EINVAL; 11559 } 11560 ret = mark_chain_precision(env, regno); 11561 if (ret < 0) 11562 return ret; 11563 meta->arg_constant.found = true; 11564 meta->arg_constant.value = reg->var_off.value; 11565 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 11566 meta->r0_rdonly = true; 11567 is_ret_buf_sz = true; 11568 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 11569 is_ret_buf_sz = true; 11570 } 11571 11572 if (is_ret_buf_sz) { 11573 if (meta->r0_size) { 11574 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 11575 return -EINVAL; 11576 } 11577 11578 if (!tnum_is_const(reg->var_off)) { 11579 verbose(env, "R%d is not a const\n", regno); 11580 return -EINVAL; 11581 } 11582 11583 meta->r0_size = reg->var_off.value; 11584 ret = mark_chain_precision(env, regno); 11585 if (ret) 11586 return ret; 11587 } 11588 continue; 11589 } 11590 11591 if (!btf_type_is_ptr(t)) { 11592 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 11593 return -EINVAL; 11594 } 11595 11596 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 11597 (register_is_null(reg) || type_may_be_null(reg->type)) && 11598 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 11599 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 11600 return -EACCES; 11601 } 11602 11603 if (reg->ref_obj_id) { 11604 if (is_kfunc_release(meta) && meta->ref_obj_id) { 11605 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 11606 regno, reg->ref_obj_id, 11607 meta->ref_obj_id); 11608 return -EFAULT; 11609 } 11610 meta->ref_obj_id = reg->ref_obj_id; 11611 if (is_kfunc_release(meta)) 11612 meta->release_regno = regno; 11613 } 11614 11615 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 11616 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 11617 11618 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 11619 if (kf_arg_type < 0) 11620 return kf_arg_type; 11621 11622 switch (kf_arg_type) { 11623 case KF_ARG_PTR_TO_NULL: 11624 continue; 11625 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11626 case KF_ARG_PTR_TO_BTF_ID: 11627 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 11628 break; 11629 11630 if (!is_trusted_reg(reg)) { 11631 if (!is_kfunc_rcu(meta)) { 11632 verbose(env, "R%d must be referenced or trusted\n", regno); 11633 return -EINVAL; 11634 } 11635 if (!is_rcu_reg(reg)) { 11636 verbose(env, "R%d must be a rcu pointer\n", regno); 11637 return -EINVAL; 11638 } 11639 } 11640 11641 fallthrough; 11642 case KF_ARG_PTR_TO_CTX: 11643 /* Trusted arguments have the same offset checks as release arguments */ 11644 arg_type |= OBJ_RELEASE; 11645 break; 11646 case KF_ARG_PTR_TO_DYNPTR: 11647 case KF_ARG_PTR_TO_ITER: 11648 case KF_ARG_PTR_TO_LIST_HEAD: 11649 case KF_ARG_PTR_TO_LIST_NODE: 11650 case KF_ARG_PTR_TO_RB_ROOT: 11651 case KF_ARG_PTR_TO_RB_NODE: 11652 case KF_ARG_PTR_TO_MEM: 11653 case KF_ARG_PTR_TO_MEM_SIZE: 11654 case KF_ARG_PTR_TO_CALLBACK: 11655 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11656 case KF_ARG_PTR_TO_CONST_STR: 11657 /* Trusted by default */ 11658 break; 11659 default: 11660 WARN_ON_ONCE(1); 11661 return -EFAULT; 11662 } 11663 11664 if (is_kfunc_release(meta) && reg->ref_obj_id) 11665 arg_type |= OBJ_RELEASE; 11666 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 11667 if (ret < 0) 11668 return ret; 11669 11670 switch (kf_arg_type) { 11671 case KF_ARG_PTR_TO_CTX: 11672 if (reg->type != PTR_TO_CTX) { 11673 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 11674 return -EINVAL; 11675 } 11676 11677 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11678 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 11679 if (ret < 0) 11680 return -EINVAL; 11681 meta->ret_btf_id = ret; 11682 } 11683 break; 11684 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11685 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 11686 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) { 11687 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i); 11688 return -EINVAL; 11689 } 11690 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 11691 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 11692 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i); 11693 return -EINVAL; 11694 } 11695 } else { 11696 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11697 return -EINVAL; 11698 } 11699 if (!reg->ref_obj_id) { 11700 verbose(env, "allocated object must be referenced\n"); 11701 return -EINVAL; 11702 } 11703 if (meta->btf == btf_vmlinux) { 11704 meta->arg_btf = reg->btf; 11705 meta->arg_btf_id = reg->btf_id; 11706 } 11707 break; 11708 case KF_ARG_PTR_TO_DYNPTR: 11709 { 11710 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 11711 int clone_ref_obj_id = 0; 11712 11713 if (reg->type != PTR_TO_STACK && 11714 reg->type != CONST_PTR_TO_DYNPTR) { 11715 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 11716 return -EINVAL; 11717 } 11718 11719 if (reg->type == CONST_PTR_TO_DYNPTR) 11720 dynptr_arg_type |= MEM_RDONLY; 11721 11722 if (is_kfunc_arg_uninit(btf, &args[i])) 11723 dynptr_arg_type |= MEM_UNINIT; 11724 11725 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 11726 dynptr_arg_type |= DYNPTR_TYPE_SKB; 11727 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 11728 dynptr_arg_type |= DYNPTR_TYPE_XDP; 11729 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 11730 (dynptr_arg_type & MEM_UNINIT)) { 11731 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 11732 11733 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 11734 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 11735 return -EFAULT; 11736 } 11737 11738 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 11739 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 11740 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 11741 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 11742 return -EFAULT; 11743 } 11744 } 11745 11746 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 11747 if (ret < 0) 11748 return ret; 11749 11750 if (!(dynptr_arg_type & MEM_UNINIT)) { 11751 int id = dynptr_id(env, reg); 11752 11753 if (id < 0) { 11754 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 11755 return id; 11756 } 11757 meta->initialized_dynptr.id = id; 11758 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 11759 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 11760 } 11761 11762 break; 11763 } 11764 case KF_ARG_PTR_TO_ITER: 11765 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 11766 if (!check_css_task_iter_allowlist(env)) { 11767 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 11768 return -EINVAL; 11769 } 11770 } 11771 ret = process_iter_arg(env, regno, insn_idx, meta); 11772 if (ret < 0) 11773 return ret; 11774 break; 11775 case KF_ARG_PTR_TO_LIST_HEAD: 11776 if (reg->type != PTR_TO_MAP_VALUE && 11777 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11778 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11779 return -EINVAL; 11780 } 11781 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11782 verbose(env, "allocated object must be referenced\n"); 11783 return -EINVAL; 11784 } 11785 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 11786 if (ret < 0) 11787 return ret; 11788 break; 11789 case KF_ARG_PTR_TO_RB_ROOT: 11790 if (reg->type != PTR_TO_MAP_VALUE && 11791 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11792 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11793 return -EINVAL; 11794 } 11795 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11796 verbose(env, "allocated object must be referenced\n"); 11797 return -EINVAL; 11798 } 11799 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 11800 if (ret < 0) 11801 return ret; 11802 break; 11803 case KF_ARG_PTR_TO_LIST_NODE: 11804 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11805 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11806 return -EINVAL; 11807 } 11808 if (!reg->ref_obj_id) { 11809 verbose(env, "allocated object must be referenced\n"); 11810 return -EINVAL; 11811 } 11812 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 11813 if (ret < 0) 11814 return ret; 11815 break; 11816 case KF_ARG_PTR_TO_RB_NODE: 11817 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 11818 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 11819 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 11820 return -EINVAL; 11821 } 11822 if (in_rbtree_lock_required_cb(env)) { 11823 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 11824 return -EINVAL; 11825 } 11826 } else { 11827 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11828 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11829 return -EINVAL; 11830 } 11831 if (!reg->ref_obj_id) { 11832 verbose(env, "allocated object must be referenced\n"); 11833 return -EINVAL; 11834 } 11835 } 11836 11837 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 11838 if (ret < 0) 11839 return ret; 11840 break; 11841 case KF_ARG_PTR_TO_BTF_ID: 11842 /* Only base_type is checked, further checks are done here */ 11843 if ((base_type(reg->type) != PTR_TO_BTF_ID || 11844 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 11845 !reg2btf_ids[base_type(reg->type)]) { 11846 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 11847 verbose(env, "expected %s or socket\n", 11848 reg_type_str(env, base_type(reg->type) | 11849 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 11850 return -EINVAL; 11851 } 11852 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 11853 if (ret < 0) 11854 return ret; 11855 break; 11856 case KF_ARG_PTR_TO_MEM: 11857 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 11858 if (IS_ERR(resolve_ret)) { 11859 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 11860 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 11861 return -EINVAL; 11862 } 11863 ret = check_mem_reg(env, reg, regno, type_size); 11864 if (ret < 0) 11865 return ret; 11866 break; 11867 case KF_ARG_PTR_TO_MEM_SIZE: 11868 { 11869 struct bpf_reg_state *buff_reg = ®s[regno]; 11870 const struct btf_param *buff_arg = &args[i]; 11871 struct bpf_reg_state *size_reg = ®s[regno + 1]; 11872 const struct btf_param *size_arg = &args[i + 1]; 11873 11874 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 11875 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 11876 if (ret < 0) { 11877 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 11878 return ret; 11879 } 11880 } 11881 11882 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 11883 if (meta->arg_constant.found) { 11884 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11885 return -EFAULT; 11886 } 11887 if (!tnum_is_const(size_reg->var_off)) { 11888 verbose(env, "R%d must be a known constant\n", regno + 1); 11889 return -EINVAL; 11890 } 11891 meta->arg_constant.found = true; 11892 meta->arg_constant.value = size_reg->var_off.value; 11893 } 11894 11895 /* Skip next '__sz' or '__szk' argument */ 11896 i++; 11897 break; 11898 } 11899 case KF_ARG_PTR_TO_CALLBACK: 11900 if (reg->type != PTR_TO_FUNC) { 11901 verbose(env, "arg%d expected pointer to func\n", i); 11902 return -EINVAL; 11903 } 11904 meta->subprogno = reg->subprogno; 11905 break; 11906 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11907 if (!type_is_ptr_alloc_obj(reg->type)) { 11908 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 11909 return -EINVAL; 11910 } 11911 if (!type_is_non_owning_ref(reg->type)) 11912 meta->arg_owning_ref = true; 11913 11914 rec = reg_btf_record(reg); 11915 if (!rec) { 11916 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 11917 return -EFAULT; 11918 } 11919 11920 if (rec->refcount_off < 0) { 11921 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 11922 return -EINVAL; 11923 } 11924 11925 meta->arg_btf = reg->btf; 11926 meta->arg_btf_id = reg->btf_id; 11927 break; 11928 case KF_ARG_PTR_TO_CONST_STR: 11929 if (reg->type != PTR_TO_MAP_VALUE) { 11930 verbose(env, "arg#%d doesn't point to a const string\n", i); 11931 return -EINVAL; 11932 } 11933 ret = check_reg_const_str(env, reg, regno); 11934 if (ret) 11935 return ret; 11936 break; 11937 } 11938 } 11939 11940 if (is_kfunc_release(meta) && !meta->release_regno) { 11941 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 11942 func_name); 11943 return -EINVAL; 11944 } 11945 11946 return 0; 11947 } 11948 11949 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 11950 struct bpf_insn *insn, 11951 struct bpf_kfunc_call_arg_meta *meta, 11952 const char **kfunc_name) 11953 { 11954 const struct btf_type *func, *func_proto; 11955 u32 func_id, *kfunc_flags; 11956 const char *func_name; 11957 struct btf *desc_btf; 11958 11959 if (kfunc_name) 11960 *kfunc_name = NULL; 11961 11962 if (!insn->imm) 11963 return -EINVAL; 11964 11965 desc_btf = find_kfunc_desc_btf(env, insn->off); 11966 if (IS_ERR(desc_btf)) 11967 return PTR_ERR(desc_btf); 11968 11969 func_id = insn->imm; 11970 func = btf_type_by_id(desc_btf, func_id); 11971 func_name = btf_name_by_offset(desc_btf, func->name_off); 11972 if (kfunc_name) 11973 *kfunc_name = func_name; 11974 func_proto = btf_type_by_id(desc_btf, func->type); 11975 11976 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 11977 if (!kfunc_flags) { 11978 return -EACCES; 11979 } 11980 11981 memset(meta, 0, sizeof(*meta)); 11982 meta->btf = desc_btf; 11983 meta->func_id = func_id; 11984 meta->kfunc_flags = *kfunc_flags; 11985 meta->func_proto = func_proto; 11986 meta->func_name = func_name; 11987 11988 return 0; 11989 } 11990 11991 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 11992 11993 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 11994 int *insn_idx_p) 11995 { 11996 const struct btf_type *t, *ptr_type; 11997 u32 i, nargs, ptr_type_id, release_ref_obj_id; 11998 struct bpf_reg_state *regs = cur_regs(env); 11999 const char *func_name, *ptr_type_name; 12000 bool sleepable, rcu_lock, rcu_unlock; 12001 struct bpf_kfunc_call_arg_meta meta; 12002 struct bpf_insn_aux_data *insn_aux; 12003 int err, insn_idx = *insn_idx_p; 12004 const struct btf_param *args; 12005 const struct btf_type *ret_t; 12006 struct btf *desc_btf; 12007 12008 /* skip for now, but return error when we find this in fixup_kfunc_call */ 12009 if (!insn->imm) 12010 return 0; 12011 12012 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 12013 if (err == -EACCES && func_name) 12014 verbose(env, "calling kernel function %s is not allowed\n", func_name); 12015 if (err) 12016 return err; 12017 desc_btf = meta.btf; 12018 insn_aux = &env->insn_aux_data[insn_idx]; 12019 12020 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 12021 12022 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 12023 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 12024 return -EACCES; 12025 } 12026 12027 sleepable = is_kfunc_sleepable(&meta); 12028 if (sleepable && !env->prog->aux->sleepable) { 12029 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 12030 return -EACCES; 12031 } 12032 12033 /* Check the arguments */ 12034 err = check_kfunc_args(env, &meta, insn_idx); 12035 if (err < 0) 12036 return err; 12037 12038 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12039 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12040 set_rbtree_add_callback_state); 12041 if (err) { 12042 verbose(env, "kfunc %s#%d failed callback verification\n", 12043 func_name, meta.func_id); 12044 return err; 12045 } 12046 } 12047 12048 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 12049 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 12050 12051 if (env->cur_state->active_rcu_lock) { 12052 struct bpf_func_state *state; 12053 struct bpf_reg_state *reg; 12054 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 12055 12056 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 12057 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 12058 return -EACCES; 12059 } 12060 12061 if (rcu_lock) { 12062 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 12063 return -EINVAL; 12064 } else if (rcu_unlock) { 12065 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({ 12066 if (reg->type & MEM_RCU) { 12067 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 12068 reg->type |= PTR_UNTRUSTED; 12069 } 12070 })); 12071 env->cur_state->active_rcu_lock = false; 12072 } else if (sleepable) { 12073 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 12074 return -EACCES; 12075 } 12076 } else if (rcu_lock) { 12077 env->cur_state->active_rcu_lock = true; 12078 } else if (rcu_unlock) { 12079 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 12080 return -EINVAL; 12081 } 12082 12083 /* In case of release function, we get register number of refcounted 12084 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 12085 */ 12086 if (meta.release_regno) { 12087 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 12088 if (err) { 12089 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12090 func_name, meta.func_id); 12091 return err; 12092 } 12093 } 12094 12095 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 12096 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 12097 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12098 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 12099 insn_aux->insert_off = regs[BPF_REG_2].off; 12100 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 12101 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 12102 if (err) { 12103 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 12104 func_name, meta.func_id); 12105 return err; 12106 } 12107 12108 err = release_reference(env, release_ref_obj_id); 12109 if (err) { 12110 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12111 func_name, meta.func_id); 12112 return err; 12113 } 12114 } 12115 12116 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 12117 if (!bpf_jit_supports_exceptions()) { 12118 verbose(env, "JIT does not support calling kfunc %s#%d\n", 12119 func_name, meta.func_id); 12120 return -ENOTSUPP; 12121 } 12122 env->seen_exception = true; 12123 12124 /* In the case of the default callback, the cookie value passed 12125 * to bpf_throw becomes the return value of the program. 12126 */ 12127 if (!env->exception_callback_subprog) { 12128 err = check_return_code(env, BPF_REG_1, "R1"); 12129 if (err < 0) 12130 return err; 12131 } 12132 } 12133 12134 for (i = 0; i < CALLER_SAVED_REGS; i++) 12135 mark_reg_not_init(env, regs, caller_saved[i]); 12136 12137 /* Check return type */ 12138 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 12139 12140 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 12141 /* Only exception is bpf_obj_new_impl */ 12142 if (meta.btf != btf_vmlinux || 12143 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 12144 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] && 12145 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 12146 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 12147 return -EINVAL; 12148 } 12149 } 12150 12151 if (btf_type_is_scalar(t)) { 12152 mark_reg_unknown(env, regs, BPF_REG_0); 12153 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 12154 } else if (btf_type_is_ptr(t)) { 12155 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 12156 12157 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12158 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 12159 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12160 struct btf_struct_meta *struct_meta; 12161 struct btf *ret_btf; 12162 u32 ret_btf_id; 12163 12164 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set) 12165 return -ENOMEM; 12166 12167 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 12168 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 12169 return -EINVAL; 12170 } 12171 12172 ret_btf = env->prog->aux->btf; 12173 ret_btf_id = meta.arg_constant.value; 12174 12175 /* This may be NULL due to user not supplying a BTF */ 12176 if (!ret_btf) { 12177 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 12178 return -EINVAL; 12179 } 12180 12181 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 12182 if (!ret_t || !__btf_type_is_struct(ret_t)) { 12183 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 12184 return -EINVAL; 12185 } 12186 12187 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12188 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 12189 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 12190 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 12191 return -EINVAL; 12192 } 12193 12194 if (!bpf_global_percpu_ma_set) { 12195 mutex_lock(&bpf_percpu_ma_lock); 12196 if (!bpf_global_percpu_ma_set) { 12197 /* Charge memory allocated with bpf_global_percpu_ma to 12198 * root memcg. The obj_cgroup for root memcg is NULL. 12199 */ 12200 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 12201 if (!err) 12202 bpf_global_percpu_ma_set = true; 12203 } 12204 mutex_unlock(&bpf_percpu_ma_lock); 12205 if (err) 12206 return err; 12207 } 12208 12209 mutex_lock(&bpf_percpu_ma_lock); 12210 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 12211 mutex_unlock(&bpf_percpu_ma_lock); 12212 if (err) 12213 return err; 12214 } 12215 12216 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 12217 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12218 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 12219 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 12220 return -EINVAL; 12221 } 12222 12223 if (struct_meta) { 12224 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 12225 return -EINVAL; 12226 } 12227 } 12228 12229 mark_reg_known_zero(env, regs, BPF_REG_0); 12230 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12231 regs[BPF_REG_0].btf = ret_btf; 12232 regs[BPF_REG_0].btf_id = ret_btf_id; 12233 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) 12234 regs[BPF_REG_0].type |= MEM_PERCPU; 12235 12236 insn_aux->obj_new_size = ret_t->size; 12237 insn_aux->kptr_struct_meta = struct_meta; 12238 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 12239 mark_reg_known_zero(env, regs, BPF_REG_0); 12240 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12241 regs[BPF_REG_0].btf = meta.arg_btf; 12242 regs[BPF_REG_0].btf_id = meta.arg_btf_id; 12243 12244 insn_aux->kptr_struct_meta = 12245 btf_find_struct_meta(meta.arg_btf, 12246 meta.arg_btf_id); 12247 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 12248 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 12249 struct btf_field *field = meta.arg_list_head.field; 12250 12251 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12252 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12253 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12254 struct btf_field *field = meta.arg_rbtree_root.field; 12255 12256 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12257 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12258 mark_reg_known_zero(env, regs, BPF_REG_0); 12259 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 12260 regs[BPF_REG_0].btf = desc_btf; 12261 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 12262 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 12263 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 12264 if (!ret_t || !btf_type_is_struct(ret_t)) { 12265 verbose(env, 12266 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 12267 return -EINVAL; 12268 } 12269 12270 mark_reg_known_zero(env, regs, BPF_REG_0); 12271 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 12272 regs[BPF_REG_0].btf = desc_btf; 12273 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 12274 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 12275 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 12276 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 12277 12278 mark_reg_known_zero(env, regs, BPF_REG_0); 12279 12280 if (!meta.arg_constant.found) { 12281 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 12282 return -EFAULT; 12283 } 12284 12285 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 12286 12287 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 12288 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 12289 12290 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 12291 regs[BPF_REG_0].type |= MEM_RDONLY; 12292 } else { 12293 /* this will set env->seen_direct_write to true */ 12294 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 12295 verbose(env, "the prog does not allow writes to packet data\n"); 12296 return -EINVAL; 12297 } 12298 } 12299 12300 if (!meta.initialized_dynptr.id) { 12301 verbose(env, "verifier internal error: no dynptr id\n"); 12302 return -EFAULT; 12303 } 12304 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 12305 12306 /* we don't need to set BPF_REG_0's ref obj id 12307 * because packet slices are not refcounted (see 12308 * dynptr_type_refcounted) 12309 */ 12310 } else { 12311 verbose(env, "kernel function %s unhandled dynamic return type\n", 12312 meta.func_name); 12313 return -EFAULT; 12314 } 12315 } else if (!__btf_type_is_struct(ptr_type)) { 12316 if (!meta.r0_size) { 12317 __u32 sz; 12318 12319 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 12320 meta.r0_size = sz; 12321 meta.r0_rdonly = true; 12322 } 12323 } 12324 if (!meta.r0_size) { 12325 ptr_type_name = btf_name_by_offset(desc_btf, 12326 ptr_type->name_off); 12327 verbose(env, 12328 "kernel function %s returns pointer type %s %s is not supported\n", 12329 func_name, 12330 btf_type_str(ptr_type), 12331 ptr_type_name); 12332 return -EINVAL; 12333 } 12334 12335 mark_reg_known_zero(env, regs, BPF_REG_0); 12336 regs[BPF_REG_0].type = PTR_TO_MEM; 12337 regs[BPF_REG_0].mem_size = meta.r0_size; 12338 12339 if (meta.r0_rdonly) 12340 regs[BPF_REG_0].type |= MEM_RDONLY; 12341 12342 /* Ensures we don't access the memory after a release_reference() */ 12343 if (meta.ref_obj_id) 12344 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 12345 } else { 12346 mark_reg_known_zero(env, regs, BPF_REG_0); 12347 regs[BPF_REG_0].btf = desc_btf; 12348 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 12349 regs[BPF_REG_0].btf_id = ptr_type_id; 12350 } 12351 12352 if (is_kfunc_ret_null(&meta)) { 12353 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 12354 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 12355 regs[BPF_REG_0].id = ++env->id_gen; 12356 } 12357 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 12358 if (is_kfunc_acquire(&meta)) { 12359 int id = acquire_reference_state(env, insn_idx); 12360 12361 if (id < 0) 12362 return id; 12363 if (is_kfunc_ret_null(&meta)) 12364 regs[BPF_REG_0].id = id; 12365 regs[BPF_REG_0].ref_obj_id = id; 12366 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12367 ref_set_non_owning(env, ®s[BPF_REG_0]); 12368 } 12369 12370 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 12371 regs[BPF_REG_0].id = ++env->id_gen; 12372 } else if (btf_type_is_void(t)) { 12373 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12374 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 12375 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 12376 insn_aux->kptr_struct_meta = 12377 btf_find_struct_meta(meta.arg_btf, 12378 meta.arg_btf_id); 12379 } 12380 } 12381 } 12382 12383 nargs = btf_type_vlen(meta.func_proto); 12384 args = (const struct btf_param *)(meta.func_proto + 1); 12385 for (i = 0; i < nargs; i++) { 12386 u32 regno = i + 1; 12387 12388 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 12389 if (btf_type_is_ptr(t)) 12390 mark_btf_func_reg_size(env, regno, sizeof(void *)); 12391 else 12392 /* scalar. ensured by btf_check_kfunc_arg_match() */ 12393 mark_btf_func_reg_size(env, regno, t->size); 12394 } 12395 12396 if (is_iter_next_kfunc(&meta)) { 12397 err = process_iter_next_call(env, insn_idx, &meta); 12398 if (err) 12399 return err; 12400 } 12401 12402 return 0; 12403 } 12404 12405 static bool signed_add_overflows(s64 a, s64 b) 12406 { 12407 /* Do the add in u64, where overflow is well-defined */ 12408 s64 res = (s64)((u64)a + (u64)b); 12409 12410 if (b < 0) 12411 return res > a; 12412 return res < a; 12413 } 12414 12415 static bool signed_add32_overflows(s32 a, s32 b) 12416 { 12417 /* Do the add in u32, where overflow is well-defined */ 12418 s32 res = (s32)((u32)a + (u32)b); 12419 12420 if (b < 0) 12421 return res > a; 12422 return res < a; 12423 } 12424 12425 static bool signed_sub_overflows(s64 a, s64 b) 12426 { 12427 /* Do the sub in u64, where overflow is well-defined */ 12428 s64 res = (s64)((u64)a - (u64)b); 12429 12430 if (b < 0) 12431 return res < a; 12432 return res > a; 12433 } 12434 12435 static bool signed_sub32_overflows(s32 a, s32 b) 12436 { 12437 /* Do the sub in u32, where overflow is well-defined */ 12438 s32 res = (s32)((u32)a - (u32)b); 12439 12440 if (b < 0) 12441 return res < a; 12442 return res > a; 12443 } 12444 12445 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 12446 const struct bpf_reg_state *reg, 12447 enum bpf_reg_type type) 12448 { 12449 bool known = tnum_is_const(reg->var_off); 12450 s64 val = reg->var_off.value; 12451 s64 smin = reg->smin_value; 12452 12453 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 12454 verbose(env, "math between %s pointer and %lld is not allowed\n", 12455 reg_type_str(env, type), val); 12456 return false; 12457 } 12458 12459 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 12460 verbose(env, "%s pointer offset %d is not allowed\n", 12461 reg_type_str(env, type), reg->off); 12462 return false; 12463 } 12464 12465 if (smin == S64_MIN) { 12466 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 12467 reg_type_str(env, type)); 12468 return false; 12469 } 12470 12471 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 12472 verbose(env, "value %lld makes %s pointer be out of bounds\n", 12473 smin, reg_type_str(env, type)); 12474 return false; 12475 } 12476 12477 return true; 12478 } 12479 12480 enum { 12481 REASON_BOUNDS = -1, 12482 REASON_TYPE = -2, 12483 REASON_PATHS = -3, 12484 REASON_LIMIT = -4, 12485 REASON_STACK = -5, 12486 }; 12487 12488 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 12489 u32 *alu_limit, bool mask_to_left) 12490 { 12491 u32 max = 0, ptr_limit = 0; 12492 12493 switch (ptr_reg->type) { 12494 case PTR_TO_STACK: 12495 /* Offset 0 is out-of-bounds, but acceptable start for the 12496 * left direction, see BPF_REG_FP. Also, unknown scalar 12497 * offset where we would need to deal with min/max bounds is 12498 * currently prohibited for unprivileged. 12499 */ 12500 max = MAX_BPF_STACK + mask_to_left; 12501 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 12502 break; 12503 case PTR_TO_MAP_VALUE: 12504 max = ptr_reg->map_ptr->value_size; 12505 ptr_limit = (mask_to_left ? 12506 ptr_reg->smin_value : 12507 ptr_reg->umax_value) + ptr_reg->off; 12508 break; 12509 default: 12510 return REASON_TYPE; 12511 } 12512 12513 if (ptr_limit >= max) 12514 return REASON_LIMIT; 12515 *alu_limit = ptr_limit; 12516 return 0; 12517 } 12518 12519 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 12520 const struct bpf_insn *insn) 12521 { 12522 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 12523 } 12524 12525 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 12526 u32 alu_state, u32 alu_limit) 12527 { 12528 /* If we arrived here from different branches with different 12529 * state or limits to sanitize, then this won't work. 12530 */ 12531 if (aux->alu_state && 12532 (aux->alu_state != alu_state || 12533 aux->alu_limit != alu_limit)) 12534 return REASON_PATHS; 12535 12536 /* Corresponding fixup done in do_misc_fixups(). */ 12537 aux->alu_state = alu_state; 12538 aux->alu_limit = alu_limit; 12539 return 0; 12540 } 12541 12542 static int sanitize_val_alu(struct bpf_verifier_env *env, 12543 struct bpf_insn *insn) 12544 { 12545 struct bpf_insn_aux_data *aux = cur_aux(env); 12546 12547 if (can_skip_alu_sanitation(env, insn)) 12548 return 0; 12549 12550 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 12551 } 12552 12553 static bool sanitize_needed(u8 opcode) 12554 { 12555 return opcode == BPF_ADD || opcode == BPF_SUB; 12556 } 12557 12558 struct bpf_sanitize_info { 12559 struct bpf_insn_aux_data aux; 12560 bool mask_to_left; 12561 }; 12562 12563 static struct bpf_verifier_state * 12564 sanitize_speculative_path(struct bpf_verifier_env *env, 12565 const struct bpf_insn *insn, 12566 u32 next_idx, u32 curr_idx) 12567 { 12568 struct bpf_verifier_state *branch; 12569 struct bpf_reg_state *regs; 12570 12571 branch = push_stack(env, next_idx, curr_idx, true); 12572 if (branch && insn) { 12573 regs = branch->frame[branch->curframe]->regs; 12574 if (BPF_SRC(insn->code) == BPF_K) { 12575 mark_reg_unknown(env, regs, insn->dst_reg); 12576 } else if (BPF_SRC(insn->code) == BPF_X) { 12577 mark_reg_unknown(env, regs, insn->dst_reg); 12578 mark_reg_unknown(env, regs, insn->src_reg); 12579 } 12580 } 12581 return branch; 12582 } 12583 12584 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 12585 struct bpf_insn *insn, 12586 const struct bpf_reg_state *ptr_reg, 12587 const struct bpf_reg_state *off_reg, 12588 struct bpf_reg_state *dst_reg, 12589 struct bpf_sanitize_info *info, 12590 const bool commit_window) 12591 { 12592 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 12593 struct bpf_verifier_state *vstate = env->cur_state; 12594 bool off_is_imm = tnum_is_const(off_reg->var_off); 12595 bool off_is_neg = off_reg->smin_value < 0; 12596 bool ptr_is_dst_reg = ptr_reg == dst_reg; 12597 u8 opcode = BPF_OP(insn->code); 12598 u32 alu_state, alu_limit; 12599 struct bpf_reg_state tmp; 12600 bool ret; 12601 int err; 12602 12603 if (can_skip_alu_sanitation(env, insn)) 12604 return 0; 12605 12606 /* We already marked aux for masking from non-speculative 12607 * paths, thus we got here in the first place. We only care 12608 * to explore bad access from here. 12609 */ 12610 if (vstate->speculative) 12611 goto do_sim; 12612 12613 if (!commit_window) { 12614 if (!tnum_is_const(off_reg->var_off) && 12615 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 12616 return REASON_BOUNDS; 12617 12618 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 12619 (opcode == BPF_SUB && !off_is_neg); 12620 } 12621 12622 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 12623 if (err < 0) 12624 return err; 12625 12626 if (commit_window) { 12627 /* In commit phase we narrow the masking window based on 12628 * the observed pointer move after the simulated operation. 12629 */ 12630 alu_state = info->aux.alu_state; 12631 alu_limit = abs(info->aux.alu_limit - alu_limit); 12632 } else { 12633 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 12634 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 12635 alu_state |= ptr_is_dst_reg ? 12636 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 12637 12638 /* Limit pruning on unknown scalars to enable deep search for 12639 * potential masking differences from other program paths. 12640 */ 12641 if (!off_is_imm) 12642 env->explore_alu_limits = true; 12643 } 12644 12645 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 12646 if (err < 0) 12647 return err; 12648 do_sim: 12649 /* If we're in commit phase, we're done here given we already 12650 * pushed the truncated dst_reg into the speculative verification 12651 * stack. 12652 * 12653 * Also, when register is a known constant, we rewrite register-based 12654 * operation to immediate-based, and thus do not need masking (and as 12655 * a consequence, do not need to simulate the zero-truncation either). 12656 */ 12657 if (commit_window || off_is_imm) 12658 return 0; 12659 12660 /* Simulate and find potential out-of-bounds access under 12661 * speculative execution from truncation as a result of 12662 * masking when off was not within expected range. If off 12663 * sits in dst, then we temporarily need to move ptr there 12664 * to simulate dst (== 0) +/-= ptr. Needed, for example, 12665 * for cases where we use K-based arithmetic in one direction 12666 * and truncated reg-based in the other in order to explore 12667 * bad access. 12668 */ 12669 if (!ptr_is_dst_reg) { 12670 tmp = *dst_reg; 12671 copy_register_state(dst_reg, ptr_reg); 12672 } 12673 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 12674 env->insn_idx); 12675 if (!ptr_is_dst_reg && ret) 12676 *dst_reg = tmp; 12677 return !ret ? REASON_STACK : 0; 12678 } 12679 12680 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 12681 { 12682 struct bpf_verifier_state *vstate = env->cur_state; 12683 12684 /* If we simulate paths under speculation, we don't update the 12685 * insn as 'seen' such that when we verify unreachable paths in 12686 * the non-speculative domain, sanitize_dead_code() can still 12687 * rewrite/sanitize them. 12688 */ 12689 if (!vstate->speculative) 12690 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 12691 } 12692 12693 static int sanitize_err(struct bpf_verifier_env *env, 12694 const struct bpf_insn *insn, int reason, 12695 const struct bpf_reg_state *off_reg, 12696 const struct bpf_reg_state *dst_reg) 12697 { 12698 static const char *err = "pointer arithmetic with it prohibited for !root"; 12699 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 12700 u32 dst = insn->dst_reg, src = insn->src_reg; 12701 12702 switch (reason) { 12703 case REASON_BOUNDS: 12704 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 12705 off_reg == dst_reg ? dst : src, err); 12706 break; 12707 case REASON_TYPE: 12708 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 12709 off_reg == dst_reg ? src : dst, err); 12710 break; 12711 case REASON_PATHS: 12712 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 12713 dst, op, err); 12714 break; 12715 case REASON_LIMIT: 12716 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 12717 dst, op, err); 12718 break; 12719 case REASON_STACK: 12720 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 12721 dst, err); 12722 break; 12723 default: 12724 verbose(env, "verifier internal error: unknown reason (%d)\n", 12725 reason); 12726 break; 12727 } 12728 12729 return -EACCES; 12730 } 12731 12732 /* check that stack access falls within stack limits and that 'reg' doesn't 12733 * have a variable offset. 12734 * 12735 * Variable offset is prohibited for unprivileged mode for simplicity since it 12736 * requires corresponding support in Spectre masking for stack ALU. See also 12737 * retrieve_ptr_limit(). 12738 * 12739 * 12740 * 'off' includes 'reg->off'. 12741 */ 12742 static int check_stack_access_for_ptr_arithmetic( 12743 struct bpf_verifier_env *env, 12744 int regno, 12745 const struct bpf_reg_state *reg, 12746 int off) 12747 { 12748 if (!tnum_is_const(reg->var_off)) { 12749 char tn_buf[48]; 12750 12751 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 12752 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 12753 regno, tn_buf, off); 12754 return -EACCES; 12755 } 12756 12757 if (off >= 0 || off < -MAX_BPF_STACK) { 12758 verbose(env, "R%d stack pointer arithmetic goes out of range, " 12759 "prohibited for !root; off=%d\n", regno, off); 12760 return -EACCES; 12761 } 12762 12763 return 0; 12764 } 12765 12766 static int sanitize_check_bounds(struct bpf_verifier_env *env, 12767 const struct bpf_insn *insn, 12768 const struct bpf_reg_state *dst_reg) 12769 { 12770 u32 dst = insn->dst_reg; 12771 12772 /* For unprivileged we require that resulting offset must be in bounds 12773 * in order to be able to sanitize access later on. 12774 */ 12775 if (env->bypass_spec_v1) 12776 return 0; 12777 12778 switch (dst_reg->type) { 12779 case PTR_TO_STACK: 12780 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 12781 dst_reg->off + dst_reg->var_off.value)) 12782 return -EACCES; 12783 break; 12784 case PTR_TO_MAP_VALUE: 12785 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 12786 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 12787 "prohibited for !root\n", dst); 12788 return -EACCES; 12789 } 12790 break; 12791 default: 12792 break; 12793 } 12794 12795 return 0; 12796 } 12797 12798 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 12799 * Caller should also handle BPF_MOV case separately. 12800 * If we return -EACCES, caller may want to try again treating pointer as a 12801 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 12802 */ 12803 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 12804 struct bpf_insn *insn, 12805 const struct bpf_reg_state *ptr_reg, 12806 const struct bpf_reg_state *off_reg) 12807 { 12808 struct bpf_verifier_state *vstate = env->cur_state; 12809 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 12810 struct bpf_reg_state *regs = state->regs, *dst_reg; 12811 bool known = tnum_is_const(off_reg->var_off); 12812 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 12813 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 12814 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 12815 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 12816 struct bpf_sanitize_info info = {}; 12817 u8 opcode = BPF_OP(insn->code); 12818 u32 dst = insn->dst_reg; 12819 int ret; 12820 12821 dst_reg = ®s[dst]; 12822 12823 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 12824 smin_val > smax_val || umin_val > umax_val) { 12825 /* Taint dst register if offset had invalid bounds derived from 12826 * e.g. dead branches. 12827 */ 12828 __mark_reg_unknown(env, dst_reg); 12829 return 0; 12830 } 12831 12832 if (BPF_CLASS(insn->code) != BPF_ALU64) { 12833 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 12834 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 12835 __mark_reg_unknown(env, dst_reg); 12836 return 0; 12837 } 12838 12839 verbose(env, 12840 "R%d 32-bit pointer arithmetic prohibited\n", 12841 dst); 12842 return -EACCES; 12843 } 12844 12845 if (ptr_reg->type & PTR_MAYBE_NULL) { 12846 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 12847 dst, reg_type_str(env, ptr_reg->type)); 12848 return -EACCES; 12849 } 12850 12851 switch (base_type(ptr_reg->type)) { 12852 case PTR_TO_FLOW_KEYS: 12853 if (known) 12854 break; 12855 fallthrough; 12856 case CONST_PTR_TO_MAP: 12857 /* smin_val represents the known value */ 12858 if (known && smin_val == 0 && opcode == BPF_ADD) 12859 break; 12860 fallthrough; 12861 case PTR_TO_PACKET_END: 12862 case PTR_TO_SOCKET: 12863 case PTR_TO_SOCK_COMMON: 12864 case PTR_TO_TCP_SOCK: 12865 case PTR_TO_XDP_SOCK: 12866 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 12867 dst, reg_type_str(env, ptr_reg->type)); 12868 return -EACCES; 12869 default: 12870 break; 12871 } 12872 12873 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 12874 * The id may be overwritten later if we create a new variable offset. 12875 */ 12876 dst_reg->type = ptr_reg->type; 12877 dst_reg->id = ptr_reg->id; 12878 12879 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 12880 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 12881 return -EINVAL; 12882 12883 /* pointer types do not carry 32-bit bounds at the moment. */ 12884 __mark_reg32_unbounded(dst_reg); 12885 12886 if (sanitize_needed(opcode)) { 12887 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 12888 &info, false); 12889 if (ret < 0) 12890 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12891 } 12892 12893 switch (opcode) { 12894 case BPF_ADD: 12895 /* We can take a fixed offset as long as it doesn't overflow 12896 * the s32 'off' field 12897 */ 12898 if (known && (ptr_reg->off + smin_val == 12899 (s64)(s32)(ptr_reg->off + smin_val))) { 12900 /* pointer += K. Accumulate it into fixed offset */ 12901 dst_reg->smin_value = smin_ptr; 12902 dst_reg->smax_value = smax_ptr; 12903 dst_reg->umin_value = umin_ptr; 12904 dst_reg->umax_value = umax_ptr; 12905 dst_reg->var_off = ptr_reg->var_off; 12906 dst_reg->off = ptr_reg->off + smin_val; 12907 dst_reg->raw = ptr_reg->raw; 12908 break; 12909 } 12910 /* A new variable offset is created. Note that off_reg->off 12911 * == 0, since it's a scalar. 12912 * dst_reg gets the pointer type and since some positive 12913 * integer value was added to the pointer, give it a new 'id' 12914 * if it's a PTR_TO_PACKET. 12915 * this creates a new 'base' pointer, off_reg (variable) gets 12916 * added into the variable offset, and we copy the fixed offset 12917 * from ptr_reg. 12918 */ 12919 if (signed_add_overflows(smin_ptr, smin_val) || 12920 signed_add_overflows(smax_ptr, smax_val)) { 12921 dst_reg->smin_value = S64_MIN; 12922 dst_reg->smax_value = S64_MAX; 12923 } else { 12924 dst_reg->smin_value = smin_ptr + smin_val; 12925 dst_reg->smax_value = smax_ptr + smax_val; 12926 } 12927 if (umin_ptr + umin_val < umin_ptr || 12928 umax_ptr + umax_val < umax_ptr) { 12929 dst_reg->umin_value = 0; 12930 dst_reg->umax_value = U64_MAX; 12931 } else { 12932 dst_reg->umin_value = umin_ptr + umin_val; 12933 dst_reg->umax_value = umax_ptr + umax_val; 12934 } 12935 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 12936 dst_reg->off = ptr_reg->off; 12937 dst_reg->raw = ptr_reg->raw; 12938 if (reg_is_pkt_pointer(ptr_reg)) { 12939 dst_reg->id = ++env->id_gen; 12940 /* something was added to pkt_ptr, set range to zero */ 12941 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12942 } 12943 break; 12944 case BPF_SUB: 12945 if (dst_reg == off_reg) { 12946 /* scalar -= pointer. Creates an unknown scalar */ 12947 verbose(env, "R%d tried to subtract pointer from scalar\n", 12948 dst); 12949 return -EACCES; 12950 } 12951 /* We don't allow subtraction from FP, because (according to 12952 * test_verifier.c test "invalid fp arithmetic", JITs might not 12953 * be able to deal with it. 12954 */ 12955 if (ptr_reg->type == PTR_TO_STACK) { 12956 verbose(env, "R%d subtraction from stack pointer prohibited\n", 12957 dst); 12958 return -EACCES; 12959 } 12960 if (known && (ptr_reg->off - smin_val == 12961 (s64)(s32)(ptr_reg->off - smin_val))) { 12962 /* pointer -= K. Subtract it from fixed offset */ 12963 dst_reg->smin_value = smin_ptr; 12964 dst_reg->smax_value = smax_ptr; 12965 dst_reg->umin_value = umin_ptr; 12966 dst_reg->umax_value = umax_ptr; 12967 dst_reg->var_off = ptr_reg->var_off; 12968 dst_reg->id = ptr_reg->id; 12969 dst_reg->off = ptr_reg->off - smin_val; 12970 dst_reg->raw = ptr_reg->raw; 12971 break; 12972 } 12973 /* A new variable offset is created. If the subtrahend is known 12974 * nonnegative, then any reg->range we had before is still good. 12975 */ 12976 if (signed_sub_overflows(smin_ptr, smax_val) || 12977 signed_sub_overflows(smax_ptr, smin_val)) { 12978 /* Overflow possible, we know nothing */ 12979 dst_reg->smin_value = S64_MIN; 12980 dst_reg->smax_value = S64_MAX; 12981 } else { 12982 dst_reg->smin_value = smin_ptr - smax_val; 12983 dst_reg->smax_value = smax_ptr - smin_val; 12984 } 12985 if (umin_ptr < umax_val) { 12986 /* Overflow possible, we know nothing */ 12987 dst_reg->umin_value = 0; 12988 dst_reg->umax_value = U64_MAX; 12989 } else { 12990 /* Cannot overflow (as long as bounds are consistent) */ 12991 dst_reg->umin_value = umin_ptr - umax_val; 12992 dst_reg->umax_value = umax_ptr - umin_val; 12993 } 12994 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 12995 dst_reg->off = ptr_reg->off; 12996 dst_reg->raw = ptr_reg->raw; 12997 if (reg_is_pkt_pointer(ptr_reg)) { 12998 dst_reg->id = ++env->id_gen; 12999 /* something was added to pkt_ptr, set range to zero */ 13000 if (smin_val < 0) 13001 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13002 } 13003 break; 13004 case BPF_AND: 13005 case BPF_OR: 13006 case BPF_XOR: 13007 /* bitwise ops on pointers are troublesome, prohibit. */ 13008 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 13009 dst, bpf_alu_string[opcode >> 4]); 13010 return -EACCES; 13011 default: 13012 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 13013 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 13014 dst, bpf_alu_string[opcode >> 4]); 13015 return -EACCES; 13016 } 13017 13018 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 13019 return -EINVAL; 13020 reg_bounds_sync(dst_reg); 13021 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 13022 return -EACCES; 13023 if (sanitize_needed(opcode)) { 13024 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 13025 &info, true); 13026 if (ret < 0) 13027 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13028 } 13029 13030 return 0; 13031 } 13032 13033 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 13034 struct bpf_reg_state *src_reg) 13035 { 13036 s32 smin_val = src_reg->s32_min_value; 13037 s32 smax_val = src_reg->s32_max_value; 13038 u32 umin_val = src_reg->u32_min_value; 13039 u32 umax_val = src_reg->u32_max_value; 13040 13041 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 13042 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 13043 dst_reg->s32_min_value = S32_MIN; 13044 dst_reg->s32_max_value = S32_MAX; 13045 } else { 13046 dst_reg->s32_min_value += smin_val; 13047 dst_reg->s32_max_value += smax_val; 13048 } 13049 if (dst_reg->u32_min_value + umin_val < umin_val || 13050 dst_reg->u32_max_value + umax_val < umax_val) { 13051 dst_reg->u32_min_value = 0; 13052 dst_reg->u32_max_value = U32_MAX; 13053 } else { 13054 dst_reg->u32_min_value += umin_val; 13055 dst_reg->u32_max_value += umax_val; 13056 } 13057 } 13058 13059 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 13060 struct bpf_reg_state *src_reg) 13061 { 13062 s64 smin_val = src_reg->smin_value; 13063 s64 smax_val = src_reg->smax_value; 13064 u64 umin_val = src_reg->umin_value; 13065 u64 umax_val = src_reg->umax_value; 13066 13067 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 13068 signed_add_overflows(dst_reg->smax_value, smax_val)) { 13069 dst_reg->smin_value = S64_MIN; 13070 dst_reg->smax_value = S64_MAX; 13071 } else { 13072 dst_reg->smin_value += smin_val; 13073 dst_reg->smax_value += smax_val; 13074 } 13075 if (dst_reg->umin_value + umin_val < umin_val || 13076 dst_reg->umax_value + umax_val < umax_val) { 13077 dst_reg->umin_value = 0; 13078 dst_reg->umax_value = U64_MAX; 13079 } else { 13080 dst_reg->umin_value += umin_val; 13081 dst_reg->umax_value += umax_val; 13082 } 13083 } 13084 13085 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 13086 struct bpf_reg_state *src_reg) 13087 { 13088 s32 smin_val = src_reg->s32_min_value; 13089 s32 smax_val = src_reg->s32_max_value; 13090 u32 umin_val = src_reg->u32_min_value; 13091 u32 umax_val = src_reg->u32_max_value; 13092 13093 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 13094 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 13095 /* Overflow possible, we know nothing */ 13096 dst_reg->s32_min_value = S32_MIN; 13097 dst_reg->s32_max_value = S32_MAX; 13098 } else { 13099 dst_reg->s32_min_value -= smax_val; 13100 dst_reg->s32_max_value -= smin_val; 13101 } 13102 if (dst_reg->u32_min_value < umax_val) { 13103 /* Overflow possible, we know nothing */ 13104 dst_reg->u32_min_value = 0; 13105 dst_reg->u32_max_value = U32_MAX; 13106 } else { 13107 /* Cannot overflow (as long as bounds are consistent) */ 13108 dst_reg->u32_min_value -= umax_val; 13109 dst_reg->u32_max_value -= umin_val; 13110 } 13111 } 13112 13113 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 13114 struct bpf_reg_state *src_reg) 13115 { 13116 s64 smin_val = src_reg->smin_value; 13117 s64 smax_val = src_reg->smax_value; 13118 u64 umin_val = src_reg->umin_value; 13119 u64 umax_val = src_reg->umax_value; 13120 13121 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 13122 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 13123 /* Overflow possible, we know nothing */ 13124 dst_reg->smin_value = S64_MIN; 13125 dst_reg->smax_value = S64_MAX; 13126 } else { 13127 dst_reg->smin_value -= smax_val; 13128 dst_reg->smax_value -= smin_val; 13129 } 13130 if (dst_reg->umin_value < umax_val) { 13131 /* Overflow possible, we know nothing */ 13132 dst_reg->umin_value = 0; 13133 dst_reg->umax_value = U64_MAX; 13134 } else { 13135 /* Cannot overflow (as long as bounds are consistent) */ 13136 dst_reg->umin_value -= umax_val; 13137 dst_reg->umax_value -= umin_val; 13138 } 13139 } 13140 13141 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 13142 struct bpf_reg_state *src_reg) 13143 { 13144 s32 smin_val = src_reg->s32_min_value; 13145 u32 umin_val = src_reg->u32_min_value; 13146 u32 umax_val = src_reg->u32_max_value; 13147 13148 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 13149 /* Ain't nobody got time to multiply that sign */ 13150 __mark_reg32_unbounded(dst_reg); 13151 return; 13152 } 13153 /* Both values are positive, so we can work with unsigned and 13154 * copy the result to signed (unless it exceeds S32_MAX). 13155 */ 13156 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 13157 /* Potential overflow, we know nothing */ 13158 __mark_reg32_unbounded(dst_reg); 13159 return; 13160 } 13161 dst_reg->u32_min_value *= umin_val; 13162 dst_reg->u32_max_value *= umax_val; 13163 if (dst_reg->u32_max_value > S32_MAX) { 13164 /* Overflow possible, we know nothing */ 13165 dst_reg->s32_min_value = S32_MIN; 13166 dst_reg->s32_max_value = S32_MAX; 13167 } else { 13168 dst_reg->s32_min_value = dst_reg->u32_min_value; 13169 dst_reg->s32_max_value = dst_reg->u32_max_value; 13170 } 13171 } 13172 13173 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 13174 struct bpf_reg_state *src_reg) 13175 { 13176 s64 smin_val = src_reg->smin_value; 13177 u64 umin_val = src_reg->umin_value; 13178 u64 umax_val = src_reg->umax_value; 13179 13180 if (smin_val < 0 || dst_reg->smin_value < 0) { 13181 /* Ain't nobody got time to multiply that sign */ 13182 __mark_reg64_unbounded(dst_reg); 13183 return; 13184 } 13185 /* Both values are positive, so we can work with unsigned and 13186 * copy the result to signed (unless it exceeds S64_MAX). 13187 */ 13188 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 13189 /* Potential overflow, we know nothing */ 13190 __mark_reg64_unbounded(dst_reg); 13191 return; 13192 } 13193 dst_reg->umin_value *= umin_val; 13194 dst_reg->umax_value *= umax_val; 13195 if (dst_reg->umax_value > S64_MAX) { 13196 /* Overflow possible, we know nothing */ 13197 dst_reg->smin_value = S64_MIN; 13198 dst_reg->smax_value = S64_MAX; 13199 } else { 13200 dst_reg->smin_value = dst_reg->umin_value; 13201 dst_reg->smax_value = dst_reg->umax_value; 13202 } 13203 } 13204 13205 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 13206 struct bpf_reg_state *src_reg) 13207 { 13208 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13209 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13210 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13211 s32 smin_val = src_reg->s32_min_value; 13212 u32 umax_val = src_reg->u32_max_value; 13213 13214 if (src_known && dst_known) { 13215 __mark_reg32_known(dst_reg, var32_off.value); 13216 return; 13217 } 13218 13219 /* We get our minimum from the var_off, since that's inherently 13220 * bitwise. Our maximum is the minimum of the operands' maxima. 13221 */ 13222 dst_reg->u32_min_value = var32_off.value; 13223 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 13224 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 13225 /* Lose signed bounds when ANDing negative numbers, 13226 * ain't nobody got time for that. 13227 */ 13228 dst_reg->s32_min_value = S32_MIN; 13229 dst_reg->s32_max_value = S32_MAX; 13230 } else { 13231 /* ANDing two positives gives a positive, so safe to 13232 * cast result into s64. 13233 */ 13234 dst_reg->s32_min_value = dst_reg->u32_min_value; 13235 dst_reg->s32_max_value = dst_reg->u32_max_value; 13236 } 13237 } 13238 13239 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 13240 struct bpf_reg_state *src_reg) 13241 { 13242 bool src_known = tnum_is_const(src_reg->var_off); 13243 bool dst_known = tnum_is_const(dst_reg->var_off); 13244 s64 smin_val = src_reg->smin_value; 13245 u64 umax_val = src_reg->umax_value; 13246 13247 if (src_known && dst_known) { 13248 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13249 return; 13250 } 13251 13252 /* We get our minimum from the var_off, since that's inherently 13253 * bitwise. Our maximum is the minimum of the operands' maxima. 13254 */ 13255 dst_reg->umin_value = dst_reg->var_off.value; 13256 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 13257 if (dst_reg->smin_value < 0 || smin_val < 0) { 13258 /* Lose signed bounds when ANDing negative numbers, 13259 * ain't nobody got time for that. 13260 */ 13261 dst_reg->smin_value = S64_MIN; 13262 dst_reg->smax_value = S64_MAX; 13263 } else { 13264 /* ANDing two positives gives a positive, so safe to 13265 * cast result into s64. 13266 */ 13267 dst_reg->smin_value = dst_reg->umin_value; 13268 dst_reg->smax_value = dst_reg->umax_value; 13269 } 13270 /* We may learn something more from the var_off */ 13271 __update_reg_bounds(dst_reg); 13272 } 13273 13274 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 13275 struct bpf_reg_state *src_reg) 13276 { 13277 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13278 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13279 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13280 s32 smin_val = src_reg->s32_min_value; 13281 u32 umin_val = src_reg->u32_min_value; 13282 13283 if (src_known && dst_known) { 13284 __mark_reg32_known(dst_reg, var32_off.value); 13285 return; 13286 } 13287 13288 /* We get our maximum from the var_off, and our minimum is the 13289 * maximum of the operands' minima 13290 */ 13291 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 13292 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13293 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 13294 /* Lose signed bounds when ORing negative numbers, 13295 * ain't nobody got time for that. 13296 */ 13297 dst_reg->s32_min_value = S32_MIN; 13298 dst_reg->s32_max_value = S32_MAX; 13299 } else { 13300 /* ORing two positives gives a positive, so safe to 13301 * cast result into s64. 13302 */ 13303 dst_reg->s32_min_value = dst_reg->u32_min_value; 13304 dst_reg->s32_max_value = dst_reg->u32_max_value; 13305 } 13306 } 13307 13308 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 13309 struct bpf_reg_state *src_reg) 13310 { 13311 bool src_known = tnum_is_const(src_reg->var_off); 13312 bool dst_known = tnum_is_const(dst_reg->var_off); 13313 s64 smin_val = src_reg->smin_value; 13314 u64 umin_val = src_reg->umin_value; 13315 13316 if (src_known && dst_known) { 13317 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13318 return; 13319 } 13320 13321 /* We get our maximum from the var_off, and our minimum is the 13322 * maximum of the operands' minima 13323 */ 13324 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 13325 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13326 if (dst_reg->smin_value < 0 || smin_val < 0) { 13327 /* Lose signed bounds when ORing negative numbers, 13328 * ain't nobody got time for that. 13329 */ 13330 dst_reg->smin_value = S64_MIN; 13331 dst_reg->smax_value = S64_MAX; 13332 } else { 13333 /* ORing two positives gives a positive, so safe to 13334 * cast result into s64. 13335 */ 13336 dst_reg->smin_value = dst_reg->umin_value; 13337 dst_reg->smax_value = dst_reg->umax_value; 13338 } 13339 /* We may learn something more from the var_off */ 13340 __update_reg_bounds(dst_reg); 13341 } 13342 13343 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 13344 struct bpf_reg_state *src_reg) 13345 { 13346 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13347 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13348 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13349 s32 smin_val = src_reg->s32_min_value; 13350 13351 if (src_known && dst_known) { 13352 __mark_reg32_known(dst_reg, var32_off.value); 13353 return; 13354 } 13355 13356 /* We get both minimum and maximum from the var32_off. */ 13357 dst_reg->u32_min_value = var32_off.value; 13358 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13359 13360 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 13361 /* XORing two positive sign numbers gives a positive, 13362 * so safe to cast u32 result into s32. 13363 */ 13364 dst_reg->s32_min_value = dst_reg->u32_min_value; 13365 dst_reg->s32_max_value = dst_reg->u32_max_value; 13366 } else { 13367 dst_reg->s32_min_value = S32_MIN; 13368 dst_reg->s32_max_value = S32_MAX; 13369 } 13370 } 13371 13372 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 13373 struct bpf_reg_state *src_reg) 13374 { 13375 bool src_known = tnum_is_const(src_reg->var_off); 13376 bool dst_known = tnum_is_const(dst_reg->var_off); 13377 s64 smin_val = src_reg->smin_value; 13378 13379 if (src_known && dst_known) { 13380 /* dst_reg->var_off.value has been updated earlier */ 13381 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13382 return; 13383 } 13384 13385 /* We get both minimum and maximum from the var_off. */ 13386 dst_reg->umin_value = dst_reg->var_off.value; 13387 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13388 13389 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 13390 /* XORing two positive sign numbers gives a positive, 13391 * so safe to cast u64 result into s64. 13392 */ 13393 dst_reg->smin_value = dst_reg->umin_value; 13394 dst_reg->smax_value = dst_reg->umax_value; 13395 } else { 13396 dst_reg->smin_value = S64_MIN; 13397 dst_reg->smax_value = S64_MAX; 13398 } 13399 13400 __update_reg_bounds(dst_reg); 13401 } 13402 13403 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13404 u64 umin_val, u64 umax_val) 13405 { 13406 /* We lose all sign bit information (except what we can pick 13407 * up from var_off) 13408 */ 13409 dst_reg->s32_min_value = S32_MIN; 13410 dst_reg->s32_max_value = S32_MAX; 13411 /* If we might shift our top bit out, then we know nothing */ 13412 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 13413 dst_reg->u32_min_value = 0; 13414 dst_reg->u32_max_value = U32_MAX; 13415 } else { 13416 dst_reg->u32_min_value <<= umin_val; 13417 dst_reg->u32_max_value <<= umax_val; 13418 } 13419 } 13420 13421 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13422 struct bpf_reg_state *src_reg) 13423 { 13424 u32 umax_val = src_reg->u32_max_value; 13425 u32 umin_val = src_reg->u32_min_value; 13426 /* u32 alu operation will zext upper bits */ 13427 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13428 13429 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13430 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 13431 /* Not required but being careful mark reg64 bounds as unknown so 13432 * that we are forced to pick them up from tnum and zext later and 13433 * if some path skips this step we are still safe. 13434 */ 13435 __mark_reg64_unbounded(dst_reg); 13436 __update_reg32_bounds(dst_reg); 13437 } 13438 13439 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 13440 u64 umin_val, u64 umax_val) 13441 { 13442 /* Special case <<32 because it is a common compiler pattern to sign 13443 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 13444 * positive we know this shift will also be positive so we can track 13445 * bounds correctly. Otherwise we lose all sign bit information except 13446 * what we can pick up from var_off. Perhaps we can generalize this 13447 * later to shifts of any length. 13448 */ 13449 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 13450 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 13451 else 13452 dst_reg->smax_value = S64_MAX; 13453 13454 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 13455 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 13456 else 13457 dst_reg->smin_value = S64_MIN; 13458 13459 /* If we might shift our top bit out, then we know nothing */ 13460 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 13461 dst_reg->umin_value = 0; 13462 dst_reg->umax_value = U64_MAX; 13463 } else { 13464 dst_reg->umin_value <<= umin_val; 13465 dst_reg->umax_value <<= umax_val; 13466 } 13467 } 13468 13469 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 13470 struct bpf_reg_state *src_reg) 13471 { 13472 u64 umax_val = src_reg->umax_value; 13473 u64 umin_val = src_reg->umin_value; 13474 13475 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 13476 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 13477 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13478 13479 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 13480 /* We may learn something more from the var_off */ 13481 __update_reg_bounds(dst_reg); 13482 } 13483 13484 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 13485 struct bpf_reg_state *src_reg) 13486 { 13487 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13488 u32 umax_val = src_reg->u32_max_value; 13489 u32 umin_val = src_reg->u32_min_value; 13490 13491 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13492 * be negative, then either: 13493 * 1) src_reg might be zero, so the sign bit of the result is 13494 * unknown, so we lose our signed bounds 13495 * 2) it's known negative, thus the unsigned bounds capture the 13496 * signed bounds 13497 * 3) the signed bounds cross zero, so they tell us nothing 13498 * about the result 13499 * If the value in dst_reg is known nonnegative, then again the 13500 * unsigned bounds capture the signed bounds. 13501 * Thus, in all cases it suffices to blow away our signed bounds 13502 * and rely on inferring new ones from the unsigned bounds and 13503 * var_off of the result. 13504 */ 13505 dst_reg->s32_min_value = S32_MIN; 13506 dst_reg->s32_max_value = S32_MAX; 13507 13508 dst_reg->var_off = tnum_rshift(subreg, umin_val); 13509 dst_reg->u32_min_value >>= umax_val; 13510 dst_reg->u32_max_value >>= umin_val; 13511 13512 __mark_reg64_unbounded(dst_reg); 13513 __update_reg32_bounds(dst_reg); 13514 } 13515 13516 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 13517 struct bpf_reg_state *src_reg) 13518 { 13519 u64 umax_val = src_reg->umax_value; 13520 u64 umin_val = src_reg->umin_value; 13521 13522 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13523 * be negative, then either: 13524 * 1) src_reg might be zero, so the sign bit of the result is 13525 * unknown, so we lose our signed bounds 13526 * 2) it's known negative, thus the unsigned bounds capture the 13527 * signed bounds 13528 * 3) the signed bounds cross zero, so they tell us nothing 13529 * about the result 13530 * If the value in dst_reg is known nonnegative, then again the 13531 * unsigned bounds capture the signed bounds. 13532 * Thus, in all cases it suffices to blow away our signed bounds 13533 * and rely on inferring new ones from the unsigned bounds and 13534 * var_off of the result. 13535 */ 13536 dst_reg->smin_value = S64_MIN; 13537 dst_reg->smax_value = S64_MAX; 13538 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 13539 dst_reg->umin_value >>= umax_val; 13540 dst_reg->umax_value >>= umin_val; 13541 13542 /* Its not easy to operate on alu32 bounds here because it depends 13543 * on bits being shifted in. Take easy way out and mark unbounded 13544 * so we can recalculate later from tnum. 13545 */ 13546 __mark_reg32_unbounded(dst_reg); 13547 __update_reg_bounds(dst_reg); 13548 } 13549 13550 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 13551 struct bpf_reg_state *src_reg) 13552 { 13553 u64 umin_val = src_reg->u32_min_value; 13554 13555 /* Upon reaching here, src_known is true and 13556 * umax_val is equal to umin_val. 13557 */ 13558 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 13559 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 13560 13561 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 13562 13563 /* blow away the dst_reg umin_value/umax_value and rely on 13564 * dst_reg var_off to refine the result. 13565 */ 13566 dst_reg->u32_min_value = 0; 13567 dst_reg->u32_max_value = U32_MAX; 13568 13569 __mark_reg64_unbounded(dst_reg); 13570 __update_reg32_bounds(dst_reg); 13571 } 13572 13573 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 13574 struct bpf_reg_state *src_reg) 13575 { 13576 u64 umin_val = src_reg->umin_value; 13577 13578 /* Upon reaching here, src_known is true and umax_val is equal 13579 * to umin_val. 13580 */ 13581 dst_reg->smin_value >>= umin_val; 13582 dst_reg->smax_value >>= umin_val; 13583 13584 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 13585 13586 /* blow away the dst_reg umin_value/umax_value and rely on 13587 * dst_reg var_off to refine the result. 13588 */ 13589 dst_reg->umin_value = 0; 13590 dst_reg->umax_value = U64_MAX; 13591 13592 /* Its not easy to operate on alu32 bounds here because it depends 13593 * on bits being shifted in from upper 32-bits. Take easy way out 13594 * and mark unbounded so we can recalculate later from tnum. 13595 */ 13596 __mark_reg32_unbounded(dst_reg); 13597 __update_reg_bounds(dst_reg); 13598 } 13599 13600 /* WARNING: This function does calculations on 64-bit values, but the actual 13601 * execution may occur on 32-bit values. Therefore, things like bitshifts 13602 * need extra checks in the 32-bit case. 13603 */ 13604 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 13605 struct bpf_insn *insn, 13606 struct bpf_reg_state *dst_reg, 13607 struct bpf_reg_state src_reg) 13608 { 13609 struct bpf_reg_state *regs = cur_regs(env); 13610 u8 opcode = BPF_OP(insn->code); 13611 bool src_known; 13612 s64 smin_val, smax_val; 13613 u64 umin_val, umax_val; 13614 s32 s32_min_val, s32_max_val; 13615 u32 u32_min_val, u32_max_val; 13616 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 13617 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 13618 int ret; 13619 13620 smin_val = src_reg.smin_value; 13621 smax_val = src_reg.smax_value; 13622 umin_val = src_reg.umin_value; 13623 umax_val = src_reg.umax_value; 13624 13625 s32_min_val = src_reg.s32_min_value; 13626 s32_max_val = src_reg.s32_max_value; 13627 u32_min_val = src_reg.u32_min_value; 13628 u32_max_val = src_reg.u32_max_value; 13629 13630 if (alu32) { 13631 src_known = tnum_subreg_is_const(src_reg.var_off); 13632 if ((src_known && 13633 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 13634 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 13635 /* Taint dst register if offset had invalid bounds 13636 * derived from e.g. dead branches. 13637 */ 13638 __mark_reg_unknown(env, dst_reg); 13639 return 0; 13640 } 13641 } else { 13642 src_known = tnum_is_const(src_reg.var_off); 13643 if ((src_known && 13644 (smin_val != smax_val || umin_val != umax_val)) || 13645 smin_val > smax_val || umin_val > umax_val) { 13646 /* Taint dst register if offset had invalid bounds 13647 * derived from e.g. dead branches. 13648 */ 13649 __mark_reg_unknown(env, dst_reg); 13650 return 0; 13651 } 13652 } 13653 13654 if (!src_known && 13655 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 13656 __mark_reg_unknown(env, dst_reg); 13657 return 0; 13658 } 13659 13660 if (sanitize_needed(opcode)) { 13661 ret = sanitize_val_alu(env, insn); 13662 if (ret < 0) 13663 return sanitize_err(env, insn, ret, NULL, NULL); 13664 } 13665 13666 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 13667 * There are two classes of instructions: The first class we track both 13668 * alu32 and alu64 sign/unsigned bounds independently this provides the 13669 * greatest amount of precision when alu operations are mixed with jmp32 13670 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 13671 * and BPF_OR. This is possible because these ops have fairly easy to 13672 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 13673 * See alu32 verifier tests for examples. The second class of 13674 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 13675 * with regards to tracking sign/unsigned bounds because the bits may 13676 * cross subreg boundaries in the alu64 case. When this happens we mark 13677 * the reg unbounded in the subreg bound space and use the resulting 13678 * tnum to calculate an approximation of the sign/unsigned bounds. 13679 */ 13680 switch (opcode) { 13681 case BPF_ADD: 13682 scalar32_min_max_add(dst_reg, &src_reg); 13683 scalar_min_max_add(dst_reg, &src_reg); 13684 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 13685 break; 13686 case BPF_SUB: 13687 scalar32_min_max_sub(dst_reg, &src_reg); 13688 scalar_min_max_sub(dst_reg, &src_reg); 13689 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 13690 break; 13691 case BPF_MUL: 13692 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 13693 scalar32_min_max_mul(dst_reg, &src_reg); 13694 scalar_min_max_mul(dst_reg, &src_reg); 13695 break; 13696 case BPF_AND: 13697 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 13698 scalar32_min_max_and(dst_reg, &src_reg); 13699 scalar_min_max_and(dst_reg, &src_reg); 13700 break; 13701 case BPF_OR: 13702 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 13703 scalar32_min_max_or(dst_reg, &src_reg); 13704 scalar_min_max_or(dst_reg, &src_reg); 13705 break; 13706 case BPF_XOR: 13707 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 13708 scalar32_min_max_xor(dst_reg, &src_reg); 13709 scalar_min_max_xor(dst_reg, &src_reg); 13710 break; 13711 case BPF_LSH: 13712 if (umax_val >= insn_bitness) { 13713 /* Shifts greater than 31 or 63 are undefined. 13714 * This includes shifts by a negative number. 13715 */ 13716 mark_reg_unknown(env, regs, insn->dst_reg); 13717 break; 13718 } 13719 if (alu32) 13720 scalar32_min_max_lsh(dst_reg, &src_reg); 13721 else 13722 scalar_min_max_lsh(dst_reg, &src_reg); 13723 break; 13724 case BPF_RSH: 13725 if (umax_val >= insn_bitness) { 13726 /* Shifts greater than 31 or 63 are undefined. 13727 * This includes shifts by a negative number. 13728 */ 13729 mark_reg_unknown(env, regs, insn->dst_reg); 13730 break; 13731 } 13732 if (alu32) 13733 scalar32_min_max_rsh(dst_reg, &src_reg); 13734 else 13735 scalar_min_max_rsh(dst_reg, &src_reg); 13736 break; 13737 case BPF_ARSH: 13738 if (umax_val >= insn_bitness) { 13739 /* Shifts greater than 31 or 63 are undefined. 13740 * This includes shifts by a negative number. 13741 */ 13742 mark_reg_unknown(env, regs, insn->dst_reg); 13743 break; 13744 } 13745 if (alu32) 13746 scalar32_min_max_arsh(dst_reg, &src_reg); 13747 else 13748 scalar_min_max_arsh(dst_reg, &src_reg); 13749 break; 13750 default: 13751 mark_reg_unknown(env, regs, insn->dst_reg); 13752 break; 13753 } 13754 13755 /* ALU32 ops are zero extended into 64bit register */ 13756 if (alu32) 13757 zext_32_to_64(dst_reg); 13758 reg_bounds_sync(dst_reg); 13759 return 0; 13760 } 13761 13762 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 13763 * and var_off. 13764 */ 13765 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 13766 struct bpf_insn *insn) 13767 { 13768 struct bpf_verifier_state *vstate = env->cur_state; 13769 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13770 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 13771 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 13772 u8 opcode = BPF_OP(insn->code); 13773 int err; 13774 13775 dst_reg = ®s[insn->dst_reg]; 13776 src_reg = NULL; 13777 if (dst_reg->type != SCALAR_VALUE) 13778 ptr_reg = dst_reg; 13779 else 13780 /* Make sure ID is cleared otherwise dst_reg min/max could be 13781 * incorrectly propagated into other registers by find_equal_scalars() 13782 */ 13783 dst_reg->id = 0; 13784 if (BPF_SRC(insn->code) == BPF_X) { 13785 src_reg = ®s[insn->src_reg]; 13786 if (src_reg->type != SCALAR_VALUE) { 13787 if (dst_reg->type != SCALAR_VALUE) { 13788 /* Combining two pointers by any ALU op yields 13789 * an arbitrary scalar. Disallow all math except 13790 * pointer subtraction 13791 */ 13792 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13793 mark_reg_unknown(env, regs, insn->dst_reg); 13794 return 0; 13795 } 13796 verbose(env, "R%d pointer %s pointer prohibited\n", 13797 insn->dst_reg, 13798 bpf_alu_string[opcode >> 4]); 13799 return -EACCES; 13800 } else { 13801 /* scalar += pointer 13802 * This is legal, but we have to reverse our 13803 * src/dest handling in computing the range 13804 */ 13805 err = mark_chain_precision(env, insn->dst_reg); 13806 if (err) 13807 return err; 13808 return adjust_ptr_min_max_vals(env, insn, 13809 src_reg, dst_reg); 13810 } 13811 } else if (ptr_reg) { 13812 /* pointer += scalar */ 13813 err = mark_chain_precision(env, insn->src_reg); 13814 if (err) 13815 return err; 13816 return adjust_ptr_min_max_vals(env, insn, 13817 dst_reg, src_reg); 13818 } else if (dst_reg->precise) { 13819 /* if dst_reg is precise, src_reg should be precise as well */ 13820 err = mark_chain_precision(env, insn->src_reg); 13821 if (err) 13822 return err; 13823 } 13824 } else { 13825 /* Pretend the src is a reg with a known value, since we only 13826 * need to be able to read from this state. 13827 */ 13828 off_reg.type = SCALAR_VALUE; 13829 __mark_reg_known(&off_reg, insn->imm); 13830 src_reg = &off_reg; 13831 if (ptr_reg) /* pointer += K */ 13832 return adjust_ptr_min_max_vals(env, insn, 13833 ptr_reg, src_reg); 13834 } 13835 13836 /* Got here implies adding two SCALAR_VALUEs */ 13837 if (WARN_ON_ONCE(ptr_reg)) { 13838 print_verifier_state(env, state, true); 13839 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 13840 return -EINVAL; 13841 } 13842 if (WARN_ON(!src_reg)) { 13843 print_verifier_state(env, state, true); 13844 verbose(env, "verifier internal error: no src_reg\n"); 13845 return -EINVAL; 13846 } 13847 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 13848 } 13849 13850 /* check validity of 32-bit and 64-bit arithmetic operations */ 13851 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 13852 { 13853 struct bpf_reg_state *regs = cur_regs(env); 13854 u8 opcode = BPF_OP(insn->code); 13855 int err; 13856 13857 if (opcode == BPF_END || opcode == BPF_NEG) { 13858 if (opcode == BPF_NEG) { 13859 if (BPF_SRC(insn->code) != BPF_K || 13860 insn->src_reg != BPF_REG_0 || 13861 insn->off != 0 || insn->imm != 0) { 13862 verbose(env, "BPF_NEG uses reserved fields\n"); 13863 return -EINVAL; 13864 } 13865 } else { 13866 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 13867 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 13868 (BPF_CLASS(insn->code) == BPF_ALU64 && 13869 BPF_SRC(insn->code) != BPF_TO_LE)) { 13870 verbose(env, "BPF_END uses reserved fields\n"); 13871 return -EINVAL; 13872 } 13873 } 13874 13875 /* check src operand */ 13876 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13877 if (err) 13878 return err; 13879 13880 if (is_pointer_value(env, insn->dst_reg)) { 13881 verbose(env, "R%d pointer arithmetic prohibited\n", 13882 insn->dst_reg); 13883 return -EACCES; 13884 } 13885 13886 /* check dest operand */ 13887 err = check_reg_arg(env, insn->dst_reg, DST_OP); 13888 if (err) 13889 return err; 13890 13891 } else if (opcode == BPF_MOV) { 13892 13893 if (BPF_SRC(insn->code) == BPF_X) { 13894 if (insn->imm != 0) { 13895 verbose(env, "BPF_MOV uses reserved fields\n"); 13896 return -EINVAL; 13897 } 13898 13899 if (BPF_CLASS(insn->code) == BPF_ALU) { 13900 if (insn->off != 0 && insn->off != 8 && insn->off != 16) { 13901 verbose(env, "BPF_MOV uses reserved fields\n"); 13902 return -EINVAL; 13903 } 13904 } else { 13905 if (insn->off != 0 && insn->off != 8 && insn->off != 16 && 13906 insn->off != 32) { 13907 verbose(env, "BPF_MOV uses reserved fields\n"); 13908 return -EINVAL; 13909 } 13910 } 13911 13912 /* check src operand */ 13913 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13914 if (err) 13915 return err; 13916 } else { 13917 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 13918 verbose(env, "BPF_MOV uses reserved fields\n"); 13919 return -EINVAL; 13920 } 13921 } 13922 13923 /* check dest operand, mark as required later */ 13924 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13925 if (err) 13926 return err; 13927 13928 if (BPF_SRC(insn->code) == BPF_X) { 13929 struct bpf_reg_state *src_reg = regs + insn->src_reg; 13930 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 13931 13932 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13933 if (insn->off == 0) { 13934 /* case: R1 = R2 13935 * copy register state to dest reg 13936 */ 13937 assign_scalar_id_before_mov(env, src_reg); 13938 copy_register_state(dst_reg, src_reg); 13939 dst_reg->live |= REG_LIVE_WRITTEN; 13940 dst_reg->subreg_def = DEF_NOT_SUBREG; 13941 } else { 13942 /* case: R1 = (s8, s16 s32)R2 */ 13943 if (is_pointer_value(env, insn->src_reg)) { 13944 verbose(env, 13945 "R%d sign-extension part of pointer\n", 13946 insn->src_reg); 13947 return -EACCES; 13948 } else if (src_reg->type == SCALAR_VALUE) { 13949 bool no_sext; 13950 13951 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13952 if (no_sext) 13953 assign_scalar_id_before_mov(env, src_reg); 13954 copy_register_state(dst_reg, src_reg); 13955 if (!no_sext) 13956 dst_reg->id = 0; 13957 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 13958 dst_reg->live |= REG_LIVE_WRITTEN; 13959 dst_reg->subreg_def = DEF_NOT_SUBREG; 13960 } else { 13961 mark_reg_unknown(env, regs, insn->dst_reg); 13962 } 13963 } 13964 } else { 13965 /* R1 = (u32) R2 */ 13966 if (is_pointer_value(env, insn->src_reg)) { 13967 verbose(env, 13968 "R%d partial copy of pointer\n", 13969 insn->src_reg); 13970 return -EACCES; 13971 } else if (src_reg->type == SCALAR_VALUE) { 13972 if (insn->off == 0) { 13973 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 13974 13975 if (is_src_reg_u32) 13976 assign_scalar_id_before_mov(env, src_reg); 13977 copy_register_state(dst_reg, src_reg); 13978 /* Make sure ID is cleared if src_reg is not in u32 13979 * range otherwise dst_reg min/max could be incorrectly 13980 * propagated into src_reg by find_equal_scalars() 13981 */ 13982 if (!is_src_reg_u32) 13983 dst_reg->id = 0; 13984 dst_reg->live |= REG_LIVE_WRITTEN; 13985 dst_reg->subreg_def = env->insn_idx + 1; 13986 } else { 13987 /* case: W1 = (s8, s16)W2 */ 13988 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13989 13990 if (no_sext) 13991 assign_scalar_id_before_mov(env, src_reg); 13992 copy_register_state(dst_reg, src_reg); 13993 if (!no_sext) 13994 dst_reg->id = 0; 13995 dst_reg->live |= REG_LIVE_WRITTEN; 13996 dst_reg->subreg_def = env->insn_idx + 1; 13997 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 13998 } 13999 } else { 14000 mark_reg_unknown(env, regs, 14001 insn->dst_reg); 14002 } 14003 zext_32_to_64(dst_reg); 14004 reg_bounds_sync(dst_reg); 14005 } 14006 } else { 14007 /* case: R = imm 14008 * remember the value we stored into this reg 14009 */ 14010 /* clear any state __mark_reg_known doesn't set */ 14011 mark_reg_unknown(env, regs, insn->dst_reg); 14012 regs[insn->dst_reg].type = SCALAR_VALUE; 14013 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14014 __mark_reg_known(regs + insn->dst_reg, 14015 insn->imm); 14016 } else { 14017 __mark_reg_known(regs + insn->dst_reg, 14018 (u32)insn->imm); 14019 } 14020 } 14021 14022 } else if (opcode > BPF_END) { 14023 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 14024 return -EINVAL; 14025 14026 } else { /* all other ALU ops: and, sub, xor, add, ... */ 14027 14028 if (BPF_SRC(insn->code) == BPF_X) { 14029 if (insn->imm != 0 || insn->off > 1 || 14030 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14031 verbose(env, "BPF_ALU uses reserved fields\n"); 14032 return -EINVAL; 14033 } 14034 /* check src1 operand */ 14035 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14036 if (err) 14037 return err; 14038 } else { 14039 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 14040 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14041 verbose(env, "BPF_ALU uses reserved fields\n"); 14042 return -EINVAL; 14043 } 14044 } 14045 14046 /* check src2 operand */ 14047 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14048 if (err) 14049 return err; 14050 14051 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 14052 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 14053 verbose(env, "div by zero\n"); 14054 return -EINVAL; 14055 } 14056 14057 if ((opcode == BPF_LSH || opcode == BPF_RSH || 14058 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 14059 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 14060 14061 if (insn->imm < 0 || insn->imm >= size) { 14062 verbose(env, "invalid shift %d\n", insn->imm); 14063 return -EINVAL; 14064 } 14065 } 14066 14067 /* check dest operand */ 14068 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14069 err = err ?: adjust_reg_min_max_vals(env, insn); 14070 if (err) 14071 return err; 14072 } 14073 14074 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 14075 } 14076 14077 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 14078 struct bpf_reg_state *dst_reg, 14079 enum bpf_reg_type type, 14080 bool range_right_open) 14081 { 14082 struct bpf_func_state *state; 14083 struct bpf_reg_state *reg; 14084 int new_range; 14085 14086 if (dst_reg->off < 0 || 14087 (dst_reg->off == 0 && range_right_open)) 14088 /* This doesn't give us any range */ 14089 return; 14090 14091 if (dst_reg->umax_value > MAX_PACKET_OFF || 14092 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 14093 /* Risk of overflow. For instance, ptr + (1<<63) may be less 14094 * than pkt_end, but that's because it's also less than pkt. 14095 */ 14096 return; 14097 14098 new_range = dst_reg->off; 14099 if (range_right_open) 14100 new_range++; 14101 14102 /* Examples for register markings: 14103 * 14104 * pkt_data in dst register: 14105 * 14106 * r2 = r3; 14107 * r2 += 8; 14108 * if (r2 > pkt_end) goto <handle exception> 14109 * <access okay> 14110 * 14111 * r2 = r3; 14112 * r2 += 8; 14113 * if (r2 < pkt_end) goto <access okay> 14114 * <handle exception> 14115 * 14116 * Where: 14117 * r2 == dst_reg, pkt_end == src_reg 14118 * r2=pkt(id=n,off=8,r=0) 14119 * r3=pkt(id=n,off=0,r=0) 14120 * 14121 * pkt_data in src register: 14122 * 14123 * r2 = r3; 14124 * r2 += 8; 14125 * if (pkt_end >= r2) goto <access okay> 14126 * <handle exception> 14127 * 14128 * r2 = r3; 14129 * r2 += 8; 14130 * if (pkt_end <= r2) goto <handle exception> 14131 * <access okay> 14132 * 14133 * Where: 14134 * pkt_end == dst_reg, r2 == src_reg 14135 * r2=pkt(id=n,off=8,r=0) 14136 * r3=pkt(id=n,off=0,r=0) 14137 * 14138 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 14139 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 14140 * and [r3, r3 + 8-1) respectively is safe to access depending on 14141 * the check. 14142 */ 14143 14144 /* If our ids match, then we must have the same max_value. And we 14145 * don't care about the other reg's fixed offset, since if it's too big 14146 * the range won't allow anything. 14147 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 14148 */ 14149 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14150 if (reg->type == type && reg->id == dst_reg->id) 14151 /* keep the maximum range already checked */ 14152 reg->range = max(reg->range, new_range); 14153 })); 14154 } 14155 14156 /* 14157 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 14158 */ 14159 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14160 u8 opcode, bool is_jmp32) 14161 { 14162 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 14163 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 14164 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value; 14165 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value; 14166 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value; 14167 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value; 14168 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value; 14169 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value; 14170 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value; 14171 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value; 14172 14173 switch (opcode) { 14174 case BPF_JEQ: 14175 /* constants, umin/umax and smin/smax checks would be 14176 * redundant in this case because they all should match 14177 */ 14178 if (tnum_is_const(t1) && tnum_is_const(t2)) 14179 return t1.value == t2.value; 14180 /* non-overlapping ranges */ 14181 if (umin1 > umax2 || umax1 < umin2) 14182 return 0; 14183 if (smin1 > smax2 || smax1 < smin2) 14184 return 0; 14185 if (!is_jmp32) { 14186 /* if 64-bit ranges are inconclusive, see if we can 14187 * utilize 32-bit subrange knowledge to eliminate 14188 * branches that can't be taken a priori 14189 */ 14190 if (reg1->u32_min_value > reg2->u32_max_value || 14191 reg1->u32_max_value < reg2->u32_min_value) 14192 return 0; 14193 if (reg1->s32_min_value > reg2->s32_max_value || 14194 reg1->s32_max_value < reg2->s32_min_value) 14195 return 0; 14196 } 14197 break; 14198 case BPF_JNE: 14199 /* constants, umin/umax and smin/smax checks would be 14200 * redundant in this case because they all should match 14201 */ 14202 if (tnum_is_const(t1) && tnum_is_const(t2)) 14203 return t1.value != t2.value; 14204 /* non-overlapping ranges */ 14205 if (umin1 > umax2 || umax1 < umin2) 14206 return 1; 14207 if (smin1 > smax2 || smax1 < smin2) 14208 return 1; 14209 if (!is_jmp32) { 14210 /* if 64-bit ranges are inconclusive, see if we can 14211 * utilize 32-bit subrange knowledge to eliminate 14212 * branches that can't be taken a priori 14213 */ 14214 if (reg1->u32_min_value > reg2->u32_max_value || 14215 reg1->u32_max_value < reg2->u32_min_value) 14216 return 1; 14217 if (reg1->s32_min_value > reg2->s32_max_value || 14218 reg1->s32_max_value < reg2->s32_min_value) 14219 return 1; 14220 } 14221 break; 14222 case BPF_JSET: 14223 if (!is_reg_const(reg2, is_jmp32)) { 14224 swap(reg1, reg2); 14225 swap(t1, t2); 14226 } 14227 if (!is_reg_const(reg2, is_jmp32)) 14228 return -1; 14229 if ((~t1.mask & t1.value) & t2.value) 14230 return 1; 14231 if (!((t1.mask | t1.value) & t2.value)) 14232 return 0; 14233 break; 14234 case BPF_JGT: 14235 if (umin1 > umax2) 14236 return 1; 14237 else if (umax1 <= umin2) 14238 return 0; 14239 break; 14240 case BPF_JSGT: 14241 if (smin1 > smax2) 14242 return 1; 14243 else if (smax1 <= smin2) 14244 return 0; 14245 break; 14246 case BPF_JLT: 14247 if (umax1 < umin2) 14248 return 1; 14249 else if (umin1 >= umax2) 14250 return 0; 14251 break; 14252 case BPF_JSLT: 14253 if (smax1 < smin2) 14254 return 1; 14255 else if (smin1 >= smax2) 14256 return 0; 14257 break; 14258 case BPF_JGE: 14259 if (umin1 >= umax2) 14260 return 1; 14261 else if (umax1 < umin2) 14262 return 0; 14263 break; 14264 case BPF_JSGE: 14265 if (smin1 >= smax2) 14266 return 1; 14267 else if (smax1 < smin2) 14268 return 0; 14269 break; 14270 case BPF_JLE: 14271 if (umax1 <= umin2) 14272 return 1; 14273 else if (umin1 > umax2) 14274 return 0; 14275 break; 14276 case BPF_JSLE: 14277 if (smax1 <= smin2) 14278 return 1; 14279 else if (smin1 > smax2) 14280 return 0; 14281 break; 14282 } 14283 14284 return -1; 14285 } 14286 14287 static int flip_opcode(u32 opcode) 14288 { 14289 /* How can we transform "a <op> b" into "b <op> a"? */ 14290 static const u8 opcode_flip[16] = { 14291 /* these stay the same */ 14292 [BPF_JEQ >> 4] = BPF_JEQ, 14293 [BPF_JNE >> 4] = BPF_JNE, 14294 [BPF_JSET >> 4] = BPF_JSET, 14295 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 14296 [BPF_JGE >> 4] = BPF_JLE, 14297 [BPF_JGT >> 4] = BPF_JLT, 14298 [BPF_JLE >> 4] = BPF_JGE, 14299 [BPF_JLT >> 4] = BPF_JGT, 14300 [BPF_JSGE >> 4] = BPF_JSLE, 14301 [BPF_JSGT >> 4] = BPF_JSLT, 14302 [BPF_JSLE >> 4] = BPF_JSGE, 14303 [BPF_JSLT >> 4] = BPF_JSGT 14304 }; 14305 return opcode_flip[opcode >> 4]; 14306 } 14307 14308 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 14309 struct bpf_reg_state *src_reg, 14310 u8 opcode) 14311 { 14312 struct bpf_reg_state *pkt; 14313 14314 if (src_reg->type == PTR_TO_PACKET_END) { 14315 pkt = dst_reg; 14316 } else if (dst_reg->type == PTR_TO_PACKET_END) { 14317 pkt = src_reg; 14318 opcode = flip_opcode(opcode); 14319 } else { 14320 return -1; 14321 } 14322 14323 if (pkt->range >= 0) 14324 return -1; 14325 14326 switch (opcode) { 14327 case BPF_JLE: 14328 /* pkt <= pkt_end */ 14329 fallthrough; 14330 case BPF_JGT: 14331 /* pkt > pkt_end */ 14332 if (pkt->range == BEYOND_PKT_END) 14333 /* pkt has at last one extra byte beyond pkt_end */ 14334 return opcode == BPF_JGT; 14335 break; 14336 case BPF_JLT: 14337 /* pkt < pkt_end */ 14338 fallthrough; 14339 case BPF_JGE: 14340 /* pkt >= pkt_end */ 14341 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 14342 return opcode == BPF_JGE; 14343 break; 14344 } 14345 return -1; 14346 } 14347 14348 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 14349 * and return: 14350 * 1 - branch will be taken and "goto target" will be executed 14351 * 0 - branch will not be taken and fall-through to next insn 14352 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 14353 * range [0,10] 14354 */ 14355 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14356 u8 opcode, bool is_jmp32) 14357 { 14358 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 14359 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 14360 14361 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 14362 u64 val; 14363 14364 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 14365 if (!is_reg_const(reg2, is_jmp32)) { 14366 opcode = flip_opcode(opcode); 14367 swap(reg1, reg2); 14368 } 14369 /* and ensure that reg2 is a constant */ 14370 if (!is_reg_const(reg2, is_jmp32)) 14371 return -1; 14372 14373 if (!reg_not_null(reg1)) 14374 return -1; 14375 14376 /* If pointer is valid tests against zero will fail so we can 14377 * use this to direct branch taken. 14378 */ 14379 val = reg_const_value(reg2, is_jmp32); 14380 if (val != 0) 14381 return -1; 14382 14383 switch (opcode) { 14384 case BPF_JEQ: 14385 return 0; 14386 case BPF_JNE: 14387 return 1; 14388 default: 14389 return -1; 14390 } 14391 } 14392 14393 /* now deal with two scalars, but not necessarily constants */ 14394 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32); 14395 } 14396 14397 /* Opcode that corresponds to a *false* branch condition. 14398 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 14399 */ 14400 static u8 rev_opcode(u8 opcode) 14401 { 14402 switch (opcode) { 14403 case BPF_JEQ: return BPF_JNE; 14404 case BPF_JNE: return BPF_JEQ; 14405 /* JSET doesn't have it's reverse opcode in BPF, so add 14406 * BPF_X flag to denote the reverse of that operation 14407 */ 14408 case BPF_JSET: return BPF_JSET | BPF_X; 14409 case BPF_JSET | BPF_X: return BPF_JSET; 14410 case BPF_JGE: return BPF_JLT; 14411 case BPF_JGT: return BPF_JLE; 14412 case BPF_JLE: return BPF_JGT; 14413 case BPF_JLT: return BPF_JGE; 14414 case BPF_JSGE: return BPF_JSLT; 14415 case BPF_JSGT: return BPF_JSLE; 14416 case BPF_JSLE: return BPF_JSGT; 14417 case BPF_JSLT: return BPF_JSGE; 14418 default: return 0; 14419 } 14420 } 14421 14422 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 14423 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14424 u8 opcode, bool is_jmp32) 14425 { 14426 struct tnum t; 14427 u64 val; 14428 14429 again: 14430 switch (opcode) { 14431 case BPF_JEQ: 14432 if (is_jmp32) { 14433 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14434 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14435 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14436 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14437 reg2->u32_min_value = reg1->u32_min_value; 14438 reg2->u32_max_value = reg1->u32_max_value; 14439 reg2->s32_min_value = reg1->s32_min_value; 14440 reg2->s32_max_value = reg1->s32_max_value; 14441 14442 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 14443 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14444 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 14445 } else { 14446 reg1->umin_value = max(reg1->umin_value, reg2->umin_value); 14447 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14448 reg1->smin_value = max(reg1->smin_value, reg2->smin_value); 14449 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14450 reg2->umin_value = reg1->umin_value; 14451 reg2->umax_value = reg1->umax_value; 14452 reg2->smin_value = reg1->smin_value; 14453 reg2->smax_value = reg1->smax_value; 14454 14455 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 14456 reg2->var_off = reg1->var_off; 14457 } 14458 break; 14459 case BPF_JNE: 14460 if (!is_reg_const(reg2, is_jmp32)) 14461 swap(reg1, reg2); 14462 if (!is_reg_const(reg2, is_jmp32)) 14463 break; 14464 14465 /* try to recompute the bound of reg1 if reg2 is a const and 14466 * is exactly the edge of reg1. 14467 */ 14468 val = reg_const_value(reg2, is_jmp32); 14469 if (is_jmp32) { 14470 /* u32_min_value is not equal to 0xffffffff at this point, 14471 * because otherwise u32_max_value is 0xffffffff as well, 14472 * in such a case both reg1 and reg2 would be constants, 14473 * jump would be predicted and reg_set_min_max() won't 14474 * be called. 14475 * 14476 * Same reasoning works for all {u,s}{min,max}{32,64} cases 14477 * below. 14478 */ 14479 if (reg1->u32_min_value == (u32)val) 14480 reg1->u32_min_value++; 14481 if (reg1->u32_max_value == (u32)val) 14482 reg1->u32_max_value--; 14483 if (reg1->s32_min_value == (s32)val) 14484 reg1->s32_min_value++; 14485 if (reg1->s32_max_value == (s32)val) 14486 reg1->s32_max_value--; 14487 } else { 14488 if (reg1->umin_value == (u64)val) 14489 reg1->umin_value++; 14490 if (reg1->umax_value == (u64)val) 14491 reg1->umax_value--; 14492 if (reg1->smin_value == (s64)val) 14493 reg1->smin_value++; 14494 if (reg1->smax_value == (s64)val) 14495 reg1->smax_value--; 14496 } 14497 break; 14498 case BPF_JSET: 14499 if (!is_reg_const(reg2, is_jmp32)) 14500 swap(reg1, reg2); 14501 if (!is_reg_const(reg2, is_jmp32)) 14502 break; 14503 val = reg_const_value(reg2, is_jmp32); 14504 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 14505 * requires single bit to learn something useful. E.g., if we 14506 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 14507 * are actually set? We can learn something definite only if 14508 * it's a single-bit value to begin with. 14509 * 14510 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 14511 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 14512 * bit 1 is set, which we can readily use in adjustments. 14513 */ 14514 if (!is_power_of_2(val)) 14515 break; 14516 if (is_jmp32) { 14517 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 14518 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14519 } else { 14520 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 14521 } 14522 break; 14523 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 14524 if (!is_reg_const(reg2, is_jmp32)) 14525 swap(reg1, reg2); 14526 if (!is_reg_const(reg2, is_jmp32)) 14527 break; 14528 val = reg_const_value(reg2, is_jmp32); 14529 if (is_jmp32) { 14530 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 14531 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14532 } else { 14533 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 14534 } 14535 break; 14536 case BPF_JLE: 14537 if (is_jmp32) { 14538 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14539 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14540 } else { 14541 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14542 reg2->umin_value = max(reg1->umin_value, reg2->umin_value); 14543 } 14544 break; 14545 case BPF_JLT: 14546 if (is_jmp32) { 14547 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1); 14548 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value); 14549 } else { 14550 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1); 14551 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value); 14552 } 14553 break; 14554 case BPF_JSLE: 14555 if (is_jmp32) { 14556 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14557 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14558 } else { 14559 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14560 reg2->smin_value = max(reg1->smin_value, reg2->smin_value); 14561 } 14562 break; 14563 case BPF_JSLT: 14564 if (is_jmp32) { 14565 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1); 14566 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value); 14567 } else { 14568 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1); 14569 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value); 14570 } 14571 break; 14572 case BPF_JGE: 14573 case BPF_JGT: 14574 case BPF_JSGE: 14575 case BPF_JSGT: 14576 /* just reuse LE/LT logic above */ 14577 opcode = flip_opcode(opcode); 14578 swap(reg1, reg2); 14579 goto again; 14580 default: 14581 return; 14582 } 14583 } 14584 14585 /* Adjusts the register min/max values in the case that the dst_reg and 14586 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K 14587 * check, in which case we havea fake SCALAR_VALUE representing insn->imm). 14588 * Technically we can do similar adjustments for pointers to the same object, 14589 * but we don't support that right now. 14590 */ 14591 static int reg_set_min_max(struct bpf_verifier_env *env, 14592 struct bpf_reg_state *true_reg1, 14593 struct bpf_reg_state *true_reg2, 14594 struct bpf_reg_state *false_reg1, 14595 struct bpf_reg_state *false_reg2, 14596 u8 opcode, bool is_jmp32) 14597 { 14598 int err; 14599 14600 /* If either register is a pointer, we can't learn anything about its 14601 * variable offset from the compare (unless they were a pointer into 14602 * the same object, but we don't bother with that). 14603 */ 14604 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE) 14605 return 0; 14606 14607 /* fallthrough (FALSE) branch */ 14608 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32); 14609 reg_bounds_sync(false_reg1); 14610 reg_bounds_sync(false_reg2); 14611 14612 /* jump (TRUE) branch */ 14613 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32); 14614 reg_bounds_sync(true_reg1); 14615 reg_bounds_sync(true_reg2); 14616 14617 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1"); 14618 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2"); 14619 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1"); 14620 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2"); 14621 return err; 14622 } 14623 14624 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 14625 struct bpf_reg_state *reg, u32 id, 14626 bool is_null) 14627 { 14628 if (type_may_be_null(reg->type) && reg->id == id && 14629 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 14630 /* Old offset (both fixed and variable parts) should have been 14631 * known-zero, because we don't allow pointer arithmetic on 14632 * pointers that might be NULL. If we see this happening, don't 14633 * convert the register. 14634 * 14635 * But in some cases, some helpers that return local kptrs 14636 * advance offset for the returned pointer. In those cases, it 14637 * is fine to expect to see reg->off. 14638 */ 14639 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 14640 return; 14641 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 14642 WARN_ON_ONCE(reg->off)) 14643 return; 14644 14645 if (is_null) { 14646 reg->type = SCALAR_VALUE; 14647 /* We don't need id and ref_obj_id from this point 14648 * onwards anymore, thus we should better reset it, 14649 * so that state pruning has chances to take effect. 14650 */ 14651 reg->id = 0; 14652 reg->ref_obj_id = 0; 14653 14654 return; 14655 } 14656 14657 mark_ptr_not_null_reg(reg); 14658 14659 if (!reg_may_point_to_spin_lock(reg)) { 14660 /* For not-NULL ptr, reg->ref_obj_id will be reset 14661 * in release_reference(). 14662 * 14663 * reg->id is still used by spin_lock ptr. Other 14664 * than spin_lock ptr type, reg->id can be reset. 14665 */ 14666 reg->id = 0; 14667 } 14668 } 14669 } 14670 14671 /* The logic is similar to find_good_pkt_pointers(), both could eventually 14672 * be folded together at some point. 14673 */ 14674 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 14675 bool is_null) 14676 { 14677 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14678 struct bpf_reg_state *regs = state->regs, *reg; 14679 u32 ref_obj_id = regs[regno].ref_obj_id; 14680 u32 id = regs[regno].id; 14681 14682 if (ref_obj_id && ref_obj_id == id && is_null) 14683 /* regs[regno] is in the " == NULL" branch. 14684 * No one could have freed the reference state before 14685 * doing the NULL check. 14686 */ 14687 WARN_ON_ONCE(release_reference_state(state, id)); 14688 14689 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14690 mark_ptr_or_null_reg(state, reg, id, is_null); 14691 })); 14692 } 14693 14694 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 14695 struct bpf_reg_state *dst_reg, 14696 struct bpf_reg_state *src_reg, 14697 struct bpf_verifier_state *this_branch, 14698 struct bpf_verifier_state *other_branch) 14699 { 14700 if (BPF_SRC(insn->code) != BPF_X) 14701 return false; 14702 14703 /* Pointers are always 64-bit. */ 14704 if (BPF_CLASS(insn->code) == BPF_JMP32) 14705 return false; 14706 14707 switch (BPF_OP(insn->code)) { 14708 case BPF_JGT: 14709 if ((dst_reg->type == PTR_TO_PACKET && 14710 src_reg->type == PTR_TO_PACKET_END) || 14711 (dst_reg->type == PTR_TO_PACKET_META && 14712 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14713 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 14714 find_good_pkt_pointers(this_branch, dst_reg, 14715 dst_reg->type, false); 14716 mark_pkt_end(other_branch, insn->dst_reg, true); 14717 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14718 src_reg->type == PTR_TO_PACKET) || 14719 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14720 src_reg->type == PTR_TO_PACKET_META)) { 14721 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 14722 find_good_pkt_pointers(other_branch, src_reg, 14723 src_reg->type, true); 14724 mark_pkt_end(this_branch, insn->src_reg, false); 14725 } else { 14726 return false; 14727 } 14728 break; 14729 case BPF_JLT: 14730 if ((dst_reg->type == PTR_TO_PACKET && 14731 src_reg->type == PTR_TO_PACKET_END) || 14732 (dst_reg->type == PTR_TO_PACKET_META && 14733 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14734 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 14735 find_good_pkt_pointers(other_branch, dst_reg, 14736 dst_reg->type, true); 14737 mark_pkt_end(this_branch, insn->dst_reg, false); 14738 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14739 src_reg->type == PTR_TO_PACKET) || 14740 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14741 src_reg->type == PTR_TO_PACKET_META)) { 14742 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 14743 find_good_pkt_pointers(this_branch, src_reg, 14744 src_reg->type, false); 14745 mark_pkt_end(other_branch, insn->src_reg, true); 14746 } else { 14747 return false; 14748 } 14749 break; 14750 case BPF_JGE: 14751 if ((dst_reg->type == PTR_TO_PACKET && 14752 src_reg->type == PTR_TO_PACKET_END) || 14753 (dst_reg->type == PTR_TO_PACKET_META && 14754 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14755 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 14756 find_good_pkt_pointers(this_branch, dst_reg, 14757 dst_reg->type, true); 14758 mark_pkt_end(other_branch, insn->dst_reg, false); 14759 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14760 src_reg->type == PTR_TO_PACKET) || 14761 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14762 src_reg->type == PTR_TO_PACKET_META)) { 14763 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 14764 find_good_pkt_pointers(other_branch, src_reg, 14765 src_reg->type, false); 14766 mark_pkt_end(this_branch, insn->src_reg, true); 14767 } else { 14768 return false; 14769 } 14770 break; 14771 case BPF_JLE: 14772 if ((dst_reg->type == PTR_TO_PACKET && 14773 src_reg->type == PTR_TO_PACKET_END) || 14774 (dst_reg->type == PTR_TO_PACKET_META && 14775 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14776 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 14777 find_good_pkt_pointers(other_branch, dst_reg, 14778 dst_reg->type, false); 14779 mark_pkt_end(this_branch, insn->dst_reg, true); 14780 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14781 src_reg->type == PTR_TO_PACKET) || 14782 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14783 src_reg->type == PTR_TO_PACKET_META)) { 14784 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 14785 find_good_pkt_pointers(this_branch, src_reg, 14786 src_reg->type, true); 14787 mark_pkt_end(other_branch, insn->src_reg, false); 14788 } else { 14789 return false; 14790 } 14791 break; 14792 default: 14793 return false; 14794 } 14795 14796 return true; 14797 } 14798 14799 static void find_equal_scalars(struct bpf_verifier_state *vstate, 14800 struct bpf_reg_state *known_reg) 14801 { 14802 struct bpf_func_state *state; 14803 struct bpf_reg_state *reg; 14804 14805 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14806 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 14807 copy_register_state(reg, known_reg); 14808 })); 14809 } 14810 14811 static int check_cond_jmp_op(struct bpf_verifier_env *env, 14812 struct bpf_insn *insn, int *insn_idx) 14813 { 14814 struct bpf_verifier_state *this_branch = env->cur_state; 14815 struct bpf_verifier_state *other_branch; 14816 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 14817 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 14818 struct bpf_reg_state *eq_branch_regs; 14819 struct bpf_reg_state fake_reg = {}; 14820 u8 opcode = BPF_OP(insn->code); 14821 bool is_jmp32; 14822 int pred = -1; 14823 int err; 14824 14825 /* Only conditional jumps are expected to reach here. */ 14826 if (opcode == BPF_JA || opcode > BPF_JSLE) { 14827 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 14828 return -EINVAL; 14829 } 14830 14831 /* check src2 operand */ 14832 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14833 if (err) 14834 return err; 14835 14836 dst_reg = ®s[insn->dst_reg]; 14837 if (BPF_SRC(insn->code) == BPF_X) { 14838 if (insn->imm != 0) { 14839 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14840 return -EINVAL; 14841 } 14842 14843 /* check src1 operand */ 14844 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14845 if (err) 14846 return err; 14847 14848 src_reg = ®s[insn->src_reg]; 14849 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 14850 is_pointer_value(env, insn->src_reg)) { 14851 verbose(env, "R%d pointer comparison prohibited\n", 14852 insn->src_reg); 14853 return -EACCES; 14854 } 14855 } else { 14856 if (insn->src_reg != BPF_REG_0) { 14857 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14858 return -EINVAL; 14859 } 14860 src_reg = &fake_reg; 14861 src_reg->type = SCALAR_VALUE; 14862 __mark_reg_known(src_reg, insn->imm); 14863 } 14864 14865 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 14866 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32); 14867 if (pred >= 0) { 14868 /* If we get here with a dst_reg pointer type it is because 14869 * above is_branch_taken() special cased the 0 comparison. 14870 */ 14871 if (!__is_pointer_value(false, dst_reg)) 14872 err = mark_chain_precision(env, insn->dst_reg); 14873 if (BPF_SRC(insn->code) == BPF_X && !err && 14874 !__is_pointer_value(false, src_reg)) 14875 err = mark_chain_precision(env, insn->src_reg); 14876 if (err) 14877 return err; 14878 } 14879 14880 if (pred == 1) { 14881 /* Only follow the goto, ignore fall-through. If needed, push 14882 * the fall-through branch for simulation under speculative 14883 * execution. 14884 */ 14885 if (!env->bypass_spec_v1 && 14886 !sanitize_speculative_path(env, insn, *insn_idx + 1, 14887 *insn_idx)) 14888 return -EFAULT; 14889 if (env->log.level & BPF_LOG_LEVEL) 14890 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14891 *insn_idx += insn->off; 14892 return 0; 14893 } else if (pred == 0) { 14894 /* Only follow the fall-through branch, since that's where the 14895 * program will go. If needed, push the goto branch for 14896 * simulation under speculative execution. 14897 */ 14898 if (!env->bypass_spec_v1 && 14899 !sanitize_speculative_path(env, insn, 14900 *insn_idx + insn->off + 1, 14901 *insn_idx)) 14902 return -EFAULT; 14903 if (env->log.level & BPF_LOG_LEVEL) 14904 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14905 return 0; 14906 } 14907 14908 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 14909 false); 14910 if (!other_branch) 14911 return -EFAULT; 14912 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 14913 14914 if (BPF_SRC(insn->code) == BPF_X) { 14915 err = reg_set_min_max(env, 14916 &other_branch_regs[insn->dst_reg], 14917 &other_branch_regs[insn->src_reg], 14918 dst_reg, src_reg, opcode, is_jmp32); 14919 } else /* BPF_SRC(insn->code) == BPF_K */ { 14920 err = reg_set_min_max(env, 14921 &other_branch_regs[insn->dst_reg], 14922 src_reg /* fake one */, 14923 dst_reg, src_reg /* same fake one */, 14924 opcode, is_jmp32); 14925 } 14926 if (err) 14927 return err; 14928 14929 if (BPF_SRC(insn->code) == BPF_X && 14930 src_reg->type == SCALAR_VALUE && src_reg->id && 14931 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 14932 find_equal_scalars(this_branch, src_reg); 14933 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 14934 } 14935 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 14936 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 14937 find_equal_scalars(this_branch, dst_reg); 14938 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 14939 } 14940 14941 /* if one pointer register is compared to another pointer 14942 * register check if PTR_MAYBE_NULL could be lifted. 14943 * E.g. register A - maybe null 14944 * register B - not null 14945 * for JNE A, B, ... - A is not null in the false branch; 14946 * for JEQ A, B, ... - A is not null in the true branch. 14947 * 14948 * Since PTR_TO_BTF_ID points to a kernel struct that does 14949 * not need to be null checked by the BPF program, i.e., 14950 * could be null even without PTR_MAYBE_NULL marking, so 14951 * only propagate nullness when neither reg is that type. 14952 */ 14953 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 14954 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 14955 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 14956 base_type(src_reg->type) != PTR_TO_BTF_ID && 14957 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 14958 eq_branch_regs = NULL; 14959 switch (opcode) { 14960 case BPF_JEQ: 14961 eq_branch_regs = other_branch_regs; 14962 break; 14963 case BPF_JNE: 14964 eq_branch_regs = regs; 14965 break; 14966 default: 14967 /* do nothing */ 14968 break; 14969 } 14970 if (eq_branch_regs) { 14971 if (type_may_be_null(src_reg->type)) 14972 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 14973 else 14974 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 14975 } 14976 } 14977 14978 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 14979 * NOTE: these optimizations below are related with pointer comparison 14980 * which will never be JMP32. 14981 */ 14982 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 14983 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 14984 type_may_be_null(dst_reg->type)) { 14985 /* Mark all identical registers in each branch as either 14986 * safe or unknown depending R == 0 or R != 0 conditional. 14987 */ 14988 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 14989 opcode == BPF_JNE); 14990 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 14991 opcode == BPF_JEQ); 14992 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 14993 this_branch, other_branch) && 14994 is_pointer_value(env, insn->dst_reg)) { 14995 verbose(env, "R%d pointer comparison prohibited\n", 14996 insn->dst_reg); 14997 return -EACCES; 14998 } 14999 if (env->log.level & BPF_LOG_LEVEL) 15000 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15001 return 0; 15002 } 15003 15004 /* verify BPF_LD_IMM64 instruction */ 15005 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 15006 { 15007 struct bpf_insn_aux_data *aux = cur_aux(env); 15008 struct bpf_reg_state *regs = cur_regs(env); 15009 struct bpf_reg_state *dst_reg; 15010 struct bpf_map *map; 15011 int err; 15012 15013 if (BPF_SIZE(insn->code) != BPF_DW) { 15014 verbose(env, "invalid BPF_LD_IMM insn\n"); 15015 return -EINVAL; 15016 } 15017 if (insn->off != 0) { 15018 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 15019 return -EINVAL; 15020 } 15021 15022 err = check_reg_arg(env, insn->dst_reg, DST_OP); 15023 if (err) 15024 return err; 15025 15026 dst_reg = ®s[insn->dst_reg]; 15027 if (insn->src_reg == 0) { 15028 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 15029 15030 dst_reg->type = SCALAR_VALUE; 15031 __mark_reg_known(®s[insn->dst_reg], imm); 15032 return 0; 15033 } 15034 15035 /* All special src_reg cases are listed below. From this point onwards 15036 * we either succeed and assign a corresponding dst_reg->type after 15037 * zeroing the offset, or fail and reject the program. 15038 */ 15039 mark_reg_known_zero(env, regs, insn->dst_reg); 15040 15041 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 15042 dst_reg->type = aux->btf_var.reg_type; 15043 switch (base_type(dst_reg->type)) { 15044 case PTR_TO_MEM: 15045 dst_reg->mem_size = aux->btf_var.mem_size; 15046 break; 15047 case PTR_TO_BTF_ID: 15048 dst_reg->btf = aux->btf_var.btf; 15049 dst_reg->btf_id = aux->btf_var.btf_id; 15050 break; 15051 default: 15052 verbose(env, "bpf verifier is misconfigured\n"); 15053 return -EFAULT; 15054 } 15055 return 0; 15056 } 15057 15058 if (insn->src_reg == BPF_PSEUDO_FUNC) { 15059 struct bpf_prog_aux *aux = env->prog->aux; 15060 u32 subprogno = find_subprog(env, 15061 env->insn_idx + insn->imm + 1); 15062 15063 if (!aux->func_info) { 15064 verbose(env, "missing btf func_info\n"); 15065 return -EINVAL; 15066 } 15067 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 15068 verbose(env, "callback function not static\n"); 15069 return -EINVAL; 15070 } 15071 15072 dst_reg->type = PTR_TO_FUNC; 15073 dst_reg->subprogno = subprogno; 15074 return 0; 15075 } 15076 15077 map = env->used_maps[aux->map_index]; 15078 dst_reg->map_ptr = map; 15079 15080 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 15081 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 15082 dst_reg->type = PTR_TO_MAP_VALUE; 15083 dst_reg->off = aux->map_off; 15084 WARN_ON_ONCE(map->max_entries != 1); 15085 /* We want reg->id to be same (0) as map_value is not distinct */ 15086 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 15087 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 15088 dst_reg->type = CONST_PTR_TO_MAP; 15089 } else { 15090 verbose(env, "bpf verifier is misconfigured\n"); 15091 return -EINVAL; 15092 } 15093 15094 return 0; 15095 } 15096 15097 static bool may_access_skb(enum bpf_prog_type type) 15098 { 15099 switch (type) { 15100 case BPF_PROG_TYPE_SOCKET_FILTER: 15101 case BPF_PROG_TYPE_SCHED_CLS: 15102 case BPF_PROG_TYPE_SCHED_ACT: 15103 return true; 15104 default: 15105 return false; 15106 } 15107 } 15108 15109 /* verify safety of LD_ABS|LD_IND instructions: 15110 * - they can only appear in the programs where ctx == skb 15111 * - since they are wrappers of function calls, they scratch R1-R5 registers, 15112 * preserve R6-R9, and store return value into R0 15113 * 15114 * Implicit input: 15115 * ctx == skb == R6 == CTX 15116 * 15117 * Explicit input: 15118 * SRC == any register 15119 * IMM == 32-bit immediate 15120 * 15121 * Output: 15122 * R0 - 8/16/32-bit skb data converted to cpu endianness 15123 */ 15124 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 15125 { 15126 struct bpf_reg_state *regs = cur_regs(env); 15127 static const int ctx_reg = BPF_REG_6; 15128 u8 mode = BPF_MODE(insn->code); 15129 int i, err; 15130 15131 if (!may_access_skb(resolve_prog_type(env->prog))) { 15132 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 15133 return -EINVAL; 15134 } 15135 15136 if (!env->ops->gen_ld_abs) { 15137 verbose(env, "bpf verifier is misconfigured\n"); 15138 return -EINVAL; 15139 } 15140 15141 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 15142 BPF_SIZE(insn->code) == BPF_DW || 15143 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 15144 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 15145 return -EINVAL; 15146 } 15147 15148 /* check whether implicit source operand (register R6) is readable */ 15149 err = check_reg_arg(env, ctx_reg, SRC_OP); 15150 if (err) 15151 return err; 15152 15153 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 15154 * gen_ld_abs() may terminate the program at runtime, leading to 15155 * reference leak. 15156 */ 15157 err = check_reference_leak(env, false); 15158 if (err) { 15159 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 15160 return err; 15161 } 15162 15163 if (env->cur_state->active_lock.ptr) { 15164 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 15165 return -EINVAL; 15166 } 15167 15168 if (env->cur_state->active_rcu_lock) { 15169 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 15170 return -EINVAL; 15171 } 15172 15173 if (regs[ctx_reg].type != PTR_TO_CTX) { 15174 verbose(env, 15175 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 15176 return -EINVAL; 15177 } 15178 15179 if (mode == BPF_IND) { 15180 /* check explicit source operand */ 15181 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15182 if (err) 15183 return err; 15184 } 15185 15186 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 15187 if (err < 0) 15188 return err; 15189 15190 /* reset caller saved regs to unreadable */ 15191 for (i = 0; i < CALLER_SAVED_REGS; i++) { 15192 mark_reg_not_init(env, regs, caller_saved[i]); 15193 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 15194 } 15195 15196 /* mark destination R0 register as readable, since it contains 15197 * the value fetched from the packet. 15198 * Already marked as written above. 15199 */ 15200 mark_reg_unknown(env, regs, BPF_REG_0); 15201 /* ld_abs load up to 32-bit skb data. */ 15202 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 15203 return 0; 15204 } 15205 15206 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 15207 { 15208 const char *exit_ctx = "At program exit"; 15209 struct tnum enforce_attach_type_range = tnum_unknown; 15210 const struct bpf_prog *prog = env->prog; 15211 struct bpf_reg_state *reg; 15212 struct bpf_retval_range range = retval_range(0, 1); 15213 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 15214 int err; 15215 struct bpf_func_state *frame = env->cur_state->frame[0]; 15216 const bool is_subprog = frame->subprogno; 15217 15218 /* LSM and struct_ops func-ptr's return type could be "void" */ 15219 if (!is_subprog || frame->in_exception_callback_fn) { 15220 switch (prog_type) { 15221 case BPF_PROG_TYPE_LSM: 15222 if (prog->expected_attach_type == BPF_LSM_CGROUP) 15223 /* See below, can be 0 or 0-1 depending on hook. */ 15224 break; 15225 fallthrough; 15226 case BPF_PROG_TYPE_STRUCT_OPS: 15227 if (!prog->aux->attach_func_proto->type) 15228 return 0; 15229 break; 15230 default: 15231 break; 15232 } 15233 } 15234 15235 /* eBPF calling convention is such that R0 is used 15236 * to return the value from eBPF program. 15237 * Make sure that it's readable at this time 15238 * of bpf_exit, which means that program wrote 15239 * something into it earlier 15240 */ 15241 err = check_reg_arg(env, regno, SRC_OP); 15242 if (err) 15243 return err; 15244 15245 if (is_pointer_value(env, regno)) { 15246 verbose(env, "R%d leaks addr as return value\n", regno); 15247 return -EACCES; 15248 } 15249 15250 reg = cur_regs(env) + regno; 15251 15252 if (frame->in_async_callback_fn) { 15253 /* enforce return zero from async callbacks like timer */ 15254 exit_ctx = "At async callback return"; 15255 range = retval_range(0, 0); 15256 goto enforce_retval; 15257 } 15258 15259 if (is_subprog && !frame->in_exception_callback_fn) { 15260 if (reg->type != SCALAR_VALUE) { 15261 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 15262 regno, reg_type_str(env, reg->type)); 15263 return -EINVAL; 15264 } 15265 return 0; 15266 } 15267 15268 switch (prog_type) { 15269 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 15270 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 15271 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 15272 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG || 15273 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 15274 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 15275 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME || 15276 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 15277 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME || 15278 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME) 15279 range = retval_range(1, 1); 15280 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 15281 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 15282 range = retval_range(0, 3); 15283 break; 15284 case BPF_PROG_TYPE_CGROUP_SKB: 15285 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 15286 range = retval_range(0, 3); 15287 enforce_attach_type_range = tnum_range(2, 3); 15288 } 15289 break; 15290 case BPF_PROG_TYPE_CGROUP_SOCK: 15291 case BPF_PROG_TYPE_SOCK_OPS: 15292 case BPF_PROG_TYPE_CGROUP_DEVICE: 15293 case BPF_PROG_TYPE_CGROUP_SYSCTL: 15294 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 15295 break; 15296 case BPF_PROG_TYPE_RAW_TRACEPOINT: 15297 if (!env->prog->aux->attach_btf_id) 15298 return 0; 15299 range = retval_range(0, 0); 15300 break; 15301 case BPF_PROG_TYPE_TRACING: 15302 switch (env->prog->expected_attach_type) { 15303 case BPF_TRACE_FENTRY: 15304 case BPF_TRACE_FEXIT: 15305 range = retval_range(0, 0); 15306 break; 15307 case BPF_TRACE_RAW_TP: 15308 case BPF_MODIFY_RETURN: 15309 return 0; 15310 case BPF_TRACE_ITER: 15311 break; 15312 default: 15313 return -ENOTSUPP; 15314 } 15315 break; 15316 case BPF_PROG_TYPE_SK_LOOKUP: 15317 range = retval_range(SK_DROP, SK_PASS); 15318 break; 15319 15320 case BPF_PROG_TYPE_LSM: 15321 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 15322 /* Regular BPF_PROG_TYPE_LSM programs can return 15323 * any value. 15324 */ 15325 return 0; 15326 } 15327 if (!env->prog->aux->attach_func_proto->type) { 15328 /* Make sure programs that attach to void 15329 * hooks don't try to modify return value. 15330 */ 15331 range = retval_range(1, 1); 15332 } 15333 break; 15334 15335 case BPF_PROG_TYPE_NETFILTER: 15336 range = retval_range(NF_DROP, NF_ACCEPT); 15337 break; 15338 case BPF_PROG_TYPE_EXT: 15339 /* freplace program can return anything as its return value 15340 * depends on the to-be-replaced kernel func or bpf program. 15341 */ 15342 default: 15343 return 0; 15344 } 15345 15346 enforce_retval: 15347 if (reg->type != SCALAR_VALUE) { 15348 verbose(env, "%s the register R%d is not a known value (%s)\n", 15349 exit_ctx, regno, reg_type_str(env, reg->type)); 15350 return -EINVAL; 15351 } 15352 15353 err = mark_chain_precision(env, regno); 15354 if (err) 15355 return err; 15356 15357 if (!retval_range_within(range, reg)) { 15358 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 15359 if (!is_subprog && 15360 prog->expected_attach_type == BPF_LSM_CGROUP && 15361 prog_type == BPF_PROG_TYPE_LSM && 15362 !prog->aux->attach_func_proto->type) 15363 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 15364 return -EINVAL; 15365 } 15366 15367 if (!tnum_is_unknown(enforce_attach_type_range) && 15368 tnum_in(enforce_attach_type_range, reg->var_off)) 15369 env->prog->enforce_expected_attach_type = 1; 15370 return 0; 15371 } 15372 15373 /* non-recursive DFS pseudo code 15374 * 1 procedure DFS-iterative(G,v): 15375 * 2 label v as discovered 15376 * 3 let S be a stack 15377 * 4 S.push(v) 15378 * 5 while S is not empty 15379 * 6 t <- S.peek() 15380 * 7 if t is what we're looking for: 15381 * 8 return t 15382 * 9 for all edges e in G.adjacentEdges(t) do 15383 * 10 if edge e is already labelled 15384 * 11 continue with the next edge 15385 * 12 w <- G.adjacentVertex(t,e) 15386 * 13 if vertex w is not discovered and not explored 15387 * 14 label e as tree-edge 15388 * 15 label w as discovered 15389 * 16 S.push(w) 15390 * 17 continue at 5 15391 * 18 else if vertex w is discovered 15392 * 19 label e as back-edge 15393 * 20 else 15394 * 21 // vertex w is explored 15395 * 22 label e as forward- or cross-edge 15396 * 23 label t as explored 15397 * 24 S.pop() 15398 * 15399 * convention: 15400 * 0x10 - discovered 15401 * 0x11 - discovered and fall-through edge labelled 15402 * 0x12 - discovered and fall-through and branch edges labelled 15403 * 0x20 - explored 15404 */ 15405 15406 enum { 15407 DISCOVERED = 0x10, 15408 EXPLORED = 0x20, 15409 FALLTHROUGH = 1, 15410 BRANCH = 2, 15411 }; 15412 15413 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 15414 { 15415 env->insn_aux_data[idx].prune_point = true; 15416 } 15417 15418 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 15419 { 15420 return env->insn_aux_data[insn_idx].prune_point; 15421 } 15422 15423 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 15424 { 15425 env->insn_aux_data[idx].force_checkpoint = true; 15426 } 15427 15428 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 15429 { 15430 return env->insn_aux_data[insn_idx].force_checkpoint; 15431 } 15432 15433 static void mark_calls_callback(struct bpf_verifier_env *env, int idx) 15434 { 15435 env->insn_aux_data[idx].calls_callback = true; 15436 } 15437 15438 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx) 15439 { 15440 return env->insn_aux_data[insn_idx].calls_callback; 15441 } 15442 15443 enum { 15444 DONE_EXPLORING = 0, 15445 KEEP_EXPLORING = 1, 15446 }; 15447 15448 /* t, w, e - match pseudo-code above: 15449 * t - index of current instruction 15450 * w - next instruction 15451 * e - edge 15452 */ 15453 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 15454 { 15455 int *insn_stack = env->cfg.insn_stack; 15456 int *insn_state = env->cfg.insn_state; 15457 15458 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 15459 return DONE_EXPLORING; 15460 15461 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 15462 return DONE_EXPLORING; 15463 15464 if (w < 0 || w >= env->prog->len) { 15465 verbose_linfo(env, t, "%d: ", t); 15466 verbose(env, "jump out of range from insn %d to %d\n", t, w); 15467 return -EINVAL; 15468 } 15469 15470 if (e == BRANCH) { 15471 /* mark branch target for state pruning */ 15472 mark_prune_point(env, w); 15473 mark_jmp_point(env, w); 15474 } 15475 15476 if (insn_state[w] == 0) { 15477 /* tree-edge */ 15478 insn_state[t] = DISCOVERED | e; 15479 insn_state[w] = DISCOVERED; 15480 if (env->cfg.cur_stack >= env->prog->len) 15481 return -E2BIG; 15482 insn_stack[env->cfg.cur_stack++] = w; 15483 return KEEP_EXPLORING; 15484 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 15485 if (env->bpf_capable) 15486 return DONE_EXPLORING; 15487 verbose_linfo(env, t, "%d: ", t); 15488 verbose_linfo(env, w, "%d: ", w); 15489 verbose(env, "back-edge from insn %d to %d\n", t, w); 15490 return -EINVAL; 15491 } else if (insn_state[w] == EXPLORED) { 15492 /* forward- or cross-edge */ 15493 insn_state[t] = DISCOVERED | e; 15494 } else { 15495 verbose(env, "insn state internal bug\n"); 15496 return -EFAULT; 15497 } 15498 return DONE_EXPLORING; 15499 } 15500 15501 static int visit_func_call_insn(int t, struct bpf_insn *insns, 15502 struct bpf_verifier_env *env, 15503 bool visit_callee) 15504 { 15505 int ret, insn_sz; 15506 15507 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 15508 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 15509 if (ret) 15510 return ret; 15511 15512 mark_prune_point(env, t + insn_sz); 15513 /* when we exit from subprog, we need to record non-linear history */ 15514 mark_jmp_point(env, t + insn_sz); 15515 15516 if (visit_callee) { 15517 mark_prune_point(env, t); 15518 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env); 15519 } 15520 return ret; 15521 } 15522 15523 /* Visits the instruction at index t and returns one of the following: 15524 * < 0 - an error occurred 15525 * DONE_EXPLORING - the instruction was fully explored 15526 * KEEP_EXPLORING - there is still work to be done before it is fully explored 15527 */ 15528 static int visit_insn(int t, struct bpf_verifier_env *env) 15529 { 15530 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 15531 int ret, off, insn_sz; 15532 15533 if (bpf_pseudo_func(insn)) 15534 return visit_func_call_insn(t, insns, env, true); 15535 15536 /* All non-branch instructions have a single fall-through edge. */ 15537 if (BPF_CLASS(insn->code) != BPF_JMP && 15538 BPF_CLASS(insn->code) != BPF_JMP32) { 15539 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 15540 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 15541 } 15542 15543 switch (BPF_OP(insn->code)) { 15544 case BPF_EXIT: 15545 return DONE_EXPLORING; 15546 15547 case BPF_CALL: 15548 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback) 15549 /* Mark this call insn as a prune point to trigger 15550 * is_state_visited() check before call itself is 15551 * processed by __check_func_call(). Otherwise new 15552 * async state will be pushed for further exploration. 15553 */ 15554 mark_prune_point(env, t); 15555 /* For functions that invoke callbacks it is not known how many times 15556 * callback would be called. Verifier models callback calling functions 15557 * by repeatedly visiting callback bodies and returning to origin call 15558 * instruction. 15559 * In order to stop such iteration verifier needs to identify when a 15560 * state identical some state from a previous iteration is reached. 15561 * Check below forces creation of checkpoint before callback calling 15562 * instruction to allow search for such identical states. 15563 */ 15564 if (is_sync_callback_calling_insn(insn)) { 15565 mark_calls_callback(env, t); 15566 mark_force_checkpoint(env, t); 15567 mark_prune_point(env, t); 15568 mark_jmp_point(env, t); 15569 } 15570 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 15571 struct bpf_kfunc_call_arg_meta meta; 15572 15573 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 15574 if (ret == 0 && is_iter_next_kfunc(&meta)) { 15575 mark_prune_point(env, t); 15576 /* Checking and saving state checkpoints at iter_next() call 15577 * is crucial for fast convergence of open-coded iterator loop 15578 * logic, so we need to force it. If we don't do that, 15579 * is_state_visited() might skip saving a checkpoint, causing 15580 * unnecessarily long sequence of not checkpointed 15581 * instructions and jumps, leading to exhaustion of jump 15582 * history buffer, and potentially other undesired outcomes. 15583 * It is expected that with correct open-coded iterators 15584 * convergence will happen quickly, so we don't run a risk of 15585 * exhausting memory. 15586 */ 15587 mark_force_checkpoint(env, t); 15588 } 15589 } 15590 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 15591 15592 case BPF_JA: 15593 if (BPF_SRC(insn->code) != BPF_K) 15594 return -EINVAL; 15595 15596 if (BPF_CLASS(insn->code) == BPF_JMP) 15597 off = insn->off; 15598 else 15599 off = insn->imm; 15600 15601 /* unconditional jump with single edge */ 15602 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 15603 if (ret) 15604 return ret; 15605 15606 mark_prune_point(env, t + off + 1); 15607 mark_jmp_point(env, t + off + 1); 15608 15609 return ret; 15610 15611 default: 15612 /* conditional jump with two edges */ 15613 mark_prune_point(env, t); 15614 15615 ret = push_insn(t, t + 1, FALLTHROUGH, env); 15616 if (ret) 15617 return ret; 15618 15619 return push_insn(t, t + insn->off + 1, BRANCH, env); 15620 } 15621 } 15622 15623 /* non-recursive depth-first-search to detect loops in BPF program 15624 * loop == back-edge in directed graph 15625 */ 15626 static int check_cfg(struct bpf_verifier_env *env) 15627 { 15628 int insn_cnt = env->prog->len; 15629 int *insn_stack, *insn_state; 15630 int ex_insn_beg, i, ret = 0; 15631 bool ex_done = false; 15632 15633 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15634 if (!insn_state) 15635 return -ENOMEM; 15636 15637 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15638 if (!insn_stack) { 15639 kvfree(insn_state); 15640 return -ENOMEM; 15641 } 15642 15643 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 15644 insn_stack[0] = 0; /* 0 is the first instruction */ 15645 env->cfg.cur_stack = 1; 15646 15647 walk_cfg: 15648 while (env->cfg.cur_stack > 0) { 15649 int t = insn_stack[env->cfg.cur_stack - 1]; 15650 15651 ret = visit_insn(t, env); 15652 switch (ret) { 15653 case DONE_EXPLORING: 15654 insn_state[t] = EXPLORED; 15655 env->cfg.cur_stack--; 15656 break; 15657 case KEEP_EXPLORING: 15658 break; 15659 default: 15660 if (ret > 0) { 15661 verbose(env, "visit_insn internal bug\n"); 15662 ret = -EFAULT; 15663 } 15664 goto err_free; 15665 } 15666 } 15667 15668 if (env->cfg.cur_stack < 0) { 15669 verbose(env, "pop stack internal bug\n"); 15670 ret = -EFAULT; 15671 goto err_free; 15672 } 15673 15674 if (env->exception_callback_subprog && !ex_done) { 15675 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start; 15676 15677 insn_state[ex_insn_beg] = DISCOVERED; 15678 insn_stack[0] = ex_insn_beg; 15679 env->cfg.cur_stack = 1; 15680 ex_done = true; 15681 goto walk_cfg; 15682 } 15683 15684 for (i = 0; i < insn_cnt; i++) { 15685 struct bpf_insn *insn = &env->prog->insnsi[i]; 15686 15687 if (insn_state[i] != EXPLORED) { 15688 verbose(env, "unreachable insn %d\n", i); 15689 ret = -EINVAL; 15690 goto err_free; 15691 } 15692 if (bpf_is_ldimm64(insn)) { 15693 if (insn_state[i + 1] != 0) { 15694 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 15695 ret = -EINVAL; 15696 goto err_free; 15697 } 15698 i++; /* skip second half of ldimm64 */ 15699 } 15700 } 15701 ret = 0; /* cfg looks good */ 15702 15703 err_free: 15704 kvfree(insn_state); 15705 kvfree(insn_stack); 15706 env->cfg.insn_state = env->cfg.insn_stack = NULL; 15707 return ret; 15708 } 15709 15710 static int check_abnormal_return(struct bpf_verifier_env *env) 15711 { 15712 int i; 15713 15714 for (i = 1; i < env->subprog_cnt; i++) { 15715 if (env->subprog_info[i].has_ld_abs) { 15716 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 15717 return -EINVAL; 15718 } 15719 if (env->subprog_info[i].has_tail_call) { 15720 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 15721 return -EINVAL; 15722 } 15723 } 15724 return 0; 15725 } 15726 15727 /* The minimum supported BTF func info size */ 15728 #define MIN_BPF_FUNCINFO_SIZE 8 15729 #define MAX_FUNCINFO_REC_SIZE 252 15730 15731 static int check_btf_func_early(struct bpf_verifier_env *env, 15732 const union bpf_attr *attr, 15733 bpfptr_t uattr) 15734 { 15735 u32 krec_size = sizeof(struct bpf_func_info); 15736 const struct btf_type *type, *func_proto; 15737 u32 i, nfuncs, urec_size, min_size; 15738 struct bpf_func_info *krecord; 15739 struct bpf_prog *prog; 15740 const struct btf *btf; 15741 u32 prev_offset = 0; 15742 bpfptr_t urecord; 15743 int ret = -ENOMEM; 15744 15745 nfuncs = attr->func_info_cnt; 15746 if (!nfuncs) { 15747 if (check_abnormal_return(env)) 15748 return -EINVAL; 15749 return 0; 15750 } 15751 15752 urec_size = attr->func_info_rec_size; 15753 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 15754 urec_size > MAX_FUNCINFO_REC_SIZE || 15755 urec_size % sizeof(u32)) { 15756 verbose(env, "invalid func info rec size %u\n", urec_size); 15757 return -EINVAL; 15758 } 15759 15760 prog = env->prog; 15761 btf = prog->aux->btf; 15762 15763 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15764 min_size = min_t(u32, krec_size, urec_size); 15765 15766 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 15767 if (!krecord) 15768 return -ENOMEM; 15769 15770 for (i = 0; i < nfuncs; i++) { 15771 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 15772 if (ret) { 15773 if (ret == -E2BIG) { 15774 verbose(env, "nonzero tailing record in func info"); 15775 /* set the size kernel expects so loader can zero 15776 * out the rest of the record. 15777 */ 15778 if (copy_to_bpfptr_offset(uattr, 15779 offsetof(union bpf_attr, func_info_rec_size), 15780 &min_size, sizeof(min_size))) 15781 ret = -EFAULT; 15782 } 15783 goto err_free; 15784 } 15785 15786 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 15787 ret = -EFAULT; 15788 goto err_free; 15789 } 15790 15791 /* check insn_off */ 15792 ret = -EINVAL; 15793 if (i == 0) { 15794 if (krecord[i].insn_off) { 15795 verbose(env, 15796 "nonzero insn_off %u for the first func info record", 15797 krecord[i].insn_off); 15798 goto err_free; 15799 } 15800 } else if (krecord[i].insn_off <= prev_offset) { 15801 verbose(env, 15802 "same or smaller insn offset (%u) than previous func info record (%u)", 15803 krecord[i].insn_off, prev_offset); 15804 goto err_free; 15805 } 15806 15807 /* check type_id */ 15808 type = btf_type_by_id(btf, krecord[i].type_id); 15809 if (!type || !btf_type_is_func(type)) { 15810 verbose(env, "invalid type id %d in func info", 15811 krecord[i].type_id); 15812 goto err_free; 15813 } 15814 15815 func_proto = btf_type_by_id(btf, type->type); 15816 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 15817 /* btf_func_check() already verified it during BTF load */ 15818 goto err_free; 15819 15820 prev_offset = krecord[i].insn_off; 15821 bpfptr_add(&urecord, urec_size); 15822 } 15823 15824 prog->aux->func_info = krecord; 15825 prog->aux->func_info_cnt = nfuncs; 15826 return 0; 15827 15828 err_free: 15829 kvfree(krecord); 15830 return ret; 15831 } 15832 15833 static int check_btf_func(struct bpf_verifier_env *env, 15834 const union bpf_attr *attr, 15835 bpfptr_t uattr) 15836 { 15837 const struct btf_type *type, *func_proto, *ret_type; 15838 u32 i, nfuncs, urec_size; 15839 struct bpf_func_info *krecord; 15840 struct bpf_func_info_aux *info_aux = NULL; 15841 struct bpf_prog *prog; 15842 const struct btf *btf; 15843 bpfptr_t urecord; 15844 bool scalar_return; 15845 int ret = -ENOMEM; 15846 15847 nfuncs = attr->func_info_cnt; 15848 if (!nfuncs) { 15849 if (check_abnormal_return(env)) 15850 return -EINVAL; 15851 return 0; 15852 } 15853 if (nfuncs != env->subprog_cnt) { 15854 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 15855 return -EINVAL; 15856 } 15857 15858 urec_size = attr->func_info_rec_size; 15859 15860 prog = env->prog; 15861 btf = prog->aux->btf; 15862 15863 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15864 15865 krecord = prog->aux->func_info; 15866 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 15867 if (!info_aux) 15868 return -ENOMEM; 15869 15870 for (i = 0; i < nfuncs; i++) { 15871 /* check insn_off */ 15872 ret = -EINVAL; 15873 15874 if (env->subprog_info[i].start != krecord[i].insn_off) { 15875 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 15876 goto err_free; 15877 } 15878 15879 /* Already checked type_id */ 15880 type = btf_type_by_id(btf, krecord[i].type_id); 15881 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 15882 /* Already checked func_proto */ 15883 func_proto = btf_type_by_id(btf, type->type); 15884 15885 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 15886 scalar_return = 15887 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 15888 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 15889 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 15890 goto err_free; 15891 } 15892 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 15893 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 15894 goto err_free; 15895 } 15896 15897 bpfptr_add(&urecord, urec_size); 15898 } 15899 15900 prog->aux->func_info_aux = info_aux; 15901 return 0; 15902 15903 err_free: 15904 kfree(info_aux); 15905 return ret; 15906 } 15907 15908 static void adjust_btf_func(struct bpf_verifier_env *env) 15909 { 15910 struct bpf_prog_aux *aux = env->prog->aux; 15911 int i; 15912 15913 if (!aux->func_info) 15914 return; 15915 15916 /* func_info is not available for hidden subprogs */ 15917 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 15918 aux->func_info[i].insn_off = env->subprog_info[i].start; 15919 } 15920 15921 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 15922 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 15923 15924 static int check_btf_line(struct bpf_verifier_env *env, 15925 const union bpf_attr *attr, 15926 bpfptr_t uattr) 15927 { 15928 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 15929 struct bpf_subprog_info *sub; 15930 struct bpf_line_info *linfo; 15931 struct bpf_prog *prog; 15932 const struct btf *btf; 15933 bpfptr_t ulinfo; 15934 int err; 15935 15936 nr_linfo = attr->line_info_cnt; 15937 if (!nr_linfo) 15938 return 0; 15939 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 15940 return -EINVAL; 15941 15942 rec_size = attr->line_info_rec_size; 15943 if (rec_size < MIN_BPF_LINEINFO_SIZE || 15944 rec_size > MAX_LINEINFO_REC_SIZE || 15945 rec_size & (sizeof(u32) - 1)) 15946 return -EINVAL; 15947 15948 /* Need to zero it in case the userspace may 15949 * pass in a smaller bpf_line_info object. 15950 */ 15951 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 15952 GFP_KERNEL | __GFP_NOWARN); 15953 if (!linfo) 15954 return -ENOMEM; 15955 15956 prog = env->prog; 15957 btf = prog->aux->btf; 15958 15959 s = 0; 15960 sub = env->subprog_info; 15961 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 15962 expected_size = sizeof(struct bpf_line_info); 15963 ncopy = min_t(u32, expected_size, rec_size); 15964 for (i = 0; i < nr_linfo; i++) { 15965 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 15966 if (err) { 15967 if (err == -E2BIG) { 15968 verbose(env, "nonzero tailing record in line_info"); 15969 if (copy_to_bpfptr_offset(uattr, 15970 offsetof(union bpf_attr, line_info_rec_size), 15971 &expected_size, sizeof(expected_size))) 15972 err = -EFAULT; 15973 } 15974 goto err_free; 15975 } 15976 15977 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 15978 err = -EFAULT; 15979 goto err_free; 15980 } 15981 15982 /* 15983 * Check insn_off to ensure 15984 * 1) strictly increasing AND 15985 * 2) bounded by prog->len 15986 * 15987 * The linfo[0].insn_off == 0 check logically falls into 15988 * the later "missing bpf_line_info for func..." case 15989 * because the first linfo[0].insn_off must be the 15990 * first sub also and the first sub must have 15991 * subprog_info[0].start == 0. 15992 */ 15993 if ((i && linfo[i].insn_off <= prev_offset) || 15994 linfo[i].insn_off >= prog->len) { 15995 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 15996 i, linfo[i].insn_off, prev_offset, 15997 prog->len); 15998 err = -EINVAL; 15999 goto err_free; 16000 } 16001 16002 if (!prog->insnsi[linfo[i].insn_off].code) { 16003 verbose(env, 16004 "Invalid insn code at line_info[%u].insn_off\n", 16005 i); 16006 err = -EINVAL; 16007 goto err_free; 16008 } 16009 16010 if (!btf_name_by_offset(btf, linfo[i].line_off) || 16011 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 16012 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 16013 err = -EINVAL; 16014 goto err_free; 16015 } 16016 16017 if (s != env->subprog_cnt) { 16018 if (linfo[i].insn_off == sub[s].start) { 16019 sub[s].linfo_idx = i; 16020 s++; 16021 } else if (sub[s].start < linfo[i].insn_off) { 16022 verbose(env, "missing bpf_line_info for func#%u\n", s); 16023 err = -EINVAL; 16024 goto err_free; 16025 } 16026 } 16027 16028 prev_offset = linfo[i].insn_off; 16029 bpfptr_add(&ulinfo, rec_size); 16030 } 16031 16032 if (s != env->subprog_cnt) { 16033 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 16034 env->subprog_cnt - s, s); 16035 err = -EINVAL; 16036 goto err_free; 16037 } 16038 16039 prog->aux->linfo = linfo; 16040 prog->aux->nr_linfo = nr_linfo; 16041 16042 return 0; 16043 16044 err_free: 16045 kvfree(linfo); 16046 return err; 16047 } 16048 16049 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 16050 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 16051 16052 static int check_core_relo(struct bpf_verifier_env *env, 16053 const union bpf_attr *attr, 16054 bpfptr_t uattr) 16055 { 16056 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 16057 struct bpf_core_relo core_relo = {}; 16058 struct bpf_prog *prog = env->prog; 16059 const struct btf *btf = prog->aux->btf; 16060 struct bpf_core_ctx ctx = { 16061 .log = &env->log, 16062 .btf = btf, 16063 }; 16064 bpfptr_t u_core_relo; 16065 int err; 16066 16067 nr_core_relo = attr->core_relo_cnt; 16068 if (!nr_core_relo) 16069 return 0; 16070 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 16071 return -EINVAL; 16072 16073 rec_size = attr->core_relo_rec_size; 16074 if (rec_size < MIN_CORE_RELO_SIZE || 16075 rec_size > MAX_CORE_RELO_SIZE || 16076 rec_size % sizeof(u32)) 16077 return -EINVAL; 16078 16079 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 16080 expected_size = sizeof(struct bpf_core_relo); 16081 ncopy = min_t(u32, expected_size, rec_size); 16082 16083 /* Unlike func_info and line_info, copy and apply each CO-RE 16084 * relocation record one at a time. 16085 */ 16086 for (i = 0; i < nr_core_relo; i++) { 16087 /* future proofing when sizeof(bpf_core_relo) changes */ 16088 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 16089 if (err) { 16090 if (err == -E2BIG) { 16091 verbose(env, "nonzero tailing record in core_relo"); 16092 if (copy_to_bpfptr_offset(uattr, 16093 offsetof(union bpf_attr, core_relo_rec_size), 16094 &expected_size, sizeof(expected_size))) 16095 err = -EFAULT; 16096 } 16097 break; 16098 } 16099 16100 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 16101 err = -EFAULT; 16102 break; 16103 } 16104 16105 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 16106 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 16107 i, core_relo.insn_off, prog->len); 16108 err = -EINVAL; 16109 break; 16110 } 16111 16112 err = bpf_core_apply(&ctx, &core_relo, i, 16113 &prog->insnsi[core_relo.insn_off / 8]); 16114 if (err) 16115 break; 16116 bpfptr_add(&u_core_relo, rec_size); 16117 } 16118 return err; 16119 } 16120 16121 static int check_btf_info_early(struct bpf_verifier_env *env, 16122 const union bpf_attr *attr, 16123 bpfptr_t uattr) 16124 { 16125 struct btf *btf; 16126 int err; 16127 16128 if (!attr->func_info_cnt && !attr->line_info_cnt) { 16129 if (check_abnormal_return(env)) 16130 return -EINVAL; 16131 return 0; 16132 } 16133 16134 btf = btf_get_by_fd(attr->prog_btf_fd); 16135 if (IS_ERR(btf)) 16136 return PTR_ERR(btf); 16137 if (btf_is_kernel(btf)) { 16138 btf_put(btf); 16139 return -EACCES; 16140 } 16141 env->prog->aux->btf = btf; 16142 16143 err = check_btf_func_early(env, attr, uattr); 16144 if (err) 16145 return err; 16146 return 0; 16147 } 16148 16149 static int check_btf_info(struct bpf_verifier_env *env, 16150 const union bpf_attr *attr, 16151 bpfptr_t uattr) 16152 { 16153 int err; 16154 16155 if (!attr->func_info_cnt && !attr->line_info_cnt) { 16156 if (check_abnormal_return(env)) 16157 return -EINVAL; 16158 return 0; 16159 } 16160 16161 err = check_btf_func(env, attr, uattr); 16162 if (err) 16163 return err; 16164 16165 err = check_btf_line(env, attr, uattr); 16166 if (err) 16167 return err; 16168 16169 err = check_core_relo(env, attr, uattr); 16170 if (err) 16171 return err; 16172 16173 return 0; 16174 } 16175 16176 /* check %cur's range satisfies %old's */ 16177 static bool range_within(struct bpf_reg_state *old, 16178 struct bpf_reg_state *cur) 16179 { 16180 return old->umin_value <= cur->umin_value && 16181 old->umax_value >= cur->umax_value && 16182 old->smin_value <= cur->smin_value && 16183 old->smax_value >= cur->smax_value && 16184 old->u32_min_value <= cur->u32_min_value && 16185 old->u32_max_value >= cur->u32_max_value && 16186 old->s32_min_value <= cur->s32_min_value && 16187 old->s32_max_value >= cur->s32_max_value; 16188 } 16189 16190 /* If in the old state two registers had the same id, then they need to have 16191 * the same id in the new state as well. But that id could be different from 16192 * the old state, so we need to track the mapping from old to new ids. 16193 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 16194 * regs with old id 5 must also have new id 9 for the new state to be safe. But 16195 * regs with a different old id could still have new id 9, we don't care about 16196 * that. 16197 * So we look through our idmap to see if this old id has been seen before. If 16198 * so, we require the new id to match; otherwise, we add the id pair to the map. 16199 */ 16200 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 16201 { 16202 struct bpf_id_pair *map = idmap->map; 16203 unsigned int i; 16204 16205 /* either both IDs should be set or both should be zero */ 16206 if (!!old_id != !!cur_id) 16207 return false; 16208 16209 if (old_id == 0) /* cur_id == 0 as well */ 16210 return true; 16211 16212 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 16213 if (!map[i].old) { 16214 /* Reached an empty slot; haven't seen this id before */ 16215 map[i].old = old_id; 16216 map[i].cur = cur_id; 16217 return true; 16218 } 16219 if (map[i].old == old_id) 16220 return map[i].cur == cur_id; 16221 if (map[i].cur == cur_id) 16222 return false; 16223 } 16224 /* We ran out of idmap slots, which should be impossible */ 16225 WARN_ON_ONCE(1); 16226 return false; 16227 } 16228 16229 /* Similar to check_ids(), but allocate a unique temporary ID 16230 * for 'old_id' or 'cur_id' of zero. 16231 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 16232 */ 16233 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 16234 { 16235 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 16236 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 16237 16238 return check_ids(old_id, cur_id, idmap); 16239 } 16240 16241 static void clean_func_state(struct bpf_verifier_env *env, 16242 struct bpf_func_state *st) 16243 { 16244 enum bpf_reg_liveness live; 16245 int i, j; 16246 16247 for (i = 0; i < BPF_REG_FP; i++) { 16248 live = st->regs[i].live; 16249 /* liveness must not touch this register anymore */ 16250 st->regs[i].live |= REG_LIVE_DONE; 16251 if (!(live & REG_LIVE_READ)) 16252 /* since the register is unused, clear its state 16253 * to make further comparison simpler 16254 */ 16255 __mark_reg_not_init(env, &st->regs[i]); 16256 } 16257 16258 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 16259 live = st->stack[i].spilled_ptr.live; 16260 /* liveness must not touch this stack slot anymore */ 16261 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 16262 if (!(live & REG_LIVE_READ)) { 16263 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 16264 for (j = 0; j < BPF_REG_SIZE; j++) 16265 st->stack[i].slot_type[j] = STACK_INVALID; 16266 } 16267 } 16268 } 16269 16270 static void clean_verifier_state(struct bpf_verifier_env *env, 16271 struct bpf_verifier_state *st) 16272 { 16273 int i; 16274 16275 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 16276 /* all regs in this state in all frames were already marked */ 16277 return; 16278 16279 for (i = 0; i <= st->curframe; i++) 16280 clean_func_state(env, st->frame[i]); 16281 } 16282 16283 /* the parentage chains form a tree. 16284 * the verifier states are added to state lists at given insn and 16285 * pushed into state stack for future exploration. 16286 * when the verifier reaches bpf_exit insn some of the verifer states 16287 * stored in the state lists have their final liveness state already, 16288 * but a lot of states will get revised from liveness point of view when 16289 * the verifier explores other branches. 16290 * Example: 16291 * 1: r0 = 1 16292 * 2: if r1 == 100 goto pc+1 16293 * 3: r0 = 2 16294 * 4: exit 16295 * when the verifier reaches exit insn the register r0 in the state list of 16296 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 16297 * of insn 2 and goes exploring further. At the insn 4 it will walk the 16298 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 16299 * 16300 * Since the verifier pushes the branch states as it sees them while exploring 16301 * the program the condition of walking the branch instruction for the second 16302 * time means that all states below this branch were already explored and 16303 * their final liveness marks are already propagated. 16304 * Hence when the verifier completes the search of state list in is_state_visited() 16305 * we can call this clean_live_states() function to mark all liveness states 16306 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 16307 * will not be used. 16308 * This function also clears the registers and stack for states that !READ 16309 * to simplify state merging. 16310 * 16311 * Important note here that walking the same branch instruction in the callee 16312 * doesn't meant that the states are DONE. The verifier has to compare 16313 * the callsites 16314 */ 16315 static void clean_live_states(struct bpf_verifier_env *env, int insn, 16316 struct bpf_verifier_state *cur) 16317 { 16318 struct bpf_verifier_state_list *sl; 16319 16320 sl = *explored_state(env, insn); 16321 while (sl) { 16322 if (sl->state.branches) 16323 goto next; 16324 if (sl->state.insn_idx != insn || 16325 !same_callsites(&sl->state, cur)) 16326 goto next; 16327 clean_verifier_state(env, &sl->state); 16328 next: 16329 sl = sl->next; 16330 } 16331 } 16332 16333 static bool regs_exact(const struct bpf_reg_state *rold, 16334 const struct bpf_reg_state *rcur, 16335 struct bpf_idmap *idmap) 16336 { 16337 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16338 check_ids(rold->id, rcur->id, idmap) && 16339 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16340 } 16341 16342 /* Returns true if (rold safe implies rcur safe) */ 16343 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 16344 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact) 16345 { 16346 if (exact) 16347 return regs_exact(rold, rcur, idmap); 16348 16349 if (!(rold->live & REG_LIVE_READ)) 16350 /* explored state didn't use this */ 16351 return true; 16352 if (rold->type == NOT_INIT) 16353 /* explored state can't have used this */ 16354 return true; 16355 if (rcur->type == NOT_INIT) 16356 return false; 16357 16358 /* Enforce that register types have to match exactly, including their 16359 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 16360 * rule. 16361 * 16362 * One can make a point that using a pointer register as unbounded 16363 * SCALAR would be technically acceptable, but this could lead to 16364 * pointer leaks because scalars are allowed to leak while pointers 16365 * are not. We could make this safe in special cases if root is 16366 * calling us, but it's probably not worth the hassle. 16367 * 16368 * Also, register types that are *not* MAYBE_NULL could technically be 16369 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 16370 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 16371 * to the same map). 16372 * However, if the old MAYBE_NULL register then got NULL checked, 16373 * doing so could have affected others with the same id, and we can't 16374 * check for that because we lost the id when we converted to 16375 * a non-MAYBE_NULL variant. 16376 * So, as a general rule we don't allow mixing MAYBE_NULL and 16377 * non-MAYBE_NULL registers as well. 16378 */ 16379 if (rold->type != rcur->type) 16380 return false; 16381 16382 switch (base_type(rold->type)) { 16383 case SCALAR_VALUE: 16384 if (env->explore_alu_limits) { 16385 /* explore_alu_limits disables tnum_in() and range_within() 16386 * logic and requires everything to be strict 16387 */ 16388 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16389 check_scalar_ids(rold->id, rcur->id, idmap); 16390 } 16391 if (!rold->precise) 16392 return true; 16393 /* Why check_ids() for scalar registers? 16394 * 16395 * Consider the following BPF code: 16396 * 1: r6 = ... unbound scalar, ID=a ... 16397 * 2: r7 = ... unbound scalar, ID=b ... 16398 * 3: if (r6 > r7) goto +1 16399 * 4: r6 = r7 16400 * 5: if (r6 > X) goto ... 16401 * 6: ... memory operation using r7 ... 16402 * 16403 * First verification path is [1-6]: 16404 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 16405 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark 16406 * r7 <= X, because r6 and r7 share same id. 16407 * Next verification path is [1-4, 6]. 16408 * 16409 * Instruction (6) would be reached in two states: 16410 * I. r6{.id=b}, r7{.id=b} via path 1-6; 16411 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 16412 * 16413 * Use check_ids() to distinguish these states. 16414 * --- 16415 * Also verify that new value satisfies old value range knowledge. 16416 */ 16417 return range_within(rold, rcur) && 16418 tnum_in(rold->var_off, rcur->var_off) && 16419 check_scalar_ids(rold->id, rcur->id, idmap); 16420 case PTR_TO_MAP_KEY: 16421 case PTR_TO_MAP_VALUE: 16422 case PTR_TO_MEM: 16423 case PTR_TO_BUF: 16424 case PTR_TO_TP_BUFFER: 16425 /* If the new min/max/var_off satisfy the old ones and 16426 * everything else matches, we are OK. 16427 */ 16428 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 16429 range_within(rold, rcur) && 16430 tnum_in(rold->var_off, rcur->var_off) && 16431 check_ids(rold->id, rcur->id, idmap) && 16432 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16433 case PTR_TO_PACKET_META: 16434 case PTR_TO_PACKET: 16435 /* We must have at least as much range as the old ptr 16436 * did, so that any accesses which were safe before are 16437 * still safe. This is true even if old range < old off, 16438 * since someone could have accessed through (ptr - k), or 16439 * even done ptr -= k in a register, to get a safe access. 16440 */ 16441 if (rold->range > rcur->range) 16442 return false; 16443 /* If the offsets don't match, we can't trust our alignment; 16444 * nor can we be sure that we won't fall out of range. 16445 */ 16446 if (rold->off != rcur->off) 16447 return false; 16448 /* id relations must be preserved */ 16449 if (!check_ids(rold->id, rcur->id, idmap)) 16450 return false; 16451 /* new val must satisfy old val knowledge */ 16452 return range_within(rold, rcur) && 16453 tnum_in(rold->var_off, rcur->var_off); 16454 case PTR_TO_STACK: 16455 /* two stack pointers are equal only if they're pointing to 16456 * the same stack frame, since fp-8 in foo != fp-8 in bar 16457 */ 16458 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 16459 default: 16460 return regs_exact(rold, rcur, idmap); 16461 } 16462 } 16463 16464 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 16465 struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact) 16466 { 16467 int i, spi; 16468 16469 /* walk slots of the explored stack and ignore any additional 16470 * slots in the current stack, since explored(safe) state 16471 * didn't use them 16472 */ 16473 for (i = 0; i < old->allocated_stack; i++) { 16474 struct bpf_reg_state *old_reg, *cur_reg; 16475 16476 spi = i / BPF_REG_SIZE; 16477 16478 if (exact && 16479 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16480 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16481 return false; 16482 16483 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) { 16484 i += BPF_REG_SIZE - 1; 16485 /* explored state didn't use this */ 16486 continue; 16487 } 16488 16489 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 16490 continue; 16491 16492 if (env->allow_uninit_stack && 16493 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 16494 continue; 16495 16496 /* explored stack has more populated slots than current stack 16497 * and these slots were used 16498 */ 16499 if (i >= cur->allocated_stack) 16500 return false; 16501 16502 /* if old state was safe with misc data in the stack 16503 * it will be safe with zero-initialized stack. 16504 * The opposite is not true 16505 */ 16506 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 16507 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 16508 continue; 16509 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16510 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16511 /* Ex: old explored (safe) state has STACK_SPILL in 16512 * this stack slot, but current has STACK_MISC -> 16513 * this verifier states are not equivalent, 16514 * return false to continue verification of this path 16515 */ 16516 return false; 16517 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 16518 continue; 16519 /* Both old and cur are having same slot_type */ 16520 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 16521 case STACK_SPILL: 16522 /* when explored and current stack slot are both storing 16523 * spilled registers, check that stored pointers types 16524 * are the same as well. 16525 * Ex: explored safe path could have stored 16526 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 16527 * but current path has stored: 16528 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 16529 * such verifier states are not equivalent. 16530 * return false to continue verification of this path 16531 */ 16532 if (!regsafe(env, &old->stack[spi].spilled_ptr, 16533 &cur->stack[spi].spilled_ptr, idmap, exact)) 16534 return false; 16535 break; 16536 case STACK_DYNPTR: 16537 old_reg = &old->stack[spi].spilled_ptr; 16538 cur_reg = &cur->stack[spi].spilled_ptr; 16539 if (old_reg->dynptr.type != cur_reg->dynptr.type || 16540 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 16541 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16542 return false; 16543 break; 16544 case STACK_ITER: 16545 old_reg = &old->stack[spi].spilled_ptr; 16546 cur_reg = &cur->stack[spi].spilled_ptr; 16547 /* iter.depth is not compared between states as it 16548 * doesn't matter for correctness and would otherwise 16549 * prevent convergence; we maintain it only to prevent 16550 * infinite loop check triggering, see 16551 * iter_active_depths_differ() 16552 */ 16553 if (old_reg->iter.btf != cur_reg->iter.btf || 16554 old_reg->iter.btf_id != cur_reg->iter.btf_id || 16555 old_reg->iter.state != cur_reg->iter.state || 16556 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 16557 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16558 return false; 16559 break; 16560 case STACK_MISC: 16561 case STACK_ZERO: 16562 case STACK_INVALID: 16563 continue; 16564 /* Ensure that new unhandled slot types return false by default */ 16565 default: 16566 return false; 16567 } 16568 } 16569 return true; 16570 } 16571 16572 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 16573 struct bpf_idmap *idmap) 16574 { 16575 int i; 16576 16577 if (old->acquired_refs != cur->acquired_refs) 16578 return false; 16579 16580 for (i = 0; i < old->acquired_refs; i++) { 16581 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 16582 return false; 16583 } 16584 16585 return true; 16586 } 16587 16588 /* compare two verifier states 16589 * 16590 * all states stored in state_list are known to be valid, since 16591 * verifier reached 'bpf_exit' instruction through them 16592 * 16593 * this function is called when verifier exploring different branches of 16594 * execution popped from the state stack. If it sees an old state that has 16595 * more strict register state and more strict stack state then this execution 16596 * branch doesn't need to be explored further, since verifier already 16597 * concluded that more strict state leads to valid finish. 16598 * 16599 * Therefore two states are equivalent if register state is more conservative 16600 * and explored stack state is more conservative than the current one. 16601 * Example: 16602 * explored current 16603 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 16604 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 16605 * 16606 * In other words if current stack state (one being explored) has more 16607 * valid slots than old one that already passed validation, it means 16608 * the verifier can stop exploring and conclude that current state is valid too 16609 * 16610 * Similarly with registers. If explored state has register type as invalid 16611 * whereas register type in current state is meaningful, it means that 16612 * the current state will reach 'bpf_exit' instruction safely 16613 */ 16614 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 16615 struct bpf_func_state *cur, bool exact) 16616 { 16617 int i; 16618 16619 for (i = 0; i < MAX_BPF_REG; i++) 16620 if (!regsafe(env, &old->regs[i], &cur->regs[i], 16621 &env->idmap_scratch, exact)) 16622 return false; 16623 16624 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 16625 return false; 16626 16627 if (!refsafe(old, cur, &env->idmap_scratch)) 16628 return false; 16629 16630 return true; 16631 } 16632 16633 static void reset_idmap_scratch(struct bpf_verifier_env *env) 16634 { 16635 env->idmap_scratch.tmp_id_gen = env->id_gen; 16636 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 16637 } 16638 16639 static bool states_equal(struct bpf_verifier_env *env, 16640 struct bpf_verifier_state *old, 16641 struct bpf_verifier_state *cur, 16642 bool exact) 16643 { 16644 int i; 16645 16646 if (old->curframe != cur->curframe) 16647 return false; 16648 16649 reset_idmap_scratch(env); 16650 16651 /* Verification state from speculative execution simulation 16652 * must never prune a non-speculative execution one. 16653 */ 16654 if (old->speculative && !cur->speculative) 16655 return false; 16656 16657 if (old->active_lock.ptr != cur->active_lock.ptr) 16658 return false; 16659 16660 /* Old and cur active_lock's have to be either both present 16661 * or both absent. 16662 */ 16663 if (!!old->active_lock.id != !!cur->active_lock.id) 16664 return false; 16665 16666 if (old->active_lock.id && 16667 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch)) 16668 return false; 16669 16670 if (old->active_rcu_lock != cur->active_rcu_lock) 16671 return false; 16672 16673 /* for states to be equal callsites have to be the same 16674 * and all frame states need to be equivalent 16675 */ 16676 for (i = 0; i <= old->curframe; i++) { 16677 if (old->frame[i]->callsite != cur->frame[i]->callsite) 16678 return false; 16679 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact)) 16680 return false; 16681 } 16682 return true; 16683 } 16684 16685 /* Return 0 if no propagation happened. Return negative error code if error 16686 * happened. Otherwise, return the propagated bit. 16687 */ 16688 static int propagate_liveness_reg(struct bpf_verifier_env *env, 16689 struct bpf_reg_state *reg, 16690 struct bpf_reg_state *parent_reg) 16691 { 16692 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 16693 u8 flag = reg->live & REG_LIVE_READ; 16694 int err; 16695 16696 /* When comes here, read flags of PARENT_REG or REG could be any of 16697 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 16698 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 16699 */ 16700 if (parent_flag == REG_LIVE_READ64 || 16701 /* Or if there is no read flag from REG. */ 16702 !flag || 16703 /* Or if the read flag from REG is the same as PARENT_REG. */ 16704 parent_flag == flag) 16705 return 0; 16706 16707 err = mark_reg_read(env, reg, parent_reg, flag); 16708 if (err) 16709 return err; 16710 16711 return flag; 16712 } 16713 16714 /* A write screens off any subsequent reads; but write marks come from the 16715 * straight-line code between a state and its parent. When we arrive at an 16716 * equivalent state (jump target or such) we didn't arrive by the straight-line 16717 * code, so read marks in the state must propagate to the parent regardless 16718 * of the state's write marks. That's what 'parent == state->parent' comparison 16719 * in mark_reg_read() is for. 16720 */ 16721 static int propagate_liveness(struct bpf_verifier_env *env, 16722 const struct bpf_verifier_state *vstate, 16723 struct bpf_verifier_state *vparent) 16724 { 16725 struct bpf_reg_state *state_reg, *parent_reg; 16726 struct bpf_func_state *state, *parent; 16727 int i, frame, err = 0; 16728 16729 if (vparent->curframe != vstate->curframe) { 16730 WARN(1, "propagate_live: parent frame %d current frame %d\n", 16731 vparent->curframe, vstate->curframe); 16732 return -EFAULT; 16733 } 16734 /* Propagate read liveness of registers... */ 16735 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 16736 for (frame = 0; frame <= vstate->curframe; frame++) { 16737 parent = vparent->frame[frame]; 16738 state = vstate->frame[frame]; 16739 parent_reg = parent->regs; 16740 state_reg = state->regs; 16741 /* We don't need to worry about FP liveness, it's read-only */ 16742 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 16743 err = propagate_liveness_reg(env, &state_reg[i], 16744 &parent_reg[i]); 16745 if (err < 0) 16746 return err; 16747 if (err == REG_LIVE_READ64) 16748 mark_insn_zext(env, &parent_reg[i]); 16749 } 16750 16751 /* Propagate stack slots. */ 16752 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 16753 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 16754 parent_reg = &parent->stack[i].spilled_ptr; 16755 state_reg = &state->stack[i].spilled_ptr; 16756 err = propagate_liveness_reg(env, state_reg, 16757 parent_reg); 16758 if (err < 0) 16759 return err; 16760 } 16761 } 16762 return 0; 16763 } 16764 16765 /* find precise scalars in the previous equivalent state and 16766 * propagate them into the current state 16767 */ 16768 static int propagate_precision(struct bpf_verifier_env *env, 16769 const struct bpf_verifier_state *old) 16770 { 16771 struct bpf_reg_state *state_reg; 16772 struct bpf_func_state *state; 16773 int i, err = 0, fr; 16774 bool first; 16775 16776 for (fr = old->curframe; fr >= 0; fr--) { 16777 state = old->frame[fr]; 16778 state_reg = state->regs; 16779 first = true; 16780 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 16781 if (state_reg->type != SCALAR_VALUE || 16782 !state_reg->precise || 16783 !(state_reg->live & REG_LIVE_READ)) 16784 continue; 16785 if (env->log.level & BPF_LOG_LEVEL2) { 16786 if (first) 16787 verbose(env, "frame %d: propagating r%d", fr, i); 16788 else 16789 verbose(env, ",r%d", i); 16790 } 16791 bt_set_frame_reg(&env->bt, fr, i); 16792 first = false; 16793 } 16794 16795 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16796 if (!is_spilled_reg(&state->stack[i])) 16797 continue; 16798 state_reg = &state->stack[i].spilled_ptr; 16799 if (state_reg->type != SCALAR_VALUE || 16800 !state_reg->precise || 16801 !(state_reg->live & REG_LIVE_READ)) 16802 continue; 16803 if (env->log.level & BPF_LOG_LEVEL2) { 16804 if (first) 16805 verbose(env, "frame %d: propagating fp%d", 16806 fr, (-i - 1) * BPF_REG_SIZE); 16807 else 16808 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 16809 } 16810 bt_set_frame_slot(&env->bt, fr, i); 16811 first = false; 16812 } 16813 if (!first) 16814 verbose(env, "\n"); 16815 } 16816 16817 err = mark_chain_precision_batch(env); 16818 if (err < 0) 16819 return err; 16820 16821 return 0; 16822 } 16823 16824 static bool states_maybe_looping(struct bpf_verifier_state *old, 16825 struct bpf_verifier_state *cur) 16826 { 16827 struct bpf_func_state *fold, *fcur; 16828 int i, fr = cur->curframe; 16829 16830 if (old->curframe != fr) 16831 return false; 16832 16833 fold = old->frame[fr]; 16834 fcur = cur->frame[fr]; 16835 for (i = 0; i < MAX_BPF_REG; i++) 16836 if (memcmp(&fold->regs[i], &fcur->regs[i], 16837 offsetof(struct bpf_reg_state, parent))) 16838 return false; 16839 return true; 16840 } 16841 16842 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 16843 { 16844 return env->insn_aux_data[insn_idx].is_iter_next; 16845 } 16846 16847 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 16848 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 16849 * states to match, which otherwise would look like an infinite loop. So while 16850 * iter_next() calls are taken care of, we still need to be careful and 16851 * prevent erroneous and too eager declaration of "ininite loop", when 16852 * iterators are involved. 16853 * 16854 * Here's a situation in pseudo-BPF assembly form: 16855 * 16856 * 0: again: ; set up iter_next() call args 16857 * 1: r1 = &it ; <CHECKPOINT HERE> 16858 * 2: call bpf_iter_num_next ; this is iter_next() call 16859 * 3: if r0 == 0 goto done 16860 * 4: ... something useful here ... 16861 * 5: goto again ; another iteration 16862 * 6: done: 16863 * 7: r1 = &it 16864 * 8: call bpf_iter_num_destroy ; clean up iter state 16865 * 9: exit 16866 * 16867 * This is a typical loop. Let's assume that we have a prune point at 1:, 16868 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 16869 * again`, assuming other heuristics don't get in a way). 16870 * 16871 * When we first time come to 1:, let's say we have some state X. We proceed 16872 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 16873 * Now we come back to validate that forked ACTIVE state. We proceed through 16874 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 16875 * are converging. But the problem is that we don't know that yet, as this 16876 * convergence has to happen at iter_next() call site only. So if nothing is 16877 * done, at 1: verifier will use bounded loop logic and declare infinite 16878 * looping (and would be *technically* correct, if not for iterator's 16879 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 16880 * don't want that. So what we do in process_iter_next_call() when we go on 16881 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 16882 * a different iteration. So when we suspect an infinite loop, we additionally 16883 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 16884 * pretend we are not looping and wait for next iter_next() call. 16885 * 16886 * This only applies to ACTIVE state. In DRAINED state we don't expect to 16887 * loop, because that would actually mean infinite loop, as DRAINED state is 16888 * "sticky", and so we'll keep returning into the same instruction with the 16889 * same state (at least in one of possible code paths). 16890 * 16891 * This approach allows to keep infinite loop heuristic even in the face of 16892 * active iterator. E.g., C snippet below is and will be detected as 16893 * inifintely looping: 16894 * 16895 * struct bpf_iter_num it; 16896 * int *p, x; 16897 * 16898 * bpf_iter_num_new(&it, 0, 10); 16899 * while ((p = bpf_iter_num_next(&t))) { 16900 * x = p; 16901 * while (x--) {} // <<-- infinite loop here 16902 * } 16903 * 16904 */ 16905 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 16906 { 16907 struct bpf_reg_state *slot, *cur_slot; 16908 struct bpf_func_state *state; 16909 int i, fr; 16910 16911 for (fr = old->curframe; fr >= 0; fr--) { 16912 state = old->frame[fr]; 16913 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16914 if (state->stack[i].slot_type[0] != STACK_ITER) 16915 continue; 16916 16917 slot = &state->stack[i].spilled_ptr; 16918 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 16919 continue; 16920 16921 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 16922 if (cur_slot->iter.depth != slot->iter.depth) 16923 return true; 16924 } 16925 } 16926 return false; 16927 } 16928 16929 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 16930 { 16931 struct bpf_verifier_state_list *new_sl; 16932 struct bpf_verifier_state_list *sl, **pprev; 16933 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry; 16934 int i, j, n, err, states_cnt = 0; 16935 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx); 16936 bool add_new_state = force_new_state; 16937 bool force_exact; 16938 16939 /* bpf progs typically have pruning point every 4 instructions 16940 * http://vger.kernel.org/bpfconf2019.html#session-1 16941 * Do not add new state for future pruning if the verifier hasn't seen 16942 * at least 2 jumps and at least 8 instructions. 16943 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 16944 * In tests that amounts to up to 50% reduction into total verifier 16945 * memory consumption and 20% verifier time speedup. 16946 */ 16947 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 16948 env->insn_processed - env->prev_insn_processed >= 8) 16949 add_new_state = true; 16950 16951 pprev = explored_state(env, insn_idx); 16952 sl = *pprev; 16953 16954 clean_live_states(env, insn_idx, cur); 16955 16956 while (sl) { 16957 states_cnt++; 16958 if (sl->state.insn_idx != insn_idx) 16959 goto next; 16960 16961 if (sl->state.branches) { 16962 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 16963 16964 if (frame->in_async_callback_fn && 16965 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 16966 /* Different async_entry_cnt means that the verifier is 16967 * processing another entry into async callback. 16968 * Seeing the same state is not an indication of infinite 16969 * loop or infinite recursion. 16970 * But finding the same state doesn't mean that it's safe 16971 * to stop processing the current state. The previous state 16972 * hasn't yet reached bpf_exit, since state.branches > 0. 16973 * Checking in_async_callback_fn alone is not enough either. 16974 * Since the verifier still needs to catch infinite loops 16975 * inside async callbacks. 16976 */ 16977 goto skip_inf_loop_check; 16978 } 16979 /* BPF open-coded iterators loop detection is special. 16980 * states_maybe_looping() logic is too simplistic in detecting 16981 * states that *might* be equivalent, because it doesn't know 16982 * about ID remapping, so don't even perform it. 16983 * See process_iter_next_call() and iter_active_depths_differ() 16984 * for overview of the logic. When current and one of parent 16985 * states are detected as equivalent, it's a good thing: we prove 16986 * convergence and can stop simulating further iterations. 16987 * It's safe to assume that iterator loop will finish, taking into 16988 * account iter_next() contract of eventually returning 16989 * sticky NULL result. 16990 * 16991 * Note, that states have to be compared exactly in this case because 16992 * read and precision marks might not be finalized inside the loop. 16993 * E.g. as in the program below: 16994 * 16995 * 1. r7 = -16 16996 * 2. r6 = bpf_get_prandom_u32() 16997 * 3. while (bpf_iter_num_next(&fp[-8])) { 16998 * 4. if (r6 != 42) { 16999 * 5. r7 = -32 17000 * 6. r6 = bpf_get_prandom_u32() 17001 * 7. continue 17002 * 8. } 17003 * 9. r0 = r10 17004 * 10. r0 += r7 17005 * 11. r8 = *(u64 *)(r0 + 0) 17006 * 12. r6 = bpf_get_prandom_u32() 17007 * 13. } 17008 * 17009 * Here verifier would first visit path 1-3, create a checkpoint at 3 17010 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 17011 * not have read or precision mark for r7 yet, thus inexact states 17012 * comparison would discard current state with r7=-32 17013 * => unsafe memory access at 11 would not be caught. 17014 */ 17015 if (is_iter_next_insn(env, insn_idx)) { 17016 if (states_equal(env, &sl->state, cur, true)) { 17017 struct bpf_func_state *cur_frame; 17018 struct bpf_reg_state *iter_state, *iter_reg; 17019 int spi; 17020 17021 cur_frame = cur->frame[cur->curframe]; 17022 /* btf_check_iter_kfuncs() enforces that 17023 * iter state pointer is always the first arg 17024 */ 17025 iter_reg = &cur_frame->regs[BPF_REG_1]; 17026 /* current state is valid due to states_equal(), 17027 * so we can assume valid iter and reg state, 17028 * no need for extra (re-)validations 17029 */ 17030 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 17031 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 17032 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 17033 update_loop_entry(cur, &sl->state); 17034 goto hit; 17035 } 17036 } 17037 goto skip_inf_loop_check; 17038 } 17039 if (calls_callback(env, insn_idx)) { 17040 if (states_equal(env, &sl->state, cur, true)) 17041 goto hit; 17042 goto skip_inf_loop_check; 17043 } 17044 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 17045 if (states_maybe_looping(&sl->state, cur) && 17046 states_equal(env, &sl->state, cur, true) && 17047 !iter_active_depths_differ(&sl->state, cur) && 17048 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 17049 verbose_linfo(env, insn_idx, "; "); 17050 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 17051 verbose(env, "cur state:"); 17052 print_verifier_state(env, cur->frame[cur->curframe], true); 17053 verbose(env, "old state:"); 17054 print_verifier_state(env, sl->state.frame[cur->curframe], true); 17055 return -EINVAL; 17056 } 17057 /* if the verifier is processing a loop, avoid adding new state 17058 * too often, since different loop iterations have distinct 17059 * states and may not help future pruning. 17060 * This threshold shouldn't be too low to make sure that 17061 * a loop with large bound will be rejected quickly. 17062 * The most abusive loop will be: 17063 * r1 += 1 17064 * if r1 < 1000000 goto pc-2 17065 * 1M insn_procssed limit / 100 == 10k peak states. 17066 * This threshold shouldn't be too high either, since states 17067 * at the end of the loop are likely to be useful in pruning. 17068 */ 17069 skip_inf_loop_check: 17070 if (!force_new_state && 17071 env->jmps_processed - env->prev_jmps_processed < 20 && 17072 env->insn_processed - env->prev_insn_processed < 100) 17073 add_new_state = false; 17074 goto miss; 17075 } 17076 /* If sl->state is a part of a loop and this loop's entry is a part of 17077 * current verification path then states have to be compared exactly. 17078 * 'force_exact' is needed to catch the following case: 17079 * 17080 * initial Here state 'succ' was processed first, 17081 * | it was eventually tracked to produce a 17082 * V state identical to 'hdr'. 17083 * .---------> hdr All branches from 'succ' had been explored 17084 * | | and thus 'succ' has its .branches == 0. 17085 * | V 17086 * | .------... Suppose states 'cur' and 'succ' correspond 17087 * | | | to the same instruction + callsites. 17088 * | V V In such case it is necessary to check 17089 * | ... ... if 'succ' and 'cur' are states_equal(). 17090 * | | | If 'succ' and 'cur' are a part of the 17091 * | V V same loop exact flag has to be set. 17092 * | succ <- cur To check if that is the case, verify 17093 * | | if loop entry of 'succ' is in current 17094 * | V DFS path. 17095 * | ... 17096 * | | 17097 * '----' 17098 * 17099 * Additional details are in the comment before get_loop_entry(). 17100 */ 17101 loop_entry = get_loop_entry(&sl->state); 17102 force_exact = loop_entry && loop_entry->branches > 0; 17103 if (states_equal(env, &sl->state, cur, force_exact)) { 17104 if (force_exact) 17105 update_loop_entry(cur, loop_entry); 17106 hit: 17107 sl->hit_cnt++; 17108 /* reached equivalent register/stack state, 17109 * prune the search. 17110 * Registers read by the continuation are read by us. 17111 * If we have any write marks in env->cur_state, they 17112 * will prevent corresponding reads in the continuation 17113 * from reaching our parent (an explored_state). Our 17114 * own state will get the read marks recorded, but 17115 * they'll be immediately forgotten as we're pruning 17116 * this state and will pop a new one. 17117 */ 17118 err = propagate_liveness(env, &sl->state, cur); 17119 17120 /* if previous state reached the exit with precision and 17121 * current state is equivalent to it (except precsion marks) 17122 * the precision needs to be propagated back in 17123 * the current state. 17124 */ 17125 if (is_jmp_point(env, env->insn_idx)) 17126 err = err ? : push_jmp_history(env, cur, 0); 17127 err = err ? : propagate_precision(env, &sl->state); 17128 if (err) 17129 return err; 17130 return 1; 17131 } 17132 miss: 17133 /* when new state is not going to be added do not increase miss count. 17134 * Otherwise several loop iterations will remove the state 17135 * recorded earlier. The goal of these heuristics is to have 17136 * states from some iterations of the loop (some in the beginning 17137 * and some at the end) to help pruning. 17138 */ 17139 if (add_new_state) 17140 sl->miss_cnt++; 17141 /* heuristic to determine whether this state is beneficial 17142 * to keep checking from state equivalence point of view. 17143 * Higher numbers increase max_states_per_insn and verification time, 17144 * but do not meaningfully decrease insn_processed. 17145 * 'n' controls how many times state could miss before eviction. 17146 * Use bigger 'n' for checkpoints because evicting checkpoint states 17147 * too early would hinder iterator convergence. 17148 */ 17149 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 17150 if (sl->miss_cnt > sl->hit_cnt * n + n) { 17151 /* the state is unlikely to be useful. Remove it to 17152 * speed up verification 17153 */ 17154 *pprev = sl->next; 17155 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE && 17156 !sl->state.used_as_loop_entry) { 17157 u32 br = sl->state.branches; 17158 17159 WARN_ONCE(br, 17160 "BUG live_done but branches_to_explore %d\n", 17161 br); 17162 free_verifier_state(&sl->state, false); 17163 kfree(sl); 17164 env->peak_states--; 17165 } else { 17166 /* cannot free this state, since parentage chain may 17167 * walk it later. Add it for free_list instead to 17168 * be freed at the end of verification 17169 */ 17170 sl->next = env->free_list; 17171 env->free_list = sl; 17172 } 17173 sl = *pprev; 17174 continue; 17175 } 17176 next: 17177 pprev = &sl->next; 17178 sl = *pprev; 17179 } 17180 17181 if (env->max_states_per_insn < states_cnt) 17182 env->max_states_per_insn = states_cnt; 17183 17184 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 17185 return 0; 17186 17187 if (!add_new_state) 17188 return 0; 17189 17190 /* There were no equivalent states, remember the current one. 17191 * Technically the current state is not proven to be safe yet, 17192 * but it will either reach outer most bpf_exit (which means it's safe) 17193 * or it will be rejected. When there are no loops the verifier won't be 17194 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 17195 * again on the way to bpf_exit. 17196 * When looping the sl->state.branches will be > 0 and this state 17197 * will not be considered for equivalence until branches == 0. 17198 */ 17199 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 17200 if (!new_sl) 17201 return -ENOMEM; 17202 env->total_states++; 17203 env->peak_states++; 17204 env->prev_jmps_processed = env->jmps_processed; 17205 env->prev_insn_processed = env->insn_processed; 17206 17207 /* forget precise markings we inherited, see __mark_chain_precision */ 17208 if (env->bpf_capable) 17209 mark_all_scalars_imprecise(env, cur); 17210 17211 /* add new state to the head of linked list */ 17212 new = &new_sl->state; 17213 err = copy_verifier_state(new, cur); 17214 if (err) { 17215 free_verifier_state(new, false); 17216 kfree(new_sl); 17217 return err; 17218 } 17219 new->insn_idx = insn_idx; 17220 WARN_ONCE(new->branches != 1, 17221 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 17222 17223 cur->parent = new; 17224 cur->first_insn_idx = insn_idx; 17225 cur->dfs_depth = new->dfs_depth + 1; 17226 clear_jmp_history(cur); 17227 new_sl->next = *explored_state(env, insn_idx); 17228 *explored_state(env, insn_idx) = new_sl; 17229 /* connect new state to parentage chain. Current frame needs all 17230 * registers connected. Only r6 - r9 of the callers are alive (pushed 17231 * to the stack implicitly by JITs) so in callers' frames connect just 17232 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 17233 * the state of the call instruction (with WRITTEN set), and r0 comes 17234 * from callee with its full parentage chain, anyway. 17235 */ 17236 /* clear write marks in current state: the writes we did are not writes 17237 * our child did, so they don't screen off its reads from us. 17238 * (There are no read marks in current state, because reads always mark 17239 * their parent and current state never has children yet. Only 17240 * explored_states can get read marks.) 17241 */ 17242 for (j = 0; j <= cur->curframe; j++) { 17243 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 17244 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 17245 for (i = 0; i < BPF_REG_FP; i++) 17246 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 17247 } 17248 17249 /* all stack frames are accessible from callee, clear them all */ 17250 for (j = 0; j <= cur->curframe; j++) { 17251 struct bpf_func_state *frame = cur->frame[j]; 17252 struct bpf_func_state *newframe = new->frame[j]; 17253 17254 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 17255 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 17256 frame->stack[i].spilled_ptr.parent = 17257 &newframe->stack[i].spilled_ptr; 17258 } 17259 } 17260 return 0; 17261 } 17262 17263 /* Return true if it's OK to have the same insn return a different type. */ 17264 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 17265 { 17266 switch (base_type(type)) { 17267 case PTR_TO_CTX: 17268 case PTR_TO_SOCKET: 17269 case PTR_TO_SOCK_COMMON: 17270 case PTR_TO_TCP_SOCK: 17271 case PTR_TO_XDP_SOCK: 17272 case PTR_TO_BTF_ID: 17273 return false; 17274 default: 17275 return true; 17276 } 17277 } 17278 17279 /* If an instruction was previously used with particular pointer types, then we 17280 * need to be careful to avoid cases such as the below, where it may be ok 17281 * for one branch accessing the pointer, but not ok for the other branch: 17282 * 17283 * R1 = sock_ptr 17284 * goto X; 17285 * ... 17286 * R1 = some_other_valid_ptr; 17287 * goto X; 17288 * ... 17289 * R2 = *(u32 *)(R1 + 0); 17290 */ 17291 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 17292 { 17293 return src != prev && (!reg_type_mismatch_ok(src) || 17294 !reg_type_mismatch_ok(prev)); 17295 } 17296 17297 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 17298 bool allow_trust_missmatch) 17299 { 17300 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 17301 17302 if (*prev_type == NOT_INIT) { 17303 /* Saw a valid insn 17304 * dst_reg = *(u32 *)(src_reg + off) 17305 * save type to validate intersecting paths 17306 */ 17307 *prev_type = type; 17308 } else if (reg_type_mismatch(type, *prev_type)) { 17309 /* Abuser program is trying to use the same insn 17310 * dst_reg = *(u32*) (src_reg + off) 17311 * with different pointer types: 17312 * src_reg == ctx in one branch and 17313 * src_reg == stack|map in some other branch. 17314 * Reject it. 17315 */ 17316 if (allow_trust_missmatch && 17317 base_type(type) == PTR_TO_BTF_ID && 17318 base_type(*prev_type) == PTR_TO_BTF_ID) { 17319 /* 17320 * Have to support a use case when one path through 17321 * the program yields TRUSTED pointer while another 17322 * is UNTRUSTED. Fallback to UNTRUSTED to generate 17323 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 17324 */ 17325 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 17326 } else { 17327 verbose(env, "same insn cannot be used with different pointers\n"); 17328 return -EINVAL; 17329 } 17330 } 17331 17332 return 0; 17333 } 17334 17335 static int do_check(struct bpf_verifier_env *env) 17336 { 17337 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17338 struct bpf_verifier_state *state = env->cur_state; 17339 struct bpf_insn *insns = env->prog->insnsi; 17340 struct bpf_reg_state *regs; 17341 int insn_cnt = env->prog->len; 17342 bool do_print_state = false; 17343 int prev_insn_idx = -1; 17344 17345 for (;;) { 17346 bool exception_exit = false; 17347 struct bpf_insn *insn; 17348 u8 class; 17349 int err; 17350 17351 /* reset current history entry on each new instruction */ 17352 env->cur_hist_ent = NULL; 17353 17354 env->prev_insn_idx = prev_insn_idx; 17355 if (env->insn_idx >= insn_cnt) { 17356 verbose(env, "invalid insn idx %d insn_cnt %d\n", 17357 env->insn_idx, insn_cnt); 17358 return -EFAULT; 17359 } 17360 17361 insn = &insns[env->insn_idx]; 17362 class = BPF_CLASS(insn->code); 17363 17364 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 17365 verbose(env, 17366 "BPF program is too large. Processed %d insn\n", 17367 env->insn_processed); 17368 return -E2BIG; 17369 } 17370 17371 state->last_insn_idx = env->prev_insn_idx; 17372 17373 if (is_prune_point(env, env->insn_idx)) { 17374 err = is_state_visited(env, env->insn_idx); 17375 if (err < 0) 17376 return err; 17377 if (err == 1) { 17378 /* found equivalent state, can prune the search */ 17379 if (env->log.level & BPF_LOG_LEVEL) { 17380 if (do_print_state) 17381 verbose(env, "\nfrom %d to %d%s: safe\n", 17382 env->prev_insn_idx, env->insn_idx, 17383 env->cur_state->speculative ? 17384 " (speculative execution)" : ""); 17385 else 17386 verbose(env, "%d: safe\n", env->insn_idx); 17387 } 17388 goto process_bpf_exit; 17389 } 17390 } 17391 17392 if (is_jmp_point(env, env->insn_idx)) { 17393 err = push_jmp_history(env, state, 0); 17394 if (err) 17395 return err; 17396 } 17397 17398 if (signal_pending(current)) 17399 return -EAGAIN; 17400 17401 if (need_resched()) 17402 cond_resched(); 17403 17404 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17405 verbose(env, "\nfrom %d to %d%s:", 17406 env->prev_insn_idx, env->insn_idx, 17407 env->cur_state->speculative ? 17408 " (speculative execution)" : ""); 17409 print_verifier_state(env, state->frame[state->curframe], true); 17410 do_print_state = false; 17411 } 17412 17413 if (env->log.level & BPF_LOG_LEVEL) { 17414 const struct bpf_insn_cbs cbs = { 17415 .cb_call = disasm_kfunc_name, 17416 .cb_print = verbose, 17417 .private_data = env, 17418 }; 17419 17420 if (verifier_state_scratched(env)) 17421 print_insn_state(env, state->frame[state->curframe]); 17422 17423 verbose_linfo(env, env->insn_idx, "; "); 17424 env->prev_log_pos = env->log.end_pos; 17425 verbose(env, "%d: ", env->insn_idx); 17426 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 17427 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17428 env->prev_log_pos = env->log.end_pos; 17429 } 17430 17431 if (bpf_prog_is_offloaded(env->prog->aux)) { 17432 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17433 env->prev_insn_idx); 17434 if (err) 17435 return err; 17436 } 17437 17438 regs = cur_regs(env); 17439 sanitize_mark_insn_seen(env); 17440 prev_insn_idx = env->insn_idx; 17441 17442 if (class == BPF_ALU || class == BPF_ALU64) { 17443 err = check_alu_op(env, insn); 17444 if (err) 17445 return err; 17446 17447 } else if (class == BPF_LDX) { 17448 enum bpf_reg_type src_reg_type; 17449 17450 /* check for reserved fields is already done */ 17451 17452 /* check src operand */ 17453 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17454 if (err) 17455 return err; 17456 17457 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 17458 if (err) 17459 return err; 17460 17461 src_reg_type = regs[insn->src_reg].type; 17462 17463 /* check that memory (src_reg + off) is readable, 17464 * the state of dst_reg will be updated by this func 17465 */ 17466 err = check_mem_access(env, env->insn_idx, insn->src_reg, 17467 insn->off, BPF_SIZE(insn->code), 17468 BPF_READ, insn->dst_reg, false, 17469 BPF_MODE(insn->code) == BPF_MEMSX); 17470 err = err ?: save_aux_ptr_type(env, src_reg_type, true); 17471 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], "ldx"); 17472 if (err) 17473 return err; 17474 } else if (class == BPF_STX) { 17475 enum bpf_reg_type dst_reg_type; 17476 17477 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 17478 err = check_atomic(env, env->insn_idx, insn); 17479 if (err) 17480 return err; 17481 env->insn_idx++; 17482 continue; 17483 } 17484 17485 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 17486 verbose(env, "BPF_STX uses reserved fields\n"); 17487 return -EINVAL; 17488 } 17489 17490 /* check src1 operand */ 17491 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17492 if (err) 17493 return err; 17494 /* check src2 operand */ 17495 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17496 if (err) 17497 return err; 17498 17499 dst_reg_type = regs[insn->dst_reg].type; 17500 17501 /* check that memory (dst_reg + off) is writeable */ 17502 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17503 insn->off, BPF_SIZE(insn->code), 17504 BPF_WRITE, insn->src_reg, false, false); 17505 if (err) 17506 return err; 17507 17508 err = save_aux_ptr_type(env, dst_reg_type, false); 17509 if (err) 17510 return err; 17511 } else if (class == BPF_ST) { 17512 enum bpf_reg_type dst_reg_type; 17513 17514 if (BPF_MODE(insn->code) != BPF_MEM || 17515 insn->src_reg != BPF_REG_0) { 17516 verbose(env, "BPF_ST uses reserved fields\n"); 17517 return -EINVAL; 17518 } 17519 /* check src operand */ 17520 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17521 if (err) 17522 return err; 17523 17524 dst_reg_type = regs[insn->dst_reg].type; 17525 17526 /* check that memory (dst_reg + off) is writeable */ 17527 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17528 insn->off, BPF_SIZE(insn->code), 17529 BPF_WRITE, -1, false, false); 17530 if (err) 17531 return err; 17532 17533 err = save_aux_ptr_type(env, dst_reg_type, false); 17534 if (err) 17535 return err; 17536 } else if (class == BPF_JMP || class == BPF_JMP32) { 17537 u8 opcode = BPF_OP(insn->code); 17538 17539 env->jmps_processed++; 17540 if (opcode == BPF_CALL) { 17541 if (BPF_SRC(insn->code) != BPF_K || 17542 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 17543 && insn->off != 0) || 17544 (insn->src_reg != BPF_REG_0 && 17545 insn->src_reg != BPF_PSEUDO_CALL && 17546 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 17547 insn->dst_reg != BPF_REG_0 || 17548 class == BPF_JMP32) { 17549 verbose(env, "BPF_CALL uses reserved fields\n"); 17550 return -EINVAL; 17551 } 17552 17553 if (env->cur_state->active_lock.ptr) { 17554 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 17555 (insn->src_reg == BPF_PSEUDO_CALL) || 17556 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17557 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 17558 verbose(env, "function calls are not allowed while holding a lock\n"); 17559 return -EINVAL; 17560 } 17561 } 17562 if (insn->src_reg == BPF_PSEUDO_CALL) { 17563 err = check_func_call(env, insn, &env->insn_idx); 17564 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 17565 err = check_kfunc_call(env, insn, &env->insn_idx); 17566 if (!err && is_bpf_throw_kfunc(insn)) { 17567 exception_exit = true; 17568 goto process_bpf_exit_full; 17569 } 17570 } else { 17571 err = check_helper_call(env, insn, &env->insn_idx); 17572 } 17573 if (err) 17574 return err; 17575 17576 mark_reg_scratched(env, BPF_REG_0); 17577 } else if (opcode == BPF_JA) { 17578 if (BPF_SRC(insn->code) != BPF_K || 17579 insn->src_reg != BPF_REG_0 || 17580 insn->dst_reg != BPF_REG_0 || 17581 (class == BPF_JMP && insn->imm != 0) || 17582 (class == BPF_JMP32 && insn->off != 0)) { 17583 verbose(env, "BPF_JA uses reserved fields\n"); 17584 return -EINVAL; 17585 } 17586 17587 if (class == BPF_JMP) 17588 env->insn_idx += insn->off + 1; 17589 else 17590 env->insn_idx += insn->imm + 1; 17591 continue; 17592 17593 } else if (opcode == BPF_EXIT) { 17594 if (BPF_SRC(insn->code) != BPF_K || 17595 insn->imm != 0 || 17596 insn->src_reg != BPF_REG_0 || 17597 insn->dst_reg != BPF_REG_0 || 17598 class == BPF_JMP32) { 17599 verbose(env, "BPF_EXIT uses reserved fields\n"); 17600 return -EINVAL; 17601 } 17602 process_bpf_exit_full: 17603 if (env->cur_state->active_lock.ptr && 17604 !in_rbtree_lock_required_cb(env)) { 17605 verbose(env, "bpf_spin_unlock is missing\n"); 17606 return -EINVAL; 17607 } 17608 17609 if (env->cur_state->active_rcu_lock && 17610 !in_rbtree_lock_required_cb(env)) { 17611 verbose(env, "bpf_rcu_read_unlock is missing\n"); 17612 return -EINVAL; 17613 } 17614 17615 /* We must do check_reference_leak here before 17616 * prepare_func_exit to handle the case when 17617 * state->curframe > 0, it may be a callback 17618 * function, for which reference_state must 17619 * match caller reference state when it exits. 17620 */ 17621 err = check_reference_leak(env, exception_exit); 17622 if (err) 17623 return err; 17624 17625 /* The side effect of the prepare_func_exit 17626 * which is being skipped is that it frees 17627 * bpf_func_state. Typically, process_bpf_exit 17628 * will only be hit with outermost exit. 17629 * copy_verifier_state in pop_stack will handle 17630 * freeing of any extra bpf_func_state left over 17631 * from not processing all nested function 17632 * exits. We also skip return code checks as 17633 * they are not needed for exceptional exits. 17634 */ 17635 if (exception_exit) 17636 goto process_bpf_exit; 17637 17638 if (state->curframe) { 17639 /* exit from nested function */ 17640 err = prepare_func_exit(env, &env->insn_idx); 17641 if (err) 17642 return err; 17643 do_print_state = true; 17644 continue; 17645 } 17646 17647 err = check_return_code(env, BPF_REG_0, "R0"); 17648 if (err) 17649 return err; 17650 process_bpf_exit: 17651 mark_verifier_state_scratched(env); 17652 update_branch_counts(env, env->cur_state); 17653 err = pop_stack(env, &prev_insn_idx, 17654 &env->insn_idx, pop_log); 17655 if (err < 0) { 17656 if (err != -ENOENT) 17657 return err; 17658 break; 17659 } else { 17660 do_print_state = true; 17661 continue; 17662 } 17663 } else { 17664 err = check_cond_jmp_op(env, insn, &env->insn_idx); 17665 if (err) 17666 return err; 17667 } 17668 } else if (class == BPF_LD) { 17669 u8 mode = BPF_MODE(insn->code); 17670 17671 if (mode == BPF_ABS || mode == BPF_IND) { 17672 err = check_ld_abs(env, insn); 17673 if (err) 17674 return err; 17675 17676 } else if (mode == BPF_IMM) { 17677 err = check_ld_imm(env, insn); 17678 if (err) 17679 return err; 17680 17681 env->insn_idx++; 17682 sanitize_mark_insn_seen(env); 17683 } else { 17684 verbose(env, "invalid BPF_LD mode\n"); 17685 return -EINVAL; 17686 } 17687 } else { 17688 verbose(env, "unknown insn class %d\n", class); 17689 return -EINVAL; 17690 } 17691 17692 env->insn_idx++; 17693 } 17694 17695 return 0; 17696 } 17697 17698 static int find_btf_percpu_datasec(struct btf *btf) 17699 { 17700 const struct btf_type *t; 17701 const char *tname; 17702 int i, n; 17703 17704 /* 17705 * Both vmlinux and module each have their own ".data..percpu" 17706 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17707 * types to look at only module's own BTF types. 17708 */ 17709 n = btf_nr_types(btf); 17710 if (btf_is_module(btf)) 17711 i = btf_nr_types(btf_vmlinux); 17712 else 17713 i = 1; 17714 17715 for(; i < n; i++) { 17716 t = btf_type_by_id(btf, i); 17717 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17718 continue; 17719 17720 tname = btf_name_by_offset(btf, t->name_off); 17721 if (!strcmp(tname, ".data..percpu")) 17722 return i; 17723 } 17724 17725 return -ENOENT; 17726 } 17727 17728 /* replace pseudo btf_id with kernel symbol address */ 17729 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 17730 struct bpf_insn *insn, 17731 struct bpf_insn_aux_data *aux) 17732 { 17733 const struct btf_var_secinfo *vsi; 17734 const struct btf_type *datasec; 17735 struct btf_mod_pair *btf_mod; 17736 const struct btf_type *t; 17737 const char *sym_name; 17738 bool percpu = false; 17739 u32 type, id = insn->imm; 17740 struct btf *btf; 17741 s32 datasec_id; 17742 u64 addr; 17743 int i, btf_fd, err; 17744 17745 btf_fd = insn[1].imm; 17746 if (btf_fd) { 17747 btf = btf_get_by_fd(btf_fd); 17748 if (IS_ERR(btf)) { 17749 verbose(env, "invalid module BTF object FD specified.\n"); 17750 return -EINVAL; 17751 } 17752 } else { 17753 if (!btf_vmlinux) { 17754 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 17755 return -EINVAL; 17756 } 17757 btf = btf_vmlinux; 17758 btf_get(btf); 17759 } 17760 17761 t = btf_type_by_id(btf, id); 17762 if (!t) { 17763 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17764 err = -ENOENT; 17765 goto err_put; 17766 } 17767 17768 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 17769 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 17770 err = -EINVAL; 17771 goto err_put; 17772 } 17773 17774 sym_name = btf_name_by_offset(btf, t->name_off); 17775 addr = kallsyms_lookup_name(sym_name); 17776 if (!addr) { 17777 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 17778 sym_name); 17779 err = -ENOENT; 17780 goto err_put; 17781 } 17782 insn[0].imm = (u32)addr; 17783 insn[1].imm = addr >> 32; 17784 17785 if (btf_type_is_func(t)) { 17786 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17787 aux->btf_var.mem_size = 0; 17788 goto check_btf; 17789 } 17790 17791 datasec_id = find_btf_percpu_datasec(btf); 17792 if (datasec_id > 0) { 17793 datasec = btf_type_by_id(btf, datasec_id); 17794 for_each_vsi(i, datasec, vsi) { 17795 if (vsi->type == id) { 17796 percpu = true; 17797 break; 17798 } 17799 } 17800 } 17801 17802 type = t->type; 17803 t = btf_type_skip_modifiers(btf, type, NULL); 17804 if (percpu) { 17805 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 17806 aux->btf_var.btf = btf; 17807 aux->btf_var.btf_id = type; 17808 } else if (!btf_type_is_struct(t)) { 17809 const struct btf_type *ret; 17810 const char *tname; 17811 u32 tsize; 17812 17813 /* resolve the type size of ksym. */ 17814 ret = btf_resolve_size(btf, t, &tsize); 17815 if (IS_ERR(ret)) { 17816 tname = btf_name_by_offset(btf, t->name_off); 17817 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 17818 tname, PTR_ERR(ret)); 17819 err = -EINVAL; 17820 goto err_put; 17821 } 17822 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17823 aux->btf_var.mem_size = tsize; 17824 } else { 17825 aux->btf_var.reg_type = PTR_TO_BTF_ID; 17826 aux->btf_var.btf = btf; 17827 aux->btf_var.btf_id = type; 17828 } 17829 check_btf: 17830 /* check whether we recorded this BTF (and maybe module) already */ 17831 for (i = 0; i < env->used_btf_cnt; i++) { 17832 if (env->used_btfs[i].btf == btf) { 17833 btf_put(btf); 17834 return 0; 17835 } 17836 } 17837 17838 if (env->used_btf_cnt >= MAX_USED_BTFS) { 17839 err = -E2BIG; 17840 goto err_put; 17841 } 17842 17843 btf_mod = &env->used_btfs[env->used_btf_cnt]; 17844 btf_mod->btf = btf; 17845 btf_mod->module = NULL; 17846 17847 /* if we reference variables from kernel module, bump its refcount */ 17848 if (btf_is_module(btf)) { 17849 btf_mod->module = btf_try_get_module(btf); 17850 if (!btf_mod->module) { 17851 err = -ENXIO; 17852 goto err_put; 17853 } 17854 } 17855 17856 env->used_btf_cnt++; 17857 17858 return 0; 17859 err_put: 17860 btf_put(btf); 17861 return err; 17862 } 17863 17864 static bool is_tracing_prog_type(enum bpf_prog_type type) 17865 { 17866 switch (type) { 17867 case BPF_PROG_TYPE_KPROBE: 17868 case BPF_PROG_TYPE_TRACEPOINT: 17869 case BPF_PROG_TYPE_PERF_EVENT: 17870 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17871 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 17872 return true; 17873 default: 17874 return false; 17875 } 17876 } 17877 17878 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 17879 struct bpf_map *map, 17880 struct bpf_prog *prog) 17881 17882 { 17883 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17884 17885 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 17886 btf_record_has_field(map->record, BPF_RB_ROOT)) { 17887 if (is_tracing_prog_type(prog_type)) { 17888 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 17889 return -EINVAL; 17890 } 17891 } 17892 17893 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 17894 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 17895 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 17896 return -EINVAL; 17897 } 17898 17899 if (is_tracing_prog_type(prog_type)) { 17900 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 17901 return -EINVAL; 17902 } 17903 } 17904 17905 if (btf_record_has_field(map->record, BPF_TIMER)) { 17906 if (is_tracing_prog_type(prog_type)) { 17907 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 17908 return -EINVAL; 17909 } 17910 } 17911 17912 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 17913 !bpf_offload_prog_map_match(prog, map)) { 17914 verbose(env, "offload device mismatch between prog and map\n"); 17915 return -EINVAL; 17916 } 17917 17918 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 17919 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 17920 return -EINVAL; 17921 } 17922 17923 if (prog->aux->sleepable) 17924 switch (map->map_type) { 17925 case BPF_MAP_TYPE_HASH: 17926 case BPF_MAP_TYPE_LRU_HASH: 17927 case BPF_MAP_TYPE_ARRAY: 17928 case BPF_MAP_TYPE_PERCPU_HASH: 17929 case BPF_MAP_TYPE_PERCPU_ARRAY: 17930 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 17931 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 17932 case BPF_MAP_TYPE_HASH_OF_MAPS: 17933 case BPF_MAP_TYPE_RINGBUF: 17934 case BPF_MAP_TYPE_USER_RINGBUF: 17935 case BPF_MAP_TYPE_INODE_STORAGE: 17936 case BPF_MAP_TYPE_SK_STORAGE: 17937 case BPF_MAP_TYPE_TASK_STORAGE: 17938 case BPF_MAP_TYPE_CGRP_STORAGE: 17939 break; 17940 default: 17941 verbose(env, 17942 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 17943 return -EINVAL; 17944 } 17945 17946 return 0; 17947 } 17948 17949 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 17950 { 17951 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 17952 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 17953 } 17954 17955 /* find and rewrite pseudo imm in ld_imm64 instructions: 17956 * 17957 * 1. if it accesses map FD, replace it with actual map pointer. 17958 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 17959 * 17960 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 17961 */ 17962 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 17963 { 17964 struct bpf_insn *insn = env->prog->insnsi; 17965 int insn_cnt = env->prog->len; 17966 int i, j, err; 17967 17968 err = bpf_prog_calc_tag(env->prog); 17969 if (err) 17970 return err; 17971 17972 for (i = 0; i < insn_cnt; i++, insn++) { 17973 if (BPF_CLASS(insn->code) == BPF_LDX && 17974 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 17975 insn->imm != 0)) { 17976 verbose(env, "BPF_LDX uses reserved fields\n"); 17977 return -EINVAL; 17978 } 17979 17980 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 17981 struct bpf_insn_aux_data *aux; 17982 struct bpf_map *map; 17983 struct fd f; 17984 u64 addr; 17985 u32 fd; 17986 17987 if (i == insn_cnt - 1 || insn[1].code != 0 || 17988 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 17989 insn[1].off != 0) { 17990 verbose(env, "invalid bpf_ld_imm64 insn\n"); 17991 return -EINVAL; 17992 } 17993 17994 if (insn[0].src_reg == 0) 17995 /* valid generic load 64-bit imm */ 17996 goto next_insn; 17997 17998 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 17999 aux = &env->insn_aux_data[i]; 18000 err = check_pseudo_btf_id(env, insn, aux); 18001 if (err) 18002 return err; 18003 goto next_insn; 18004 } 18005 18006 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 18007 aux = &env->insn_aux_data[i]; 18008 aux->ptr_type = PTR_TO_FUNC; 18009 goto next_insn; 18010 } 18011 18012 /* In final convert_pseudo_ld_imm64() step, this is 18013 * converted into regular 64-bit imm load insn. 18014 */ 18015 switch (insn[0].src_reg) { 18016 case BPF_PSEUDO_MAP_VALUE: 18017 case BPF_PSEUDO_MAP_IDX_VALUE: 18018 break; 18019 case BPF_PSEUDO_MAP_FD: 18020 case BPF_PSEUDO_MAP_IDX: 18021 if (insn[1].imm == 0) 18022 break; 18023 fallthrough; 18024 default: 18025 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 18026 return -EINVAL; 18027 } 18028 18029 switch (insn[0].src_reg) { 18030 case BPF_PSEUDO_MAP_IDX_VALUE: 18031 case BPF_PSEUDO_MAP_IDX: 18032 if (bpfptr_is_null(env->fd_array)) { 18033 verbose(env, "fd_idx without fd_array is invalid\n"); 18034 return -EPROTO; 18035 } 18036 if (copy_from_bpfptr_offset(&fd, env->fd_array, 18037 insn[0].imm * sizeof(fd), 18038 sizeof(fd))) 18039 return -EFAULT; 18040 break; 18041 default: 18042 fd = insn[0].imm; 18043 break; 18044 } 18045 18046 f = fdget(fd); 18047 map = __bpf_map_get(f); 18048 if (IS_ERR(map)) { 18049 verbose(env, "fd %d is not pointing to valid bpf_map\n", 18050 insn[0].imm); 18051 return PTR_ERR(map); 18052 } 18053 18054 err = check_map_prog_compatibility(env, map, env->prog); 18055 if (err) { 18056 fdput(f); 18057 return err; 18058 } 18059 18060 aux = &env->insn_aux_data[i]; 18061 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 18062 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 18063 addr = (unsigned long)map; 18064 } else { 18065 u32 off = insn[1].imm; 18066 18067 if (off >= BPF_MAX_VAR_OFF) { 18068 verbose(env, "direct value offset of %u is not allowed\n", off); 18069 fdput(f); 18070 return -EINVAL; 18071 } 18072 18073 if (!map->ops->map_direct_value_addr) { 18074 verbose(env, "no direct value access support for this map type\n"); 18075 fdput(f); 18076 return -EINVAL; 18077 } 18078 18079 err = map->ops->map_direct_value_addr(map, &addr, off); 18080 if (err) { 18081 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 18082 map->value_size, off); 18083 fdput(f); 18084 return err; 18085 } 18086 18087 aux->map_off = off; 18088 addr += off; 18089 } 18090 18091 insn[0].imm = (u32)addr; 18092 insn[1].imm = addr >> 32; 18093 18094 /* check whether we recorded this map already */ 18095 for (j = 0; j < env->used_map_cnt; j++) { 18096 if (env->used_maps[j] == map) { 18097 aux->map_index = j; 18098 fdput(f); 18099 goto next_insn; 18100 } 18101 } 18102 18103 if (env->used_map_cnt >= MAX_USED_MAPS) { 18104 fdput(f); 18105 return -E2BIG; 18106 } 18107 18108 if (env->prog->aux->sleepable) 18109 atomic64_inc(&map->sleepable_refcnt); 18110 /* hold the map. If the program is rejected by verifier, 18111 * the map will be released by release_maps() or it 18112 * will be used by the valid program until it's unloaded 18113 * and all maps are released in bpf_free_used_maps() 18114 */ 18115 bpf_map_inc(map); 18116 18117 aux->map_index = env->used_map_cnt; 18118 env->used_maps[env->used_map_cnt++] = map; 18119 18120 if (bpf_map_is_cgroup_storage(map) && 18121 bpf_cgroup_storage_assign(env->prog->aux, map)) { 18122 verbose(env, "only one cgroup storage of each type is allowed\n"); 18123 fdput(f); 18124 return -EBUSY; 18125 } 18126 18127 fdput(f); 18128 next_insn: 18129 insn++; 18130 i++; 18131 continue; 18132 } 18133 18134 /* Basic sanity check before we invest more work here. */ 18135 if (!bpf_opcode_in_insntable(insn->code)) { 18136 verbose(env, "unknown opcode %02x\n", insn->code); 18137 return -EINVAL; 18138 } 18139 } 18140 18141 /* now all pseudo BPF_LD_IMM64 instructions load valid 18142 * 'struct bpf_map *' into a register instead of user map_fd. 18143 * These pointers will be used later by verifier to validate map access. 18144 */ 18145 return 0; 18146 } 18147 18148 /* drop refcnt of maps used by the rejected program */ 18149 static void release_maps(struct bpf_verifier_env *env) 18150 { 18151 __bpf_free_used_maps(env->prog->aux, env->used_maps, 18152 env->used_map_cnt); 18153 } 18154 18155 /* drop refcnt of maps used by the rejected program */ 18156 static void release_btfs(struct bpf_verifier_env *env) 18157 { 18158 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 18159 env->used_btf_cnt); 18160 } 18161 18162 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 18163 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 18164 { 18165 struct bpf_insn *insn = env->prog->insnsi; 18166 int insn_cnt = env->prog->len; 18167 int i; 18168 18169 for (i = 0; i < insn_cnt; i++, insn++) { 18170 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 18171 continue; 18172 if (insn->src_reg == BPF_PSEUDO_FUNC) 18173 continue; 18174 insn->src_reg = 0; 18175 } 18176 } 18177 18178 /* single env->prog->insni[off] instruction was replaced with the range 18179 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 18180 * [0, off) and [off, end) to new locations, so the patched range stays zero 18181 */ 18182 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 18183 struct bpf_insn_aux_data *new_data, 18184 struct bpf_prog *new_prog, u32 off, u32 cnt) 18185 { 18186 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 18187 struct bpf_insn *insn = new_prog->insnsi; 18188 u32 old_seen = old_data[off].seen; 18189 u32 prog_len; 18190 int i; 18191 18192 /* aux info at OFF always needs adjustment, no matter fast path 18193 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 18194 * original insn at old prog. 18195 */ 18196 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 18197 18198 if (cnt == 1) 18199 return; 18200 prog_len = new_prog->len; 18201 18202 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 18203 memcpy(new_data + off + cnt - 1, old_data + off, 18204 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 18205 for (i = off; i < off + cnt - 1; i++) { 18206 /* Expand insni[off]'s seen count to the patched range. */ 18207 new_data[i].seen = old_seen; 18208 new_data[i].zext_dst = insn_has_def32(env, insn + i); 18209 } 18210 env->insn_aux_data = new_data; 18211 vfree(old_data); 18212 } 18213 18214 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 18215 { 18216 int i; 18217 18218 if (len == 1) 18219 return; 18220 /* NOTE: fake 'exit' subprog should be updated as well. */ 18221 for (i = 0; i <= env->subprog_cnt; i++) { 18222 if (env->subprog_info[i].start <= off) 18223 continue; 18224 env->subprog_info[i].start += len - 1; 18225 } 18226 } 18227 18228 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 18229 { 18230 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 18231 int i, sz = prog->aux->size_poke_tab; 18232 struct bpf_jit_poke_descriptor *desc; 18233 18234 for (i = 0; i < sz; i++) { 18235 desc = &tab[i]; 18236 if (desc->insn_idx <= off) 18237 continue; 18238 desc->insn_idx += len - 1; 18239 } 18240 } 18241 18242 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 18243 const struct bpf_insn *patch, u32 len) 18244 { 18245 struct bpf_prog *new_prog; 18246 struct bpf_insn_aux_data *new_data = NULL; 18247 18248 if (len > 1) { 18249 new_data = vzalloc(array_size(env->prog->len + len - 1, 18250 sizeof(struct bpf_insn_aux_data))); 18251 if (!new_data) 18252 return NULL; 18253 } 18254 18255 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 18256 if (IS_ERR(new_prog)) { 18257 if (PTR_ERR(new_prog) == -ERANGE) 18258 verbose(env, 18259 "insn %d cannot be patched due to 16-bit range\n", 18260 env->insn_aux_data[off].orig_idx); 18261 vfree(new_data); 18262 return NULL; 18263 } 18264 adjust_insn_aux_data(env, new_data, new_prog, off, len); 18265 adjust_subprog_starts(env, off, len); 18266 adjust_poke_descs(new_prog, off, len); 18267 return new_prog; 18268 } 18269 18270 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 18271 u32 off, u32 cnt) 18272 { 18273 int i, j; 18274 18275 /* find first prog starting at or after off (first to remove) */ 18276 for (i = 0; i < env->subprog_cnt; i++) 18277 if (env->subprog_info[i].start >= off) 18278 break; 18279 /* find first prog starting at or after off + cnt (first to stay) */ 18280 for (j = i; j < env->subprog_cnt; j++) 18281 if (env->subprog_info[j].start >= off + cnt) 18282 break; 18283 /* if j doesn't start exactly at off + cnt, we are just removing 18284 * the front of previous prog 18285 */ 18286 if (env->subprog_info[j].start != off + cnt) 18287 j--; 18288 18289 if (j > i) { 18290 struct bpf_prog_aux *aux = env->prog->aux; 18291 int move; 18292 18293 /* move fake 'exit' subprog as well */ 18294 move = env->subprog_cnt + 1 - j; 18295 18296 memmove(env->subprog_info + i, 18297 env->subprog_info + j, 18298 sizeof(*env->subprog_info) * move); 18299 env->subprog_cnt -= j - i; 18300 18301 /* remove func_info */ 18302 if (aux->func_info) { 18303 move = aux->func_info_cnt - j; 18304 18305 memmove(aux->func_info + i, 18306 aux->func_info + j, 18307 sizeof(*aux->func_info) * move); 18308 aux->func_info_cnt -= j - i; 18309 /* func_info->insn_off is set after all code rewrites, 18310 * in adjust_btf_func() - no need to adjust 18311 */ 18312 } 18313 } else { 18314 /* convert i from "first prog to remove" to "first to adjust" */ 18315 if (env->subprog_info[i].start == off) 18316 i++; 18317 } 18318 18319 /* update fake 'exit' subprog as well */ 18320 for (; i <= env->subprog_cnt; i++) 18321 env->subprog_info[i].start -= cnt; 18322 18323 return 0; 18324 } 18325 18326 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 18327 u32 cnt) 18328 { 18329 struct bpf_prog *prog = env->prog; 18330 u32 i, l_off, l_cnt, nr_linfo; 18331 struct bpf_line_info *linfo; 18332 18333 nr_linfo = prog->aux->nr_linfo; 18334 if (!nr_linfo) 18335 return 0; 18336 18337 linfo = prog->aux->linfo; 18338 18339 /* find first line info to remove, count lines to be removed */ 18340 for (i = 0; i < nr_linfo; i++) 18341 if (linfo[i].insn_off >= off) 18342 break; 18343 18344 l_off = i; 18345 l_cnt = 0; 18346 for (; i < nr_linfo; i++) 18347 if (linfo[i].insn_off < off + cnt) 18348 l_cnt++; 18349 else 18350 break; 18351 18352 /* First live insn doesn't match first live linfo, it needs to "inherit" 18353 * last removed linfo. prog is already modified, so prog->len == off 18354 * means no live instructions after (tail of the program was removed). 18355 */ 18356 if (prog->len != off && l_cnt && 18357 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 18358 l_cnt--; 18359 linfo[--i].insn_off = off + cnt; 18360 } 18361 18362 /* remove the line info which refer to the removed instructions */ 18363 if (l_cnt) { 18364 memmove(linfo + l_off, linfo + i, 18365 sizeof(*linfo) * (nr_linfo - i)); 18366 18367 prog->aux->nr_linfo -= l_cnt; 18368 nr_linfo = prog->aux->nr_linfo; 18369 } 18370 18371 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 18372 for (i = l_off; i < nr_linfo; i++) 18373 linfo[i].insn_off -= cnt; 18374 18375 /* fix up all subprogs (incl. 'exit') which start >= off */ 18376 for (i = 0; i <= env->subprog_cnt; i++) 18377 if (env->subprog_info[i].linfo_idx > l_off) { 18378 /* program may have started in the removed region but 18379 * may not be fully removed 18380 */ 18381 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 18382 env->subprog_info[i].linfo_idx -= l_cnt; 18383 else 18384 env->subprog_info[i].linfo_idx = l_off; 18385 } 18386 18387 return 0; 18388 } 18389 18390 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 18391 { 18392 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18393 unsigned int orig_prog_len = env->prog->len; 18394 int err; 18395 18396 if (bpf_prog_is_offloaded(env->prog->aux)) 18397 bpf_prog_offload_remove_insns(env, off, cnt); 18398 18399 err = bpf_remove_insns(env->prog, off, cnt); 18400 if (err) 18401 return err; 18402 18403 err = adjust_subprog_starts_after_remove(env, off, cnt); 18404 if (err) 18405 return err; 18406 18407 err = bpf_adj_linfo_after_remove(env, off, cnt); 18408 if (err) 18409 return err; 18410 18411 memmove(aux_data + off, aux_data + off + cnt, 18412 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 18413 18414 return 0; 18415 } 18416 18417 /* The verifier does more data flow analysis than llvm and will not 18418 * explore branches that are dead at run time. Malicious programs can 18419 * have dead code too. Therefore replace all dead at-run-time code 18420 * with 'ja -1'. 18421 * 18422 * Just nops are not optimal, e.g. if they would sit at the end of the 18423 * program and through another bug we would manage to jump there, then 18424 * we'd execute beyond program memory otherwise. Returning exception 18425 * code also wouldn't work since we can have subprogs where the dead 18426 * code could be located. 18427 */ 18428 static void sanitize_dead_code(struct bpf_verifier_env *env) 18429 { 18430 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18431 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18432 struct bpf_insn *insn = env->prog->insnsi; 18433 const int insn_cnt = env->prog->len; 18434 int i; 18435 18436 for (i = 0; i < insn_cnt; i++) { 18437 if (aux_data[i].seen) 18438 continue; 18439 memcpy(insn + i, &trap, sizeof(trap)); 18440 aux_data[i].zext_dst = false; 18441 } 18442 } 18443 18444 static bool insn_is_cond_jump(u8 code) 18445 { 18446 u8 op; 18447 18448 op = BPF_OP(code); 18449 if (BPF_CLASS(code) == BPF_JMP32) 18450 return op != BPF_JA; 18451 18452 if (BPF_CLASS(code) != BPF_JMP) 18453 return false; 18454 18455 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 18456 } 18457 18458 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 18459 { 18460 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18461 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18462 struct bpf_insn *insn = env->prog->insnsi; 18463 const int insn_cnt = env->prog->len; 18464 int i; 18465 18466 for (i = 0; i < insn_cnt; i++, insn++) { 18467 if (!insn_is_cond_jump(insn->code)) 18468 continue; 18469 18470 if (!aux_data[i + 1].seen) 18471 ja.off = insn->off; 18472 else if (!aux_data[i + 1 + insn->off].seen) 18473 ja.off = 0; 18474 else 18475 continue; 18476 18477 if (bpf_prog_is_offloaded(env->prog->aux)) 18478 bpf_prog_offload_replace_insn(env, i, &ja); 18479 18480 memcpy(insn, &ja, sizeof(ja)); 18481 } 18482 } 18483 18484 static int opt_remove_dead_code(struct bpf_verifier_env *env) 18485 { 18486 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18487 int insn_cnt = env->prog->len; 18488 int i, err; 18489 18490 for (i = 0; i < insn_cnt; i++) { 18491 int j; 18492 18493 j = 0; 18494 while (i + j < insn_cnt && !aux_data[i + j].seen) 18495 j++; 18496 if (!j) 18497 continue; 18498 18499 err = verifier_remove_insns(env, i, j); 18500 if (err) 18501 return err; 18502 insn_cnt = env->prog->len; 18503 } 18504 18505 return 0; 18506 } 18507 18508 static int opt_remove_nops(struct bpf_verifier_env *env) 18509 { 18510 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18511 struct bpf_insn *insn = env->prog->insnsi; 18512 int insn_cnt = env->prog->len; 18513 int i, err; 18514 18515 for (i = 0; i < insn_cnt; i++) { 18516 if (memcmp(&insn[i], &ja, sizeof(ja))) 18517 continue; 18518 18519 err = verifier_remove_insns(env, i, 1); 18520 if (err) 18521 return err; 18522 insn_cnt--; 18523 i--; 18524 } 18525 18526 return 0; 18527 } 18528 18529 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 18530 const union bpf_attr *attr) 18531 { 18532 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 18533 struct bpf_insn_aux_data *aux = env->insn_aux_data; 18534 int i, patch_len, delta = 0, len = env->prog->len; 18535 struct bpf_insn *insns = env->prog->insnsi; 18536 struct bpf_prog *new_prog; 18537 bool rnd_hi32; 18538 18539 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 18540 zext_patch[1] = BPF_ZEXT_REG(0); 18541 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 18542 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 18543 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 18544 for (i = 0; i < len; i++) { 18545 int adj_idx = i + delta; 18546 struct bpf_insn insn; 18547 int load_reg; 18548 18549 insn = insns[adj_idx]; 18550 load_reg = insn_def_regno(&insn); 18551 if (!aux[adj_idx].zext_dst) { 18552 u8 code, class; 18553 u32 imm_rnd; 18554 18555 if (!rnd_hi32) 18556 continue; 18557 18558 code = insn.code; 18559 class = BPF_CLASS(code); 18560 if (load_reg == -1) 18561 continue; 18562 18563 /* NOTE: arg "reg" (the fourth one) is only used for 18564 * BPF_STX + SRC_OP, so it is safe to pass NULL 18565 * here. 18566 */ 18567 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 18568 if (class == BPF_LD && 18569 BPF_MODE(code) == BPF_IMM) 18570 i++; 18571 continue; 18572 } 18573 18574 /* ctx load could be transformed into wider load. */ 18575 if (class == BPF_LDX && 18576 aux[adj_idx].ptr_type == PTR_TO_CTX) 18577 continue; 18578 18579 imm_rnd = get_random_u32(); 18580 rnd_hi32_patch[0] = insn; 18581 rnd_hi32_patch[1].imm = imm_rnd; 18582 rnd_hi32_patch[3].dst_reg = load_reg; 18583 patch = rnd_hi32_patch; 18584 patch_len = 4; 18585 goto apply_patch_buffer; 18586 } 18587 18588 /* Add in an zero-extend instruction if a) the JIT has requested 18589 * it or b) it's a CMPXCHG. 18590 * 18591 * The latter is because: BPF_CMPXCHG always loads a value into 18592 * R0, therefore always zero-extends. However some archs' 18593 * equivalent instruction only does this load when the 18594 * comparison is successful. This detail of CMPXCHG is 18595 * orthogonal to the general zero-extension behaviour of the 18596 * CPU, so it's treated independently of bpf_jit_needs_zext. 18597 */ 18598 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 18599 continue; 18600 18601 /* Zero-extension is done by the caller. */ 18602 if (bpf_pseudo_kfunc_call(&insn)) 18603 continue; 18604 18605 if (WARN_ON(load_reg == -1)) { 18606 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 18607 return -EFAULT; 18608 } 18609 18610 zext_patch[0] = insn; 18611 zext_patch[1].dst_reg = load_reg; 18612 zext_patch[1].src_reg = load_reg; 18613 patch = zext_patch; 18614 patch_len = 2; 18615 apply_patch_buffer: 18616 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 18617 if (!new_prog) 18618 return -ENOMEM; 18619 env->prog = new_prog; 18620 insns = new_prog->insnsi; 18621 aux = env->insn_aux_data; 18622 delta += patch_len - 1; 18623 } 18624 18625 return 0; 18626 } 18627 18628 /* convert load instructions that access fields of a context type into a 18629 * sequence of instructions that access fields of the underlying structure: 18630 * struct __sk_buff -> struct sk_buff 18631 * struct bpf_sock_ops -> struct sock 18632 */ 18633 static int convert_ctx_accesses(struct bpf_verifier_env *env) 18634 { 18635 const struct bpf_verifier_ops *ops = env->ops; 18636 int i, cnt, size, ctx_field_size, delta = 0; 18637 const int insn_cnt = env->prog->len; 18638 struct bpf_insn insn_buf[16], *insn; 18639 u32 target_size, size_default, off; 18640 struct bpf_prog *new_prog; 18641 enum bpf_access_type type; 18642 bool is_narrower_load; 18643 18644 if (ops->gen_prologue || env->seen_direct_write) { 18645 if (!ops->gen_prologue) { 18646 verbose(env, "bpf verifier is misconfigured\n"); 18647 return -EINVAL; 18648 } 18649 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 18650 env->prog); 18651 if (cnt >= ARRAY_SIZE(insn_buf)) { 18652 verbose(env, "bpf verifier is misconfigured\n"); 18653 return -EINVAL; 18654 } else if (cnt) { 18655 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 18656 if (!new_prog) 18657 return -ENOMEM; 18658 18659 env->prog = new_prog; 18660 delta += cnt - 1; 18661 } 18662 } 18663 18664 if (bpf_prog_is_offloaded(env->prog->aux)) 18665 return 0; 18666 18667 insn = env->prog->insnsi + delta; 18668 18669 for (i = 0; i < insn_cnt; i++, insn++) { 18670 bpf_convert_ctx_access_t convert_ctx_access; 18671 u8 mode; 18672 18673 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 18674 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 18675 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 18676 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 18677 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 18678 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 18679 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 18680 type = BPF_READ; 18681 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 18682 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 18683 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 18684 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 18685 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 18686 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 18687 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 18688 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 18689 type = BPF_WRITE; 18690 } else { 18691 continue; 18692 } 18693 18694 if (type == BPF_WRITE && 18695 env->insn_aux_data[i + delta].sanitize_stack_spill) { 18696 struct bpf_insn patch[] = { 18697 *insn, 18698 BPF_ST_NOSPEC(), 18699 }; 18700 18701 cnt = ARRAY_SIZE(patch); 18702 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 18703 if (!new_prog) 18704 return -ENOMEM; 18705 18706 delta += cnt - 1; 18707 env->prog = new_prog; 18708 insn = new_prog->insnsi + i + delta; 18709 continue; 18710 } 18711 18712 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 18713 case PTR_TO_CTX: 18714 if (!ops->convert_ctx_access) 18715 continue; 18716 convert_ctx_access = ops->convert_ctx_access; 18717 break; 18718 case PTR_TO_SOCKET: 18719 case PTR_TO_SOCK_COMMON: 18720 convert_ctx_access = bpf_sock_convert_ctx_access; 18721 break; 18722 case PTR_TO_TCP_SOCK: 18723 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 18724 break; 18725 case PTR_TO_XDP_SOCK: 18726 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 18727 break; 18728 case PTR_TO_BTF_ID: 18729 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 18730 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 18731 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 18732 * be said once it is marked PTR_UNTRUSTED, hence we must handle 18733 * any faults for loads into such types. BPF_WRITE is disallowed 18734 * for this case. 18735 */ 18736 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 18737 if (type == BPF_READ) { 18738 if (BPF_MODE(insn->code) == BPF_MEM) 18739 insn->code = BPF_LDX | BPF_PROBE_MEM | 18740 BPF_SIZE((insn)->code); 18741 else 18742 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 18743 BPF_SIZE((insn)->code); 18744 env->prog->aux->num_exentries++; 18745 } 18746 continue; 18747 default: 18748 continue; 18749 } 18750 18751 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 18752 size = BPF_LDST_BYTES(insn); 18753 mode = BPF_MODE(insn->code); 18754 18755 /* If the read access is a narrower load of the field, 18756 * convert to a 4/8-byte load, to minimum program type specific 18757 * convert_ctx_access changes. If conversion is successful, 18758 * we will apply proper mask to the result. 18759 */ 18760 is_narrower_load = size < ctx_field_size; 18761 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 18762 off = insn->off; 18763 if (is_narrower_load) { 18764 u8 size_code; 18765 18766 if (type == BPF_WRITE) { 18767 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 18768 return -EINVAL; 18769 } 18770 18771 size_code = BPF_H; 18772 if (ctx_field_size == 4) 18773 size_code = BPF_W; 18774 else if (ctx_field_size == 8) 18775 size_code = BPF_DW; 18776 18777 insn->off = off & ~(size_default - 1); 18778 insn->code = BPF_LDX | BPF_MEM | size_code; 18779 } 18780 18781 target_size = 0; 18782 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 18783 &target_size); 18784 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 18785 (ctx_field_size && !target_size)) { 18786 verbose(env, "bpf verifier is misconfigured\n"); 18787 return -EINVAL; 18788 } 18789 18790 if (is_narrower_load && size < target_size) { 18791 u8 shift = bpf_ctx_narrow_access_offset( 18792 off, size, size_default) * 8; 18793 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 18794 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 18795 return -EINVAL; 18796 } 18797 if (ctx_field_size <= 4) { 18798 if (shift) 18799 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 18800 insn->dst_reg, 18801 shift); 18802 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18803 (1 << size * 8) - 1); 18804 } else { 18805 if (shift) 18806 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 18807 insn->dst_reg, 18808 shift); 18809 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18810 (1ULL << size * 8) - 1); 18811 } 18812 } 18813 if (mode == BPF_MEMSX) 18814 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 18815 insn->dst_reg, insn->dst_reg, 18816 size * 8, 0); 18817 18818 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18819 if (!new_prog) 18820 return -ENOMEM; 18821 18822 delta += cnt - 1; 18823 18824 /* keep walking new program and skip insns we just inserted */ 18825 env->prog = new_prog; 18826 insn = new_prog->insnsi + i + delta; 18827 } 18828 18829 return 0; 18830 } 18831 18832 static int jit_subprogs(struct bpf_verifier_env *env) 18833 { 18834 struct bpf_prog *prog = env->prog, **func, *tmp; 18835 int i, j, subprog_start, subprog_end = 0, len, subprog; 18836 struct bpf_map *map_ptr; 18837 struct bpf_insn *insn; 18838 void *old_bpf_func; 18839 int err, num_exentries; 18840 18841 if (env->subprog_cnt <= 1) 18842 return 0; 18843 18844 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18845 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 18846 continue; 18847 18848 /* Upon error here we cannot fall back to interpreter but 18849 * need a hard reject of the program. Thus -EFAULT is 18850 * propagated in any case. 18851 */ 18852 subprog = find_subprog(env, i + insn->imm + 1); 18853 if (subprog < 0) { 18854 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 18855 i + insn->imm + 1); 18856 return -EFAULT; 18857 } 18858 /* temporarily remember subprog id inside insn instead of 18859 * aux_data, since next loop will split up all insns into funcs 18860 */ 18861 insn->off = subprog; 18862 /* remember original imm in case JIT fails and fallback 18863 * to interpreter will be needed 18864 */ 18865 env->insn_aux_data[i].call_imm = insn->imm; 18866 /* point imm to __bpf_call_base+1 from JITs point of view */ 18867 insn->imm = 1; 18868 if (bpf_pseudo_func(insn)) 18869 /* jit (e.g. x86_64) may emit fewer instructions 18870 * if it learns a u32 imm is the same as a u64 imm. 18871 * Force a non zero here. 18872 */ 18873 insn[1].imm = 1; 18874 } 18875 18876 err = bpf_prog_alloc_jited_linfo(prog); 18877 if (err) 18878 goto out_undo_insn; 18879 18880 err = -ENOMEM; 18881 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 18882 if (!func) 18883 goto out_undo_insn; 18884 18885 for (i = 0; i < env->subprog_cnt; i++) { 18886 subprog_start = subprog_end; 18887 subprog_end = env->subprog_info[i + 1].start; 18888 18889 len = subprog_end - subprog_start; 18890 /* bpf_prog_run() doesn't call subprogs directly, 18891 * hence main prog stats include the runtime of subprogs. 18892 * subprogs don't have IDs and not reachable via prog_get_next_id 18893 * func[i]->stats will never be accessed and stays NULL 18894 */ 18895 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 18896 if (!func[i]) 18897 goto out_free; 18898 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 18899 len * sizeof(struct bpf_insn)); 18900 func[i]->type = prog->type; 18901 func[i]->len = len; 18902 if (bpf_prog_calc_tag(func[i])) 18903 goto out_free; 18904 func[i]->is_func = 1; 18905 func[i]->aux->func_idx = i; 18906 /* Below members will be freed only at prog->aux */ 18907 func[i]->aux->btf = prog->aux->btf; 18908 func[i]->aux->func_info = prog->aux->func_info; 18909 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 18910 func[i]->aux->poke_tab = prog->aux->poke_tab; 18911 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 18912 18913 for (j = 0; j < prog->aux->size_poke_tab; j++) { 18914 struct bpf_jit_poke_descriptor *poke; 18915 18916 poke = &prog->aux->poke_tab[j]; 18917 if (poke->insn_idx < subprog_end && 18918 poke->insn_idx >= subprog_start) 18919 poke->aux = func[i]->aux; 18920 } 18921 18922 func[i]->aux->name[0] = 'F'; 18923 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 18924 func[i]->jit_requested = 1; 18925 func[i]->blinding_requested = prog->blinding_requested; 18926 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 18927 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 18928 func[i]->aux->linfo = prog->aux->linfo; 18929 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 18930 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 18931 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 18932 num_exentries = 0; 18933 insn = func[i]->insnsi; 18934 for (j = 0; j < func[i]->len; j++, insn++) { 18935 if (BPF_CLASS(insn->code) == BPF_LDX && 18936 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 18937 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 18938 num_exentries++; 18939 } 18940 func[i]->aux->num_exentries = num_exentries; 18941 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 18942 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb; 18943 if (!i) 18944 func[i]->aux->exception_boundary = env->seen_exception; 18945 func[i] = bpf_int_jit_compile(func[i]); 18946 if (!func[i]->jited) { 18947 err = -ENOTSUPP; 18948 goto out_free; 18949 } 18950 cond_resched(); 18951 } 18952 18953 /* at this point all bpf functions were successfully JITed 18954 * now populate all bpf_calls with correct addresses and 18955 * run last pass of JIT 18956 */ 18957 for (i = 0; i < env->subprog_cnt; i++) { 18958 insn = func[i]->insnsi; 18959 for (j = 0; j < func[i]->len; j++, insn++) { 18960 if (bpf_pseudo_func(insn)) { 18961 subprog = insn->off; 18962 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 18963 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 18964 continue; 18965 } 18966 if (!bpf_pseudo_call(insn)) 18967 continue; 18968 subprog = insn->off; 18969 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 18970 } 18971 18972 /* we use the aux data to keep a list of the start addresses 18973 * of the JITed images for each function in the program 18974 * 18975 * for some architectures, such as powerpc64, the imm field 18976 * might not be large enough to hold the offset of the start 18977 * address of the callee's JITed image from __bpf_call_base 18978 * 18979 * in such cases, we can lookup the start address of a callee 18980 * by using its subprog id, available from the off field of 18981 * the call instruction, as an index for this list 18982 */ 18983 func[i]->aux->func = func; 18984 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 18985 func[i]->aux->real_func_cnt = env->subprog_cnt; 18986 } 18987 for (i = 0; i < env->subprog_cnt; i++) { 18988 old_bpf_func = func[i]->bpf_func; 18989 tmp = bpf_int_jit_compile(func[i]); 18990 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 18991 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 18992 err = -ENOTSUPP; 18993 goto out_free; 18994 } 18995 cond_resched(); 18996 } 18997 18998 /* finally lock prog and jit images for all functions and 18999 * populate kallsysm. Begin at the first subprogram, since 19000 * bpf_prog_load will add the kallsyms for the main program. 19001 */ 19002 for (i = 1; i < env->subprog_cnt; i++) { 19003 bpf_prog_lock_ro(func[i]); 19004 bpf_prog_kallsyms_add(func[i]); 19005 } 19006 19007 /* Last step: make now unused interpreter insns from main 19008 * prog consistent for later dump requests, so they can 19009 * later look the same as if they were interpreted only. 19010 */ 19011 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 19012 if (bpf_pseudo_func(insn)) { 19013 insn[0].imm = env->insn_aux_data[i].call_imm; 19014 insn[1].imm = insn->off; 19015 insn->off = 0; 19016 continue; 19017 } 19018 if (!bpf_pseudo_call(insn)) 19019 continue; 19020 insn->off = env->insn_aux_data[i].call_imm; 19021 subprog = find_subprog(env, i + insn->off + 1); 19022 insn->imm = subprog; 19023 } 19024 19025 prog->jited = 1; 19026 prog->bpf_func = func[0]->bpf_func; 19027 prog->jited_len = func[0]->jited_len; 19028 prog->aux->extable = func[0]->aux->extable; 19029 prog->aux->num_exentries = func[0]->aux->num_exentries; 19030 prog->aux->func = func; 19031 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 19032 prog->aux->real_func_cnt = env->subprog_cnt; 19033 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func; 19034 prog->aux->exception_boundary = func[0]->aux->exception_boundary; 19035 bpf_prog_jit_attempt_done(prog); 19036 return 0; 19037 out_free: 19038 /* We failed JIT'ing, so at this point we need to unregister poke 19039 * descriptors from subprogs, so that kernel is not attempting to 19040 * patch it anymore as we're freeing the subprog JIT memory. 19041 */ 19042 for (i = 0; i < prog->aux->size_poke_tab; i++) { 19043 map_ptr = prog->aux->poke_tab[i].tail_call.map; 19044 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 19045 } 19046 /* At this point we're guaranteed that poke descriptors are not 19047 * live anymore. We can just unlink its descriptor table as it's 19048 * released with the main prog. 19049 */ 19050 for (i = 0; i < env->subprog_cnt; i++) { 19051 if (!func[i]) 19052 continue; 19053 func[i]->aux->poke_tab = NULL; 19054 bpf_jit_free(func[i]); 19055 } 19056 kfree(func); 19057 out_undo_insn: 19058 /* cleanup main prog to be interpreted */ 19059 prog->jit_requested = 0; 19060 prog->blinding_requested = 0; 19061 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 19062 if (!bpf_pseudo_call(insn)) 19063 continue; 19064 insn->off = 0; 19065 insn->imm = env->insn_aux_data[i].call_imm; 19066 } 19067 bpf_prog_jit_attempt_done(prog); 19068 return err; 19069 } 19070 19071 static int fixup_call_args(struct bpf_verifier_env *env) 19072 { 19073 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 19074 struct bpf_prog *prog = env->prog; 19075 struct bpf_insn *insn = prog->insnsi; 19076 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 19077 int i, depth; 19078 #endif 19079 int err = 0; 19080 19081 if (env->prog->jit_requested && 19082 !bpf_prog_is_offloaded(env->prog->aux)) { 19083 err = jit_subprogs(env); 19084 if (err == 0) 19085 return 0; 19086 if (err == -EFAULT) 19087 return err; 19088 } 19089 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 19090 if (has_kfunc_call) { 19091 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 19092 return -EINVAL; 19093 } 19094 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 19095 /* When JIT fails the progs with bpf2bpf calls and tail_calls 19096 * have to be rejected, since interpreter doesn't support them yet. 19097 */ 19098 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 19099 return -EINVAL; 19100 } 19101 for (i = 0; i < prog->len; i++, insn++) { 19102 if (bpf_pseudo_func(insn)) { 19103 /* When JIT fails the progs with callback calls 19104 * have to be rejected, since interpreter doesn't support them yet. 19105 */ 19106 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 19107 return -EINVAL; 19108 } 19109 19110 if (!bpf_pseudo_call(insn)) 19111 continue; 19112 depth = get_callee_stack_depth(env, insn, i); 19113 if (depth < 0) 19114 return depth; 19115 bpf_patch_call_args(insn, depth); 19116 } 19117 err = 0; 19118 #endif 19119 return err; 19120 } 19121 19122 /* replace a generic kfunc with a specialized version if necessary */ 19123 static void specialize_kfunc(struct bpf_verifier_env *env, 19124 u32 func_id, u16 offset, unsigned long *addr) 19125 { 19126 struct bpf_prog *prog = env->prog; 19127 bool seen_direct_write; 19128 void *xdp_kfunc; 19129 bool is_rdonly; 19130 19131 if (bpf_dev_bound_kfunc_id(func_id)) { 19132 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 19133 if (xdp_kfunc) { 19134 *addr = (unsigned long)xdp_kfunc; 19135 return; 19136 } 19137 /* fallback to default kfunc when not supported by netdev */ 19138 } 19139 19140 if (offset) 19141 return; 19142 19143 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 19144 seen_direct_write = env->seen_direct_write; 19145 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 19146 19147 if (is_rdonly) 19148 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 19149 19150 /* restore env->seen_direct_write to its original value, since 19151 * may_access_direct_pkt_data mutates it 19152 */ 19153 env->seen_direct_write = seen_direct_write; 19154 } 19155 } 19156 19157 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 19158 u16 struct_meta_reg, 19159 u16 node_offset_reg, 19160 struct bpf_insn *insn, 19161 struct bpf_insn *insn_buf, 19162 int *cnt) 19163 { 19164 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 19165 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 19166 19167 insn_buf[0] = addr[0]; 19168 insn_buf[1] = addr[1]; 19169 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 19170 insn_buf[3] = *insn; 19171 *cnt = 4; 19172 } 19173 19174 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 19175 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 19176 { 19177 const struct bpf_kfunc_desc *desc; 19178 19179 if (!insn->imm) { 19180 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 19181 return -EINVAL; 19182 } 19183 19184 *cnt = 0; 19185 19186 /* insn->imm has the btf func_id. Replace it with an offset relative to 19187 * __bpf_call_base, unless the JIT needs to call functions that are 19188 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 19189 */ 19190 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 19191 if (!desc) { 19192 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 19193 insn->imm); 19194 return -EFAULT; 19195 } 19196 19197 if (!bpf_jit_supports_far_kfunc_call()) 19198 insn->imm = BPF_CALL_IMM(desc->addr); 19199 if (insn->off) 19200 return 0; 19201 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 19202 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 19203 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19204 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19205 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 19206 19207 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) { 19208 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 19209 insn_idx); 19210 return -EFAULT; 19211 } 19212 19213 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 19214 insn_buf[1] = addr[0]; 19215 insn_buf[2] = addr[1]; 19216 insn_buf[3] = *insn; 19217 *cnt = 4; 19218 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 19219 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] || 19220 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 19221 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19222 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19223 19224 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) { 19225 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 19226 insn_idx); 19227 return -EFAULT; 19228 } 19229 19230 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 19231 !kptr_struct_meta) { 19232 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 19233 insn_idx); 19234 return -EFAULT; 19235 } 19236 19237 insn_buf[0] = addr[0]; 19238 insn_buf[1] = addr[1]; 19239 insn_buf[2] = *insn; 19240 *cnt = 3; 19241 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 19242 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 19243 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 19244 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19245 int struct_meta_reg = BPF_REG_3; 19246 int node_offset_reg = BPF_REG_4; 19247 19248 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 19249 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 19250 struct_meta_reg = BPF_REG_4; 19251 node_offset_reg = BPF_REG_5; 19252 } 19253 19254 if (!kptr_struct_meta) { 19255 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 19256 insn_idx); 19257 return -EFAULT; 19258 } 19259 19260 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 19261 node_offset_reg, insn, insn_buf, cnt); 19262 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 19263 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 19264 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 19265 *cnt = 1; 19266 } 19267 return 0; 19268 } 19269 19270 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */ 19271 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len) 19272 { 19273 struct bpf_subprog_info *info = env->subprog_info; 19274 int cnt = env->subprog_cnt; 19275 struct bpf_prog *prog; 19276 19277 /* We only reserve one slot for hidden subprogs in subprog_info. */ 19278 if (env->hidden_subprog_cnt) { 19279 verbose(env, "verifier internal error: only one hidden subprog supported\n"); 19280 return -EFAULT; 19281 } 19282 /* We're not patching any existing instruction, just appending the new 19283 * ones for the hidden subprog. Hence all of the adjustment operations 19284 * in bpf_patch_insn_data are no-ops. 19285 */ 19286 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len); 19287 if (!prog) 19288 return -ENOMEM; 19289 env->prog = prog; 19290 info[cnt + 1].start = info[cnt].start; 19291 info[cnt].start = prog->len - len + 1; 19292 env->subprog_cnt++; 19293 env->hidden_subprog_cnt++; 19294 return 0; 19295 } 19296 19297 /* Do various post-verification rewrites in a single program pass. 19298 * These rewrites simplify JIT and interpreter implementations. 19299 */ 19300 static int do_misc_fixups(struct bpf_verifier_env *env) 19301 { 19302 struct bpf_prog *prog = env->prog; 19303 enum bpf_attach_type eatype = prog->expected_attach_type; 19304 enum bpf_prog_type prog_type = resolve_prog_type(prog); 19305 struct bpf_insn *insn = prog->insnsi; 19306 const struct bpf_func_proto *fn; 19307 const int insn_cnt = prog->len; 19308 const struct bpf_map_ops *ops; 19309 struct bpf_insn_aux_data *aux; 19310 struct bpf_insn insn_buf[16]; 19311 struct bpf_prog *new_prog; 19312 struct bpf_map *map_ptr; 19313 int i, ret, cnt, delta = 0; 19314 19315 if (env->seen_exception && !env->exception_callback_subprog) { 19316 struct bpf_insn patch[] = { 19317 env->prog->insnsi[insn_cnt - 1], 19318 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1), 19319 BPF_EXIT_INSN(), 19320 }; 19321 19322 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch)); 19323 if (ret < 0) 19324 return ret; 19325 prog = env->prog; 19326 insn = prog->insnsi; 19327 19328 env->exception_callback_subprog = env->subprog_cnt - 1; 19329 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */ 19330 mark_subprog_exc_cb(env, env->exception_callback_subprog); 19331 } 19332 19333 for (i = 0; i < insn_cnt; i++, insn++) { 19334 /* Make divide-by-zero exceptions impossible. */ 19335 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 19336 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 19337 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 19338 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 19339 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 19340 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 19341 struct bpf_insn *patchlet; 19342 struct bpf_insn chk_and_div[] = { 19343 /* [R,W]x div 0 -> 0 */ 19344 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 19345 BPF_JNE | BPF_K, insn->src_reg, 19346 0, 2, 0), 19347 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 19348 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 19349 *insn, 19350 }; 19351 struct bpf_insn chk_and_mod[] = { 19352 /* [R,W]x mod 0 -> [R,W]x */ 19353 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 19354 BPF_JEQ | BPF_K, insn->src_reg, 19355 0, 1 + (is64 ? 0 : 1), 0), 19356 *insn, 19357 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 19358 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 19359 }; 19360 19361 patchlet = isdiv ? chk_and_div : chk_and_mod; 19362 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 19363 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 19364 19365 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 19366 if (!new_prog) 19367 return -ENOMEM; 19368 19369 delta += cnt - 1; 19370 env->prog = prog = new_prog; 19371 insn = new_prog->insnsi + i + delta; 19372 continue; 19373 } 19374 19375 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 19376 if (BPF_CLASS(insn->code) == BPF_LD && 19377 (BPF_MODE(insn->code) == BPF_ABS || 19378 BPF_MODE(insn->code) == BPF_IND)) { 19379 cnt = env->ops->gen_ld_abs(insn, insn_buf); 19380 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19381 verbose(env, "bpf verifier is misconfigured\n"); 19382 return -EINVAL; 19383 } 19384 19385 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19386 if (!new_prog) 19387 return -ENOMEM; 19388 19389 delta += cnt - 1; 19390 env->prog = prog = new_prog; 19391 insn = new_prog->insnsi + i + delta; 19392 continue; 19393 } 19394 19395 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 19396 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 19397 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 19398 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 19399 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 19400 struct bpf_insn *patch = &insn_buf[0]; 19401 bool issrc, isneg, isimm; 19402 u32 off_reg; 19403 19404 aux = &env->insn_aux_data[i + delta]; 19405 if (!aux->alu_state || 19406 aux->alu_state == BPF_ALU_NON_POINTER) 19407 continue; 19408 19409 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 19410 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 19411 BPF_ALU_SANITIZE_SRC; 19412 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 19413 19414 off_reg = issrc ? insn->src_reg : insn->dst_reg; 19415 if (isimm) { 19416 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19417 } else { 19418 if (isneg) 19419 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19420 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19421 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 19422 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 19423 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 19424 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 19425 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 19426 } 19427 if (!issrc) 19428 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 19429 insn->src_reg = BPF_REG_AX; 19430 if (isneg) 19431 insn->code = insn->code == code_add ? 19432 code_sub : code_add; 19433 *patch++ = *insn; 19434 if (issrc && isneg && !isimm) 19435 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19436 cnt = patch - insn_buf; 19437 19438 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19439 if (!new_prog) 19440 return -ENOMEM; 19441 19442 delta += cnt - 1; 19443 env->prog = prog = new_prog; 19444 insn = new_prog->insnsi + i + delta; 19445 continue; 19446 } 19447 19448 if (insn->code != (BPF_JMP | BPF_CALL)) 19449 continue; 19450 if (insn->src_reg == BPF_PSEUDO_CALL) 19451 continue; 19452 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 19453 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 19454 if (ret) 19455 return ret; 19456 if (cnt == 0) 19457 continue; 19458 19459 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19460 if (!new_prog) 19461 return -ENOMEM; 19462 19463 delta += cnt - 1; 19464 env->prog = prog = new_prog; 19465 insn = new_prog->insnsi + i + delta; 19466 continue; 19467 } 19468 19469 if (insn->imm == BPF_FUNC_get_route_realm) 19470 prog->dst_needed = 1; 19471 if (insn->imm == BPF_FUNC_get_prandom_u32) 19472 bpf_user_rnd_init_once(); 19473 if (insn->imm == BPF_FUNC_override_return) 19474 prog->kprobe_override = 1; 19475 if (insn->imm == BPF_FUNC_tail_call) { 19476 /* If we tail call into other programs, we 19477 * cannot make any assumptions since they can 19478 * be replaced dynamically during runtime in 19479 * the program array. 19480 */ 19481 prog->cb_access = 1; 19482 if (!allow_tail_call_in_subprogs(env)) 19483 prog->aux->stack_depth = MAX_BPF_STACK; 19484 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 19485 19486 /* mark bpf_tail_call as different opcode to avoid 19487 * conditional branch in the interpreter for every normal 19488 * call and to prevent accidental JITing by JIT compiler 19489 * that doesn't support bpf_tail_call yet 19490 */ 19491 insn->imm = 0; 19492 insn->code = BPF_JMP | BPF_TAIL_CALL; 19493 19494 aux = &env->insn_aux_data[i + delta]; 19495 if (env->bpf_capable && !prog->blinding_requested && 19496 prog->jit_requested && 19497 !bpf_map_key_poisoned(aux) && 19498 !bpf_map_ptr_poisoned(aux) && 19499 !bpf_map_ptr_unpriv(aux)) { 19500 struct bpf_jit_poke_descriptor desc = { 19501 .reason = BPF_POKE_REASON_TAIL_CALL, 19502 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 19503 .tail_call.key = bpf_map_key_immediate(aux), 19504 .insn_idx = i + delta, 19505 }; 19506 19507 ret = bpf_jit_add_poke_descriptor(prog, &desc); 19508 if (ret < 0) { 19509 verbose(env, "adding tail call poke descriptor failed\n"); 19510 return ret; 19511 } 19512 19513 insn->imm = ret + 1; 19514 continue; 19515 } 19516 19517 if (!bpf_map_ptr_unpriv(aux)) 19518 continue; 19519 19520 /* instead of changing every JIT dealing with tail_call 19521 * emit two extra insns: 19522 * if (index >= max_entries) goto out; 19523 * index &= array->index_mask; 19524 * to avoid out-of-bounds cpu speculation 19525 */ 19526 if (bpf_map_ptr_poisoned(aux)) { 19527 verbose(env, "tail_call abusing map_ptr\n"); 19528 return -EINVAL; 19529 } 19530 19531 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19532 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 19533 map_ptr->max_entries, 2); 19534 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 19535 container_of(map_ptr, 19536 struct bpf_array, 19537 map)->index_mask); 19538 insn_buf[2] = *insn; 19539 cnt = 3; 19540 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19541 if (!new_prog) 19542 return -ENOMEM; 19543 19544 delta += cnt - 1; 19545 env->prog = prog = new_prog; 19546 insn = new_prog->insnsi + i + delta; 19547 continue; 19548 } 19549 19550 if (insn->imm == BPF_FUNC_timer_set_callback) { 19551 /* The verifier will process callback_fn as many times as necessary 19552 * with different maps and the register states prepared by 19553 * set_timer_callback_state will be accurate. 19554 * 19555 * The following use case is valid: 19556 * map1 is shared by prog1, prog2, prog3. 19557 * prog1 calls bpf_timer_init for some map1 elements 19558 * prog2 calls bpf_timer_set_callback for some map1 elements. 19559 * Those that were not bpf_timer_init-ed will return -EINVAL. 19560 * prog3 calls bpf_timer_start for some map1 elements. 19561 * Those that were not both bpf_timer_init-ed and 19562 * bpf_timer_set_callback-ed will return -EINVAL. 19563 */ 19564 struct bpf_insn ld_addrs[2] = { 19565 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 19566 }; 19567 19568 insn_buf[0] = ld_addrs[0]; 19569 insn_buf[1] = ld_addrs[1]; 19570 insn_buf[2] = *insn; 19571 cnt = 3; 19572 19573 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19574 if (!new_prog) 19575 return -ENOMEM; 19576 19577 delta += cnt - 1; 19578 env->prog = prog = new_prog; 19579 insn = new_prog->insnsi + i + delta; 19580 goto patch_call_imm; 19581 } 19582 19583 if (is_storage_get_function(insn->imm)) { 19584 if (!env->prog->aux->sleepable || 19585 env->insn_aux_data[i + delta].storage_get_func_atomic) 19586 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 19587 else 19588 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 19589 insn_buf[1] = *insn; 19590 cnt = 2; 19591 19592 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19593 if (!new_prog) 19594 return -ENOMEM; 19595 19596 delta += cnt - 1; 19597 env->prog = prog = new_prog; 19598 insn = new_prog->insnsi + i + delta; 19599 goto patch_call_imm; 19600 } 19601 19602 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */ 19603 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) { 19604 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data, 19605 * bpf_mem_alloc() returns a ptr to the percpu data ptr. 19606 */ 19607 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0); 19608 insn_buf[1] = *insn; 19609 cnt = 2; 19610 19611 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19612 if (!new_prog) 19613 return -ENOMEM; 19614 19615 delta += cnt - 1; 19616 env->prog = prog = new_prog; 19617 insn = new_prog->insnsi + i + delta; 19618 goto patch_call_imm; 19619 } 19620 19621 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 19622 * and other inlining handlers are currently limited to 64 bit 19623 * only. 19624 */ 19625 if (prog->jit_requested && BITS_PER_LONG == 64 && 19626 (insn->imm == BPF_FUNC_map_lookup_elem || 19627 insn->imm == BPF_FUNC_map_update_elem || 19628 insn->imm == BPF_FUNC_map_delete_elem || 19629 insn->imm == BPF_FUNC_map_push_elem || 19630 insn->imm == BPF_FUNC_map_pop_elem || 19631 insn->imm == BPF_FUNC_map_peek_elem || 19632 insn->imm == BPF_FUNC_redirect_map || 19633 insn->imm == BPF_FUNC_for_each_map_elem || 19634 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 19635 aux = &env->insn_aux_data[i + delta]; 19636 if (bpf_map_ptr_poisoned(aux)) 19637 goto patch_call_imm; 19638 19639 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19640 ops = map_ptr->ops; 19641 if (insn->imm == BPF_FUNC_map_lookup_elem && 19642 ops->map_gen_lookup) { 19643 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 19644 if (cnt == -EOPNOTSUPP) 19645 goto patch_map_ops_generic; 19646 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19647 verbose(env, "bpf verifier is misconfigured\n"); 19648 return -EINVAL; 19649 } 19650 19651 new_prog = bpf_patch_insn_data(env, i + delta, 19652 insn_buf, cnt); 19653 if (!new_prog) 19654 return -ENOMEM; 19655 19656 delta += cnt - 1; 19657 env->prog = prog = new_prog; 19658 insn = new_prog->insnsi + i + delta; 19659 continue; 19660 } 19661 19662 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 19663 (void *(*)(struct bpf_map *map, void *key))NULL)); 19664 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 19665 (long (*)(struct bpf_map *map, void *key))NULL)); 19666 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 19667 (long (*)(struct bpf_map *map, void *key, void *value, 19668 u64 flags))NULL)); 19669 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 19670 (long (*)(struct bpf_map *map, void *value, 19671 u64 flags))NULL)); 19672 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 19673 (long (*)(struct bpf_map *map, void *value))NULL)); 19674 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 19675 (long (*)(struct bpf_map *map, void *value))NULL)); 19676 BUILD_BUG_ON(!__same_type(ops->map_redirect, 19677 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 19678 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 19679 (long (*)(struct bpf_map *map, 19680 bpf_callback_t callback_fn, 19681 void *callback_ctx, 19682 u64 flags))NULL)); 19683 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 19684 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 19685 19686 patch_map_ops_generic: 19687 switch (insn->imm) { 19688 case BPF_FUNC_map_lookup_elem: 19689 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 19690 continue; 19691 case BPF_FUNC_map_update_elem: 19692 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 19693 continue; 19694 case BPF_FUNC_map_delete_elem: 19695 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 19696 continue; 19697 case BPF_FUNC_map_push_elem: 19698 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 19699 continue; 19700 case BPF_FUNC_map_pop_elem: 19701 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 19702 continue; 19703 case BPF_FUNC_map_peek_elem: 19704 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 19705 continue; 19706 case BPF_FUNC_redirect_map: 19707 insn->imm = BPF_CALL_IMM(ops->map_redirect); 19708 continue; 19709 case BPF_FUNC_for_each_map_elem: 19710 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 19711 continue; 19712 case BPF_FUNC_map_lookup_percpu_elem: 19713 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 19714 continue; 19715 } 19716 19717 goto patch_call_imm; 19718 } 19719 19720 /* Implement bpf_jiffies64 inline. */ 19721 if (prog->jit_requested && BITS_PER_LONG == 64 && 19722 insn->imm == BPF_FUNC_jiffies64) { 19723 struct bpf_insn ld_jiffies_addr[2] = { 19724 BPF_LD_IMM64(BPF_REG_0, 19725 (unsigned long)&jiffies), 19726 }; 19727 19728 insn_buf[0] = ld_jiffies_addr[0]; 19729 insn_buf[1] = ld_jiffies_addr[1]; 19730 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 19731 BPF_REG_0, 0); 19732 cnt = 3; 19733 19734 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 19735 cnt); 19736 if (!new_prog) 19737 return -ENOMEM; 19738 19739 delta += cnt - 1; 19740 env->prog = prog = new_prog; 19741 insn = new_prog->insnsi + i + delta; 19742 continue; 19743 } 19744 19745 /* Implement bpf_get_func_arg inline. */ 19746 if (prog_type == BPF_PROG_TYPE_TRACING && 19747 insn->imm == BPF_FUNC_get_func_arg) { 19748 /* Load nr_args from ctx - 8 */ 19749 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19750 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 19751 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 19752 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 19753 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 19754 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19755 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 19756 insn_buf[7] = BPF_JMP_A(1); 19757 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 19758 cnt = 9; 19759 19760 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19761 if (!new_prog) 19762 return -ENOMEM; 19763 19764 delta += cnt - 1; 19765 env->prog = prog = new_prog; 19766 insn = new_prog->insnsi + i + delta; 19767 continue; 19768 } 19769 19770 /* Implement bpf_get_func_ret inline. */ 19771 if (prog_type == BPF_PROG_TYPE_TRACING && 19772 insn->imm == BPF_FUNC_get_func_ret) { 19773 if (eatype == BPF_TRACE_FEXIT || 19774 eatype == BPF_MODIFY_RETURN) { 19775 /* Load nr_args from ctx - 8 */ 19776 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19777 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 19778 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 19779 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19780 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 19781 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 19782 cnt = 6; 19783 } else { 19784 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 19785 cnt = 1; 19786 } 19787 19788 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19789 if (!new_prog) 19790 return -ENOMEM; 19791 19792 delta += cnt - 1; 19793 env->prog = prog = new_prog; 19794 insn = new_prog->insnsi + i + delta; 19795 continue; 19796 } 19797 19798 /* Implement get_func_arg_cnt inline. */ 19799 if (prog_type == BPF_PROG_TYPE_TRACING && 19800 insn->imm == BPF_FUNC_get_func_arg_cnt) { 19801 /* Load nr_args from ctx - 8 */ 19802 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19803 19804 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19805 if (!new_prog) 19806 return -ENOMEM; 19807 19808 env->prog = prog = new_prog; 19809 insn = new_prog->insnsi + i + delta; 19810 continue; 19811 } 19812 19813 /* Implement bpf_get_func_ip inline. */ 19814 if (prog_type == BPF_PROG_TYPE_TRACING && 19815 insn->imm == BPF_FUNC_get_func_ip) { 19816 /* Load IP address from ctx - 16 */ 19817 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 19818 19819 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19820 if (!new_prog) 19821 return -ENOMEM; 19822 19823 env->prog = prog = new_prog; 19824 insn = new_prog->insnsi + i + delta; 19825 continue; 19826 } 19827 19828 /* Implement bpf_kptr_xchg inline */ 19829 if (prog->jit_requested && BITS_PER_LONG == 64 && 19830 insn->imm == BPF_FUNC_kptr_xchg && 19831 bpf_jit_supports_ptr_xchg()) { 19832 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2); 19833 insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0); 19834 cnt = 2; 19835 19836 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19837 if (!new_prog) 19838 return -ENOMEM; 19839 19840 delta += cnt - 1; 19841 env->prog = prog = new_prog; 19842 insn = new_prog->insnsi + i + delta; 19843 continue; 19844 } 19845 patch_call_imm: 19846 fn = env->ops->get_func_proto(insn->imm, env->prog); 19847 /* all functions that have prototype and verifier allowed 19848 * programs to call them, must be real in-kernel functions 19849 */ 19850 if (!fn->func) { 19851 verbose(env, 19852 "kernel subsystem misconfigured func %s#%d\n", 19853 func_id_name(insn->imm), insn->imm); 19854 return -EFAULT; 19855 } 19856 insn->imm = fn->func - __bpf_call_base; 19857 } 19858 19859 /* Since poke tab is now finalized, publish aux to tracker. */ 19860 for (i = 0; i < prog->aux->size_poke_tab; i++) { 19861 map_ptr = prog->aux->poke_tab[i].tail_call.map; 19862 if (!map_ptr->ops->map_poke_track || 19863 !map_ptr->ops->map_poke_untrack || 19864 !map_ptr->ops->map_poke_run) { 19865 verbose(env, "bpf verifier is misconfigured\n"); 19866 return -EINVAL; 19867 } 19868 19869 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 19870 if (ret < 0) { 19871 verbose(env, "tracking tail call prog failed\n"); 19872 return ret; 19873 } 19874 } 19875 19876 sort_kfunc_descs_by_imm_off(env->prog); 19877 19878 return 0; 19879 } 19880 19881 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 19882 int position, 19883 s32 stack_base, 19884 u32 callback_subprogno, 19885 u32 *cnt) 19886 { 19887 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 19888 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 19889 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 19890 int reg_loop_max = BPF_REG_6; 19891 int reg_loop_cnt = BPF_REG_7; 19892 int reg_loop_ctx = BPF_REG_8; 19893 19894 struct bpf_prog *new_prog; 19895 u32 callback_start; 19896 u32 call_insn_offset; 19897 s32 callback_offset; 19898 19899 /* This represents an inlined version of bpf_iter.c:bpf_loop, 19900 * be careful to modify this code in sync. 19901 */ 19902 struct bpf_insn insn_buf[] = { 19903 /* Return error and jump to the end of the patch if 19904 * expected number of iterations is too big. 19905 */ 19906 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 19907 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 19908 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 19909 /* spill R6, R7, R8 to use these as loop vars */ 19910 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 19911 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 19912 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 19913 /* initialize loop vars */ 19914 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 19915 BPF_MOV32_IMM(reg_loop_cnt, 0), 19916 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 19917 /* loop header, 19918 * if reg_loop_cnt >= reg_loop_max skip the loop body 19919 */ 19920 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 19921 /* callback call, 19922 * correct callback offset would be set after patching 19923 */ 19924 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 19925 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 19926 BPF_CALL_REL(0), 19927 /* increment loop counter */ 19928 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 19929 /* jump to loop header if callback returned 0 */ 19930 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 19931 /* return value of bpf_loop, 19932 * set R0 to the number of iterations 19933 */ 19934 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 19935 /* restore original values of R6, R7, R8 */ 19936 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 19937 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 19938 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 19939 }; 19940 19941 *cnt = ARRAY_SIZE(insn_buf); 19942 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 19943 if (!new_prog) 19944 return new_prog; 19945 19946 /* callback start is known only after patching */ 19947 callback_start = env->subprog_info[callback_subprogno].start; 19948 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 19949 call_insn_offset = position + 12; 19950 callback_offset = callback_start - call_insn_offset - 1; 19951 new_prog->insnsi[call_insn_offset].imm = callback_offset; 19952 19953 return new_prog; 19954 } 19955 19956 static bool is_bpf_loop_call(struct bpf_insn *insn) 19957 { 19958 return insn->code == (BPF_JMP | BPF_CALL) && 19959 insn->src_reg == 0 && 19960 insn->imm == BPF_FUNC_loop; 19961 } 19962 19963 /* For all sub-programs in the program (including main) check 19964 * insn_aux_data to see if there are bpf_loop calls that require 19965 * inlining. If such calls are found the calls are replaced with a 19966 * sequence of instructions produced by `inline_bpf_loop` function and 19967 * subprog stack_depth is increased by the size of 3 registers. 19968 * This stack space is used to spill values of the R6, R7, R8. These 19969 * registers are used to store the loop bound, counter and context 19970 * variables. 19971 */ 19972 static int optimize_bpf_loop(struct bpf_verifier_env *env) 19973 { 19974 struct bpf_subprog_info *subprogs = env->subprog_info; 19975 int i, cur_subprog = 0, cnt, delta = 0; 19976 struct bpf_insn *insn = env->prog->insnsi; 19977 int insn_cnt = env->prog->len; 19978 u16 stack_depth = subprogs[cur_subprog].stack_depth; 19979 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19980 u16 stack_depth_extra = 0; 19981 19982 for (i = 0; i < insn_cnt; i++, insn++) { 19983 struct bpf_loop_inline_state *inline_state = 19984 &env->insn_aux_data[i + delta].loop_inline_state; 19985 19986 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 19987 struct bpf_prog *new_prog; 19988 19989 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 19990 new_prog = inline_bpf_loop(env, 19991 i + delta, 19992 -(stack_depth + stack_depth_extra), 19993 inline_state->callback_subprogno, 19994 &cnt); 19995 if (!new_prog) 19996 return -ENOMEM; 19997 19998 delta += cnt - 1; 19999 env->prog = new_prog; 20000 insn = new_prog->insnsi + i + delta; 20001 } 20002 20003 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 20004 subprogs[cur_subprog].stack_depth += stack_depth_extra; 20005 cur_subprog++; 20006 stack_depth = subprogs[cur_subprog].stack_depth; 20007 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 20008 stack_depth_extra = 0; 20009 } 20010 } 20011 20012 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 20013 20014 return 0; 20015 } 20016 20017 static void free_states(struct bpf_verifier_env *env) 20018 { 20019 struct bpf_verifier_state_list *sl, *sln; 20020 int i; 20021 20022 sl = env->free_list; 20023 while (sl) { 20024 sln = sl->next; 20025 free_verifier_state(&sl->state, false); 20026 kfree(sl); 20027 sl = sln; 20028 } 20029 env->free_list = NULL; 20030 20031 if (!env->explored_states) 20032 return; 20033 20034 for (i = 0; i < state_htab_size(env); i++) { 20035 sl = env->explored_states[i]; 20036 20037 while (sl) { 20038 sln = sl->next; 20039 free_verifier_state(&sl->state, false); 20040 kfree(sl); 20041 sl = sln; 20042 } 20043 env->explored_states[i] = NULL; 20044 } 20045 } 20046 20047 static int do_check_common(struct bpf_verifier_env *env, int subprog) 20048 { 20049 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 20050 struct bpf_subprog_info *sub = subprog_info(env, subprog); 20051 struct bpf_verifier_state *state; 20052 struct bpf_reg_state *regs; 20053 int ret, i; 20054 20055 env->prev_linfo = NULL; 20056 env->pass_cnt++; 20057 20058 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 20059 if (!state) 20060 return -ENOMEM; 20061 state->curframe = 0; 20062 state->speculative = false; 20063 state->branches = 1; 20064 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 20065 if (!state->frame[0]) { 20066 kfree(state); 20067 return -ENOMEM; 20068 } 20069 env->cur_state = state; 20070 init_func_state(env, state->frame[0], 20071 BPF_MAIN_FUNC /* callsite */, 20072 0 /* frameno */, 20073 subprog); 20074 state->first_insn_idx = env->subprog_info[subprog].start; 20075 state->last_insn_idx = -1; 20076 20077 regs = state->frame[state->curframe]->regs; 20078 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 20079 const char *sub_name = subprog_name(env, subprog); 20080 struct bpf_subprog_arg_info *arg; 20081 struct bpf_reg_state *reg; 20082 20083 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 20084 ret = btf_prepare_func_args(env, subprog); 20085 if (ret) 20086 goto out; 20087 20088 if (subprog_is_exc_cb(env, subprog)) { 20089 state->frame[0]->in_exception_callback_fn = true; 20090 /* We have already ensured that the callback returns an integer, just 20091 * like all global subprogs. We need to determine it only has a single 20092 * scalar argument. 20093 */ 20094 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 20095 verbose(env, "exception cb only supports single integer argument\n"); 20096 ret = -EINVAL; 20097 goto out; 20098 } 20099 } 20100 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) { 20101 arg = &sub->args[i - BPF_REG_1]; 20102 reg = ®s[i]; 20103 20104 if (arg->arg_type == ARG_PTR_TO_CTX) { 20105 reg->type = PTR_TO_CTX; 20106 mark_reg_known_zero(env, regs, i); 20107 } else if (arg->arg_type == ARG_ANYTHING) { 20108 reg->type = SCALAR_VALUE; 20109 mark_reg_unknown(env, regs, i); 20110 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 20111 /* assume unspecial LOCAL dynptr type */ 20112 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen); 20113 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 20114 reg->type = PTR_TO_MEM; 20115 if (arg->arg_type & PTR_MAYBE_NULL) 20116 reg->type |= PTR_MAYBE_NULL; 20117 mark_reg_known_zero(env, regs, i); 20118 reg->mem_size = arg->mem_size; 20119 reg->id = ++env->id_gen; 20120 } else { 20121 WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n", 20122 i - BPF_REG_1, arg->arg_type); 20123 ret = -EFAULT; 20124 goto out; 20125 } 20126 } 20127 } else { 20128 /* if main BPF program has associated BTF info, validate that 20129 * it's matching expected signature, and otherwise mark BTF 20130 * info for main program as unreliable 20131 */ 20132 if (env->prog->aux->func_info_aux) { 20133 ret = btf_prepare_func_args(env, 0); 20134 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) 20135 env->prog->aux->func_info_aux[0].unreliable = true; 20136 } 20137 20138 /* 1st arg to a function */ 20139 regs[BPF_REG_1].type = PTR_TO_CTX; 20140 mark_reg_known_zero(env, regs, BPF_REG_1); 20141 } 20142 20143 ret = do_check(env); 20144 out: 20145 /* check for NULL is necessary, since cur_state can be freed inside 20146 * do_check() under memory pressure. 20147 */ 20148 if (env->cur_state) { 20149 free_verifier_state(env->cur_state, true); 20150 env->cur_state = NULL; 20151 } 20152 while (!pop_stack(env, NULL, NULL, false)); 20153 if (!ret && pop_log) 20154 bpf_vlog_reset(&env->log, 0); 20155 free_states(env); 20156 return ret; 20157 } 20158 20159 /* Lazily verify all global functions based on their BTF, if they are called 20160 * from main BPF program or any of subprograms transitively. 20161 * BPF global subprogs called from dead code are not validated. 20162 * All callable global functions must pass verification. 20163 * Otherwise the whole program is rejected. 20164 * Consider: 20165 * int bar(int); 20166 * int foo(int f) 20167 * { 20168 * return bar(f); 20169 * } 20170 * int bar(int b) 20171 * { 20172 * ... 20173 * } 20174 * foo() will be verified first for R1=any_scalar_value. During verification it 20175 * will be assumed that bar() already verified successfully and call to bar() 20176 * from foo() will be checked for type match only. Later bar() will be verified 20177 * independently to check that it's safe for R1=any_scalar_value. 20178 */ 20179 static int do_check_subprogs(struct bpf_verifier_env *env) 20180 { 20181 struct bpf_prog_aux *aux = env->prog->aux; 20182 struct bpf_func_info_aux *sub_aux; 20183 int i, ret, new_cnt; 20184 20185 if (!aux->func_info) 20186 return 0; 20187 20188 /* exception callback is presumed to be always called */ 20189 if (env->exception_callback_subprog) 20190 subprog_aux(env, env->exception_callback_subprog)->called = true; 20191 20192 again: 20193 new_cnt = 0; 20194 for (i = 1; i < env->subprog_cnt; i++) { 20195 if (!subprog_is_global(env, i)) 20196 continue; 20197 20198 sub_aux = subprog_aux(env, i); 20199 if (!sub_aux->called || sub_aux->verified) 20200 continue; 20201 20202 env->insn_idx = env->subprog_info[i].start; 20203 WARN_ON_ONCE(env->insn_idx == 0); 20204 ret = do_check_common(env, i); 20205 if (ret) { 20206 return ret; 20207 } else if (env->log.level & BPF_LOG_LEVEL) { 20208 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 20209 i, subprog_name(env, i)); 20210 } 20211 20212 /* We verified new global subprog, it might have called some 20213 * more global subprogs that we haven't verified yet, so we 20214 * need to do another pass over subprogs to verify those. 20215 */ 20216 sub_aux->verified = true; 20217 new_cnt++; 20218 } 20219 20220 /* We can't loop forever as we verify at least one global subprog on 20221 * each pass. 20222 */ 20223 if (new_cnt) 20224 goto again; 20225 20226 return 0; 20227 } 20228 20229 static int do_check_main(struct bpf_verifier_env *env) 20230 { 20231 int ret; 20232 20233 env->insn_idx = 0; 20234 ret = do_check_common(env, 0); 20235 if (!ret) 20236 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 20237 return ret; 20238 } 20239 20240 20241 static void print_verification_stats(struct bpf_verifier_env *env) 20242 { 20243 int i; 20244 20245 if (env->log.level & BPF_LOG_STATS) { 20246 verbose(env, "verification time %lld usec\n", 20247 div_u64(env->verification_time, 1000)); 20248 verbose(env, "stack depth "); 20249 for (i = 0; i < env->subprog_cnt; i++) { 20250 u32 depth = env->subprog_info[i].stack_depth; 20251 20252 verbose(env, "%d", depth); 20253 if (i + 1 < env->subprog_cnt) 20254 verbose(env, "+"); 20255 } 20256 verbose(env, "\n"); 20257 } 20258 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 20259 "total_states %d peak_states %d mark_read %d\n", 20260 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 20261 env->max_states_per_insn, env->total_states, 20262 env->peak_states, env->longest_mark_read_walk); 20263 } 20264 20265 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 20266 { 20267 const struct btf_type *t, *func_proto; 20268 const struct bpf_struct_ops *st_ops; 20269 const struct btf_member *member; 20270 struct bpf_prog *prog = env->prog; 20271 u32 btf_id, member_idx; 20272 const char *mname; 20273 20274 if (!prog->gpl_compatible) { 20275 verbose(env, "struct ops programs must have a GPL compatible license\n"); 20276 return -EINVAL; 20277 } 20278 20279 btf_id = prog->aux->attach_btf_id; 20280 st_ops = bpf_struct_ops_find(btf_id); 20281 if (!st_ops) { 20282 verbose(env, "attach_btf_id %u is not a supported struct\n", 20283 btf_id); 20284 return -ENOTSUPP; 20285 } 20286 20287 t = st_ops->type; 20288 member_idx = prog->expected_attach_type; 20289 if (member_idx >= btf_type_vlen(t)) { 20290 verbose(env, "attach to invalid member idx %u of struct %s\n", 20291 member_idx, st_ops->name); 20292 return -EINVAL; 20293 } 20294 20295 member = &btf_type_member(t)[member_idx]; 20296 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 20297 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 20298 NULL); 20299 if (!func_proto) { 20300 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 20301 mname, member_idx, st_ops->name); 20302 return -EINVAL; 20303 } 20304 20305 if (st_ops->check_member) { 20306 int err = st_ops->check_member(t, member, prog); 20307 20308 if (err) { 20309 verbose(env, "attach to unsupported member %s of struct %s\n", 20310 mname, st_ops->name); 20311 return err; 20312 } 20313 } 20314 20315 prog->aux->attach_func_proto = func_proto; 20316 prog->aux->attach_func_name = mname; 20317 env->ops = st_ops->verifier_ops; 20318 20319 return 0; 20320 } 20321 #define SECURITY_PREFIX "security_" 20322 20323 static int check_attach_modify_return(unsigned long addr, const char *func_name) 20324 { 20325 if (within_error_injection_list(addr) || 20326 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 20327 return 0; 20328 20329 return -EINVAL; 20330 } 20331 20332 /* list of non-sleepable functions that are otherwise on 20333 * ALLOW_ERROR_INJECTION list 20334 */ 20335 BTF_SET_START(btf_non_sleepable_error_inject) 20336 /* Three functions below can be called from sleepable and non-sleepable context. 20337 * Assume non-sleepable from bpf safety point of view. 20338 */ 20339 BTF_ID(func, __filemap_add_folio) 20340 BTF_ID(func, should_fail_alloc_page) 20341 BTF_ID(func, should_failslab) 20342 BTF_SET_END(btf_non_sleepable_error_inject) 20343 20344 static int check_non_sleepable_error_inject(u32 btf_id) 20345 { 20346 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 20347 } 20348 20349 int bpf_check_attach_target(struct bpf_verifier_log *log, 20350 const struct bpf_prog *prog, 20351 const struct bpf_prog *tgt_prog, 20352 u32 btf_id, 20353 struct bpf_attach_target_info *tgt_info) 20354 { 20355 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 20356 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 20357 const char prefix[] = "btf_trace_"; 20358 int ret = 0, subprog = -1, i; 20359 const struct btf_type *t; 20360 bool conservative = true; 20361 const char *tname; 20362 struct btf *btf; 20363 long addr = 0; 20364 struct module *mod = NULL; 20365 20366 if (!btf_id) { 20367 bpf_log(log, "Tracing programs must provide btf_id\n"); 20368 return -EINVAL; 20369 } 20370 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 20371 if (!btf) { 20372 bpf_log(log, 20373 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 20374 return -EINVAL; 20375 } 20376 t = btf_type_by_id(btf, btf_id); 20377 if (!t) { 20378 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 20379 return -EINVAL; 20380 } 20381 tname = btf_name_by_offset(btf, t->name_off); 20382 if (!tname) { 20383 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 20384 return -EINVAL; 20385 } 20386 if (tgt_prog) { 20387 struct bpf_prog_aux *aux = tgt_prog->aux; 20388 20389 if (bpf_prog_is_dev_bound(prog->aux) && 20390 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 20391 bpf_log(log, "Target program bound device mismatch"); 20392 return -EINVAL; 20393 } 20394 20395 for (i = 0; i < aux->func_info_cnt; i++) 20396 if (aux->func_info[i].type_id == btf_id) { 20397 subprog = i; 20398 break; 20399 } 20400 if (subprog == -1) { 20401 bpf_log(log, "Subprog %s doesn't exist\n", tname); 20402 return -EINVAL; 20403 } 20404 if (aux->func && aux->func[subprog]->aux->exception_cb) { 20405 bpf_log(log, 20406 "%s programs cannot attach to exception callback\n", 20407 prog_extension ? "Extension" : "FENTRY/FEXIT"); 20408 return -EINVAL; 20409 } 20410 conservative = aux->func_info_aux[subprog].unreliable; 20411 if (prog_extension) { 20412 if (conservative) { 20413 bpf_log(log, 20414 "Cannot replace static functions\n"); 20415 return -EINVAL; 20416 } 20417 if (!prog->jit_requested) { 20418 bpf_log(log, 20419 "Extension programs should be JITed\n"); 20420 return -EINVAL; 20421 } 20422 } 20423 if (!tgt_prog->jited) { 20424 bpf_log(log, "Can attach to only JITed progs\n"); 20425 return -EINVAL; 20426 } 20427 if (prog_tracing) { 20428 if (aux->attach_tracing_prog) { 20429 /* 20430 * Target program is an fentry/fexit which is already attached 20431 * to another tracing program. More levels of nesting 20432 * attachment are not allowed. 20433 */ 20434 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 20435 return -EINVAL; 20436 } 20437 } else if (tgt_prog->type == prog->type) { 20438 /* 20439 * To avoid potential call chain cycles, prevent attaching of a 20440 * program extension to another extension. It's ok to attach 20441 * fentry/fexit to extension program. 20442 */ 20443 bpf_log(log, "Cannot recursively attach\n"); 20444 return -EINVAL; 20445 } 20446 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 20447 prog_extension && 20448 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 20449 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 20450 /* Program extensions can extend all program types 20451 * except fentry/fexit. The reason is the following. 20452 * The fentry/fexit programs are used for performance 20453 * analysis, stats and can be attached to any program 20454 * type. When extension program is replacing XDP function 20455 * it is necessary to allow performance analysis of all 20456 * functions. Both original XDP program and its program 20457 * extension. Hence attaching fentry/fexit to 20458 * BPF_PROG_TYPE_EXT is allowed. If extending of 20459 * fentry/fexit was allowed it would be possible to create 20460 * long call chain fentry->extension->fentry->extension 20461 * beyond reasonable stack size. Hence extending fentry 20462 * is not allowed. 20463 */ 20464 bpf_log(log, "Cannot extend fentry/fexit\n"); 20465 return -EINVAL; 20466 } 20467 } else { 20468 if (prog_extension) { 20469 bpf_log(log, "Cannot replace kernel functions\n"); 20470 return -EINVAL; 20471 } 20472 } 20473 20474 switch (prog->expected_attach_type) { 20475 case BPF_TRACE_RAW_TP: 20476 if (tgt_prog) { 20477 bpf_log(log, 20478 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 20479 return -EINVAL; 20480 } 20481 if (!btf_type_is_typedef(t)) { 20482 bpf_log(log, "attach_btf_id %u is not a typedef\n", 20483 btf_id); 20484 return -EINVAL; 20485 } 20486 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 20487 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 20488 btf_id, tname); 20489 return -EINVAL; 20490 } 20491 tname += sizeof(prefix) - 1; 20492 t = btf_type_by_id(btf, t->type); 20493 if (!btf_type_is_ptr(t)) 20494 /* should never happen in valid vmlinux build */ 20495 return -EINVAL; 20496 t = btf_type_by_id(btf, t->type); 20497 if (!btf_type_is_func_proto(t)) 20498 /* should never happen in valid vmlinux build */ 20499 return -EINVAL; 20500 20501 break; 20502 case BPF_TRACE_ITER: 20503 if (!btf_type_is_func(t)) { 20504 bpf_log(log, "attach_btf_id %u is not a function\n", 20505 btf_id); 20506 return -EINVAL; 20507 } 20508 t = btf_type_by_id(btf, t->type); 20509 if (!btf_type_is_func_proto(t)) 20510 return -EINVAL; 20511 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 20512 if (ret) 20513 return ret; 20514 break; 20515 default: 20516 if (!prog_extension) 20517 return -EINVAL; 20518 fallthrough; 20519 case BPF_MODIFY_RETURN: 20520 case BPF_LSM_MAC: 20521 case BPF_LSM_CGROUP: 20522 case BPF_TRACE_FENTRY: 20523 case BPF_TRACE_FEXIT: 20524 if (!btf_type_is_func(t)) { 20525 bpf_log(log, "attach_btf_id %u is not a function\n", 20526 btf_id); 20527 return -EINVAL; 20528 } 20529 if (prog_extension && 20530 btf_check_type_match(log, prog, btf, t)) 20531 return -EINVAL; 20532 t = btf_type_by_id(btf, t->type); 20533 if (!btf_type_is_func_proto(t)) 20534 return -EINVAL; 20535 20536 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 20537 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 20538 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 20539 return -EINVAL; 20540 20541 if (tgt_prog && conservative) 20542 t = NULL; 20543 20544 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 20545 if (ret < 0) 20546 return ret; 20547 20548 if (tgt_prog) { 20549 if (subprog == 0) 20550 addr = (long) tgt_prog->bpf_func; 20551 else 20552 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 20553 } else { 20554 if (btf_is_module(btf)) { 20555 mod = btf_try_get_module(btf); 20556 if (mod) 20557 addr = find_kallsyms_symbol_value(mod, tname); 20558 else 20559 addr = 0; 20560 } else { 20561 addr = kallsyms_lookup_name(tname); 20562 } 20563 if (!addr) { 20564 module_put(mod); 20565 bpf_log(log, 20566 "The address of function %s cannot be found\n", 20567 tname); 20568 return -ENOENT; 20569 } 20570 } 20571 20572 if (prog->aux->sleepable) { 20573 ret = -EINVAL; 20574 switch (prog->type) { 20575 case BPF_PROG_TYPE_TRACING: 20576 20577 /* fentry/fexit/fmod_ret progs can be sleepable if they are 20578 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 20579 */ 20580 if (!check_non_sleepable_error_inject(btf_id) && 20581 within_error_injection_list(addr)) 20582 ret = 0; 20583 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 20584 * in the fmodret id set with the KF_SLEEPABLE flag. 20585 */ 20586 else { 20587 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 20588 prog); 20589 20590 if (flags && (*flags & KF_SLEEPABLE)) 20591 ret = 0; 20592 } 20593 break; 20594 case BPF_PROG_TYPE_LSM: 20595 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 20596 * Only some of them are sleepable. 20597 */ 20598 if (bpf_lsm_is_sleepable_hook(btf_id)) 20599 ret = 0; 20600 break; 20601 default: 20602 break; 20603 } 20604 if (ret) { 20605 module_put(mod); 20606 bpf_log(log, "%s is not sleepable\n", tname); 20607 return ret; 20608 } 20609 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 20610 if (tgt_prog) { 20611 module_put(mod); 20612 bpf_log(log, "can't modify return codes of BPF programs\n"); 20613 return -EINVAL; 20614 } 20615 ret = -EINVAL; 20616 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 20617 !check_attach_modify_return(addr, tname)) 20618 ret = 0; 20619 if (ret) { 20620 module_put(mod); 20621 bpf_log(log, "%s() is not modifiable\n", tname); 20622 return ret; 20623 } 20624 } 20625 20626 break; 20627 } 20628 tgt_info->tgt_addr = addr; 20629 tgt_info->tgt_name = tname; 20630 tgt_info->tgt_type = t; 20631 tgt_info->tgt_mod = mod; 20632 return 0; 20633 } 20634 20635 BTF_SET_START(btf_id_deny) 20636 BTF_ID_UNUSED 20637 #ifdef CONFIG_SMP 20638 BTF_ID(func, migrate_disable) 20639 BTF_ID(func, migrate_enable) 20640 #endif 20641 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 20642 BTF_ID(func, rcu_read_unlock_strict) 20643 #endif 20644 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 20645 BTF_ID(func, preempt_count_add) 20646 BTF_ID(func, preempt_count_sub) 20647 #endif 20648 #ifdef CONFIG_PREEMPT_RCU 20649 BTF_ID(func, __rcu_read_lock) 20650 BTF_ID(func, __rcu_read_unlock) 20651 #endif 20652 BTF_SET_END(btf_id_deny) 20653 20654 static bool can_be_sleepable(struct bpf_prog *prog) 20655 { 20656 if (prog->type == BPF_PROG_TYPE_TRACING) { 20657 switch (prog->expected_attach_type) { 20658 case BPF_TRACE_FENTRY: 20659 case BPF_TRACE_FEXIT: 20660 case BPF_MODIFY_RETURN: 20661 case BPF_TRACE_ITER: 20662 return true; 20663 default: 20664 return false; 20665 } 20666 } 20667 return prog->type == BPF_PROG_TYPE_LSM || 20668 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 20669 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 20670 } 20671 20672 static int check_attach_btf_id(struct bpf_verifier_env *env) 20673 { 20674 struct bpf_prog *prog = env->prog; 20675 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 20676 struct bpf_attach_target_info tgt_info = {}; 20677 u32 btf_id = prog->aux->attach_btf_id; 20678 struct bpf_trampoline *tr; 20679 int ret; 20680 u64 key; 20681 20682 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 20683 if (prog->aux->sleepable) 20684 /* attach_btf_id checked to be zero already */ 20685 return 0; 20686 verbose(env, "Syscall programs can only be sleepable\n"); 20687 return -EINVAL; 20688 } 20689 20690 if (prog->aux->sleepable && !can_be_sleepable(prog)) { 20691 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 20692 return -EINVAL; 20693 } 20694 20695 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 20696 return check_struct_ops_btf_id(env); 20697 20698 if (prog->type != BPF_PROG_TYPE_TRACING && 20699 prog->type != BPF_PROG_TYPE_LSM && 20700 prog->type != BPF_PROG_TYPE_EXT) 20701 return 0; 20702 20703 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 20704 if (ret) 20705 return ret; 20706 20707 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 20708 /* to make freplace equivalent to their targets, they need to 20709 * inherit env->ops and expected_attach_type for the rest of the 20710 * verification 20711 */ 20712 env->ops = bpf_verifier_ops[tgt_prog->type]; 20713 prog->expected_attach_type = tgt_prog->expected_attach_type; 20714 } 20715 20716 /* store info about the attachment target that will be used later */ 20717 prog->aux->attach_func_proto = tgt_info.tgt_type; 20718 prog->aux->attach_func_name = tgt_info.tgt_name; 20719 prog->aux->mod = tgt_info.tgt_mod; 20720 20721 if (tgt_prog) { 20722 prog->aux->saved_dst_prog_type = tgt_prog->type; 20723 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 20724 } 20725 20726 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 20727 prog->aux->attach_btf_trace = true; 20728 return 0; 20729 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 20730 if (!bpf_iter_prog_supported(prog)) 20731 return -EINVAL; 20732 return 0; 20733 } 20734 20735 if (prog->type == BPF_PROG_TYPE_LSM) { 20736 ret = bpf_lsm_verify_prog(&env->log, prog); 20737 if (ret < 0) 20738 return ret; 20739 } else if (prog->type == BPF_PROG_TYPE_TRACING && 20740 btf_id_set_contains(&btf_id_deny, btf_id)) { 20741 return -EINVAL; 20742 } 20743 20744 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 20745 tr = bpf_trampoline_get(key, &tgt_info); 20746 if (!tr) 20747 return -ENOMEM; 20748 20749 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 20750 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 20751 20752 prog->aux->dst_trampoline = tr; 20753 return 0; 20754 } 20755 20756 struct btf *bpf_get_btf_vmlinux(void) 20757 { 20758 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 20759 mutex_lock(&bpf_verifier_lock); 20760 if (!btf_vmlinux) 20761 btf_vmlinux = btf_parse_vmlinux(); 20762 mutex_unlock(&bpf_verifier_lock); 20763 } 20764 return btf_vmlinux; 20765 } 20766 20767 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 20768 { 20769 u64 start_time = ktime_get_ns(); 20770 struct bpf_verifier_env *env; 20771 int i, len, ret = -EINVAL, err; 20772 u32 log_true_size; 20773 bool is_priv; 20774 20775 /* no program is valid */ 20776 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 20777 return -EINVAL; 20778 20779 /* 'struct bpf_verifier_env' can be global, but since it's not small, 20780 * allocate/free it every time bpf_check() is called 20781 */ 20782 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 20783 if (!env) 20784 return -ENOMEM; 20785 20786 env->bt.env = env; 20787 20788 len = (*prog)->len; 20789 env->insn_aux_data = 20790 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 20791 ret = -ENOMEM; 20792 if (!env->insn_aux_data) 20793 goto err_free_env; 20794 for (i = 0; i < len; i++) 20795 env->insn_aux_data[i].orig_idx = i; 20796 env->prog = *prog; 20797 env->ops = bpf_verifier_ops[env->prog->type]; 20798 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 20799 is_priv = bpf_capable(); 20800 20801 bpf_get_btf_vmlinux(); 20802 20803 /* grab the mutex to protect few globals used by verifier */ 20804 if (!is_priv) 20805 mutex_lock(&bpf_verifier_lock); 20806 20807 /* user could have requested verbose verifier output 20808 * and supplied buffer to store the verification trace 20809 */ 20810 ret = bpf_vlog_init(&env->log, attr->log_level, 20811 (char __user *) (unsigned long) attr->log_buf, 20812 attr->log_size); 20813 if (ret) 20814 goto err_unlock; 20815 20816 mark_verifier_state_clean(env); 20817 20818 if (IS_ERR(btf_vmlinux)) { 20819 /* Either gcc or pahole or kernel are broken. */ 20820 verbose(env, "in-kernel BTF is malformed\n"); 20821 ret = PTR_ERR(btf_vmlinux); 20822 goto skip_full_check; 20823 } 20824 20825 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 20826 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 20827 env->strict_alignment = true; 20828 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 20829 env->strict_alignment = false; 20830 20831 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 20832 env->allow_uninit_stack = bpf_allow_uninit_stack(); 20833 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 20834 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 20835 env->bpf_capable = bpf_capable(); 20836 20837 if (is_priv) 20838 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 20839 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 20840 20841 env->explored_states = kvcalloc(state_htab_size(env), 20842 sizeof(struct bpf_verifier_state_list *), 20843 GFP_USER); 20844 ret = -ENOMEM; 20845 if (!env->explored_states) 20846 goto skip_full_check; 20847 20848 ret = check_btf_info_early(env, attr, uattr); 20849 if (ret < 0) 20850 goto skip_full_check; 20851 20852 ret = add_subprog_and_kfunc(env); 20853 if (ret < 0) 20854 goto skip_full_check; 20855 20856 ret = check_subprogs(env); 20857 if (ret < 0) 20858 goto skip_full_check; 20859 20860 ret = check_btf_info(env, attr, uattr); 20861 if (ret < 0) 20862 goto skip_full_check; 20863 20864 ret = check_attach_btf_id(env); 20865 if (ret) 20866 goto skip_full_check; 20867 20868 ret = resolve_pseudo_ldimm64(env); 20869 if (ret < 0) 20870 goto skip_full_check; 20871 20872 if (bpf_prog_is_offloaded(env->prog->aux)) { 20873 ret = bpf_prog_offload_verifier_prep(env->prog); 20874 if (ret) 20875 goto skip_full_check; 20876 } 20877 20878 ret = check_cfg(env); 20879 if (ret < 0) 20880 goto skip_full_check; 20881 20882 ret = do_check_main(env); 20883 ret = ret ?: do_check_subprogs(env); 20884 20885 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 20886 ret = bpf_prog_offload_finalize(env); 20887 20888 skip_full_check: 20889 kvfree(env->explored_states); 20890 20891 if (ret == 0) 20892 ret = check_max_stack_depth(env); 20893 20894 /* instruction rewrites happen after this point */ 20895 if (ret == 0) 20896 ret = optimize_bpf_loop(env); 20897 20898 if (is_priv) { 20899 if (ret == 0) 20900 opt_hard_wire_dead_code_branches(env); 20901 if (ret == 0) 20902 ret = opt_remove_dead_code(env); 20903 if (ret == 0) 20904 ret = opt_remove_nops(env); 20905 } else { 20906 if (ret == 0) 20907 sanitize_dead_code(env); 20908 } 20909 20910 if (ret == 0) 20911 /* program is valid, convert *(u32*)(ctx + off) accesses */ 20912 ret = convert_ctx_accesses(env); 20913 20914 if (ret == 0) 20915 ret = do_misc_fixups(env); 20916 20917 /* do 32-bit optimization after insn patching has done so those patched 20918 * insns could be handled correctly. 20919 */ 20920 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 20921 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 20922 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 20923 : false; 20924 } 20925 20926 if (ret == 0) 20927 ret = fixup_call_args(env); 20928 20929 env->verification_time = ktime_get_ns() - start_time; 20930 print_verification_stats(env); 20931 env->prog->aux->verified_insns = env->insn_processed; 20932 20933 /* preserve original error even if log finalization is successful */ 20934 err = bpf_vlog_finalize(&env->log, &log_true_size); 20935 if (err) 20936 ret = err; 20937 20938 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 20939 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 20940 &log_true_size, sizeof(log_true_size))) { 20941 ret = -EFAULT; 20942 goto err_release_maps; 20943 } 20944 20945 if (ret) 20946 goto err_release_maps; 20947 20948 if (env->used_map_cnt) { 20949 /* if program passed verifier, update used_maps in bpf_prog_info */ 20950 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 20951 sizeof(env->used_maps[0]), 20952 GFP_KERNEL); 20953 20954 if (!env->prog->aux->used_maps) { 20955 ret = -ENOMEM; 20956 goto err_release_maps; 20957 } 20958 20959 memcpy(env->prog->aux->used_maps, env->used_maps, 20960 sizeof(env->used_maps[0]) * env->used_map_cnt); 20961 env->prog->aux->used_map_cnt = env->used_map_cnt; 20962 } 20963 if (env->used_btf_cnt) { 20964 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 20965 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 20966 sizeof(env->used_btfs[0]), 20967 GFP_KERNEL); 20968 if (!env->prog->aux->used_btfs) { 20969 ret = -ENOMEM; 20970 goto err_release_maps; 20971 } 20972 20973 memcpy(env->prog->aux->used_btfs, env->used_btfs, 20974 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 20975 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 20976 } 20977 if (env->used_map_cnt || env->used_btf_cnt) { 20978 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 20979 * bpf_ld_imm64 instructions 20980 */ 20981 convert_pseudo_ld_imm64(env); 20982 } 20983 20984 adjust_btf_func(env); 20985 20986 err_release_maps: 20987 if (!env->prog->aux->used_maps) 20988 /* if we didn't copy map pointers into bpf_prog_info, release 20989 * them now. Otherwise free_used_maps() will release them. 20990 */ 20991 release_maps(env); 20992 if (!env->prog->aux->used_btfs) 20993 release_btfs(env); 20994 20995 /* extension progs temporarily inherit the attach_type of their targets 20996 for verification purposes, so set it back to zero before returning 20997 */ 20998 if (env->prog->type == BPF_PROG_TYPE_EXT) 20999 env->prog->expected_attach_type = 0; 21000 21001 *prog = env->prog; 21002 err_unlock: 21003 if (!is_priv) 21004 mutex_unlock(&bpf_verifier_lock); 21005 vfree(env->insn_aux_data); 21006 err_free_env: 21007 kfree(env); 21008 return ret; 21009 } 21010