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 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 /* If writing_zero and the spi slot contains a spill of value 0, 4667 * maintain the spill type. 4668 */ 4669 if (writing_zero && *stype == STACK_SPILL && 4670 is_spilled_scalar_reg(&state->stack[spi])) { 4671 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr; 4672 4673 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) { 4674 zero_used = true; 4675 continue; 4676 } 4677 } 4678 4679 /* Erase all other spilled pointers. */ 4680 state->stack[spi].spilled_ptr.type = NOT_INIT; 4681 4682 /* Update the slot type. */ 4683 new_type = STACK_MISC; 4684 if (writing_zero && *stype == STACK_ZERO) { 4685 new_type = STACK_ZERO; 4686 zero_used = true; 4687 } 4688 /* If the slot is STACK_INVALID, we check whether it's OK to 4689 * pretend that it will be initialized by this write. The slot 4690 * might not actually be written to, and so if we mark it as 4691 * initialized future reads might leak uninitialized memory. 4692 * For privileged programs, we will accept such reads to slots 4693 * that may or may not be written because, if we're reject 4694 * them, the error would be too confusing. 4695 */ 4696 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4697 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4698 insn_idx, i); 4699 return -EINVAL; 4700 } 4701 *stype = new_type; 4702 } 4703 if (zero_used) { 4704 /* backtracking doesn't work for STACK_ZERO yet. */ 4705 err = mark_chain_precision(env, value_regno); 4706 if (err) 4707 return err; 4708 } 4709 return 0; 4710 } 4711 4712 /* When register 'dst_regno' is assigned some values from stack[min_off, 4713 * max_off), we set the register's type according to the types of the 4714 * respective stack slots. If all the stack values are known to be zeros, then 4715 * so is the destination reg. Otherwise, the register is considered to be 4716 * SCALAR. This function does not deal with register filling; the caller must 4717 * ensure that all spilled registers in the stack range have been marked as 4718 * read. 4719 */ 4720 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4721 /* func where src register points to */ 4722 struct bpf_func_state *ptr_state, 4723 int min_off, int max_off, int dst_regno) 4724 { 4725 struct bpf_verifier_state *vstate = env->cur_state; 4726 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4727 int i, slot, spi; 4728 u8 *stype; 4729 int zeros = 0; 4730 4731 for (i = min_off; i < max_off; i++) { 4732 slot = -i - 1; 4733 spi = slot / BPF_REG_SIZE; 4734 mark_stack_slot_scratched(env, spi); 4735 stype = ptr_state->stack[spi].slot_type; 4736 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4737 break; 4738 zeros++; 4739 } 4740 if (zeros == max_off - min_off) { 4741 /* Any access_size read into register is zero extended, 4742 * so the whole register == const_zero. 4743 */ 4744 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4745 } else { 4746 /* have read misc data from the stack */ 4747 mark_reg_unknown(env, state->regs, dst_regno); 4748 } 4749 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4750 } 4751 4752 /* Read the stack at 'off' and put the results into the register indicated by 4753 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4754 * spilled reg. 4755 * 4756 * 'dst_regno' can be -1, meaning that the read value is not going to a 4757 * register. 4758 * 4759 * The access is assumed to be within the current stack bounds. 4760 */ 4761 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4762 /* func where src register points to */ 4763 struct bpf_func_state *reg_state, 4764 int off, int size, int dst_regno) 4765 { 4766 struct bpf_verifier_state *vstate = env->cur_state; 4767 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4768 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4769 struct bpf_reg_state *reg; 4770 u8 *stype, type; 4771 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi); 4772 4773 stype = reg_state->stack[spi].slot_type; 4774 reg = ®_state->stack[spi].spilled_ptr; 4775 4776 mark_stack_slot_scratched(env, spi); 4777 4778 if (is_spilled_reg(®_state->stack[spi])) { 4779 u8 spill_size = 1; 4780 4781 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4782 spill_size++; 4783 4784 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4785 if (reg->type != SCALAR_VALUE) { 4786 verbose_linfo(env, env->insn_idx, "; "); 4787 verbose(env, "invalid size of register fill\n"); 4788 return -EACCES; 4789 } 4790 4791 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4792 if (dst_regno < 0) 4793 return 0; 4794 4795 if (!(off % BPF_REG_SIZE) && size == spill_size) { 4796 /* The earlier check_reg_arg() has decided the 4797 * subreg_def for this insn. Save it first. 4798 */ 4799 s32 subreg_def = state->regs[dst_regno].subreg_def; 4800 4801 copy_register_state(&state->regs[dst_regno], reg); 4802 state->regs[dst_regno].subreg_def = subreg_def; 4803 } else { 4804 int spill_cnt = 0, zero_cnt = 0; 4805 4806 for (i = 0; i < size; i++) { 4807 type = stype[(slot - i) % BPF_REG_SIZE]; 4808 if (type == STACK_SPILL) { 4809 spill_cnt++; 4810 continue; 4811 } 4812 if (type == STACK_MISC) 4813 continue; 4814 if (type == STACK_ZERO) { 4815 zero_cnt++; 4816 continue; 4817 } 4818 if (type == STACK_INVALID && env->allow_uninit_stack) 4819 continue; 4820 verbose(env, "invalid read from stack off %d+%d size %d\n", 4821 off, i, size); 4822 return -EACCES; 4823 } 4824 4825 if (spill_cnt == size && 4826 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 4827 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4828 /* this IS register fill, so keep insn_flags */ 4829 } else if (zero_cnt == size) { 4830 /* similarly to mark_reg_stack_read(), preserve zeroes */ 4831 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4832 insn_flags = 0; /* not restoring original register state */ 4833 } else { 4834 mark_reg_unknown(env, state->regs, dst_regno); 4835 insn_flags = 0; /* not restoring original register state */ 4836 } 4837 } 4838 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4839 } else if (dst_regno >= 0) { 4840 /* restore register state from stack */ 4841 copy_register_state(&state->regs[dst_regno], reg); 4842 /* mark reg as written since spilled pointer state likely 4843 * has its liveness marks cleared by is_state_visited() 4844 * which resets stack/reg liveness for state transitions 4845 */ 4846 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4847 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 4848 /* If dst_regno==-1, the caller is asking us whether 4849 * it is acceptable to use this value as a SCALAR_VALUE 4850 * (e.g. for XADD). 4851 * We must not allow unprivileged callers to do that 4852 * with spilled pointers. 4853 */ 4854 verbose(env, "leaking pointer from stack off %d\n", 4855 off); 4856 return -EACCES; 4857 } 4858 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4859 } else { 4860 for (i = 0; i < size; i++) { 4861 type = stype[(slot - i) % BPF_REG_SIZE]; 4862 if (type == STACK_MISC) 4863 continue; 4864 if (type == STACK_ZERO) 4865 continue; 4866 if (type == STACK_INVALID && env->allow_uninit_stack) 4867 continue; 4868 verbose(env, "invalid read from stack off %d+%d size %d\n", 4869 off, i, size); 4870 return -EACCES; 4871 } 4872 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4873 if (dst_regno >= 0) 4874 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 4875 insn_flags = 0; /* we are not restoring spilled register */ 4876 } 4877 if (insn_flags) 4878 return push_jmp_history(env, env->cur_state, insn_flags); 4879 return 0; 4880 } 4881 4882 enum bpf_access_src { 4883 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 4884 ACCESS_HELPER = 2, /* the access is performed by a helper */ 4885 }; 4886 4887 static int check_stack_range_initialized(struct bpf_verifier_env *env, 4888 int regno, int off, int access_size, 4889 bool zero_size_allowed, 4890 enum bpf_access_src type, 4891 struct bpf_call_arg_meta *meta); 4892 4893 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 4894 { 4895 return cur_regs(env) + regno; 4896 } 4897 4898 /* Read the stack at 'ptr_regno + off' and put the result into the register 4899 * 'dst_regno'. 4900 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 4901 * but not its variable offset. 4902 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 4903 * 4904 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 4905 * filling registers (i.e. reads of spilled register cannot be detected when 4906 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 4907 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 4908 * offset; for a fixed offset check_stack_read_fixed_off should be used 4909 * instead. 4910 */ 4911 static int check_stack_read_var_off(struct bpf_verifier_env *env, 4912 int ptr_regno, int off, int size, int dst_regno) 4913 { 4914 /* The state of the source register. */ 4915 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4916 struct bpf_func_state *ptr_state = func(env, reg); 4917 int err; 4918 int min_off, max_off; 4919 4920 /* Note that we pass a NULL meta, so raw access will not be permitted. 4921 */ 4922 err = check_stack_range_initialized(env, ptr_regno, off, size, 4923 false, ACCESS_DIRECT, NULL); 4924 if (err) 4925 return err; 4926 4927 min_off = reg->smin_value + off; 4928 max_off = reg->smax_value + off; 4929 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 4930 return 0; 4931 } 4932 4933 /* check_stack_read dispatches to check_stack_read_fixed_off or 4934 * check_stack_read_var_off. 4935 * 4936 * The caller must ensure that the offset falls within the allocated stack 4937 * bounds. 4938 * 4939 * 'dst_regno' is a register which will receive the value from the stack. It 4940 * can be -1, meaning that the read value is not going to a register. 4941 */ 4942 static int check_stack_read(struct bpf_verifier_env *env, 4943 int ptr_regno, int off, int size, 4944 int dst_regno) 4945 { 4946 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4947 struct bpf_func_state *state = func(env, reg); 4948 int err; 4949 /* Some accesses are only permitted with a static offset. */ 4950 bool var_off = !tnum_is_const(reg->var_off); 4951 4952 /* The offset is required to be static when reads don't go to a 4953 * register, in order to not leak pointers (see 4954 * check_stack_read_fixed_off). 4955 */ 4956 if (dst_regno < 0 && var_off) { 4957 char tn_buf[48]; 4958 4959 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4960 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 4961 tn_buf, off, size); 4962 return -EACCES; 4963 } 4964 /* Variable offset is prohibited for unprivileged mode for simplicity 4965 * since it requires corresponding support in Spectre masking for stack 4966 * ALU. See also retrieve_ptr_limit(). The check in 4967 * check_stack_access_for_ptr_arithmetic() called by 4968 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 4969 * with variable offsets, therefore no check is required here. Further, 4970 * just checking it here would be insufficient as speculative stack 4971 * writes could still lead to unsafe speculative behaviour. 4972 */ 4973 if (!var_off) { 4974 off += reg->var_off.value; 4975 err = check_stack_read_fixed_off(env, state, off, size, 4976 dst_regno); 4977 } else { 4978 /* Variable offset stack reads need more conservative handling 4979 * than fixed offset ones. Note that dst_regno >= 0 on this 4980 * branch. 4981 */ 4982 err = check_stack_read_var_off(env, ptr_regno, off, size, 4983 dst_regno); 4984 } 4985 return err; 4986 } 4987 4988 4989 /* check_stack_write dispatches to check_stack_write_fixed_off or 4990 * check_stack_write_var_off. 4991 * 4992 * 'ptr_regno' is the register used as a pointer into the stack. 4993 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 4994 * 'value_regno' is the register whose value we're writing to the stack. It can 4995 * be -1, meaning that we're not writing from a register. 4996 * 4997 * The caller must ensure that the offset falls within the maximum stack size. 4998 */ 4999 static int check_stack_write(struct bpf_verifier_env *env, 5000 int ptr_regno, int off, int size, 5001 int value_regno, int insn_idx) 5002 { 5003 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5004 struct bpf_func_state *state = func(env, reg); 5005 int err; 5006 5007 if (tnum_is_const(reg->var_off)) { 5008 off += reg->var_off.value; 5009 err = check_stack_write_fixed_off(env, state, off, size, 5010 value_regno, insn_idx); 5011 } else { 5012 /* Variable offset stack reads need more conservative handling 5013 * than fixed offset ones. 5014 */ 5015 err = check_stack_write_var_off(env, state, 5016 ptr_regno, off, size, 5017 value_regno, insn_idx); 5018 } 5019 return err; 5020 } 5021 5022 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 5023 int off, int size, enum bpf_access_type type) 5024 { 5025 struct bpf_reg_state *regs = cur_regs(env); 5026 struct bpf_map *map = regs[regno].map_ptr; 5027 u32 cap = bpf_map_flags_to_cap(map); 5028 5029 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 5030 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 5031 map->value_size, off, size); 5032 return -EACCES; 5033 } 5034 5035 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 5036 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 5037 map->value_size, off, size); 5038 return -EACCES; 5039 } 5040 5041 return 0; 5042 } 5043 5044 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 5045 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 5046 int off, int size, u32 mem_size, 5047 bool zero_size_allowed) 5048 { 5049 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 5050 struct bpf_reg_state *reg; 5051 5052 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 5053 return 0; 5054 5055 reg = &cur_regs(env)[regno]; 5056 switch (reg->type) { 5057 case PTR_TO_MAP_KEY: 5058 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 5059 mem_size, off, size); 5060 break; 5061 case PTR_TO_MAP_VALUE: 5062 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 5063 mem_size, off, size); 5064 break; 5065 case PTR_TO_PACKET: 5066 case PTR_TO_PACKET_META: 5067 case PTR_TO_PACKET_END: 5068 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 5069 off, size, regno, reg->id, off, mem_size); 5070 break; 5071 case PTR_TO_MEM: 5072 default: 5073 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 5074 mem_size, off, size); 5075 } 5076 5077 return -EACCES; 5078 } 5079 5080 /* check read/write into a memory region with possible variable offset */ 5081 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 5082 int off, int size, u32 mem_size, 5083 bool zero_size_allowed) 5084 { 5085 struct bpf_verifier_state *vstate = env->cur_state; 5086 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5087 struct bpf_reg_state *reg = &state->regs[regno]; 5088 int err; 5089 5090 /* We may have adjusted the register pointing to memory region, so we 5091 * need to try adding each of min_value and max_value to off 5092 * to make sure our theoretical access will be safe. 5093 * 5094 * The minimum value is only important with signed 5095 * comparisons where we can't assume the floor of a 5096 * value is 0. If we are using signed variables for our 5097 * index'es we need to make sure that whatever we use 5098 * will have a set floor within our range. 5099 */ 5100 if (reg->smin_value < 0 && 5101 (reg->smin_value == S64_MIN || 5102 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5103 reg->smin_value + off < 0)) { 5104 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5105 regno); 5106 return -EACCES; 5107 } 5108 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5109 mem_size, zero_size_allowed); 5110 if (err) { 5111 verbose(env, "R%d min value is outside of the allowed memory range\n", 5112 regno); 5113 return err; 5114 } 5115 5116 /* If we haven't set a max value then we need to bail since we can't be 5117 * sure we won't do bad things. 5118 * If reg->umax_value + off could overflow, treat that as unbounded too. 5119 */ 5120 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5121 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5122 regno); 5123 return -EACCES; 5124 } 5125 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5126 mem_size, zero_size_allowed); 5127 if (err) { 5128 verbose(env, "R%d max value is outside of the allowed memory range\n", 5129 regno); 5130 return err; 5131 } 5132 5133 return 0; 5134 } 5135 5136 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5137 const struct bpf_reg_state *reg, int regno, 5138 bool fixed_off_ok) 5139 { 5140 /* Access to this pointer-typed register or passing it to a helper 5141 * is only allowed in its original, unmodified form. 5142 */ 5143 5144 if (reg->off < 0) { 5145 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5146 reg_type_str(env, reg->type), regno, reg->off); 5147 return -EACCES; 5148 } 5149 5150 if (!fixed_off_ok && reg->off) { 5151 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5152 reg_type_str(env, reg->type), regno, reg->off); 5153 return -EACCES; 5154 } 5155 5156 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5157 char tn_buf[48]; 5158 5159 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5160 verbose(env, "variable %s access var_off=%s disallowed\n", 5161 reg_type_str(env, reg->type), tn_buf); 5162 return -EACCES; 5163 } 5164 5165 return 0; 5166 } 5167 5168 static int check_ptr_off_reg(struct bpf_verifier_env *env, 5169 const struct bpf_reg_state *reg, int regno) 5170 { 5171 return __check_ptr_off_reg(env, reg, regno, false); 5172 } 5173 5174 static int map_kptr_match_type(struct bpf_verifier_env *env, 5175 struct btf_field *kptr_field, 5176 struct bpf_reg_state *reg, u32 regno) 5177 { 5178 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5179 int perm_flags; 5180 const char *reg_name = ""; 5181 5182 if (btf_is_kernel(reg->btf)) { 5183 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5184 5185 /* Only unreferenced case accepts untrusted pointers */ 5186 if (kptr_field->type == BPF_KPTR_UNREF) 5187 perm_flags |= PTR_UNTRUSTED; 5188 } else { 5189 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5190 if (kptr_field->type == BPF_KPTR_PERCPU) 5191 perm_flags |= MEM_PERCPU; 5192 } 5193 5194 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5195 goto bad_type; 5196 5197 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5198 reg_name = btf_type_name(reg->btf, reg->btf_id); 5199 5200 /* For ref_ptr case, release function check should ensure we get one 5201 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5202 * normal store of unreferenced kptr, we must ensure var_off is zero. 5203 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5204 * reg->off and reg->ref_obj_id are not needed here. 5205 */ 5206 if (__check_ptr_off_reg(env, reg, regno, true)) 5207 return -EACCES; 5208 5209 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5210 * we also need to take into account the reg->off. 5211 * 5212 * We want to support cases like: 5213 * 5214 * struct foo { 5215 * struct bar br; 5216 * struct baz bz; 5217 * }; 5218 * 5219 * struct foo *v; 5220 * v = func(); // PTR_TO_BTF_ID 5221 * val->foo = v; // reg->off is zero, btf and btf_id match type 5222 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5223 * // first member type of struct after comparison fails 5224 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5225 * // to match type 5226 * 5227 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5228 * is zero. We must also ensure that btf_struct_ids_match does not walk 5229 * the struct to match type against first member of struct, i.e. reject 5230 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5231 * strict mode to true for type match. 5232 */ 5233 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5234 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5235 kptr_field->type != BPF_KPTR_UNREF)) 5236 goto bad_type; 5237 return 0; 5238 bad_type: 5239 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5240 reg_type_str(env, reg->type), reg_name); 5241 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5242 if (kptr_field->type == BPF_KPTR_UNREF) 5243 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5244 targ_name); 5245 else 5246 verbose(env, "\n"); 5247 return -EINVAL; 5248 } 5249 5250 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5251 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5252 */ 5253 static bool in_rcu_cs(struct bpf_verifier_env *env) 5254 { 5255 return env->cur_state->active_rcu_lock || 5256 env->cur_state->active_lock.ptr || 5257 !env->prog->aux->sleepable; 5258 } 5259 5260 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5261 BTF_SET_START(rcu_protected_types) 5262 BTF_ID(struct, prog_test_ref_kfunc) 5263 #ifdef CONFIG_CGROUPS 5264 BTF_ID(struct, cgroup) 5265 #endif 5266 BTF_ID(struct, bpf_cpumask) 5267 BTF_ID(struct, task_struct) 5268 BTF_SET_END(rcu_protected_types) 5269 5270 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5271 { 5272 if (!btf_is_kernel(btf)) 5273 return true; 5274 return btf_id_set_contains(&rcu_protected_types, btf_id); 5275 } 5276 5277 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 5278 { 5279 struct btf_struct_meta *meta; 5280 5281 if (btf_is_kernel(kptr_field->kptr.btf)) 5282 return NULL; 5283 5284 meta = btf_find_struct_meta(kptr_field->kptr.btf, 5285 kptr_field->kptr.btf_id); 5286 5287 return meta ? meta->record : NULL; 5288 } 5289 5290 static bool rcu_safe_kptr(const struct btf_field *field) 5291 { 5292 const struct btf_field_kptr *kptr = &field->kptr; 5293 5294 return field->type == BPF_KPTR_PERCPU || 5295 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 5296 } 5297 5298 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 5299 { 5300 struct btf_record *rec; 5301 u32 ret; 5302 5303 ret = PTR_MAYBE_NULL; 5304 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 5305 ret |= MEM_RCU; 5306 if (kptr_field->type == BPF_KPTR_PERCPU) 5307 ret |= MEM_PERCPU; 5308 else if (!btf_is_kernel(kptr_field->kptr.btf)) 5309 ret |= MEM_ALLOC; 5310 5311 rec = kptr_pointee_btf_record(kptr_field); 5312 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 5313 ret |= NON_OWN_REF; 5314 } else { 5315 ret |= PTR_UNTRUSTED; 5316 } 5317 5318 return ret; 5319 } 5320 5321 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5322 int value_regno, int insn_idx, 5323 struct btf_field *kptr_field) 5324 { 5325 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5326 int class = BPF_CLASS(insn->code); 5327 struct bpf_reg_state *val_reg; 5328 5329 /* Things we already checked for in check_map_access and caller: 5330 * - Reject cases where variable offset may touch kptr 5331 * - size of access (must be BPF_DW) 5332 * - tnum_is_const(reg->var_off) 5333 * - kptr_field->offset == off + reg->var_off.value 5334 */ 5335 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5336 if (BPF_MODE(insn->code) != BPF_MEM) { 5337 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5338 return -EACCES; 5339 } 5340 5341 /* We only allow loading referenced kptr, since it will be marked as 5342 * untrusted, similar to unreferenced kptr. 5343 */ 5344 if (class != BPF_LDX && 5345 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 5346 verbose(env, "store to referenced kptr disallowed\n"); 5347 return -EACCES; 5348 } 5349 5350 if (class == BPF_LDX) { 5351 val_reg = reg_state(env, value_regno); 5352 /* We can simply mark the value_regno receiving the pointer 5353 * value from map as PTR_TO_BTF_ID, with the correct type. 5354 */ 5355 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5356 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field)); 5357 /* For mark_ptr_or_null_reg */ 5358 val_reg->id = ++env->id_gen; 5359 } else if (class == BPF_STX) { 5360 val_reg = reg_state(env, value_regno); 5361 if (!register_is_null(val_reg) && 5362 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5363 return -EACCES; 5364 } else if (class == BPF_ST) { 5365 if (insn->imm) { 5366 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5367 kptr_field->offset); 5368 return -EACCES; 5369 } 5370 } else { 5371 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5372 return -EACCES; 5373 } 5374 return 0; 5375 } 5376 5377 /* check read/write into a map element with possible variable offset */ 5378 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5379 int off, int size, bool zero_size_allowed, 5380 enum bpf_access_src src) 5381 { 5382 struct bpf_verifier_state *vstate = env->cur_state; 5383 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5384 struct bpf_reg_state *reg = &state->regs[regno]; 5385 struct bpf_map *map = reg->map_ptr; 5386 struct btf_record *rec; 5387 int err, i; 5388 5389 err = check_mem_region_access(env, regno, off, size, map->value_size, 5390 zero_size_allowed); 5391 if (err) 5392 return err; 5393 5394 if (IS_ERR_OR_NULL(map->record)) 5395 return 0; 5396 rec = map->record; 5397 for (i = 0; i < rec->cnt; i++) { 5398 struct btf_field *field = &rec->fields[i]; 5399 u32 p = field->offset; 5400 5401 /* If any part of a field can be touched by load/store, reject 5402 * this program. To check that [x1, x2) overlaps with [y1, y2), 5403 * it is sufficient to check x1 < y2 && y1 < x2. 5404 */ 5405 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 5406 p < reg->umax_value + off + size) { 5407 switch (field->type) { 5408 case BPF_KPTR_UNREF: 5409 case BPF_KPTR_REF: 5410 case BPF_KPTR_PERCPU: 5411 if (src != ACCESS_DIRECT) { 5412 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 5413 return -EACCES; 5414 } 5415 if (!tnum_is_const(reg->var_off)) { 5416 verbose(env, "kptr access cannot have variable offset\n"); 5417 return -EACCES; 5418 } 5419 if (p != off + reg->var_off.value) { 5420 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 5421 p, off + reg->var_off.value); 5422 return -EACCES; 5423 } 5424 if (size != bpf_size_to_bytes(BPF_DW)) { 5425 verbose(env, "kptr access size must be BPF_DW\n"); 5426 return -EACCES; 5427 } 5428 break; 5429 default: 5430 verbose(env, "%s cannot be accessed directly by load/store\n", 5431 btf_field_type_name(field->type)); 5432 return -EACCES; 5433 } 5434 } 5435 } 5436 return 0; 5437 } 5438 5439 #define MAX_PACKET_OFF 0xffff 5440 5441 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5442 const struct bpf_call_arg_meta *meta, 5443 enum bpf_access_type t) 5444 { 5445 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5446 5447 switch (prog_type) { 5448 /* Program types only with direct read access go here! */ 5449 case BPF_PROG_TYPE_LWT_IN: 5450 case BPF_PROG_TYPE_LWT_OUT: 5451 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5452 case BPF_PROG_TYPE_SK_REUSEPORT: 5453 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5454 case BPF_PROG_TYPE_CGROUP_SKB: 5455 if (t == BPF_WRITE) 5456 return false; 5457 fallthrough; 5458 5459 /* Program types with direct read + write access go here! */ 5460 case BPF_PROG_TYPE_SCHED_CLS: 5461 case BPF_PROG_TYPE_SCHED_ACT: 5462 case BPF_PROG_TYPE_XDP: 5463 case BPF_PROG_TYPE_LWT_XMIT: 5464 case BPF_PROG_TYPE_SK_SKB: 5465 case BPF_PROG_TYPE_SK_MSG: 5466 if (meta) 5467 return meta->pkt_access; 5468 5469 env->seen_direct_write = true; 5470 return true; 5471 5472 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5473 if (t == BPF_WRITE) 5474 env->seen_direct_write = true; 5475 5476 return true; 5477 5478 default: 5479 return false; 5480 } 5481 } 5482 5483 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5484 int size, bool zero_size_allowed) 5485 { 5486 struct bpf_reg_state *regs = cur_regs(env); 5487 struct bpf_reg_state *reg = ®s[regno]; 5488 int err; 5489 5490 /* We may have added a variable offset to the packet pointer; but any 5491 * reg->range we have comes after that. We are only checking the fixed 5492 * offset. 5493 */ 5494 5495 /* We don't allow negative numbers, because we aren't tracking enough 5496 * detail to prove they're safe. 5497 */ 5498 if (reg->smin_value < 0) { 5499 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5500 regno); 5501 return -EACCES; 5502 } 5503 5504 err = reg->range < 0 ? -EINVAL : 5505 __check_mem_access(env, regno, off, size, reg->range, 5506 zero_size_allowed); 5507 if (err) { 5508 verbose(env, "R%d offset is outside of the packet\n", regno); 5509 return err; 5510 } 5511 5512 /* __check_mem_access has made sure "off + size - 1" is within u16. 5513 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5514 * otherwise find_good_pkt_pointers would have refused to set range info 5515 * that __check_mem_access would have rejected this pkt access. 5516 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5517 */ 5518 env->prog->aux->max_pkt_offset = 5519 max_t(u32, env->prog->aux->max_pkt_offset, 5520 off + reg->umax_value + size - 1); 5521 5522 return err; 5523 } 5524 5525 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5526 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5527 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5528 struct btf **btf, u32 *btf_id) 5529 { 5530 struct bpf_insn_access_aux info = { 5531 .reg_type = *reg_type, 5532 .log = &env->log, 5533 }; 5534 5535 if (env->ops->is_valid_access && 5536 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5537 /* A non zero info.ctx_field_size indicates that this field is a 5538 * candidate for later verifier transformation to load the whole 5539 * field and then apply a mask when accessed with a narrower 5540 * access than actual ctx access size. A zero info.ctx_field_size 5541 * will only allow for whole field access and rejects any other 5542 * type of narrower access. 5543 */ 5544 *reg_type = info.reg_type; 5545 5546 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5547 *btf = info.btf; 5548 *btf_id = info.btf_id; 5549 } else { 5550 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5551 } 5552 /* remember the offset of last byte accessed in ctx */ 5553 if (env->prog->aux->max_ctx_offset < off + size) 5554 env->prog->aux->max_ctx_offset = off + size; 5555 return 0; 5556 } 5557 5558 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5559 return -EACCES; 5560 } 5561 5562 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5563 int size) 5564 { 5565 if (size < 0 || off < 0 || 5566 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5567 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5568 off, size); 5569 return -EACCES; 5570 } 5571 return 0; 5572 } 5573 5574 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5575 u32 regno, int off, int size, 5576 enum bpf_access_type t) 5577 { 5578 struct bpf_reg_state *regs = cur_regs(env); 5579 struct bpf_reg_state *reg = ®s[regno]; 5580 struct bpf_insn_access_aux info = {}; 5581 bool valid; 5582 5583 if (reg->smin_value < 0) { 5584 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5585 regno); 5586 return -EACCES; 5587 } 5588 5589 switch (reg->type) { 5590 case PTR_TO_SOCK_COMMON: 5591 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5592 break; 5593 case PTR_TO_SOCKET: 5594 valid = bpf_sock_is_valid_access(off, size, t, &info); 5595 break; 5596 case PTR_TO_TCP_SOCK: 5597 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5598 break; 5599 case PTR_TO_XDP_SOCK: 5600 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5601 break; 5602 default: 5603 valid = false; 5604 } 5605 5606 5607 if (valid) { 5608 env->insn_aux_data[insn_idx].ctx_field_size = 5609 info.ctx_field_size; 5610 return 0; 5611 } 5612 5613 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5614 regno, reg_type_str(env, reg->type), off, size); 5615 5616 return -EACCES; 5617 } 5618 5619 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5620 { 5621 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5622 } 5623 5624 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5625 { 5626 const struct bpf_reg_state *reg = reg_state(env, regno); 5627 5628 return reg->type == PTR_TO_CTX; 5629 } 5630 5631 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5632 { 5633 const struct bpf_reg_state *reg = reg_state(env, regno); 5634 5635 return type_is_sk_pointer(reg->type); 5636 } 5637 5638 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5639 { 5640 const struct bpf_reg_state *reg = reg_state(env, regno); 5641 5642 return type_is_pkt_pointer(reg->type); 5643 } 5644 5645 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5646 { 5647 const struct bpf_reg_state *reg = reg_state(env, regno); 5648 5649 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5650 return reg->type == PTR_TO_FLOW_KEYS; 5651 } 5652 5653 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5654 #ifdef CONFIG_NET 5655 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5656 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5657 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5658 #endif 5659 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5660 }; 5661 5662 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5663 { 5664 /* A referenced register is always trusted. */ 5665 if (reg->ref_obj_id) 5666 return true; 5667 5668 /* Types listed in the reg2btf_ids are always trusted */ 5669 if (reg2btf_ids[base_type(reg->type)]) 5670 return true; 5671 5672 /* If a register is not referenced, it is trusted if it has the 5673 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5674 * other type modifiers may be safe, but we elect to take an opt-in 5675 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5676 * not. 5677 * 5678 * Eventually, we should make PTR_TRUSTED the single source of truth 5679 * for whether a register is trusted. 5680 */ 5681 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5682 !bpf_type_has_unsafe_modifiers(reg->type); 5683 } 5684 5685 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5686 { 5687 return reg->type & MEM_RCU; 5688 } 5689 5690 static void clear_trusted_flags(enum bpf_type_flag *flag) 5691 { 5692 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5693 } 5694 5695 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5696 const struct bpf_reg_state *reg, 5697 int off, int size, bool strict) 5698 { 5699 struct tnum reg_off; 5700 int ip_align; 5701 5702 /* Byte size accesses are always allowed. */ 5703 if (!strict || size == 1) 5704 return 0; 5705 5706 /* For platforms that do not have a Kconfig enabling 5707 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5708 * NET_IP_ALIGN is universally set to '2'. And on platforms 5709 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5710 * to this code only in strict mode where we want to emulate 5711 * the NET_IP_ALIGN==2 checking. Therefore use an 5712 * unconditional IP align value of '2'. 5713 */ 5714 ip_align = 2; 5715 5716 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5717 if (!tnum_is_aligned(reg_off, size)) { 5718 char tn_buf[48]; 5719 5720 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5721 verbose(env, 5722 "misaligned packet access off %d+%s+%d+%d size %d\n", 5723 ip_align, tn_buf, reg->off, off, size); 5724 return -EACCES; 5725 } 5726 5727 return 0; 5728 } 5729 5730 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5731 const struct bpf_reg_state *reg, 5732 const char *pointer_desc, 5733 int off, int size, bool strict) 5734 { 5735 struct tnum reg_off; 5736 5737 /* Byte size accesses are always allowed. */ 5738 if (!strict || size == 1) 5739 return 0; 5740 5741 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5742 if (!tnum_is_aligned(reg_off, size)) { 5743 char tn_buf[48]; 5744 5745 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5746 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5747 pointer_desc, tn_buf, reg->off, off, size); 5748 return -EACCES; 5749 } 5750 5751 return 0; 5752 } 5753 5754 static int check_ptr_alignment(struct bpf_verifier_env *env, 5755 const struct bpf_reg_state *reg, int off, 5756 int size, bool strict_alignment_once) 5757 { 5758 bool strict = env->strict_alignment || strict_alignment_once; 5759 const char *pointer_desc = ""; 5760 5761 switch (reg->type) { 5762 case PTR_TO_PACKET: 5763 case PTR_TO_PACKET_META: 5764 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5765 * right in front, treat it the very same way. 5766 */ 5767 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5768 case PTR_TO_FLOW_KEYS: 5769 pointer_desc = "flow keys "; 5770 break; 5771 case PTR_TO_MAP_KEY: 5772 pointer_desc = "key "; 5773 break; 5774 case PTR_TO_MAP_VALUE: 5775 pointer_desc = "value "; 5776 break; 5777 case PTR_TO_CTX: 5778 pointer_desc = "context "; 5779 break; 5780 case PTR_TO_STACK: 5781 pointer_desc = "stack "; 5782 /* The stack spill tracking logic in check_stack_write_fixed_off() 5783 * and check_stack_read_fixed_off() relies on stack accesses being 5784 * aligned. 5785 */ 5786 strict = true; 5787 break; 5788 case PTR_TO_SOCKET: 5789 pointer_desc = "sock "; 5790 break; 5791 case PTR_TO_SOCK_COMMON: 5792 pointer_desc = "sock_common "; 5793 break; 5794 case PTR_TO_TCP_SOCK: 5795 pointer_desc = "tcp_sock "; 5796 break; 5797 case PTR_TO_XDP_SOCK: 5798 pointer_desc = "xdp_sock "; 5799 break; 5800 default: 5801 break; 5802 } 5803 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5804 strict); 5805 } 5806 5807 /* starting from main bpf function walk all instructions of the function 5808 * and recursively walk all callees that given function can call. 5809 * Ignore jump and exit insns. 5810 * Since recursion is prevented by check_cfg() this algorithm 5811 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 5812 */ 5813 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx) 5814 { 5815 struct bpf_subprog_info *subprog = env->subprog_info; 5816 struct bpf_insn *insn = env->prog->insnsi; 5817 int depth = 0, frame = 0, i, subprog_end; 5818 bool tail_call_reachable = false; 5819 int ret_insn[MAX_CALL_FRAMES]; 5820 int ret_prog[MAX_CALL_FRAMES]; 5821 int j; 5822 5823 i = subprog[idx].start; 5824 process_func: 5825 /* protect against potential stack overflow that might happen when 5826 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5827 * depth for such case down to 256 so that the worst case scenario 5828 * would result in 8k stack size (32 which is tailcall limit * 256 = 5829 * 8k). 5830 * 5831 * To get the idea what might happen, see an example: 5832 * func1 -> sub rsp, 128 5833 * subfunc1 -> sub rsp, 256 5834 * tailcall1 -> add rsp, 256 5835 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5836 * subfunc2 -> sub rsp, 64 5837 * subfunc22 -> sub rsp, 128 5838 * tailcall2 -> add rsp, 128 5839 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5840 * 5841 * tailcall will unwind the current stack frame but it will not get rid 5842 * of caller's stack as shown on the example above. 5843 */ 5844 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5845 verbose(env, 5846 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5847 depth); 5848 return -EACCES; 5849 } 5850 /* round up to 32-bytes, since this is granularity 5851 * of interpreter stack size 5852 */ 5853 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5854 if (depth > MAX_BPF_STACK) { 5855 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5856 frame + 1, depth); 5857 return -EACCES; 5858 } 5859 continue_func: 5860 subprog_end = subprog[idx + 1].start; 5861 for (; i < subprog_end; i++) { 5862 int next_insn, sidx; 5863 5864 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 5865 bool err = false; 5866 5867 if (!is_bpf_throw_kfunc(insn + i)) 5868 continue; 5869 if (subprog[idx].is_cb) 5870 err = true; 5871 for (int c = 0; c < frame && !err; c++) { 5872 if (subprog[ret_prog[c]].is_cb) { 5873 err = true; 5874 break; 5875 } 5876 } 5877 if (!err) 5878 continue; 5879 verbose(env, 5880 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 5881 i, idx); 5882 return -EINVAL; 5883 } 5884 5885 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5886 continue; 5887 /* remember insn and function to return to */ 5888 ret_insn[frame] = i + 1; 5889 ret_prog[frame] = idx; 5890 5891 /* find the callee */ 5892 next_insn = i + insn[i].imm + 1; 5893 sidx = find_subprog(env, next_insn); 5894 if (sidx < 0) { 5895 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5896 next_insn); 5897 return -EFAULT; 5898 } 5899 if (subprog[sidx].is_async_cb) { 5900 if (subprog[sidx].has_tail_call) { 5901 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 5902 return -EFAULT; 5903 } 5904 /* async callbacks don't increase bpf prog stack size unless called directly */ 5905 if (!bpf_pseudo_call(insn + i)) 5906 continue; 5907 if (subprog[sidx].is_exception_cb) { 5908 verbose(env, "insn %d cannot call exception cb directly\n", i); 5909 return -EINVAL; 5910 } 5911 } 5912 i = next_insn; 5913 idx = sidx; 5914 5915 if (subprog[idx].has_tail_call) 5916 tail_call_reachable = true; 5917 5918 frame++; 5919 if (frame >= MAX_CALL_FRAMES) { 5920 verbose(env, "the call stack of %d frames is too deep !\n", 5921 frame); 5922 return -E2BIG; 5923 } 5924 goto process_func; 5925 } 5926 /* if tail call got detected across bpf2bpf calls then mark each of the 5927 * currently present subprog frames as tail call reachable subprogs; 5928 * this info will be utilized by JIT so that we will be preserving the 5929 * tail call counter throughout bpf2bpf calls combined with tailcalls 5930 */ 5931 if (tail_call_reachable) 5932 for (j = 0; j < frame; j++) { 5933 if (subprog[ret_prog[j]].is_exception_cb) { 5934 verbose(env, "cannot tail call within exception cb\n"); 5935 return -EINVAL; 5936 } 5937 subprog[ret_prog[j]].tail_call_reachable = true; 5938 } 5939 if (subprog[0].tail_call_reachable) 5940 env->prog->aux->tail_call_reachable = true; 5941 5942 /* end of for() loop means the last insn of the 'subprog' 5943 * was reached. Doesn't matter whether it was JA or EXIT 5944 */ 5945 if (frame == 0) 5946 return 0; 5947 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5948 frame--; 5949 i = ret_insn[frame]; 5950 idx = ret_prog[frame]; 5951 goto continue_func; 5952 } 5953 5954 static int check_max_stack_depth(struct bpf_verifier_env *env) 5955 { 5956 struct bpf_subprog_info *si = env->subprog_info; 5957 int ret; 5958 5959 for (int i = 0; i < env->subprog_cnt; i++) { 5960 if (!i || si[i].is_async_cb) { 5961 ret = check_max_stack_depth_subprog(env, i); 5962 if (ret < 0) 5963 return ret; 5964 } 5965 continue; 5966 } 5967 return 0; 5968 } 5969 5970 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 5971 static int get_callee_stack_depth(struct bpf_verifier_env *env, 5972 const struct bpf_insn *insn, int idx) 5973 { 5974 int start = idx + insn->imm + 1, subprog; 5975 5976 subprog = find_subprog(env, start); 5977 if (subprog < 0) { 5978 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5979 start); 5980 return -EFAULT; 5981 } 5982 return env->subprog_info[subprog].stack_depth; 5983 } 5984 #endif 5985 5986 static int __check_buffer_access(struct bpf_verifier_env *env, 5987 const char *buf_info, 5988 const struct bpf_reg_state *reg, 5989 int regno, int off, int size) 5990 { 5991 if (off < 0) { 5992 verbose(env, 5993 "R%d invalid %s buffer access: off=%d, size=%d\n", 5994 regno, buf_info, off, size); 5995 return -EACCES; 5996 } 5997 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5998 char tn_buf[48]; 5999 6000 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6001 verbose(env, 6002 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 6003 regno, off, tn_buf); 6004 return -EACCES; 6005 } 6006 6007 return 0; 6008 } 6009 6010 static int check_tp_buffer_access(struct bpf_verifier_env *env, 6011 const struct bpf_reg_state *reg, 6012 int regno, int off, int size) 6013 { 6014 int err; 6015 6016 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 6017 if (err) 6018 return err; 6019 6020 if (off + size > env->prog->aux->max_tp_access) 6021 env->prog->aux->max_tp_access = off + size; 6022 6023 return 0; 6024 } 6025 6026 static int check_buffer_access(struct bpf_verifier_env *env, 6027 const struct bpf_reg_state *reg, 6028 int regno, int off, int size, 6029 bool zero_size_allowed, 6030 u32 *max_access) 6031 { 6032 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 6033 int err; 6034 6035 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 6036 if (err) 6037 return err; 6038 6039 if (off + size > *max_access) 6040 *max_access = off + size; 6041 6042 return 0; 6043 } 6044 6045 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 6046 static void zext_32_to_64(struct bpf_reg_state *reg) 6047 { 6048 reg->var_off = tnum_subreg(reg->var_off); 6049 __reg_assign_32_into_64(reg); 6050 } 6051 6052 /* truncate register to smaller size (in bytes) 6053 * must be called with size < BPF_REG_SIZE 6054 */ 6055 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 6056 { 6057 u64 mask; 6058 6059 /* clear high bits in bit representation */ 6060 reg->var_off = tnum_cast(reg->var_off, size); 6061 6062 /* fix arithmetic bounds */ 6063 mask = ((u64)1 << (size * 8)) - 1; 6064 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 6065 reg->umin_value &= mask; 6066 reg->umax_value &= mask; 6067 } else { 6068 reg->umin_value = 0; 6069 reg->umax_value = mask; 6070 } 6071 reg->smin_value = reg->umin_value; 6072 reg->smax_value = reg->umax_value; 6073 6074 /* If size is smaller than 32bit register the 32bit register 6075 * values are also truncated so we push 64-bit bounds into 6076 * 32-bit bounds. Above were truncated < 32-bits already. 6077 */ 6078 if (size < 4) { 6079 __mark_reg32_unbounded(reg); 6080 reg_bounds_sync(reg); 6081 } 6082 } 6083 6084 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 6085 { 6086 if (size == 1) { 6087 reg->smin_value = reg->s32_min_value = S8_MIN; 6088 reg->smax_value = reg->s32_max_value = S8_MAX; 6089 } else if (size == 2) { 6090 reg->smin_value = reg->s32_min_value = S16_MIN; 6091 reg->smax_value = reg->s32_max_value = S16_MAX; 6092 } else { 6093 /* size == 4 */ 6094 reg->smin_value = reg->s32_min_value = S32_MIN; 6095 reg->smax_value = reg->s32_max_value = S32_MAX; 6096 } 6097 reg->umin_value = reg->u32_min_value = 0; 6098 reg->umax_value = U64_MAX; 6099 reg->u32_max_value = U32_MAX; 6100 reg->var_off = tnum_unknown; 6101 } 6102 6103 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6104 { 6105 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6106 u64 top_smax_value, top_smin_value; 6107 u64 num_bits = size * 8; 6108 6109 if (tnum_is_const(reg->var_off)) { 6110 u64_cval = reg->var_off.value; 6111 if (size == 1) 6112 reg->var_off = tnum_const((s8)u64_cval); 6113 else if (size == 2) 6114 reg->var_off = tnum_const((s16)u64_cval); 6115 else 6116 /* size == 4 */ 6117 reg->var_off = tnum_const((s32)u64_cval); 6118 6119 u64_cval = reg->var_off.value; 6120 reg->smax_value = reg->smin_value = u64_cval; 6121 reg->umax_value = reg->umin_value = u64_cval; 6122 reg->s32_max_value = reg->s32_min_value = u64_cval; 6123 reg->u32_max_value = reg->u32_min_value = u64_cval; 6124 return; 6125 } 6126 6127 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6128 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6129 6130 if (top_smax_value != top_smin_value) 6131 goto out; 6132 6133 /* find the s64_min and s64_min after sign extension */ 6134 if (size == 1) { 6135 init_s64_max = (s8)reg->smax_value; 6136 init_s64_min = (s8)reg->smin_value; 6137 } else if (size == 2) { 6138 init_s64_max = (s16)reg->smax_value; 6139 init_s64_min = (s16)reg->smin_value; 6140 } else { 6141 init_s64_max = (s32)reg->smax_value; 6142 init_s64_min = (s32)reg->smin_value; 6143 } 6144 6145 s64_max = max(init_s64_max, init_s64_min); 6146 s64_min = min(init_s64_max, init_s64_min); 6147 6148 /* both of s64_max/s64_min positive or negative */ 6149 if ((s64_max >= 0) == (s64_min >= 0)) { 6150 reg->smin_value = reg->s32_min_value = s64_min; 6151 reg->smax_value = reg->s32_max_value = s64_max; 6152 reg->umin_value = reg->u32_min_value = s64_min; 6153 reg->umax_value = reg->u32_max_value = s64_max; 6154 reg->var_off = tnum_range(s64_min, s64_max); 6155 return; 6156 } 6157 6158 out: 6159 set_sext64_default_val(reg, size); 6160 } 6161 6162 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6163 { 6164 if (size == 1) { 6165 reg->s32_min_value = S8_MIN; 6166 reg->s32_max_value = S8_MAX; 6167 } else { 6168 /* size == 2 */ 6169 reg->s32_min_value = S16_MIN; 6170 reg->s32_max_value = S16_MAX; 6171 } 6172 reg->u32_min_value = 0; 6173 reg->u32_max_value = U32_MAX; 6174 } 6175 6176 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6177 { 6178 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6179 u32 top_smax_value, top_smin_value; 6180 u32 num_bits = size * 8; 6181 6182 if (tnum_is_const(reg->var_off)) { 6183 u32_val = reg->var_off.value; 6184 if (size == 1) 6185 reg->var_off = tnum_const((s8)u32_val); 6186 else 6187 reg->var_off = tnum_const((s16)u32_val); 6188 6189 u32_val = reg->var_off.value; 6190 reg->s32_min_value = reg->s32_max_value = u32_val; 6191 reg->u32_min_value = reg->u32_max_value = u32_val; 6192 return; 6193 } 6194 6195 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 6196 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 6197 6198 if (top_smax_value != top_smin_value) 6199 goto out; 6200 6201 /* find the s32_min and s32_min after sign extension */ 6202 if (size == 1) { 6203 init_s32_max = (s8)reg->s32_max_value; 6204 init_s32_min = (s8)reg->s32_min_value; 6205 } else { 6206 /* size == 2 */ 6207 init_s32_max = (s16)reg->s32_max_value; 6208 init_s32_min = (s16)reg->s32_min_value; 6209 } 6210 s32_max = max(init_s32_max, init_s32_min); 6211 s32_min = min(init_s32_max, init_s32_min); 6212 6213 if ((s32_min >= 0) == (s32_max >= 0)) { 6214 reg->s32_min_value = s32_min; 6215 reg->s32_max_value = s32_max; 6216 reg->u32_min_value = (u32)s32_min; 6217 reg->u32_max_value = (u32)s32_max; 6218 return; 6219 } 6220 6221 out: 6222 set_sext32_default_val(reg, size); 6223 } 6224 6225 static bool bpf_map_is_rdonly(const struct bpf_map *map) 6226 { 6227 /* A map is considered read-only if the following condition are true: 6228 * 6229 * 1) BPF program side cannot change any of the map content. The 6230 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6231 * and was set at map creation time. 6232 * 2) The map value(s) have been initialized from user space by a 6233 * loader and then "frozen", such that no new map update/delete 6234 * operations from syscall side are possible for the rest of 6235 * the map's lifetime from that point onwards. 6236 * 3) Any parallel/pending map update/delete operations from syscall 6237 * side have been completed. Only after that point, it's safe to 6238 * assume that map value(s) are immutable. 6239 */ 6240 return (map->map_flags & BPF_F_RDONLY_PROG) && 6241 READ_ONCE(map->frozen) && 6242 !bpf_map_write_active(map); 6243 } 6244 6245 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6246 bool is_ldsx) 6247 { 6248 void *ptr; 6249 u64 addr; 6250 int err; 6251 6252 err = map->ops->map_direct_value_addr(map, &addr, off); 6253 if (err) 6254 return err; 6255 ptr = (void *)(long)addr + off; 6256 6257 switch (size) { 6258 case sizeof(u8): 6259 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6260 break; 6261 case sizeof(u16): 6262 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6263 break; 6264 case sizeof(u32): 6265 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6266 break; 6267 case sizeof(u64): 6268 *val = *(u64 *)ptr; 6269 break; 6270 default: 6271 return -EINVAL; 6272 } 6273 return 0; 6274 } 6275 6276 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6277 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6278 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6279 6280 /* 6281 * Allow list few fields as RCU trusted or full trusted. 6282 * This logic doesn't allow mix tagging and will be removed once GCC supports 6283 * btf_type_tag. 6284 */ 6285 6286 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6287 BTF_TYPE_SAFE_RCU(struct task_struct) { 6288 const cpumask_t *cpus_ptr; 6289 struct css_set __rcu *cgroups; 6290 struct task_struct __rcu *real_parent; 6291 struct task_struct *group_leader; 6292 }; 6293 6294 BTF_TYPE_SAFE_RCU(struct cgroup) { 6295 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6296 struct kernfs_node *kn; 6297 }; 6298 6299 BTF_TYPE_SAFE_RCU(struct css_set) { 6300 struct cgroup *dfl_cgrp; 6301 }; 6302 6303 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6304 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6305 struct file __rcu *exe_file; 6306 }; 6307 6308 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6309 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6310 */ 6311 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6312 struct sock *sk; 6313 }; 6314 6315 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6316 struct sock *sk; 6317 }; 6318 6319 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6320 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6321 struct seq_file *seq; 6322 }; 6323 6324 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6325 struct bpf_iter_meta *meta; 6326 struct task_struct *task; 6327 }; 6328 6329 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6330 struct file *file; 6331 }; 6332 6333 BTF_TYPE_SAFE_TRUSTED(struct file) { 6334 struct inode *f_inode; 6335 }; 6336 6337 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 6338 /* no negative dentry-s in places where bpf can see it */ 6339 struct inode *d_inode; 6340 }; 6341 6342 BTF_TYPE_SAFE_TRUSTED(struct socket) { 6343 struct sock *sk; 6344 }; 6345 6346 static bool type_is_rcu(struct bpf_verifier_env *env, 6347 struct bpf_reg_state *reg, 6348 const char *field_name, u32 btf_id) 6349 { 6350 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6351 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6352 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6353 6354 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6355 } 6356 6357 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6358 struct bpf_reg_state *reg, 6359 const char *field_name, u32 btf_id) 6360 { 6361 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6362 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6363 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6364 6365 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6366 } 6367 6368 static bool type_is_trusted(struct bpf_verifier_env *env, 6369 struct bpf_reg_state *reg, 6370 const char *field_name, u32 btf_id) 6371 { 6372 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 6373 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6374 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6375 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6376 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 6377 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket)); 6378 6379 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6380 } 6381 6382 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6383 struct bpf_reg_state *regs, 6384 int regno, int off, int size, 6385 enum bpf_access_type atype, 6386 int value_regno) 6387 { 6388 struct bpf_reg_state *reg = regs + regno; 6389 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6390 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6391 const char *field_name = NULL; 6392 enum bpf_type_flag flag = 0; 6393 u32 btf_id = 0; 6394 int ret; 6395 6396 if (!env->allow_ptr_leaks) { 6397 verbose(env, 6398 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6399 tname); 6400 return -EPERM; 6401 } 6402 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6403 verbose(env, 6404 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6405 tname); 6406 return -EINVAL; 6407 } 6408 if (off < 0) { 6409 verbose(env, 6410 "R%d is ptr_%s invalid negative access: off=%d\n", 6411 regno, tname, off); 6412 return -EACCES; 6413 } 6414 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6415 char tn_buf[48]; 6416 6417 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6418 verbose(env, 6419 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6420 regno, tname, off, tn_buf); 6421 return -EACCES; 6422 } 6423 6424 if (reg->type & MEM_USER) { 6425 verbose(env, 6426 "R%d is ptr_%s access user memory: off=%d\n", 6427 regno, tname, off); 6428 return -EACCES; 6429 } 6430 6431 if (reg->type & MEM_PERCPU) { 6432 verbose(env, 6433 "R%d is ptr_%s access percpu memory: off=%d\n", 6434 regno, tname, off); 6435 return -EACCES; 6436 } 6437 6438 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6439 if (!btf_is_kernel(reg->btf)) { 6440 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 6441 return -EFAULT; 6442 } 6443 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6444 } else { 6445 /* Writes are permitted with default btf_struct_access for 6446 * program allocated objects (which always have ref_obj_id > 0), 6447 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6448 */ 6449 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6450 verbose(env, "only read is supported\n"); 6451 return -EACCES; 6452 } 6453 6454 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6455 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 6456 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 6457 return -EFAULT; 6458 } 6459 6460 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6461 } 6462 6463 if (ret < 0) 6464 return ret; 6465 6466 if (ret != PTR_TO_BTF_ID) { 6467 /* just mark; */ 6468 6469 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6470 /* If this is an untrusted pointer, all pointers formed by walking it 6471 * also inherit the untrusted flag. 6472 */ 6473 flag = PTR_UNTRUSTED; 6474 6475 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6476 /* By default any pointer obtained from walking a trusted pointer is no 6477 * longer trusted, unless the field being accessed has explicitly been 6478 * marked as inheriting its parent's state of trust (either full or RCU). 6479 * For example: 6480 * 'cgroups' pointer is untrusted if task->cgroups dereference 6481 * happened in a sleepable program outside of bpf_rcu_read_lock() 6482 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6483 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6484 * 6485 * A regular RCU-protected pointer with __rcu tag can also be deemed 6486 * trusted if we are in an RCU CS. Such pointer can be NULL. 6487 */ 6488 if (type_is_trusted(env, reg, field_name, btf_id)) { 6489 flag |= PTR_TRUSTED; 6490 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6491 if (type_is_rcu(env, reg, field_name, btf_id)) { 6492 /* ignore __rcu tag and mark it MEM_RCU */ 6493 flag |= MEM_RCU; 6494 } else if (flag & MEM_RCU || 6495 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6496 /* __rcu tagged pointers can be NULL */ 6497 flag |= MEM_RCU | PTR_MAYBE_NULL; 6498 6499 /* We always trust them */ 6500 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6501 flag & PTR_UNTRUSTED) 6502 flag &= ~PTR_UNTRUSTED; 6503 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6504 /* keep as-is */ 6505 } else { 6506 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6507 clear_trusted_flags(&flag); 6508 } 6509 } else { 6510 /* 6511 * If not in RCU CS or MEM_RCU pointer can be NULL then 6512 * aggressively mark as untrusted otherwise such 6513 * pointers will be plain PTR_TO_BTF_ID without flags 6514 * and will be allowed to be passed into helpers for 6515 * compat reasons. 6516 */ 6517 flag = PTR_UNTRUSTED; 6518 } 6519 } else { 6520 /* Old compat. Deprecated */ 6521 clear_trusted_flags(&flag); 6522 } 6523 6524 if (atype == BPF_READ && value_regno >= 0) 6525 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6526 6527 return 0; 6528 } 6529 6530 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6531 struct bpf_reg_state *regs, 6532 int regno, int off, int size, 6533 enum bpf_access_type atype, 6534 int value_regno) 6535 { 6536 struct bpf_reg_state *reg = regs + regno; 6537 struct bpf_map *map = reg->map_ptr; 6538 struct bpf_reg_state map_reg; 6539 enum bpf_type_flag flag = 0; 6540 const struct btf_type *t; 6541 const char *tname; 6542 u32 btf_id; 6543 int ret; 6544 6545 if (!btf_vmlinux) { 6546 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6547 return -ENOTSUPP; 6548 } 6549 6550 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6551 verbose(env, "map_ptr access not supported for map type %d\n", 6552 map->map_type); 6553 return -ENOTSUPP; 6554 } 6555 6556 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6557 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6558 6559 if (!env->allow_ptr_leaks) { 6560 verbose(env, 6561 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6562 tname); 6563 return -EPERM; 6564 } 6565 6566 if (off < 0) { 6567 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6568 regno, tname, off); 6569 return -EACCES; 6570 } 6571 6572 if (atype != BPF_READ) { 6573 verbose(env, "only read from %s is supported\n", tname); 6574 return -EACCES; 6575 } 6576 6577 /* Simulate access to a PTR_TO_BTF_ID */ 6578 memset(&map_reg, 0, sizeof(map_reg)); 6579 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6580 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6581 if (ret < 0) 6582 return ret; 6583 6584 if (value_regno >= 0) 6585 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6586 6587 return 0; 6588 } 6589 6590 /* Check that the stack access at the given offset is within bounds. The 6591 * maximum valid offset is -1. 6592 * 6593 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6594 * -state->allocated_stack for reads. 6595 */ 6596 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 6597 s64 off, 6598 struct bpf_func_state *state, 6599 enum bpf_access_type t) 6600 { 6601 int min_valid_off; 6602 6603 if (t == BPF_WRITE || env->allow_uninit_stack) 6604 min_valid_off = -MAX_BPF_STACK; 6605 else 6606 min_valid_off = -state->allocated_stack; 6607 6608 if (off < min_valid_off || off > -1) 6609 return -EACCES; 6610 return 0; 6611 } 6612 6613 /* Check that the stack access at 'regno + off' falls within the maximum stack 6614 * bounds. 6615 * 6616 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6617 */ 6618 static int check_stack_access_within_bounds( 6619 struct bpf_verifier_env *env, 6620 int regno, int off, int access_size, 6621 enum bpf_access_src src, enum bpf_access_type type) 6622 { 6623 struct bpf_reg_state *regs = cur_regs(env); 6624 struct bpf_reg_state *reg = regs + regno; 6625 struct bpf_func_state *state = func(env, reg); 6626 s64 min_off, max_off; 6627 int err; 6628 char *err_extra; 6629 6630 if (src == ACCESS_HELPER) 6631 /* We don't know if helpers are reading or writing (or both). */ 6632 err_extra = " indirect access to"; 6633 else if (type == BPF_READ) 6634 err_extra = " read from"; 6635 else 6636 err_extra = " write to"; 6637 6638 if (tnum_is_const(reg->var_off)) { 6639 min_off = (s64)reg->var_off.value + off; 6640 max_off = min_off + access_size; 6641 } else { 6642 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6643 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6644 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6645 err_extra, regno); 6646 return -EACCES; 6647 } 6648 min_off = reg->smin_value + off; 6649 max_off = reg->smax_value + off + access_size; 6650 } 6651 6652 err = check_stack_slot_within_bounds(env, min_off, state, type); 6653 if (!err && max_off > 0) 6654 err = -EINVAL; /* out of stack access into non-negative offsets */ 6655 6656 if (err) { 6657 if (tnum_is_const(reg->var_off)) { 6658 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 6659 err_extra, regno, off, access_size); 6660 } else { 6661 char tn_buf[48]; 6662 6663 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6664 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n", 6665 err_extra, regno, tn_buf, off, access_size); 6666 } 6667 return err; 6668 } 6669 6670 /* Note that there is no stack access with offset zero, so the needed stack 6671 * size is -min_off, not -min_off+1. 6672 */ 6673 return grow_stack_state(env, state, -min_off /* size */); 6674 } 6675 6676 /* check whether memory at (regno + off) is accessible for t = (read | write) 6677 * if t==write, value_regno is a register which value is stored into memory 6678 * if t==read, value_regno is a register which will receive the value from memory 6679 * if t==write && value_regno==-1, some unknown value is stored into memory 6680 * if t==read && value_regno==-1, don't care what we read from memory 6681 */ 6682 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6683 int off, int bpf_size, enum bpf_access_type t, 6684 int value_regno, bool strict_alignment_once, bool is_ldsx) 6685 { 6686 struct bpf_reg_state *regs = cur_regs(env); 6687 struct bpf_reg_state *reg = regs + regno; 6688 int size, err = 0; 6689 6690 size = bpf_size_to_bytes(bpf_size); 6691 if (size < 0) 6692 return size; 6693 6694 /* alignment checks will add in reg->off themselves */ 6695 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6696 if (err) 6697 return err; 6698 6699 /* for access checks, reg->off is just part of off */ 6700 off += reg->off; 6701 6702 if (reg->type == PTR_TO_MAP_KEY) { 6703 if (t == BPF_WRITE) { 6704 verbose(env, "write to change key R%d not allowed\n", regno); 6705 return -EACCES; 6706 } 6707 6708 err = check_mem_region_access(env, regno, off, size, 6709 reg->map_ptr->key_size, false); 6710 if (err) 6711 return err; 6712 if (value_regno >= 0) 6713 mark_reg_unknown(env, regs, value_regno); 6714 } else if (reg->type == PTR_TO_MAP_VALUE) { 6715 struct btf_field *kptr_field = NULL; 6716 6717 if (t == BPF_WRITE && value_regno >= 0 && 6718 is_pointer_value(env, value_regno)) { 6719 verbose(env, "R%d leaks addr into map\n", value_regno); 6720 return -EACCES; 6721 } 6722 err = check_map_access_type(env, regno, off, size, t); 6723 if (err) 6724 return err; 6725 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6726 if (err) 6727 return err; 6728 if (tnum_is_const(reg->var_off)) 6729 kptr_field = btf_record_find(reg->map_ptr->record, 6730 off + reg->var_off.value, BPF_KPTR); 6731 if (kptr_field) { 6732 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6733 } else if (t == BPF_READ && value_regno >= 0) { 6734 struct bpf_map *map = reg->map_ptr; 6735 6736 /* if map is read-only, track its contents as scalars */ 6737 if (tnum_is_const(reg->var_off) && 6738 bpf_map_is_rdonly(map) && 6739 map->ops->map_direct_value_addr) { 6740 int map_off = off + reg->var_off.value; 6741 u64 val = 0; 6742 6743 err = bpf_map_direct_read(map, map_off, size, 6744 &val, is_ldsx); 6745 if (err) 6746 return err; 6747 6748 regs[value_regno].type = SCALAR_VALUE; 6749 __mark_reg_known(®s[value_regno], val); 6750 } else { 6751 mark_reg_unknown(env, regs, value_regno); 6752 } 6753 } 6754 } else if (base_type(reg->type) == PTR_TO_MEM) { 6755 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6756 6757 if (type_may_be_null(reg->type)) { 6758 verbose(env, "R%d invalid mem access '%s'\n", regno, 6759 reg_type_str(env, reg->type)); 6760 return -EACCES; 6761 } 6762 6763 if (t == BPF_WRITE && rdonly_mem) { 6764 verbose(env, "R%d cannot write into %s\n", 6765 regno, reg_type_str(env, reg->type)); 6766 return -EACCES; 6767 } 6768 6769 if (t == BPF_WRITE && value_regno >= 0 && 6770 is_pointer_value(env, value_regno)) { 6771 verbose(env, "R%d leaks addr into mem\n", value_regno); 6772 return -EACCES; 6773 } 6774 6775 err = check_mem_region_access(env, regno, off, size, 6776 reg->mem_size, false); 6777 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6778 mark_reg_unknown(env, regs, value_regno); 6779 } else if (reg->type == PTR_TO_CTX) { 6780 enum bpf_reg_type reg_type = SCALAR_VALUE; 6781 struct btf *btf = NULL; 6782 u32 btf_id = 0; 6783 6784 if (t == BPF_WRITE && value_regno >= 0 && 6785 is_pointer_value(env, value_regno)) { 6786 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6787 return -EACCES; 6788 } 6789 6790 err = check_ptr_off_reg(env, reg, regno); 6791 if (err < 0) 6792 return err; 6793 6794 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 6795 &btf_id); 6796 if (err) 6797 verbose_linfo(env, insn_idx, "; "); 6798 if (!err && t == BPF_READ && value_regno >= 0) { 6799 /* ctx access returns either a scalar, or a 6800 * PTR_TO_PACKET[_META,_END]. In the latter 6801 * case, we know the offset is zero. 6802 */ 6803 if (reg_type == SCALAR_VALUE) { 6804 mark_reg_unknown(env, regs, value_regno); 6805 } else { 6806 mark_reg_known_zero(env, regs, 6807 value_regno); 6808 if (type_may_be_null(reg_type)) 6809 regs[value_regno].id = ++env->id_gen; 6810 /* A load of ctx field could have different 6811 * actual load size with the one encoded in the 6812 * insn. When the dst is PTR, it is for sure not 6813 * a sub-register. 6814 */ 6815 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6816 if (base_type(reg_type) == PTR_TO_BTF_ID) { 6817 regs[value_regno].btf = btf; 6818 regs[value_regno].btf_id = btf_id; 6819 } 6820 } 6821 regs[value_regno].type = reg_type; 6822 } 6823 6824 } else if (reg->type == PTR_TO_STACK) { 6825 /* Basic bounds checks. */ 6826 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 6827 if (err) 6828 return err; 6829 6830 if (t == BPF_READ) 6831 err = check_stack_read(env, regno, off, size, 6832 value_regno); 6833 else 6834 err = check_stack_write(env, regno, off, size, 6835 value_regno, insn_idx); 6836 } else if (reg_is_pkt_pointer(reg)) { 6837 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6838 verbose(env, "cannot write into packet\n"); 6839 return -EACCES; 6840 } 6841 if (t == BPF_WRITE && value_regno >= 0 && 6842 is_pointer_value(env, value_regno)) { 6843 verbose(env, "R%d leaks addr into packet\n", 6844 value_regno); 6845 return -EACCES; 6846 } 6847 err = check_packet_access(env, regno, off, size, false); 6848 if (!err && t == BPF_READ && value_regno >= 0) 6849 mark_reg_unknown(env, regs, value_regno); 6850 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6851 if (t == BPF_WRITE && value_regno >= 0 && 6852 is_pointer_value(env, value_regno)) { 6853 verbose(env, "R%d leaks addr into flow keys\n", 6854 value_regno); 6855 return -EACCES; 6856 } 6857 6858 err = check_flow_keys_access(env, off, size); 6859 if (!err && t == BPF_READ && value_regno >= 0) 6860 mark_reg_unknown(env, regs, value_regno); 6861 } else if (type_is_sk_pointer(reg->type)) { 6862 if (t == BPF_WRITE) { 6863 verbose(env, "R%d cannot write into %s\n", 6864 regno, reg_type_str(env, reg->type)); 6865 return -EACCES; 6866 } 6867 err = check_sock_access(env, insn_idx, regno, off, size, t); 6868 if (!err && value_regno >= 0) 6869 mark_reg_unknown(env, regs, value_regno); 6870 } else if (reg->type == PTR_TO_TP_BUFFER) { 6871 err = check_tp_buffer_access(env, reg, regno, off, size); 6872 if (!err && t == BPF_READ && value_regno >= 0) 6873 mark_reg_unknown(env, regs, value_regno); 6874 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6875 !type_may_be_null(reg->type)) { 6876 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 6877 value_regno); 6878 } else if (reg->type == CONST_PTR_TO_MAP) { 6879 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 6880 value_regno); 6881 } else if (base_type(reg->type) == PTR_TO_BUF) { 6882 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6883 u32 *max_access; 6884 6885 if (rdonly_mem) { 6886 if (t == BPF_WRITE) { 6887 verbose(env, "R%d cannot write into %s\n", 6888 regno, reg_type_str(env, reg->type)); 6889 return -EACCES; 6890 } 6891 max_access = &env->prog->aux->max_rdonly_access; 6892 } else { 6893 max_access = &env->prog->aux->max_rdwr_access; 6894 } 6895 6896 err = check_buffer_access(env, reg, regno, off, size, false, 6897 max_access); 6898 6899 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6900 mark_reg_unknown(env, regs, value_regno); 6901 } else { 6902 verbose(env, "R%d invalid mem access '%s'\n", regno, 6903 reg_type_str(env, reg->type)); 6904 return -EACCES; 6905 } 6906 6907 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6908 regs[value_regno].type == SCALAR_VALUE) { 6909 if (!is_ldsx) 6910 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6911 coerce_reg_to_size(®s[value_regno], size); 6912 else 6913 coerce_reg_to_size_sx(®s[value_regno], size); 6914 } 6915 return err; 6916 } 6917 6918 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 6919 { 6920 int load_reg; 6921 int err; 6922 6923 switch (insn->imm) { 6924 case BPF_ADD: 6925 case BPF_ADD | BPF_FETCH: 6926 case BPF_AND: 6927 case BPF_AND | BPF_FETCH: 6928 case BPF_OR: 6929 case BPF_OR | BPF_FETCH: 6930 case BPF_XOR: 6931 case BPF_XOR | BPF_FETCH: 6932 case BPF_XCHG: 6933 case BPF_CMPXCHG: 6934 break; 6935 default: 6936 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 6937 return -EINVAL; 6938 } 6939 6940 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6941 verbose(env, "invalid atomic operand size\n"); 6942 return -EINVAL; 6943 } 6944 6945 /* check src1 operand */ 6946 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6947 if (err) 6948 return err; 6949 6950 /* check src2 operand */ 6951 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6952 if (err) 6953 return err; 6954 6955 if (insn->imm == BPF_CMPXCHG) { 6956 /* Check comparison of R0 with memory location */ 6957 const u32 aux_reg = BPF_REG_0; 6958 6959 err = check_reg_arg(env, aux_reg, SRC_OP); 6960 if (err) 6961 return err; 6962 6963 if (is_pointer_value(env, aux_reg)) { 6964 verbose(env, "R%d leaks addr into mem\n", aux_reg); 6965 return -EACCES; 6966 } 6967 } 6968 6969 if (is_pointer_value(env, insn->src_reg)) { 6970 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 6971 return -EACCES; 6972 } 6973 6974 if (is_ctx_reg(env, insn->dst_reg) || 6975 is_pkt_reg(env, insn->dst_reg) || 6976 is_flow_key_reg(env, insn->dst_reg) || 6977 is_sk_reg(env, insn->dst_reg)) { 6978 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6979 insn->dst_reg, 6980 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6981 return -EACCES; 6982 } 6983 6984 if (insn->imm & BPF_FETCH) { 6985 if (insn->imm == BPF_CMPXCHG) 6986 load_reg = BPF_REG_0; 6987 else 6988 load_reg = insn->src_reg; 6989 6990 /* check and record load of old value */ 6991 err = check_reg_arg(env, load_reg, DST_OP); 6992 if (err) 6993 return err; 6994 } else { 6995 /* This instruction accesses a memory location but doesn't 6996 * actually load it into a register. 6997 */ 6998 load_reg = -1; 6999 } 7000 7001 /* Check whether we can read the memory, with second call for fetch 7002 * case to simulate the register fill. 7003 */ 7004 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7005 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 7006 if (!err && load_reg >= 0) 7007 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7008 BPF_SIZE(insn->code), BPF_READ, load_reg, 7009 true, false); 7010 if (err) 7011 return err; 7012 7013 /* Check whether we can write into the same memory. */ 7014 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7015 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 7016 if (err) 7017 return err; 7018 return 0; 7019 } 7020 7021 /* When register 'regno' is used to read the stack (either directly or through 7022 * a helper function) make sure that it's within stack boundary and, depending 7023 * on the access type and privileges, that all elements of the stack are 7024 * initialized. 7025 * 7026 * 'off' includes 'regno->off', but not its dynamic part (if any). 7027 * 7028 * All registers that have been spilled on the stack in the slots within the 7029 * read offsets are marked as read. 7030 */ 7031 static int check_stack_range_initialized( 7032 struct bpf_verifier_env *env, int regno, int off, 7033 int access_size, bool zero_size_allowed, 7034 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 7035 { 7036 struct bpf_reg_state *reg = reg_state(env, regno); 7037 struct bpf_func_state *state = func(env, reg); 7038 int err, min_off, max_off, i, j, slot, spi; 7039 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 7040 enum bpf_access_type bounds_check_type; 7041 /* Some accesses can write anything into the stack, others are 7042 * read-only. 7043 */ 7044 bool clobber = false; 7045 7046 if (access_size == 0 && !zero_size_allowed) { 7047 verbose(env, "invalid zero-sized read\n"); 7048 return -EACCES; 7049 } 7050 7051 if (type == ACCESS_HELPER) { 7052 /* The bounds checks for writes are more permissive than for 7053 * reads. However, if raw_mode is not set, we'll do extra 7054 * checks below. 7055 */ 7056 bounds_check_type = BPF_WRITE; 7057 clobber = true; 7058 } else { 7059 bounds_check_type = BPF_READ; 7060 } 7061 err = check_stack_access_within_bounds(env, regno, off, access_size, 7062 type, bounds_check_type); 7063 if (err) 7064 return err; 7065 7066 7067 if (tnum_is_const(reg->var_off)) { 7068 min_off = max_off = reg->var_off.value + off; 7069 } else { 7070 /* Variable offset is prohibited for unprivileged mode for 7071 * simplicity since it requires corresponding support in 7072 * Spectre masking for stack ALU. 7073 * See also retrieve_ptr_limit(). 7074 */ 7075 if (!env->bypass_spec_v1) { 7076 char tn_buf[48]; 7077 7078 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7079 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 7080 regno, err_extra, tn_buf); 7081 return -EACCES; 7082 } 7083 /* Only initialized buffer on stack is allowed to be accessed 7084 * with variable offset. With uninitialized buffer it's hard to 7085 * guarantee that whole memory is marked as initialized on 7086 * helper return since specific bounds are unknown what may 7087 * cause uninitialized stack leaking. 7088 */ 7089 if (meta && meta->raw_mode) 7090 meta = NULL; 7091 7092 min_off = reg->smin_value + off; 7093 max_off = reg->smax_value + off; 7094 } 7095 7096 if (meta && meta->raw_mode) { 7097 /* Ensure we won't be overwriting dynptrs when simulating byte 7098 * by byte access in check_helper_call using meta.access_size. 7099 * This would be a problem if we have a helper in the future 7100 * which takes: 7101 * 7102 * helper(uninit_mem, len, dynptr) 7103 * 7104 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 7105 * may end up writing to dynptr itself when touching memory from 7106 * arg 1. This can be relaxed on a case by case basis for known 7107 * safe cases, but reject due to the possibilitiy of aliasing by 7108 * default. 7109 */ 7110 for (i = min_off; i < max_off + access_size; i++) { 7111 int stack_off = -i - 1; 7112 7113 spi = __get_spi(i); 7114 /* raw_mode may write past allocated_stack */ 7115 if (state->allocated_stack <= stack_off) 7116 continue; 7117 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 7118 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 7119 return -EACCES; 7120 } 7121 } 7122 meta->access_size = access_size; 7123 meta->regno = regno; 7124 return 0; 7125 } 7126 7127 for (i = min_off; i < max_off + access_size; i++) { 7128 u8 *stype; 7129 7130 slot = -i - 1; 7131 spi = slot / BPF_REG_SIZE; 7132 if (state->allocated_stack <= slot) { 7133 verbose(env, "verifier bug: allocated_stack too small"); 7134 return -EFAULT; 7135 } 7136 7137 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 7138 if (*stype == STACK_MISC) 7139 goto mark; 7140 if ((*stype == STACK_ZERO) || 7141 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 7142 if (clobber) { 7143 /* helper can write anything into the stack */ 7144 *stype = STACK_MISC; 7145 } 7146 goto mark; 7147 } 7148 7149 if (is_spilled_reg(&state->stack[spi]) && 7150 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 7151 env->allow_ptr_leaks)) { 7152 if (clobber) { 7153 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 7154 for (j = 0; j < BPF_REG_SIZE; j++) 7155 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 7156 } 7157 goto mark; 7158 } 7159 7160 if (tnum_is_const(reg->var_off)) { 7161 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 7162 err_extra, regno, min_off, i - min_off, access_size); 7163 } else { 7164 char tn_buf[48]; 7165 7166 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7167 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 7168 err_extra, regno, tn_buf, i - min_off, access_size); 7169 } 7170 return -EACCES; 7171 mark: 7172 /* reading any byte out of 8-byte 'spill_slot' will cause 7173 * the whole slot to be marked as 'read' 7174 */ 7175 mark_reg_read(env, &state->stack[spi].spilled_ptr, 7176 state->stack[spi].spilled_ptr.parent, 7177 REG_LIVE_READ64); 7178 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 7179 * be sure that whether stack slot is written to or not. Hence, 7180 * we must still conservatively propagate reads upwards even if 7181 * helper may write to the entire memory range. 7182 */ 7183 } 7184 return 0; 7185 } 7186 7187 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 7188 int access_size, bool zero_size_allowed, 7189 struct bpf_call_arg_meta *meta) 7190 { 7191 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7192 u32 *max_access; 7193 7194 switch (base_type(reg->type)) { 7195 case PTR_TO_PACKET: 7196 case PTR_TO_PACKET_META: 7197 return check_packet_access(env, regno, reg->off, access_size, 7198 zero_size_allowed); 7199 case PTR_TO_MAP_KEY: 7200 if (meta && meta->raw_mode) { 7201 verbose(env, "R%d cannot write into %s\n", regno, 7202 reg_type_str(env, reg->type)); 7203 return -EACCES; 7204 } 7205 return check_mem_region_access(env, regno, reg->off, access_size, 7206 reg->map_ptr->key_size, false); 7207 case PTR_TO_MAP_VALUE: 7208 if (check_map_access_type(env, regno, reg->off, access_size, 7209 meta && meta->raw_mode ? BPF_WRITE : 7210 BPF_READ)) 7211 return -EACCES; 7212 return check_map_access(env, regno, reg->off, access_size, 7213 zero_size_allowed, ACCESS_HELPER); 7214 case PTR_TO_MEM: 7215 if (type_is_rdonly_mem(reg->type)) { 7216 if (meta && meta->raw_mode) { 7217 verbose(env, "R%d cannot write into %s\n", regno, 7218 reg_type_str(env, reg->type)); 7219 return -EACCES; 7220 } 7221 } 7222 return check_mem_region_access(env, regno, reg->off, 7223 access_size, reg->mem_size, 7224 zero_size_allowed); 7225 case PTR_TO_BUF: 7226 if (type_is_rdonly_mem(reg->type)) { 7227 if (meta && meta->raw_mode) { 7228 verbose(env, "R%d cannot write into %s\n", regno, 7229 reg_type_str(env, reg->type)); 7230 return -EACCES; 7231 } 7232 7233 max_access = &env->prog->aux->max_rdonly_access; 7234 } else { 7235 max_access = &env->prog->aux->max_rdwr_access; 7236 } 7237 return check_buffer_access(env, reg, regno, reg->off, 7238 access_size, zero_size_allowed, 7239 max_access); 7240 case PTR_TO_STACK: 7241 return check_stack_range_initialized( 7242 env, 7243 regno, reg->off, access_size, 7244 zero_size_allowed, ACCESS_HELPER, meta); 7245 case PTR_TO_BTF_ID: 7246 return check_ptr_to_btf_access(env, regs, regno, reg->off, 7247 access_size, BPF_READ, -1); 7248 case PTR_TO_CTX: 7249 /* in case the function doesn't know how to access the context, 7250 * (because we are in a program of type SYSCALL for example), we 7251 * can not statically check its size. 7252 * Dynamically check it now. 7253 */ 7254 if (!env->ops->convert_ctx_access) { 7255 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 7256 int offset = access_size - 1; 7257 7258 /* Allow zero-byte read from PTR_TO_CTX */ 7259 if (access_size == 0) 7260 return zero_size_allowed ? 0 : -EACCES; 7261 7262 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 7263 atype, -1, false, false); 7264 } 7265 7266 fallthrough; 7267 default: /* scalar_value or invalid ptr */ 7268 /* Allow zero-byte read from NULL, regardless of pointer type */ 7269 if (zero_size_allowed && access_size == 0 && 7270 register_is_null(reg)) 7271 return 0; 7272 7273 verbose(env, "R%d type=%s ", regno, 7274 reg_type_str(env, reg->type)); 7275 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7276 return -EACCES; 7277 } 7278 } 7279 7280 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 7281 * size. 7282 * 7283 * @regno is the register containing the access size. regno-1 is the register 7284 * containing the pointer. 7285 */ 7286 static int check_mem_size_reg(struct bpf_verifier_env *env, 7287 struct bpf_reg_state *reg, u32 regno, 7288 bool zero_size_allowed, 7289 struct bpf_call_arg_meta *meta) 7290 { 7291 int err; 7292 7293 /* This is used to refine r0 return value bounds for helpers 7294 * that enforce this value as an upper bound on return values. 7295 * See do_refine_retval_range() for helpers that can refine 7296 * the return value. C type of helper is u32 so we pull register 7297 * bound from umax_value however, if negative verifier errors 7298 * out. Only upper bounds can be learned because retval is an 7299 * int type and negative retvals are allowed. 7300 */ 7301 meta->msize_max_value = reg->umax_value; 7302 7303 /* The register is SCALAR_VALUE; the access check 7304 * happens using its boundaries. 7305 */ 7306 if (!tnum_is_const(reg->var_off)) 7307 /* For unprivileged variable accesses, disable raw 7308 * mode so that the program is required to 7309 * initialize all the memory that the helper could 7310 * just partially fill up. 7311 */ 7312 meta = NULL; 7313 7314 if (reg->smin_value < 0) { 7315 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7316 regno); 7317 return -EACCES; 7318 } 7319 7320 if (reg->umin_value == 0 && !zero_size_allowed) { 7321 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n", 7322 regno, reg->umin_value, reg->umax_value); 7323 return -EACCES; 7324 } 7325 7326 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7327 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7328 regno); 7329 return -EACCES; 7330 } 7331 err = check_helper_mem_access(env, regno - 1, 7332 reg->umax_value, 7333 zero_size_allowed, meta); 7334 if (!err) 7335 err = mark_chain_precision(env, regno); 7336 return err; 7337 } 7338 7339 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7340 u32 regno, u32 mem_size) 7341 { 7342 bool may_be_null = type_may_be_null(reg->type); 7343 struct bpf_reg_state saved_reg; 7344 struct bpf_call_arg_meta meta; 7345 int err; 7346 7347 if (register_is_null(reg)) 7348 return 0; 7349 7350 memset(&meta, 0, sizeof(meta)); 7351 /* Assuming that the register contains a value check if the memory 7352 * access is safe. Temporarily save and restore the register's state as 7353 * the conversion shouldn't be visible to a caller. 7354 */ 7355 if (may_be_null) { 7356 saved_reg = *reg; 7357 mark_ptr_not_null_reg(reg); 7358 } 7359 7360 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 7361 /* Check access for BPF_WRITE */ 7362 meta.raw_mode = true; 7363 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 7364 7365 if (may_be_null) 7366 *reg = saved_reg; 7367 7368 return err; 7369 } 7370 7371 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7372 u32 regno) 7373 { 7374 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7375 bool may_be_null = type_may_be_null(mem_reg->type); 7376 struct bpf_reg_state saved_reg; 7377 struct bpf_call_arg_meta meta; 7378 int err; 7379 7380 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7381 7382 memset(&meta, 0, sizeof(meta)); 7383 7384 if (may_be_null) { 7385 saved_reg = *mem_reg; 7386 mark_ptr_not_null_reg(mem_reg); 7387 } 7388 7389 err = check_mem_size_reg(env, reg, regno, true, &meta); 7390 /* Check access for BPF_WRITE */ 7391 meta.raw_mode = true; 7392 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 7393 7394 if (may_be_null) 7395 *mem_reg = saved_reg; 7396 return err; 7397 } 7398 7399 /* Implementation details: 7400 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7401 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7402 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7403 * Two separate bpf_obj_new will also have different reg->id. 7404 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7405 * clears reg->id after value_or_null->value transition, since the verifier only 7406 * cares about the range of access to valid map value pointer and doesn't care 7407 * about actual address of the map element. 7408 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7409 * reg->id > 0 after value_or_null->value transition. By doing so 7410 * two bpf_map_lookups will be considered two different pointers that 7411 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7412 * returned from bpf_obj_new. 7413 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7414 * dead-locks. 7415 * Since only one bpf_spin_lock is allowed the checks are simpler than 7416 * reg_is_refcounted() logic. The verifier needs to remember only 7417 * one spin_lock instead of array of acquired_refs. 7418 * cur_state->active_lock remembers which map value element or allocated 7419 * object got locked and clears it after bpf_spin_unlock. 7420 */ 7421 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 7422 bool is_lock) 7423 { 7424 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7425 struct bpf_verifier_state *cur = env->cur_state; 7426 bool is_const = tnum_is_const(reg->var_off); 7427 u64 val = reg->var_off.value; 7428 struct bpf_map *map = NULL; 7429 struct btf *btf = NULL; 7430 struct btf_record *rec; 7431 7432 if (!is_const) { 7433 verbose(env, 7434 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 7435 regno); 7436 return -EINVAL; 7437 } 7438 if (reg->type == PTR_TO_MAP_VALUE) { 7439 map = reg->map_ptr; 7440 if (!map->btf) { 7441 verbose(env, 7442 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 7443 map->name); 7444 return -EINVAL; 7445 } 7446 } else { 7447 btf = reg->btf; 7448 } 7449 7450 rec = reg_btf_record(reg); 7451 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 7452 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 7453 map ? map->name : "kptr"); 7454 return -EINVAL; 7455 } 7456 if (rec->spin_lock_off != val + reg->off) { 7457 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 7458 val + reg->off, rec->spin_lock_off); 7459 return -EINVAL; 7460 } 7461 if (is_lock) { 7462 if (cur->active_lock.ptr) { 7463 verbose(env, 7464 "Locking two bpf_spin_locks are not allowed\n"); 7465 return -EINVAL; 7466 } 7467 if (map) 7468 cur->active_lock.ptr = map; 7469 else 7470 cur->active_lock.ptr = btf; 7471 cur->active_lock.id = reg->id; 7472 } else { 7473 void *ptr; 7474 7475 if (map) 7476 ptr = map; 7477 else 7478 ptr = btf; 7479 7480 if (!cur->active_lock.ptr) { 7481 verbose(env, "bpf_spin_unlock without taking a lock\n"); 7482 return -EINVAL; 7483 } 7484 if (cur->active_lock.ptr != ptr || 7485 cur->active_lock.id != reg->id) { 7486 verbose(env, "bpf_spin_unlock of different lock\n"); 7487 return -EINVAL; 7488 } 7489 7490 invalidate_non_owning_refs(env); 7491 7492 cur->active_lock.ptr = NULL; 7493 cur->active_lock.id = 0; 7494 } 7495 return 0; 7496 } 7497 7498 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7499 struct bpf_call_arg_meta *meta) 7500 { 7501 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7502 bool is_const = tnum_is_const(reg->var_off); 7503 struct bpf_map *map = reg->map_ptr; 7504 u64 val = reg->var_off.value; 7505 7506 if (!is_const) { 7507 verbose(env, 7508 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 7509 regno); 7510 return -EINVAL; 7511 } 7512 if (!map->btf) { 7513 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 7514 map->name); 7515 return -EINVAL; 7516 } 7517 if (!btf_record_has_field(map->record, BPF_TIMER)) { 7518 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 7519 return -EINVAL; 7520 } 7521 if (map->record->timer_off != val + reg->off) { 7522 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 7523 val + reg->off, map->record->timer_off); 7524 return -EINVAL; 7525 } 7526 if (meta->map_ptr) { 7527 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 7528 return -EFAULT; 7529 } 7530 meta->map_uid = reg->map_uid; 7531 meta->map_ptr = map; 7532 return 0; 7533 } 7534 7535 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7536 struct bpf_call_arg_meta *meta) 7537 { 7538 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7539 struct bpf_map *map_ptr = reg->map_ptr; 7540 struct btf_field *kptr_field; 7541 u32 kptr_off; 7542 7543 if (!tnum_is_const(reg->var_off)) { 7544 verbose(env, 7545 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7546 regno); 7547 return -EINVAL; 7548 } 7549 if (!map_ptr->btf) { 7550 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7551 map_ptr->name); 7552 return -EINVAL; 7553 } 7554 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 7555 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 7556 return -EINVAL; 7557 } 7558 7559 meta->map_ptr = map_ptr; 7560 kptr_off = reg->off + reg->var_off.value; 7561 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 7562 if (!kptr_field) { 7563 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7564 return -EACCES; 7565 } 7566 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7567 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7568 return -EACCES; 7569 } 7570 meta->kptr_field = kptr_field; 7571 return 0; 7572 } 7573 7574 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7575 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7576 * 7577 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7578 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7579 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7580 * 7581 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7582 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7583 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7584 * mutate the view of the dynptr and also possibly destroy it. In the latter 7585 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7586 * memory that dynptr points to. 7587 * 7588 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7589 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7590 * readonly dynptr view yet, hence only the first case is tracked and checked. 7591 * 7592 * This is consistent with how C applies the const modifier to a struct object, 7593 * where the pointer itself inside bpf_dynptr becomes const but not what it 7594 * points to. 7595 * 7596 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7597 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7598 */ 7599 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7600 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7601 { 7602 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7603 int err; 7604 7605 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7606 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7607 */ 7608 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7609 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 7610 return -EFAULT; 7611 } 7612 7613 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7614 * constructing a mutable bpf_dynptr object. 7615 * 7616 * Currently, this is only possible with PTR_TO_STACK 7617 * pointing to a region of at least 16 bytes which doesn't 7618 * contain an existing bpf_dynptr. 7619 * 7620 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7621 * mutated or destroyed. However, the memory it points to 7622 * may be mutated. 7623 * 7624 * None - Points to a initialized dynptr that can be mutated and 7625 * destroyed, including mutation of the memory it points 7626 * to. 7627 */ 7628 if (arg_type & MEM_UNINIT) { 7629 int i; 7630 7631 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7632 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7633 return -EINVAL; 7634 } 7635 7636 /* we write BPF_DW bits (8 bytes) at a time */ 7637 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7638 err = check_mem_access(env, insn_idx, regno, 7639 i, BPF_DW, BPF_WRITE, -1, false, false); 7640 if (err) 7641 return err; 7642 } 7643 7644 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7645 } else /* MEM_RDONLY and None case from above */ { 7646 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7647 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7648 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7649 return -EINVAL; 7650 } 7651 7652 if (!is_dynptr_reg_valid_init(env, reg)) { 7653 verbose(env, 7654 "Expected an initialized dynptr as arg #%d\n", 7655 regno); 7656 return -EINVAL; 7657 } 7658 7659 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7660 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7661 verbose(env, 7662 "Expected a dynptr of type %s as arg #%d\n", 7663 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 7664 return -EINVAL; 7665 } 7666 7667 err = mark_dynptr_read(env, reg); 7668 } 7669 return err; 7670 } 7671 7672 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7673 { 7674 struct bpf_func_state *state = func(env, reg); 7675 7676 return state->stack[spi].spilled_ptr.ref_obj_id; 7677 } 7678 7679 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7680 { 7681 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7682 } 7683 7684 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7685 { 7686 return meta->kfunc_flags & KF_ITER_NEW; 7687 } 7688 7689 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7690 { 7691 return meta->kfunc_flags & KF_ITER_NEXT; 7692 } 7693 7694 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7695 { 7696 return meta->kfunc_flags & KF_ITER_DESTROY; 7697 } 7698 7699 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg) 7700 { 7701 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7702 * kfunc is iter state pointer 7703 */ 7704 return arg == 0 && is_iter_kfunc(meta); 7705 } 7706 7707 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7708 struct bpf_kfunc_call_arg_meta *meta) 7709 { 7710 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7711 const struct btf_type *t; 7712 const struct btf_param *arg; 7713 int spi, err, i, nr_slots; 7714 u32 btf_id; 7715 7716 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */ 7717 arg = &btf_params(meta->func_proto)[0]; 7718 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */ 7719 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */ 7720 nr_slots = t->size / BPF_REG_SIZE; 7721 7722 if (is_iter_new_kfunc(meta)) { 7723 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7724 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7725 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 7726 iter_type_str(meta->btf, btf_id), regno); 7727 return -EINVAL; 7728 } 7729 7730 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7731 err = check_mem_access(env, insn_idx, regno, 7732 i, BPF_DW, BPF_WRITE, -1, false, false); 7733 if (err) 7734 return err; 7735 } 7736 7737 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 7738 if (err) 7739 return err; 7740 } else { 7741 /* iter_next() or iter_destroy() expect initialized iter state*/ 7742 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 7743 switch (err) { 7744 case 0: 7745 break; 7746 case -EINVAL: 7747 verbose(env, "expected an initialized iter_%s as arg #%d\n", 7748 iter_type_str(meta->btf, btf_id), regno); 7749 return err; 7750 case -EPROTO: 7751 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 7752 return err; 7753 default: 7754 return err; 7755 } 7756 7757 spi = iter_get_spi(env, reg, nr_slots); 7758 if (spi < 0) 7759 return spi; 7760 7761 err = mark_iter_read(env, reg, spi, nr_slots); 7762 if (err) 7763 return err; 7764 7765 /* remember meta->iter info for process_iter_next_call() */ 7766 meta->iter.spi = spi; 7767 meta->iter.frameno = reg->frameno; 7768 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 7769 7770 if (is_iter_destroy_kfunc(meta)) { 7771 err = unmark_stack_slots_iter(env, reg, nr_slots); 7772 if (err) 7773 return err; 7774 } 7775 } 7776 7777 return 0; 7778 } 7779 7780 /* Look for a previous loop entry at insn_idx: nearest parent state 7781 * stopped at insn_idx with callsites matching those in cur->frame. 7782 */ 7783 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 7784 struct bpf_verifier_state *cur, 7785 int insn_idx) 7786 { 7787 struct bpf_verifier_state_list *sl; 7788 struct bpf_verifier_state *st; 7789 7790 /* Explored states are pushed in stack order, most recent states come first */ 7791 sl = *explored_state(env, insn_idx); 7792 for (; sl; sl = sl->next) { 7793 /* If st->branches != 0 state is a part of current DFS verification path, 7794 * hence cur & st for a loop. 7795 */ 7796 st = &sl->state; 7797 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 7798 st->dfs_depth < cur->dfs_depth) 7799 return st; 7800 } 7801 7802 return NULL; 7803 } 7804 7805 static void reset_idmap_scratch(struct bpf_verifier_env *env); 7806 static bool regs_exact(const struct bpf_reg_state *rold, 7807 const struct bpf_reg_state *rcur, 7808 struct bpf_idmap *idmap); 7809 7810 static void maybe_widen_reg(struct bpf_verifier_env *env, 7811 struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 7812 struct bpf_idmap *idmap) 7813 { 7814 if (rold->type != SCALAR_VALUE) 7815 return; 7816 if (rold->type != rcur->type) 7817 return; 7818 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap)) 7819 return; 7820 __mark_reg_unknown(env, rcur); 7821 } 7822 7823 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 7824 struct bpf_verifier_state *old, 7825 struct bpf_verifier_state *cur) 7826 { 7827 struct bpf_func_state *fold, *fcur; 7828 int i, fr; 7829 7830 reset_idmap_scratch(env); 7831 for (fr = old->curframe; fr >= 0; fr--) { 7832 fold = old->frame[fr]; 7833 fcur = cur->frame[fr]; 7834 7835 for (i = 0; i < MAX_BPF_REG; i++) 7836 maybe_widen_reg(env, 7837 &fold->regs[i], 7838 &fcur->regs[i], 7839 &env->idmap_scratch); 7840 7841 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) { 7842 if (!is_spilled_reg(&fold->stack[i]) || 7843 !is_spilled_reg(&fcur->stack[i])) 7844 continue; 7845 7846 maybe_widen_reg(env, 7847 &fold->stack[i].spilled_ptr, 7848 &fcur->stack[i].spilled_ptr, 7849 &env->idmap_scratch); 7850 } 7851 } 7852 return 0; 7853 } 7854 7855 /* process_iter_next_call() is called when verifier gets to iterator's next 7856 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7857 * to it as just "iter_next()" in comments below. 7858 * 7859 * BPF verifier relies on a crucial contract for any iter_next() 7860 * implementation: it should *eventually* return NULL, and once that happens 7861 * it should keep returning NULL. That is, once iterator exhausts elements to 7862 * iterate, it should never reset or spuriously return new elements. 7863 * 7864 * With the assumption of such contract, process_iter_next_call() simulates 7865 * a fork in the verifier state to validate loop logic correctness and safety 7866 * without having to simulate infinite amount of iterations. 7867 * 7868 * In current state, we first assume that iter_next() returned NULL and 7869 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7870 * conditions we should not form an infinite loop and should eventually reach 7871 * exit. 7872 * 7873 * Besides that, we also fork current state and enqueue it for later 7874 * verification. In a forked state we keep iterator state as ACTIVE 7875 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7876 * also bump iteration depth to prevent erroneous infinite loop detection 7877 * later on (see iter_active_depths_differ() comment for details). In this 7878 * state we assume that we'll eventually loop back to another iter_next() 7879 * calls (it could be in exactly same location or in some other instruction, 7880 * it doesn't matter, we don't make any unnecessary assumptions about this, 7881 * everything revolves around iterator state in a stack slot, not which 7882 * instruction is calling iter_next()). When that happens, we either will come 7883 * to iter_next() with equivalent state and can conclude that next iteration 7884 * will proceed in exactly the same way as we just verified, so it's safe to 7885 * assume that loop converges. If not, we'll go on another iteration 7886 * simulation with a different input state, until all possible starting states 7887 * are validated or we reach maximum number of instructions limit. 7888 * 7889 * This way, we will either exhaustively discover all possible input states 7890 * that iterator loop can start with and eventually will converge, or we'll 7891 * effectively regress into bounded loop simulation logic and either reach 7892 * maximum number of instructions if loop is not provably convergent, or there 7893 * is some statically known limit on number of iterations (e.g., if there is 7894 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7895 * 7896 * Iteration convergence logic in is_state_visited() relies on exact 7897 * states comparison, which ignores read and precision marks. 7898 * This is necessary because read and precision marks are not finalized 7899 * while in the loop. Exact comparison might preclude convergence for 7900 * simple programs like below: 7901 * 7902 * i = 0; 7903 * while(iter_next(&it)) 7904 * i++; 7905 * 7906 * At each iteration step i++ would produce a new distinct state and 7907 * eventually instruction processing limit would be reached. 7908 * 7909 * To avoid such behavior speculatively forget (widen) range for 7910 * imprecise scalar registers, if those registers were not precise at the 7911 * end of the previous iteration and do not match exactly. 7912 * 7913 * This is a conservative heuristic that allows to verify wide range of programs, 7914 * however it precludes verification of programs that conjure an 7915 * imprecise value on the first loop iteration and use it as precise on a second. 7916 * For example, the following safe program would fail to verify: 7917 * 7918 * struct bpf_num_iter it; 7919 * int arr[10]; 7920 * int i = 0, a = 0; 7921 * bpf_iter_num_new(&it, 0, 10); 7922 * while (bpf_iter_num_next(&it)) { 7923 * if (a == 0) { 7924 * a = 1; 7925 * i = 7; // Because i changed verifier would forget 7926 * // it's range on second loop entry. 7927 * } else { 7928 * arr[i] = 42; // This would fail to verify. 7929 * } 7930 * } 7931 * bpf_iter_num_destroy(&it); 7932 */ 7933 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7934 struct bpf_kfunc_call_arg_meta *meta) 7935 { 7936 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 7937 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7938 struct bpf_reg_state *cur_iter, *queued_iter; 7939 int iter_frameno = meta->iter.frameno; 7940 int iter_spi = meta->iter.spi; 7941 7942 BTF_TYPE_EMIT(struct bpf_iter); 7943 7944 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7945 7946 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 7947 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 7948 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 7949 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 7950 return -EFAULT; 7951 } 7952 7953 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 7954 /* Because iter_next() call is a checkpoint is_state_visitied() 7955 * should guarantee parent state with same call sites and insn_idx. 7956 */ 7957 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 7958 !same_callsites(cur_st->parent, cur_st)) { 7959 verbose(env, "bug: bad parent state for iter next call"); 7960 return -EFAULT; 7961 } 7962 /* Note cur_st->parent in the call below, it is necessary to skip 7963 * checkpoint created for cur_st by is_state_visited() 7964 * right at this instruction. 7965 */ 7966 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 7967 /* branch out active iter state */ 7968 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 7969 if (!queued_st) 7970 return -ENOMEM; 7971 7972 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7973 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 7974 queued_iter->iter.depth++; 7975 if (prev_st) 7976 widen_imprecise_scalars(env, prev_st, queued_st); 7977 7978 queued_fr = queued_st->frame[queued_st->curframe]; 7979 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 7980 } 7981 7982 /* switch to DRAINED state, but keep the depth unchanged */ 7983 /* mark current iter state as drained and assume returned NULL */ 7984 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 7985 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 7986 7987 return 0; 7988 } 7989 7990 static bool arg_type_is_mem_size(enum bpf_arg_type type) 7991 { 7992 return type == ARG_CONST_SIZE || 7993 type == ARG_CONST_SIZE_OR_ZERO; 7994 } 7995 7996 static bool arg_type_is_release(enum bpf_arg_type type) 7997 { 7998 return type & OBJ_RELEASE; 7999 } 8000 8001 static bool arg_type_is_dynptr(enum bpf_arg_type type) 8002 { 8003 return base_type(type) == ARG_PTR_TO_DYNPTR; 8004 } 8005 8006 static int int_ptr_type_to_size(enum bpf_arg_type type) 8007 { 8008 if (type == ARG_PTR_TO_INT) 8009 return sizeof(u32); 8010 else if (type == ARG_PTR_TO_LONG) 8011 return sizeof(u64); 8012 8013 return -EINVAL; 8014 } 8015 8016 static int resolve_map_arg_type(struct bpf_verifier_env *env, 8017 const struct bpf_call_arg_meta *meta, 8018 enum bpf_arg_type *arg_type) 8019 { 8020 if (!meta->map_ptr) { 8021 /* kernel subsystem misconfigured verifier */ 8022 verbose(env, "invalid map_ptr to access map->type\n"); 8023 return -EACCES; 8024 } 8025 8026 switch (meta->map_ptr->map_type) { 8027 case BPF_MAP_TYPE_SOCKMAP: 8028 case BPF_MAP_TYPE_SOCKHASH: 8029 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 8030 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 8031 } else { 8032 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 8033 return -EINVAL; 8034 } 8035 break; 8036 case BPF_MAP_TYPE_BLOOM_FILTER: 8037 if (meta->func_id == BPF_FUNC_map_peek_elem) 8038 *arg_type = ARG_PTR_TO_MAP_VALUE; 8039 break; 8040 default: 8041 break; 8042 } 8043 return 0; 8044 } 8045 8046 struct bpf_reg_types { 8047 const enum bpf_reg_type types[10]; 8048 u32 *btf_id; 8049 }; 8050 8051 static const struct bpf_reg_types sock_types = { 8052 .types = { 8053 PTR_TO_SOCK_COMMON, 8054 PTR_TO_SOCKET, 8055 PTR_TO_TCP_SOCK, 8056 PTR_TO_XDP_SOCK, 8057 }, 8058 }; 8059 8060 #ifdef CONFIG_NET 8061 static const struct bpf_reg_types btf_id_sock_common_types = { 8062 .types = { 8063 PTR_TO_SOCK_COMMON, 8064 PTR_TO_SOCKET, 8065 PTR_TO_TCP_SOCK, 8066 PTR_TO_XDP_SOCK, 8067 PTR_TO_BTF_ID, 8068 PTR_TO_BTF_ID | PTR_TRUSTED, 8069 }, 8070 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 8071 }; 8072 #endif 8073 8074 static const struct bpf_reg_types mem_types = { 8075 .types = { 8076 PTR_TO_STACK, 8077 PTR_TO_PACKET, 8078 PTR_TO_PACKET_META, 8079 PTR_TO_MAP_KEY, 8080 PTR_TO_MAP_VALUE, 8081 PTR_TO_MEM, 8082 PTR_TO_MEM | MEM_RINGBUF, 8083 PTR_TO_BUF, 8084 PTR_TO_BTF_ID | PTR_TRUSTED, 8085 }, 8086 }; 8087 8088 static const struct bpf_reg_types int_ptr_types = { 8089 .types = { 8090 PTR_TO_STACK, 8091 PTR_TO_PACKET, 8092 PTR_TO_PACKET_META, 8093 PTR_TO_MAP_KEY, 8094 PTR_TO_MAP_VALUE, 8095 }, 8096 }; 8097 8098 static const struct bpf_reg_types spin_lock_types = { 8099 .types = { 8100 PTR_TO_MAP_VALUE, 8101 PTR_TO_BTF_ID | MEM_ALLOC, 8102 } 8103 }; 8104 8105 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 8106 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 8107 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 8108 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 8109 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 8110 static const struct bpf_reg_types btf_ptr_types = { 8111 .types = { 8112 PTR_TO_BTF_ID, 8113 PTR_TO_BTF_ID | PTR_TRUSTED, 8114 PTR_TO_BTF_ID | MEM_RCU, 8115 }, 8116 }; 8117 static const struct bpf_reg_types percpu_btf_ptr_types = { 8118 .types = { 8119 PTR_TO_BTF_ID | MEM_PERCPU, 8120 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 8121 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 8122 } 8123 }; 8124 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 8125 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 8126 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8127 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 8128 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8129 static const struct bpf_reg_types dynptr_types = { 8130 .types = { 8131 PTR_TO_STACK, 8132 CONST_PTR_TO_DYNPTR, 8133 } 8134 }; 8135 8136 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 8137 [ARG_PTR_TO_MAP_KEY] = &mem_types, 8138 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 8139 [ARG_CONST_SIZE] = &scalar_types, 8140 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 8141 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 8142 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 8143 [ARG_PTR_TO_CTX] = &context_types, 8144 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 8145 #ifdef CONFIG_NET 8146 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 8147 #endif 8148 [ARG_PTR_TO_SOCKET] = &fullsock_types, 8149 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 8150 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 8151 [ARG_PTR_TO_MEM] = &mem_types, 8152 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 8153 [ARG_PTR_TO_INT] = &int_ptr_types, 8154 [ARG_PTR_TO_LONG] = &int_ptr_types, 8155 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 8156 [ARG_PTR_TO_FUNC] = &func_ptr_types, 8157 [ARG_PTR_TO_STACK] = &stack_ptr_types, 8158 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 8159 [ARG_PTR_TO_TIMER] = &timer_types, 8160 [ARG_PTR_TO_KPTR] = &kptr_types, 8161 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 8162 }; 8163 8164 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 8165 enum bpf_arg_type arg_type, 8166 const u32 *arg_btf_id, 8167 struct bpf_call_arg_meta *meta) 8168 { 8169 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8170 enum bpf_reg_type expected, type = reg->type; 8171 const struct bpf_reg_types *compatible; 8172 int i, j; 8173 8174 compatible = compatible_reg_types[base_type(arg_type)]; 8175 if (!compatible) { 8176 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 8177 return -EFAULT; 8178 } 8179 8180 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 8181 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 8182 * 8183 * Same for MAYBE_NULL: 8184 * 8185 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 8186 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 8187 * 8188 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 8189 * 8190 * Therefore we fold these flags depending on the arg_type before comparison. 8191 */ 8192 if (arg_type & MEM_RDONLY) 8193 type &= ~MEM_RDONLY; 8194 if (arg_type & PTR_MAYBE_NULL) 8195 type &= ~PTR_MAYBE_NULL; 8196 if (base_type(arg_type) == ARG_PTR_TO_MEM) 8197 type &= ~DYNPTR_TYPE_FLAG_MASK; 8198 8199 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) { 8200 type &= ~MEM_ALLOC; 8201 type &= ~MEM_PERCPU; 8202 } 8203 8204 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 8205 expected = compatible->types[i]; 8206 if (expected == NOT_INIT) 8207 break; 8208 8209 if (type == expected) 8210 goto found; 8211 } 8212 8213 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 8214 for (j = 0; j + 1 < i; j++) 8215 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 8216 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 8217 return -EACCES; 8218 8219 found: 8220 if (base_type(reg->type) != PTR_TO_BTF_ID) 8221 return 0; 8222 8223 if (compatible == &mem_types) { 8224 if (!(arg_type & MEM_RDONLY)) { 8225 verbose(env, 8226 "%s() may write into memory pointed by R%d type=%s\n", 8227 func_id_name(meta->func_id), 8228 regno, reg_type_str(env, reg->type)); 8229 return -EACCES; 8230 } 8231 return 0; 8232 } 8233 8234 switch ((int)reg->type) { 8235 case PTR_TO_BTF_ID: 8236 case PTR_TO_BTF_ID | PTR_TRUSTED: 8237 case PTR_TO_BTF_ID | MEM_RCU: 8238 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 8239 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 8240 { 8241 /* For bpf_sk_release, it needs to match against first member 8242 * 'struct sock_common', hence make an exception for it. This 8243 * allows bpf_sk_release to work for multiple socket types. 8244 */ 8245 bool strict_type_match = arg_type_is_release(arg_type) && 8246 meta->func_id != BPF_FUNC_sk_release; 8247 8248 if (type_may_be_null(reg->type) && 8249 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 8250 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 8251 return -EACCES; 8252 } 8253 8254 if (!arg_btf_id) { 8255 if (!compatible->btf_id) { 8256 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 8257 return -EFAULT; 8258 } 8259 arg_btf_id = compatible->btf_id; 8260 } 8261 8262 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8263 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8264 return -EACCES; 8265 } else { 8266 if (arg_btf_id == BPF_PTR_POISON) { 8267 verbose(env, "verifier internal error:"); 8268 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 8269 regno); 8270 return -EACCES; 8271 } 8272 8273 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 8274 btf_vmlinux, *arg_btf_id, 8275 strict_type_match)) { 8276 verbose(env, "R%d is of type %s but %s is expected\n", 8277 regno, btf_type_name(reg->btf, reg->btf_id), 8278 btf_type_name(btf_vmlinux, *arg_btf_id)); 8279 return -EACCES; 8280 } 8281 } 8282 break; 8283 } 8284 case PTR_TO_BTF_ID | MEM_ALLOC: 8285 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 8286 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8287 meta->func_id != BPF_FUNC_kptr_xchg) { 8288 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 8289 return -EFAULT; 8290 } 8291 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8292 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8293 return -EACCES; 8294 } 8295 break; 8296 case PTR_TO_BTF_ID | MEM_PERCPU: 8297 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 8298 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8299 /* Handled by helper specific checks */ 8300 break; 8301 default: 8302 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 8303 return -EFAULT; 8304 } 8305 return 0; 8306 } 8307 8308 static struct btf_field * 8309 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8310 { 8311 struct btf_field *field; 8312 struct btf_record *rec; 8313 8314 rec = reg_btf_record(reg); 8315 if (!rec) 8316 return NULL; 8317 8318 field = btf_record_find(rec, off, fields); 8319 if (!field) 8320 return NULL; 8321 8322 return field; 8323 } 8324 8325 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 8326 const struct bpf_reg_state *reg, int regno, 8327 enum bpf_arg_type arg_type) 8328 { 8329 u32 type = reg->type; 8330 8331 /* When referenced register is passed to release function, its fixed 8332 * offset must be 0. 8333 * 8334 * We will check arg_type_is_release reg has ref_obj_id when storing 8335 * meta->release_regno. 8336 */ 8337 if (arg_type_is_release(arg_type)) { 8338 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8339 * may not directly point to the object being released, but to 8340 * dynptr pointing to such object, which might be at some offset 8341 * on the stack. In that case, we simply to fallback to the 8342 * default handling. 8343 */ 8344 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8345 return 0; 8346 8347 /* Doing check_ptr_off_reg check for the offset will catch this 8348 * because fixed_off_ok is false, but checking here allows us 8349 * to give the user a better error message. 8350 */ 8351 if (reg->off) { 8352 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 8353 regno); 8354 return -EINVAL; 8355 } 8356 return __check_ptr_off_reg(env, reg, regno, false); 8357 } 8358 8359 switch (type) { 8360 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8361 case PTR_TO_STACK: 8362 case PTR_TO_PACKET: 8363 case PTR_TO_PACKET_META: 8364 case PTR_TO_MAP_KEY: 8365 case PTR_TO_MAP_VALUE: 8366 case PTR_TO_MEM: 8367 case PTR_TO_MEM | MEM_RDONLY: 8368 case PTR_TO_MEM | MEM_RINGBUF: 8369 case PTR_TO_BUF: 8370 case PTR_TO_BUF | MEM_RDONLY: 8371 case SCALAR_VALUE: 8372 return 0; 8373 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8374 * fixed offset. 8375 */ 8376 case PTR_TO_BTF_ID: 8377 case PTR_TO_BTF_ID | MEM_ALLOC: 8378 case PTR_TO_BTF_ID | PTR_TRUSTED: 8379 case PTR_TO_BTF_ID | MEM_RCU: 8380 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8381 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8382 /* When referenced PTR_TO_BTF_ID is passed to release function, 8383 * its fixed offset must be 0. In the other cases, fixed offset 8384 * can be non-zero. This was already checked above. So pass 8385 * fixed_off_ok as true to allow fixed offset for all other 8386 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8387 * still need to do checks instead of returning. 8388 */ 8389 return __check_ptr_off_reg(env, reg, regno, true); 8390 default: 8391 return __check_ptr_off_reg(env, reg, regno, false); 8392 } 8393 } 8394 8395 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8396 const struct bpf_func_proto *fn, 8397 struct bpf_reg_state *regs) 8398 { 8399 struct bpf_reg_state *state = NULL; 8400 int i; 8401 8402 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8403 if (arg_type_is_dynptr(fn->arg_type[i])) { 8404 if (state) { 8405 verbose(env, "verifier internal error: multiple dynptr args\n"); 8406 return NULL; 8407 } 8408 state = ®s[BPF_REG_1 + i]; 8409 } 8410 8411 if (!state) 8412 verbose(env, "verifier internal error: no dynptr arg found\n"); 8413 8414 return state; 8415 } 8416 8417 static int dynptr_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->id; 8424 spi = dynptr_get_spi(env, reg); 8425 if (spi < 0) 8426 return spi; 8427 return state->stack[spi].spilled_ptr.id; 8428 } 8429 8430 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8431 { 8432 struct bpf_func_state *state = func(env, reg); 8433 int spi; 8434 8435 if (reg->type == CONST_PTR_TO_DYNPTR) 8436 return reg->ref_obj_id; 8437 spi = dynptr_get_spi(env, reg); 8438 if (spi < 0) 8439 return spi; 8440 return state->stack[spi].spilled_ptr.ref_obj_id; 8441 } 8442 8443 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8444 struct bpf_reg_state *reg) 8445 { 8446 struct bpf_func_state *state = func(env, reg); 8447 int spi; 8448 8449 if (reg->type == CONST_PTR_TO_DYNPTR) 8450 return reg->dynptr.type; 8451 8452 spi = __get_spi(reg->off); 8453 if (spi < 0) { 8454 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8455 return BPF_DYNPTR_TYPE_INVALID; 8456 } 8457 8458 return state->stack[spi].spilled_ptr.dynptr.type; 8459 } 8460 8461 static int check_reg_const_str(struct bpf_verifier_env *env, 8462 struct bpf_reg_state *reg, u32 regno) 8463 { 8464 struct bpf_map *map = reg->map_ptr; 8465 int err; 8466 int map_off; 8467 u64 map_addr; 8468 char *str_ptr; 8469 8470 if (reg->type != PTR_TO_MAP_VALUE) 8471 return -EINVAL; 8472 8473 if (!bpf_map_is_rdonly(map)) { 8474 verbose(env, "R%d does not point to a readonly map'\n", regno); 8475 return -EACCES; 8476 } 8477 8478 if (!tnum_is_const(reg->var_off)) { 8479 verbose(env, "R%d is not a constant address'\n", regno); 8480 return -EACCES; 8481 } 8482 8483 if (!map->ops->map_direct_value_addr) { 8484 verbose(env, "no direct value access support for this map type\n"); 8485 return -EACCES; 8486 } 8487 8488 err = check_map_access(env, regno, reg->off, 8489 map->value_size - reg->off, false, 8490 ACCESS_HELPER); 8491 if (err) 8492 return err; 8493 8494 map_off = reg->off + reg->var_off.value; 8495 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8496 if (err) { 8497 verbose(env, "direct value access on string failed\n"); 8498 return err; 8499 } 8500 8501 str_ptr = (char *)(long)(map_addr); 8502 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8503 verbose(env, "string is not zero-terminated\n"); 8504 return -EINVAL; 8505 } 8506 return 0; 8507 } 8508 8509 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8510 struct bpf_call_arg_meta *meta, 8511 const struct bpf_func_proto *fn, 8512 int insn_idx) 8513 { 8514 u32 regno = BPF_REG_1 + arg; 8515 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8516 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8517 enum bpf_reg_type type = reg->type; 8518 u32 *arg_btf_id = NULL; 8519 int err = 0; 8520 8521 if (arg_type == ARG_DONTCARE) 8522 return 0; 8523 8524 err = check_reg_arg(env, regno, SRC_OP); 8525 if (err) 8526 return err; 8527 8528 if (arg_type == ARG_ANYTHING) { 8529 if (is_pointer_value(env, regno)) { 8530 verbose(env, "R%d leaks addr into helper function\n", 8531 regno); 8532 return -EACCES; 8533 } 8534 return 0; 8535 } 8536 8537 if (type_is_pkt_pointer(type) && 8538 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8539 verbose(env, "helper access to the packet is not allowed\n"); 8540 return -EACCES; 8541 } 8542 8543 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8544 err = resolve_map_arg_type(env, meta, &arg_type); 8545 if (err) 8546 return err; 8547 } 8548 8549 if (register_is_null(reg) && type_may_be_null(arg_type)) 8550 /* A NULL register has a SCALAR_VALUE type, so skip 8551 * type checking. 8552 */ 8553 goto skip_type_check; 8554 8555 /* arg_btf_id and arg_size are in a union. */ 8556 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8557 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8558 arg_btf_id = fn->arg_btf_id[arg]; 8559 8560 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 8561 if (err) 8562 return err; 8563 8564 err = check_func_arg_reg_off(env, reg, regno, arg_type); 8565 if (err) 8566 return err; 8567 8568 skip_type_check: 8569 if (arg_type_is_release(arg_type)) { 8570 if (arg_type_is_dynptr(arg_type)) { 8571 struct bpf_func_state *state = func(env, reg); 8572 int spi; 8573 8574 /* Only dynptr created on stack can be released, thus 8575 * the get_spi and stack state checks for spilled_ptr 8576 * should only be done before process_dynptr_func for 8577 * PTR_TO_STACK. 8578 */ 8579 if (reg->type == PTR_TO_STACK) { 8580 spi = dynptr_get_spi(env, reg); 8581 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8582 verbose(env, "arg %d is an unacquired reference\n", regno); 8583 return -EINVAL; 8584 } 8585 } else { 8586 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8587 return -EINVAL; 8588 } 8589 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 8590 verbose(env, "R%d must be referenced when passed to release function\n", 8591 regno); 8592 return -EINVAL; 8593 } 8594 if (meta->release_regno) { 8595 verbose(env, "verifier internal error: more than one release argument\n"); 8596 return -EFAULT; 8597 } 8598 meta->release_regno = regno; 8599 } 8600 8601 if (reg->ref_obj_id) { 8602 if (meta->ref_obj_id) { 8603 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 8604 regno, reg->ref_obj_id, 8605 meta->ref_obj_id); 8606 return -EFAULT; 8607 } 8608 meta->ref_obj_id = reg->ref_obj_id; 8609 } 8610 8611 switch (base_type(arg_type)) { 8612 case ARG_CONST_MAP_PTR: 8613 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8614 if (meta->map_ptr) { 8615 /* Use map_uid (which is unique id of inner map) to reject: 8616 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8617 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8618 * if (inner_map1 && inner_map2) { 8619 * timer = bpf_map_lookup_elem(inner_map1); 8620 * if (timer) 8621 * // mismatch would have been allowed 8622 * bpf_timer_init(timer, inner_map2); 8623 * } 8624 * 8625 * Comparing map_ptr is enough to distinguish normal and outer maps. 8626 */ 8627 if (meta->map_ptr != reg->map_ptr || 8628 meta->map_uid != reg->map_uid) { 8629 verbose(env, 8630 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8631 meta->map_uid, reg->map_uid); 8632 return -EINVAL; 8633 } 8634 } 8635 meta->map_ptr = reg->map_ptr; 8636 meta->map_uid = reg->map_uid; 8637 break; 8638 case ARG_PTR_TO_MAP_KEY: 8639 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8640 * check that [key, key + map->key_size) are within 8641 * stack limits and initialized 8642 */ 8643 if (!meta->map_ptr) { 8644 /* in function declaration map_ptr must come before 8645 * map_key, so that it's verified and known before 8646 * we have to check map_key here. Otherwise it means 8647 * that kernel subsystem misconfigured verifier 8648 */ 8649 verbose(env, "invalid map_ptr to access map->key\n"); 8650 return -EACCES; 8651 } 8652 err = check_helper_mem_access(env, regno, 8653 meta->map_ptr->key_size, false, 8654 NULL); 8655 break; 8656 case ARG_PTR_TO_MAP_VALUE: 8657 if (type_may_be_null(arg_type) && register_is_null(reg)) 8658 return 0; 8659 8660 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8661 * check [value, value + map->value_size) validity 8662 */ 8663 if (!meta->map_ptr) { 8664 /* kernel subsystem misconfigured verifier */ 8665 verbose(env, "invalid map_ptr to access map->value\n"); 8666 return -EACCES; 8667 } 8668 meta->raw_mode = arg_type & MEM_UNINIT; 8669 err = check_helper_mem_access(env, regno, 8670 meta->map_ptr->value_size, false, 8671 meta); 8672 break; 8673 case ARG_PTR_TO_PERCPU_BTF_ID: 8674 if (!reg->btf_id) { 8675 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8676 return -EACCES; 8677 } 8678 meta->ret_btf = reg->btf; 8679 meta->ret_btf_id = reg->btf_id; 8680 break; 8681 case ARG_PTR_TO_SPIN_LOCK: 8682 if (in_rbtree_lock_required_cb(env)) { 8683 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8684 return -EACCES; 8685 } 8686 if (meta->func_id == BPF_FUNC_spin_lock) { 8687 err = process_spin_lock(env, regno, true); 8688 if (err) 8689 return err; 8690 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8691 err = process_spin_lock(env, regno, false); 8692 if (err) 8693 return err; 8694 } else { 8695 verbose(env, "verifier internal error\n"); 8696 return -EFAULT; 8697 } 8698 break; 8699 case ARG_PTR_TO_TIMER: 8700 err = process_timer_func(env, regno, meta); 8701 if (err) 8702 return err; 8703 break; 8704 case ARG_PTR_TO_FUNC: 8705 meta->subprogno = reg->subprogno; 8706 break; 8707 case ARG_PTR_TO_MEM: 8708 /* The access to this pointer is only checked when we hit the 8709 * next is_mem_size argument below. 8710 */ 8711 meta->raw_mode = arg_type & MEM_UNINIT; 8712 if (arg_type & MEM_FIXED_SIZE) { 8713 err = check_helper_mem_access(env, regno, 8714 fn->arg_size[arg], false, 8715 meta); 8716 } 8717 break; 8718 case ARG_CONST_SIZE: 8719 err = check_mem_size_reg(env, reg, regno, false, meta); 8720 break; 8721 case ARG_CONST_SIZE_OR_ZERO: 8722 err = check_mem_size_reg(env, reg, regno, true, meta); 8723 break; 8724 case ARG_PTR_TO_DYNPTR: 8725 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 8726 if (err) 8727 return err; 8728 break; 8729 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8730 if (!tnum_is_const(reg->var_off)) { 8731 verbose(env, "R%d is not a known constant'\n", 8732 regno); 8733 return -EACCES; 8734 } 8735 meta->mem_size = reg->var_off.value; 8736 err = mark_chain_precision(env, regno); 8737 if (err) 8738 return err; 8739 break; 8740 case ARG_PTR_TO_INT: 8741 case ARG_PTR_TO_LONG: 8742 { 8743 int size = int_ptr_type_to_size(arg_type); 8744 8745 err = check_helper_mem_access(env, regno, size, false, meta); 8746 if (err) 8747 return err; 8748 err = check_ptr_alignment(env, reg, 0, size, true); 8749 break; 8750 } 8751 case ARG_PTR_TO_CONST_STR: 8752 { 8753 err = check_reg_const_str(env, reg, regno); 8754 if (err) 8755 return err; 8756 break; 8757 } 8758 case ARG_PTR_TO_KPTR: 8759 err = process_kptr_func(env, regno, meta); 8760 if (err) 8761 return err; 8762 break; 8763 } 8764 8765 return err; 8766 } 8767 8768 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8769 { 8770 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8771 enum bpf_prog_type type = resolve_prog_type(env->prog); 8772 8773 if (func_id != BPF_FUNC_map_update_elem) 8774 return false; 8775 8776 /* It's not possible to get access to a locked struct sock in these 8777 * contexts, so updating is safe. 8778 */ 8779 switch (type) { 8780 case BPF_PROG_TYPE_TRACING: 8781 if (eatype == BPF_TRACE_ITER) 8782 return true; 8783 break; 8784 case BPF_PROG_TYPE_SOCKET_FILTER: 8785 case BPF_PROG_TYPE_SCHED_CLS: 8786 case BPF_PROG_TYPE_SCHED_ACT: 8787 case BPF_PROG_TYPE_XDP: 8788 case BPF_PROG_TYPE_SK_REUSEPORT: 8789 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8790 case BPF_PROG_TYPE_SK_LOOKUP: 8791 return true; 8792 default: 8793 break; 8794 } 8795 8796 verbose(env, "cannot update sockmap in this context\n"); 8797 return false; 8798 } 8799 8800 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8801 { 8802 return env->prog->jit_requested && 8803 bpf_jit_supports_subprog_tailcalls(); 8804 } 8805 8806 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8807 struct bpf_map *map, int func_id) 8808 { 8809 if (!map) 8810 return 0; 8811 8812 /* We need a two way check, first is from map perspective ... */ 8813 switch (map->map_type) { 8814 case BPF_MAP_TYPE_PROG_ARRAY: 8815 if (func_id != BPF_FUNC_tail_call) 8816 goto error; 8817 break; 8818 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8819 if (func_id != BPF_FUNC_perf_event_read && 8820 func_id != BPF_FUNC_perf_event_output && 8821 func_id != BPF_FUNC_skb_output && 8822 func_id != BPF_FUNC_perf_event_read_value && 8823 func_id != BPF_FUNC_xdp_output) 8824 goto error; 8825 break; 8826 case BPF_MAP_TYPE_RINGBUF: 8827 if (func_id != BPF_FUNC_ringbuf_output && 8828 func_id != BPF_FUNC_ringbuf_reserve && 8829 func_id != BPF_FUNC_ringbuf_query && 8830 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8831 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8832 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8833 goto error; 8834 break; 8835 case BPF_MAP_TYPE_USER_RINGBUF: 8836 if (func_id != BPF_FUNC_user_ringbuf_drain) 8837 goto error; 8838 break; 8839 case BPF_MAP_TYPE_STACK_TRACE: 8840 if (func_id != BPF_FUNC_get_stackid) 8841 goto error; 8842 break; 8843 case BPF_MAP_TYPE_CGROUP_ARRAY: 8844 if (func_id != BPF_FUNC_skb_under_cgroup && 8845 func_id != BPF_FUNC_current_task_under_cgroup) 8846 goto error; 8847 break; 8848 case BPF_MAP_TYPE_CGROUP_STORAGE: 8849 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8850 if (func_id != BPF_FUNC_get_local_storage) 8851 goto error; 8852 break; 8853 case BPF_MAP_TYPE_DEVMAP: 8854 case BPF_MAP_TYPE_DEVMAP_HASH: 8855 if (func_id != BPF_FUNC_redirect_map && 8856 func_id != BPF_FUNC_map_lookup_elem) 8857 goto error; 8858 break; 8859 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8860 * appear. 8861 */ 8862 case BPF_MAP_TYPE_CPUMAP: 8863 if (func_id != BPF_FUNC_redirect_map) 8864 goto error; 8865 break; 8866 case BPF_MAP_TYPE_XSKMAP: 8867 if (func_id != BPF_FUNC_redirect_map && 8868 func_id != BPF_FUNC_map_lookup_elem) 8869 goto error; 8870 break; 8871 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8872 case BPF_MAP_TYPE_HASH_OF_MAPS: 8873 if (func_id != BPF_FUNC_map_lookup_elem) 8874 goto error; 8875 break; 8876 case BPF_MAP_TYPE_SOCKMAP: 8877 if (func_id != BPF_FUNC_sk_redirect_map && 8878 func_id != BPF_FUNC_sock_map_update && 8879 func_id != BPF_FUNC_map_delete_elem && 8880 func_id != BPF_FUNC_msg_redirect_map && 8881 func_id != BPF_FUNC_sk_select_reuseport && 8882 func_id != BPF_FUNC_map_lookup_elem && 8883 !may_update_sockmap(env, func_id)) 8884 goto error; 8885 break; 8886 case BPF_MAP_TYPE_SOCKHASH: 8887 if (func_id != BPF_FUNC_sk_redirect_hash && 8888 func_id != BPF_FUNC_sock_hash_update && 8889 func_id != BPF_FUNC_map_delete_elem && 8890 func_id != BPF_FUNC_msg_redirect_hash && 8891 func_id != BPF_FUNC_sk_select_reuseport && 8892 func_id != BPF_FUNC_map_lookup_elem && 8893 !may_update_sockmap(env, func_id)) 8894 goto error; 8895 break; 8896 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8897 if (func_id != BPF_FUNC_sk_select_reuseport) 8898 goto error; 8899 break; 8900 case BPF_MAP_TYPE_QUEUE: 8901 case BPF_MAP_TYPE_STACK: 8902 if (func_id != BPF_FUNC_map_peek_elem && 8903 func_id != BPF_FUNC_map_pop_elem && 8904 func_id != BPF_FUNC_map_push_elem) 8905 goto error; 8906 break; 8907 case BPF_MAP_TYPE_SK_STORAGE: 8908 if (func_id != BPF_FUNC_sk_storage_get && 8909 func_id != BPF_FUNC_sk_storage_delete && 8910 func_id != BPF_FUNC_kptr_xchg) 8911 goto error; 8912 break; 8913 case BPF_MAP_TYPE_INODE_STORAGE: 8914 if (func_id != BPF_FUNC_inode_storage_get && 8915 func_id != BPF_FUNC_inode_storage_delete && 8916 func_id != BPF_FUNC_kptr_xchg) 8917 goto error; 8918 break; 8919 case BPF_MAP_TYPE_TASK_STORAGE: 8920 if (func_id != BPF_FUNC_task_storage_get && 8921 func_id != BPF_FUNC_task_storage_delete && 8922 func_id != BPF_FUNC_kptr_xchg) 8923 goto error; 8924 break; 8925 case BPF_MAP_TYPE_CGRP_STORAGE: 8926 if (func_id != BPF_FUNC_cgrp_storage_get && 8927 func_id != BPF_FUNC_cgrp_storage_delete && 8928 func_id != BPF_FUNC_kptr_xchg) 8929 goto error; 8930 break; 8931 case BPF_MAP_TYPE_BLOOM_FILTER: 8932 if (func_id != BPF_FUNC_map_peek_elem && 8933 func_id != BPF_FUNC_map_push_elem) 8934 goto error; 8935 break; 8936 default: 8937 break; 8938 } 8939 8940 /* ... and second from the function itself. */ 8941 switch (func_id) { 8942 case BPF_FUNC_tail_call: 8943 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8944 goto error; 8945 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 8946 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 8947 return -EINVAL; 8948 } 8949 break; 8950 case BPF_FUNC_perf_event_read: 8951 case BPF_FUNC_perf_event_output: 8952 case BPF_FUNC_perf_event_read_value: 8953 case BPF_FUNC_skb_output: 8954 case BPF_FUNC_xdp_output: 8955 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 8956 goto error; 8957 break; 8958 case BPF_FUNC_ringbuf_output: 8959 case BPF_FUNC_ringbuf_reserve: 8960 case BPF_FUNC_ringbuf_query: 8961 case BPF_FUNC_ringbuf_reserve_dynptr: 8962 case BPF_FUNC_ringbuf_submit_dynptr: 8963 case BPF_FUNC_ringbuf_discard_dynptr: 8964 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 8965 goto error; 8966 break; 8967 case BPF_FUNC_user_ringbuf_drain: 8968 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 8969 goto error; 8970 break; 8971 case BPF_FUNC_get_stackid: 8972 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 8973 goto error; 8974 break; 8975 case BPF_FUNC_current_task_under_cgroup: 8976 case BPF_FUNC_skb_under_cgroup: 8977 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 8978 goto error; 8979 break; 8980 case BPF_FUNC_redirect_map: 8981 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 8982 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 8983 map->map_type != BPF_MAP_TYPE_CPUMAP && 8984 map->map_type != BPF_MAP_TYPE_XSKMAP) 8985 goto error; 8986 break; 8987 case BPF_FUNC_sk_redirect_map: 8988 case BPF_FUNC_msg_redirect_map: 8989 case BPF_FUNC_sock_map_update: 8990 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 8991 goto error; 8992 break; 8993 case BPF_FUNC_sk_redirect_hash: 8994 case BPF_FUNC_msg_redirect_hash: 8995 case BPF_FUNC_sock_hash_update: 8996 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 8997 goto error; 8998 break; 8999 case BPF_FUNC_get_local_storage: 9000 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 9001 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 9002 goto error; 9003 break; 9004 case BPF_FUNC_sk_select_reuseport: 9005 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 9006 map->map_type != BPF_MAP_TYPE_SOCKMAP && 9007 map->map_type != BPF_MAP_TYPE_SOCKHASH) 9008 goto error; 9009 break; 9010 case BPF_FUNC_map_pop_elem: 9011 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9012 map->map_type != BPF_MAP_TYPE_STACK) 9013 goto error; 9014 break; 9015 case BPF_FUNC_map_peek_elem: 9016 case BPF_FUNC_map_push_elem: 9017 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9018 map->map_type != BPF_MAP_TYPE_STACK && 9019 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 9020 goto error; 9021 break; 9022 case BPF_FUNC_map_lookup_percpu_elem: 9023 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 9024 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 9025 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 9026 goto error; 9027 break; 9028 case BPF_FUNC_sk_storage_get: 9029 case BPF_FUNC_sk_storage_delete: 9030 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 9031 goto error; 9032 break; 9033 case BPF_FUNC_inode_storage_get: 9034 case BPF_FUNC_inode_storage_delete: 9035 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 9036 goto error; 9037 break; 9038 case BPF_FUNC_task_storage_get: 9039 case BPF_FUNC_task_storage_delete: 9040 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 9041 goto error; 9042 break; 9043 case BPF_FUNC_cgrp_storage_get: 9044 case BPF_FUNC_cgrp_storage_delete: 9045 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 9046 goto error; 9047 break; 9048 default: 9049 break; 9050 } 9051 9052 return 0; 9053 error: 9054 verbose(env, "cannot pass map_type %d into func %s#%d\n", 9055 map->map_type, func_id_name(func_id), func_id); 9056 return -EINVAL; 9057 } 9058 9059 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 9060 { 9061 int count = 0; 9062 9063 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 9064 count++; 9065 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 9066 count++; 9067 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 9068 count++; 9069 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 9070 count++; 9071 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 9072 count++; 9073 9074 /* We only support one arg being in raw mode at the moment, 9075 * which is sufficient for the helper functions we have 9076 * right now. 9077 */ 9078 return count <= 1; 9079 } 9080 9081 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 9082 { 9083 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 9084 bool has_size = fn->arg_size[arg] != 0; 9085 bool is_next_size = false; 9086 9087 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 9088 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 9089 9090 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 9091 return is_next_size; 9092 9093 return has_size == is_next_size || is_next_size == is_fixed; 9094 } 9095 9096 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 9097 { 9098 /* bpf_xxx(..., buf, len) call will access 'len' 9099 * bytes from memory 'buf'. Both arg types need 9100 * to be paired, so make sure there's no buggy 9101 * helper function specification. 9102 */ 9103 if (arg_type_is_mem_size(fn->arg1_type) || 9104 check_args_pair_invalid(fn, 0) || 9105 check_args_pair_invalid(fn, 1) || 9106 check_args_pair_invalid(fn, 2) || 9107 check_args_pair_invalid(fn, 3) || 9108 check_args_pair_invalid(fn, 4)) 9109 return false; 9110 9111 return true; 9112 } 9113 9114 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 9115 { 9116 int i; 9117 9118 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 9119 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 9120 return !!fn->arg_btf_id[i]; 9121 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 9122 return fn->arg_btf_id[i] == BPF_PTR_POISON; 9123 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 9124 /* arg_btf_id and arg_size are in a union. */ 9125 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 9126 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 9127 return false; 9128 } 9129 9130 return true; 9131 } 9132 9133 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 9134 { 9135 return check_raw_mode_ok(fn) && 9136 check_arg_pair_ok(fn) && 9137 check_btf_id_ok(fn) ? 0 : -EINVAL; 9138 } 9139 9140 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 9141 * are now invalid, so turn them into unknown SCALAR_VALUE. 9142 * 9143 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 9144 * since these slices point to packet data. 9145 */ 9146 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 9147 { 9148 struct bpf_func_state *state; 9149 struct bpf_reg_state *reg; 9150 9151 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9152 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 9153 mark_reg_invalid(env, reg); 9154 })); 9155 } 9156 9157 enum { 9158 AT_PKT_END = -1, 9159 BEYOND_PKT_END = -2, 9160 }; 9161 9162 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 9163 { 9164 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9165 struct bpf_reg_state *reg = &state->regs[regn]; 9166 9167 if (reg->type != PTR_TO_PACKET) 9168 /* PTR_TO_PACKET_META is not supported yet */ 9169 return; 9170 9171 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 9172 * How far beyond pkt_end it goes is unknown. 9173 * if (!range_open) it's the case of pkt >= pkt_end 9174 * if (range_open) it's the case of pkt > pkt_end 9175 * hence this pointer is at least 1 byte bigger than pkt_end 9176 */ 9177 if (range_open) 9178 reg->range = BEYOND_PKT_END; 9179 else 9180 reg->range = AT_PKT_END; 9181 } 9182 9183 /* The pointer with the specified id has released its reference to kernel 9184 * resources. Identify all copies of the same pointer and clear the reference. 9185 */ 9186 static int release_reference(struct bpf_verifier_env *env, 9187 int ref_obj_id) 9188 { 9189 struct bpf_func_state *state; 9190 struct bpf_reg_state *reg; 9191 int err; 9192 9193 err = release_reference_state(cur_func(env), ref_obj_id); 9194 if (err) 9195 return err; 9196 9197 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9198 if (reg->ref_obj_id == ref_obj_id) 9199 mark_reg_invalid(env, reg); 9200 })); 9201 9202 return 0; 9203 } 9204 9205 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9206 { 9207 struct bpf_func_state *unused; 9208 struct bpf_reg_state *reg; 9209 9210 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9211 if (type_is_non_owning_ref(reg->type)) 9212 mark_reg_invalid(env, reg); 9213 })); 9214 } 9215 9216 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9217 struct bpf_reg_state *regs) 9218 { 9219 int i; 9220 9221 /* after the call registers r0 - r5 were scratched */ 9222 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9223 mark_reg_not_init(env, regs, caller_saved[i]); 9224 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9225 } 9226 } 9227 9228 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9229 struct bpf_func_state *caller, 9230 struct bpf_func_state *callee, 9231 int insn_idx); 9232 9233 static int set_callee_state(struct bpf_verifier_env *env, 9234 struct bpf_func_state *caller, 9235 struct bpf_func_state *callee, int insn_idx); 9236 9237 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9238 set_callee_state_fn set_callee_state_cb, 9239 struct bpf_verifier_state *state) 9240 { 9241 struct bpf_func_state *caller, *callee; 9242 int err; 9243 9244 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9245 verbose(env, "the call stack of %d frames is too deep\n", 9246 state->curframe + 2); 9247 return -E2BIG; 9248 } 9249 9250 if (state->frame[state->curframe + 1]) { 9251 verbose(env, "verifier bug. Frame %d already allocated\n", 9252 state->curframe + 1); 9253 return -EFAULT; 9254 } 9255 9256 caller = state->frame[state->curframe]; 9257 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 9258 if (!callee) 9259 return -ENOMEM; 9260 state->frame[state->curframe + 1] = callee; 9261 9262 /* callee cannot access r0, r6 - r9 for reading and has to write 9263 * into its own stack before reading from it. 9264 * callee can read/write into caller's stack 9265 */ 9266 init_func_state(env, callee, 9267 /* remember the callsite, it will be used by bpf_exit */ 9268 callsite, 9269 state->curframe + 1 /* frameno within this callchain */, 9270 subprog /* subprog number within this prog */); 9271 /* Transfer references to the callee */ 9272 err = copy_reference_state(callee, caller); 9273 err = err ?: set_callee_state_cb(env, caller, callee, callsite); 9274 if (err) 9275 goto err_out; 9276 9277 /* only increment it after check_reg_arg() finished */ 9278 state->curframe++; 9279 9280 return 0; 9281 9282 err_out: 9283 free_func_state(callee); 9284 state->frame[state->curframe + 1] = NULL; 9285 return err; 9286 } 9287 9288 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, 9289 const struct btf *btf, 9290 struct bpf_reg_state *regs) 9291 { 9292 struct bpf_subprog_info *sub = subprog_info(env, subprog); 9293 struct bpf_verifier_log *log = &env->log; 9294 u32 i; 9295 int ret; 9296 9297 ret = btf_prepare_func_args(env, subprog); 9298 if (ret) 9299 return ret; 9300 9301 /* check that BTF function arguments match actual types that the 9302 * verifier sees. 9303 */ 9304 for (i = 0; i < sub->arg_cnt; i++) { 9305 u32 regno = i + 1; 9306 struct bpf_reg_state *reg = ®s[regno]; 9307 struct bpf_subprog_arg_info *arg = &sub->args[i]; 9308 9309 if (arg->arg_type == ARG_ANYTHING) { 9310 if (reg->type != SCALAR_VALUE) { 9311 bpf_log(log, "R%d is not a scalar\n", regno); 9312 return -EINVAL; 9313 } 9314 } else if (arg->arg_type == ARG_PTR_TO_CTX) { 9315 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9316 if (ret < 0) 9317 return ret; 9318 /* If function expects ctx type in BTF check that caller 9319 * is passing PTR_TO_CTX. 9320 */ 9321 if (reg->type != PTR_TO_CTX) { 9322 bpf_log(log, "arg#%d expects pointer to ctx\n", i); 9323 return -EINVAL; 9324 } 9325 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 9326 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9327 if (ret < 0) 9328 return ret; 9329 if (check_mem_reg(env, reg, regno, arg->mem_size)) 9330 return -EINVAL; 9331 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) { 9332 bpf_log(log, "arg#%d is expected to be non-NULL\n", i); 9333 return -EINVAL; 9334 } 9335 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 9336 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0); 9337 if (ret) 9338 return ret; 9339 } else { 9340 bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n", 9341 i, arg->arg_type); 9342 return -EFAULT; 9343 } 9344 } 9345 9346 return 0; 9347 } 9348 9349 /* Compare BTF of a function call with given bpf_reg_state. 9350 * Returns: 9351 * EFAULT - there is a verifier bug. Abort verification. 9352 * EINVAL - there is a type mismatch or BTF is not available. 9353 * 0 - BTF matches with what bpf_reg_state expects. 9354 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized. 9355 */ 9356 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog, 9357 struct bpf_reg_state *regs) 9358 { 9359 struct bpf_prog *prog = env->prog; 9360 struct btf *btf = prog->aux->btf; 9361 u32 btf_id; 9362 int err; 9363 9364 if (!prog->aux->func_info) 9365 return -EINVAL; 9366 9367 btf_id = prog->aux->func_info[subprog].type_id; 9368 if (!btf_id) 9369 return -EFAULT; 9370 9371 if (prog->aux->func_info_aux[subprog].unreliable) 9372 return -EINVAL; 9373 9374 err = btf_check_func_arg_match(env, subprog, btf, regs); 9375 /* Compiler optimizations can remove arguments from static functions 9376 * or mismatched type can be passed into a global function. 9377 * In such cases mark the function as unreliable from BTF point of view. 9378 */ 9379 if (err) 9380 prog->aux->func_info_aux[subprog].unreliable = true; 9381 return err; 9382 } 9383 9384 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9385 int insn_idx, int subprog, 9386 set_callee_state_fn set_callee_state_cb) 9387 { 9388 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9389 struct bpf_func_state *caller, *callee; 9390 int err; 9391 9392 caller = state->frame[state->curframe]; 9393 err = btf_check_subprog_call(env, subprog, caller->regs); 9394 if (err == -EFAULT) 9395 return err; 9396 9397 /* set_callee_state is used for direct subprog calls, but we are 9398 * interested in validating only BPF helpers that can call subprogs as 9399 * callbacks 9400 */ 9401 env->subprog_info[subprog].is_cb = true; 9402 if (bpf_pseudo_kfunc_call(insn) && 9403 !is_sync_callback_calling_kfunc(insn->imm)) { 9404 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 9405 func_id_name(insn->imm), insn->imm); 9406 return -EFAULT; 9407 } else if (!bpf_pseudo_kfunc_call(insn) && 9408 !is_callback_calling_function(insn->imm)) { /* helper */ 9409 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 9410 func_id_name(insn->imm), insn->imm); 9411 return -EFAULT; 9412 } 9413 9414 if (insn->code == (BPF_JMP | BPF_CALL) && 9415 insn->src_reg == 0 && 9416 insn->imm == BPF_FUNC_timer_set_callback) { 9417 struct bpf_verifier_state *async_cb; 9418 9419 /* there is no real recursion here. timer callbacks are async */ 9420 env->subprog_info[subprog].is_async_cb = true; 9421 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9422 insn_idx, subprog); 9423 if (!async_cb) 9424 return -EFAULT; 9425 callee = async_cb->frame[0]; 9426 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9427 9428 /* Convert bpf_timer_set_callback() args into timer callback args */ 9429 err = set_callee_state_cb(env, caller, callee, insn_idx); 9430 if (err) 9431 return err; 9432 9433 return 0; 9434 } 9435 9436 /* for callback functions enqueue entry to callback and 9437 * proceed with next instruction within current frame. 9438 */ 9439 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9440 if (!callback_state) 9441 return -ENOMEM; 9442 9443 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9444 callback_state); 9445 if (err) 9446 return err; 9447 9448 callback_state->callback_unroll_depth++; 9449 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9450 caller->callback_depth = 0; 9451 return 0; 9452 } 9453 9454 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9455 int *insn_idx) 9456 { 9457 struct bpf_verifier_state *state = env->cur_state; 9458 struct bpf_func_state *caller; 9459 int err, subprog, target_insn; 9460 9461 target_insn = *insn_idx + insn->imm + 1; 9462 subprog = find_subprog(env, target_insn); 9463 if (subprog < 0) { 9464 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn); 9465 return -EFAULT; 9466 } 9467 9468 caller = state->frame[state->curframe]; 9469 err = btf_check_subprog_call(env, subprog, caller->regs); 9470 if (err == -EFAULT) 9471 return err; 9472 if (subprog_is_global(env, subprog)) { 9473 const char *sub_name = subprog_name(env, subprog); 9474 9475 if (err) { 9476 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 9477 subprog, sub_name); 9478 return err; 9479 } 9480 9481 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 9482 subprog, sub_name); 9483 /* mark global subprog for verifying after main prog */ 9484 subprog_aux(env, subprog)->called = true; 9485 clear_caller_saved_regs(env, caller->regs); 9486 9487 /* All global functions return a 64-bit SCALAR_VALUE */ 9488 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9489 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9490 9491 /* continue with next insn after call */ 9492 return 0; 9493 } 9494 9495 /* for regular function entry setup new frame and continue 9496 * from that frame. 9497 */ 9498 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9499 if (err) 9500 return err; 9501 9502 clear_caller_saved_regs(env, caller->regs); 9503 9504 /* and go analyze first insn of the callee */ 9505 *insn_idx = env->subprog_info[subprog].start - 1; 9506 9507 if (env->log.level & BPF_LOG_LEVEL) { 9508 verbose(env, "caller:\n"); 9509 print_verifier_state(env, caller, true); 9510 verbose(env, "callee:\n"); 9511 print_verifier_state(env, state->frame[state->curframe], true); 9512 } 9513 9514 return 0; 9515 } 9516 9517 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9518 struct bpf_func_state *caller, 9519 struct bpf_func_state *callee) 9520 { 9521 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9522 * void *callback_ctx, u64 flags); 9523 * callback_fn(struct bpf_map *map, void *key, void *value, 9524 * void *callback_ctx); 9525 */ 9526 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9527 9528 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9529 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9530 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9531 9532 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9533 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9534 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9535 9536 /* pointer to stack or null */ 9537 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9538 9539 /* unused */ 9540 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9541 return 0; 9542 } 9543 9544 static int set_callee_state(struct bpf_verifier_env *env, 9545 struct bpf_func_state *caller, 9546 struct bpf_func_state *callee, int insn_idx) 9547 { 9548 int i; 9549 9550 /* copy r1 - r5 args that callee can access. The copy includes parent 9551 * pointers, which connects us up to the liveness chain 9552 */ 9553 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9554 callee->regs[i] = caller->regs[i]; 9555 return 0; 9556 } 9557 9558 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9559 struct bpf_func_state *caller, 9560 struct bpf_func_state *callee, 9561 int insn_idx) 9562 { 9563 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9564 struct bpf_map *map; 9565 int err; 9566 9567 if (bpf_map_ptr_poisoned(insn_aux)) { 9568 verbose(env, "tail_call abusing map_ptr\n"); 9569 return -EINVAL; 9570 } 9571 9572 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 9573 if (!map->ops->map_set_for_each_callback_args || 9574 !map->ops->map_for_each_callback) { 9575 verbose(env, "callback function not allowed for map\n"); 9576 return -ENOTSUPP; 9577 } 9578 9579 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9580 if (err) 9581 return err; 9582 9583 callee->in_callback_fn = true; 9584 callee->callback_ret_range = retval_range(0, 1); 9585 return 0; 9586 } 9587 9588 static int set_loop_callback_state(struct bpf_verifier_env *env, 9589 struct bpf_func_state *caller, 9590 struct bpf_func_state *callee, 9591 int insn_idx) 9592 { 9593 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9594 * u64 flags); 9595 * callback_fn(u32 index, void *callback_ctx); 9596 */ 9597 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9598 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9599 9600 /* unused */ 9601 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9602 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9603 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9604 9605 callee->in_callback_fn = true; 9606 callee->callback_ret_range = retval_range(0, 1); 9607 return 0; 9608 } 9609 9610 static int set_timer_callback_state(struct bpf_verifier_env *env, 9611 struct bpf_func_state *caller, 9612 struct bpf_func_state *callee, 9613 int insn_idx) 9614 { 9615 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9616 9617 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9618 * callback_fn(struct bpf_map *map, void *key, void *value); 9619 */ 9620 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9621 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9622 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9623 9624 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9625 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9626 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9627 9628 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9629 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9630 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9631 9632 /* unused */ 9633 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9634 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9635 callee->in_async_callback_fn = true; 9636 callee->callback_ret_range = retval_range(0, 1); 9637 return 0; 9638 } 9639 9640 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9641 struct bpf_func_state *caller, 9642 struct bpf_func_state *callee, 9643 int insn_idx) 9644 { 9645 /* bpf_find_vma(struct task_struct *task, u64 addr, 9646 * void *callback_fn, void *callback_ctx, u64 flags) 9647 * (callback_fn)(struct task_struct *task, 9648 * struct vm_area_struct *vma, void *callback_ctx); 9649 */ 9650 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9651 9652 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9653 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9654 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9655 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 9656 9657 /* pointer to stack or null */ 9658 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9659 9660 /* unused */ 9661 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9662 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9663 callee->in_callback_fn = true; 9664 callee->callback_ret_range = retval_range(0, 1); 9665 return 0; 9666 } 9667 9668 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9669 struct bpf_func_state *caller, 9670 struct bpf_func_state *callee, 9671 int insn_idx) 9672 { 9673 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9674 * callback_ctx, u64 flags); 9675 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9676 */ 9677 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9678 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9679 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9680 9681 /* unused */ 9682 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9683 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9684 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9685 9686 callee->in_callback_fn = true; 9687 callee->callback_ret_range = retval_range(0, 1); 9688 return 0; 9689 } 9690 9691 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9692 struct bpf_func_state *caller, 9693 struct bpf_func_state *callee, 9694 int insn_idx) 9695 { 9696 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9697 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9698 * 9699 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9700 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9701 * by this point, so look at 'root' 9702 */ 9703 struct btf_field *field; 9704 9705 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 9706 BPF_RB_ROOT); 9707 if (!field || !field->graph_root.value_btf_id) 9708 return -EFAULT; 9709 9710 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9711 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9712 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9713 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9714 9715 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9716 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9717 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9718 callee->in_callback_fn = true; 9719 callee->callback_ret_range = retval_range(0, 1); 9720 return 0; 9721 } 9722 9723 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9724 9725 /* Are we currently verifying the callback for a rbtree helper that must 9726 * be called with lock held? If so, no need to complain about unreleased 9727 * lock 9728 */ 9729 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9730 { 9731 struct bpf_verifier_state *state = env->cur_state; 9732 struct bpf_insn *insn = env->prog->insnsi; 9733 struct bpf_func_state *callee; 9734 int kfunc_btf_id; 9735 9736 if (!state->curframe) 9737 return false; 9738 9739 callee = state->frame[state->curframe]; 9740 9741 if (!callee->in_callback_fn) 9742 return false; 9743 9744 kfunc_btf_id = insn[callee->callsite].imm; 9745 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9746 } 9747 9748 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg) 9749 { 9750 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval; 9751 } 9752 9753 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9754 { 9755 struct bpf_verifier_state *state = env->cur_state, *prev_st; 9756 struct bpf_func_state *caller, *callee; 9757 struct bpf_reg_state *r0; 9758 bool in_callback_fn; 9759 int err; 9760 9761 callee = state->frame[state->curframe]; 9762 r0 = &callee->regs[BPF_REG_0]; 9763 if (r0->type == PTR_TO_STACK) { 9764 /* technically it's ok to return caller's stack pointer 9765 * (or caller's caller's pointer) back to the caller, 9766 * since these pointers are valid. Only current stack 9767 * pointer will be invalid as soon as function exits, 9768 * but let's be conservative 9769 */ 9770 verbose(env, "cannot return stack pointer to the caller\n"); 9771 return -EINVAL; 9772 } 9773 9774 caller = state->frame[state->curframe - 1]; 9775 if (callee->in_callback_fn) { 9776 if (r0->type != SCALAR_VALUE) { 9777 verbose(env, "R0 not a scalar value\n"); 9778 return -EACCES; 9779 } 9780 9781 /* we are going to rely on register's precise value */ 9782 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64); 9783 err = err ?: mark_chain_precision(env, BPF_REG_0); 9784 if (err) 9785 return err; 9786 9787 /* enforce R0 return value range */ 9788 if (!retval_range_within(callee->callback_ret_range, r0)) { 9789 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 9790 "At callback return", "R0"); 9791 return -EINVAL; 9792 } 9793 if (!calls_callback(env, callee->callsite)) { 9794 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n", 9795 *insn_idx, callee->callsite); 9796 return -EFAULT; 9797 } 9798 } else { 9799 /* return to the caller whatever r0 had in the callee */ 9800 caller->regs[BPF_REG_0] = *r0; 9801 } 9802 9803 /* callback_fn frame should have released its own additions to parent's 9804 * reference state at this point, or check_reference_leak would 9805 * complain, hence it must be the same as the caller. There is no need 9806 * to copy it back. 9807 */ 9808 if (!callee->in_callback_fn) { 9809 /* Transfer references to the caller */ 9810 err = copy_reference_state(caller, callee); 9811 if (err) 9812 return err; 9813 } 9814 9815 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 9816 * there function call logic would reschedule callback visit. If iteration 9817 * converges is_state_visited() would prune that visit eventually. 9818 */ 9819 in_callback_fn = callee->in_callback_fn; 9820 if (in_callback_fn) 9821 *insn_idx = callee->callsite; 9822 else 9823 *insn_idx = callee->callsite + 1; 9824 9825 if (env->log.level & BPF_LOG_LEVEL) { 9826 verbose(env, "returning from callee:\n"); 9827 print_verifier_state(env, callee, true); 9828 verbose(env, "to caller at %d:\n", *insn_idx); 9829 print_verifier_state(env, caller, true); 9830 } 9831 /* clear everything in the callee. In case of exceptional exits using 9832 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 9833 free_func_state(callee); 9834 state->frame[state->curframe--] = NULL; 9835 9836 /* for callbacks widen imprecise scalars to make programs like below verify: 9837 * 9838 * struct ctx { int i; } 9839 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 9840 * ... 9841 * struct ctx = { .i = 0; } 9842 * bpf_loop(100, cb, &ctx, 0); 9843 * 9844 * This is similar to what is done in process_iter_next_call() for open 9845 * coded iterators. 9846 */ 9847 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 9848 if (prev_st) { 9849 err = widen_imprecise_scalars(env, prev_st, state); 9850 if (err) 9851 return err; 9852 } 9853 return 0; 9854 } 9855 9856 static int do_refine_retval_range(struct bpf_verifier_env *env, 9857 struct bpf_reg_state *regs, int ret_type, 9858 int func_id, 9859 struct bpf_call_arg_meta *meta) 9860 { 9861 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 9862 9863 if (ret_type != RET_INTEGER) 9864 return 0; 9865 9866 switch (func_id) { 9867 case BPF_FUNC_get_stack: 9868 case BPF_FUNC_get_task_stack: 9869 case BPF_FUNC_probe_read_str: 9870 case BPF_FUNC_probe_read_kernel_str: 9871 case BPF_FUNC_probe_read_user_str: 9872 ret_reg->smax_value = meta->msize_max_value; 9873 ret_reg->s32_max_value = meta->msize_max_value; 9874 ret_reg->smin_value = -MAX_ERRNO; 9875 ret_reg->s32_min_value = -MAX_ERRNO; 9876 reg_bounds_sync(ret_reg); 9877 break; 9878 case BPF_FUNC_get_smp_processor_id: 9879 ret_reg->umax_value = nr_cpu_ids - 1; 9880 ret_reg->u32_max_value = nr_cpu_ids - 1; 9881 ret_reg->smax_value = nr_cpu_ids - 1; 9882 ret_reg->s32_max_value = nr_cpu_ids - 1; 9883 ret_reg->umin_value = 0; 9884 ret_reg->u32_min_value = 0; 9885 ret_reg->smin_value = 0; 9886 ret_reg->s32_min_value = 0; 9887 reg_bounds_sync(ret_reg); 9888 break; 9889 } 9890 9891 return reg_bounds_sanity_check(env, ret_reg, "retval"); 9892 } 9893 9894 static int 9895 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9896 int func_id, int insn_idx) 9897 { 9898 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9899 struct bpf_map *map = meta->map_ptr; 9900 9901 if (func_id != BPF_FUNC_tail_call && 9902 func_id != BPF_FUNC_map_lookup_elem && 9903 func_id != BPF_FUNC_map_update_elem && 9904 func_id != BPF_FUNC_map_delete_elem && 9905 func_id != BPF_FUNC_map_push_elem && 9906 func_id != BPF_FUNC_map_pop_elem && 9907 func_id != BPF_FUNC_map_peek_elem && 9908 func_id != BPF_FUNC_for_each_map_elem && 9909 func_id != BPF_FUNC_redirect_map && 9910 func_id != BPF_FUNC_map_lookup_percpu_elem) 9911 return 0; 9912 9913 if (map == NULL) { 9914 verbose(env, "kernel subsystem misconfigured verifier\n"); 9915 return -EINVAL; 9916 } 9917 9918 /* In case of read-only, some additional restrictions 9919 * need to be applied in order to prevent altering the 9920 * state of the map from program side. 9921 */ 9922 if ((map->map_flags & BPF_F_RDONLY_PROG) && 9923 (func_id == BPF_FUNC_map_delete_elem || 9924 func_id == BPF_FUNC_map_update_elem || 9925 func_id == BPF_FUNC_map_push_elem || 9926 func_id == BPF_FUNC_map_pop_elem)) { 9927 verbose(env, "write into map forbidden\n"); 9928 return -EACCES; 9929 } 9930 9931 if (!BPF_MAP_PTR(aux->map_ptr_state)) 9932 bpf_map_ptr_store(aux, meta->map_ptr, 9933 !meta->map_ptr->bypass_spec_v1); 9934 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 9935 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 9936 !meta->map_ptr->bypass_spec_v1); 9937 return 0; 9938 } 9939 9940 static int 9941 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9942 int func_id, int insn_idx) 9943 { 9944 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9945 struct bpf_reg_state *regs = cur_regs(env), *reg; 9946 struct bpf_map *map = meta->map_ptr; 9947 u64 val, max; 9948 int err; 9949 9950 if (func_id != BPF_FUNC_tail_call) 9951 return 0; 9952 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 9953 verbose(env, "kernel subsystem misconfigured verifier\n"); 9954 return -EINVAL; 9955 } 9956 9957 reg = ®s[BPF_REG_3]; 9958 val = reg->var_off.value; 9959 max = map->max_entries; 9960 9961 if (!(is_reg_const(reg, false) && val < max)) { 9962 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9963 return 0; 9964 } 9965 9966 err = mark_chain_precision(env, BPF_REG_3); 9967 if (err) 9968 return err; 9969 if (bpf_map_key_unseen(aux)) 9970 bpf_map_key_store(aux, val); 9971 else if (!bpf_map_key_poisoned(aux) && 9972 bpf_map_key_immediate(aux) != val) 9973 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9974 return 0; 9975 } 9976 9977 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 9978 { 9979 struct bpf_func_state *state = cur_func(env); 9980 bool refs_lingering = false; 9981 int i; 9982 9983 if (!exception_exit && state->frameno && !state->in_callback_fn) 9984 return 0; 9985 9986 for (i = 0; i < state->acquired_refs; i++) { 9987 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 9988 continue; 9989 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 9990 state->refs[i].id, state->refs[i].insn_idx); 9991 refs_lingering = true; 9992 } 9993 return refs_lingering ? -EINVAL : 0; 9994 } 9995 9996 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 9997 struct bpf_reg_state *regs) 9998 { 9999 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 10000 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 10001 struct bpf_map *fmt_map = fmt_reg->map_ptr; 10002 struct bpf_bprintf_data data = {}; 10003 int err, fmt_map_off, num_args; 10004 u64 fmt_addr; 10005 char *fmt; 10006 10007 /* data must be an array of u64 */ 10008 if (data_len_reg->var_off.value % 8) 10009 return -EINVAL; 10010 num_args = data_len_reg->var_off.value / 8; 10011 10012 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 10013 * and map_direct_value_addr is set. 10014 */ 10015 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 10016 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 10017 fmt_map_off); 10018 if (err) { 10019 verbose(env, "verifier bug\n"); 10020 return -EFAULT; 10021 } 10022 fmt = (char *)(long)fmt_addr + fmt_map_off; 10023 10024 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 10025 * can focus on validating the format specifiers. 10026 */ 10027 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 10028 if (err < 0) 10029 verbose(env, "Invalid format string\n"); 10030 10031 return err; 10032 } 10033 10034 static int check_get_func_ip(struct bpf_verifier_env *env) 10035 { 10036 enum bpf_prog_type type = resolve_prog_type(env->prog); 10037 int func_id = BPF_FUNC_get_func_ip; 10038 10039 if (type == BPF_PROG_TYPE_TRACING) { 10040 if (!bpf_prog_has_trampoline(env->prog)) { 10041 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 10042 func_id_name(func_id), func_id); 10043 return -ENOTSUPP; 10044 } 10045 return 0; 10046 } else if (type == BPF_PROG_TYPE_KPROBE) { 10047 return 0; 10048 } 10049 10050 verbose(env, "func %s#%d not supported for program type %d\n", 10051 func_id_name(func_id), func_id, type); 10052 return -ENOTSUPP; 10053 } 10054 10055 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 10056 { 10057 return &env->insn_aux_data[env->insn_idx]; 10058 } 10059 10060 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 10061 { 10062 struct bpf_reg_state *regs = cur_regs(env); 10063 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 10064 bool reg_is_null = register_is_null(reg); 10065 10066 if (reg_is_null) 10067 mark_chain_precision(env, BPF_REG_4); 10068 10069 return reg_is_null; 10070 } 10071 10072 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 10073 { 10074 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 10075 10076 if (!state->initialized) { 10077 state->initialized = 1; 10078 state->fit_for_inline = loop_flag_is_zero(env); 10079 state->callback_subprogno = subprogno; 10080 return; 10081 } 10082 10083 if (!state->fit_for_inline) 10084 return; 10085 10086 state->fit_for_inline = (loop_flag_is_zero(env) && 10087 state->callback_subprogno == subprogno); 10088 } 10089 10090 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10091 int *insn_idx_p) 10092 { 10093 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 10094 bool returns_cpu_specific_alloc_ptr = false; 10095 const struct bpf_func_proto *fn = NULL; 10096 enum bpf_return_type ret_type; 10097 enum bpf_type_flag ret_flag; 10098 struct bpf_reg_state *regs; 10099 struct bpf_call_arg_meta meta; 10100 int insn_idx = *insn_idx_p; 10101 bool changes_data; 10102 int i, err, func_id; 10103 10104 /* find function prototype */ 10105 func_id = insn->imm; 10106 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 10107 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 10108 func_id); 10109 return -EINVAL; 10110 } 10111 10112 if (env->ops->get_func_proto) 10113 fn = env->ops->get_func_proto(func_id, env->prog); 10114 if (!fn) { 10115 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 10116 func_id); 10117 return -EINVAL; 10118 } 10119 10120 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 10121 if (!env->prog->gpl_compatible && fn->gpl_only) { 10122 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10123 return -EINVAL; 10124 } 10125 10126 if (fn->allowed && !fn->allowed(env->prog)) { 10127 verbose(env, "helper call is not allowed in probe\n"); 10128 return -EINVAL; 10129 } 10130 10131 if (!env->prog->aux->sleepable && fn->might_sleep) { 10132 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 10133 return -EINVAL; 10134 } 10135 10136 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10137 changes_data = bpf_helper_changes_pkt_data(fn->func); 10138 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10139 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 10140 func_id_name(func_id), func_id); 10141 return -EINVAL; 10142 } 10143 10144 memset(&meta, 0, sizeof(meta)); 10145 meta.pkt_access = fn->pkt_access; 10146 10147 err = check_func_proto(fn, func_id); 10148 if (err) { 10149 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 10150 func_id_name(func_id), func_id); 10151 return err; 10152 } 10153 10154 if (env->cur_state->active_rcu_lock) { 10155 if (fn->might_sleep) { 10156 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 10157 func_id_name(func_id), func_id); 10158 return -EINVAL; 10159 } 10160 10161 if (env->prog->aux->sleepable && is_storage_get_function(func_id)) 10162 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10163 } 10164 10165 meta.func_id = func_id; 10166 /* check args */ 10167 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10168 err = check_func_arg(env, i, &meta, fn, insn_idx); 10169 if (err) 10170 return err; 10171 } 10172 10173 err = record_func_map(env, &meta, func_id, insn_idx); 10174 if (err) 10175 return err; 10176 10177 err = record_func_key(env, &meta, func_id, insn_idx); 10178 if (err) 10179 return err; 10180 10181 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10182 * is inferred from register state. 10183 */ 10184 for (i = 0; i < meta.access_size; i++) { 10185 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 10186 BPF_WRITE, -1, false, false); 10187 if (err) 10188 return err; 10189 } 10190 10191 regs = cur_regs(env); 10192 10193 if (meta.release_regno) { 10194 err = -EINVAL; 10195 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 10196 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 10197 * is safe to do directly. 10198 */ 10199 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 10200 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 10201 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 10202 return -EFAULT; 10203 } 10204 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 10205 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 10206 u32 ref_obj_id = meta.ref_obj_id; 10207 bool in_rcu = in_rcu_cs(env); 10208 struct bpf_func_state *state; 10209 struct bpf_reg_state *reg; 10210 10211 err = release_reference_state(cur_func(env), ref_obj_id); 10212 if (!err) { 10213 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10214 if (reg->ref_obj_id == ref_obj_id) { 10215 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 10216 reg->ref_obj_id = 0; 10217 reg->type &= ~MEM_ALLOC; 10218 reg->type |= MEM_RCU; 10219 } else { 10220 mark_reg_invalid(env, reg); 10221 } 10222 } 10223 })); 10224 } 10225 } else if (meta.ref_obj_id) { 10226 err = release_reference(env, meta.ref_obj_id); 10227 } else if (register_is_null(®s[meta.release_regno])) { 10228 /* meta.ref_obj_id can only be 0 if register that is meant to be 10229 * released is NULL, which must be > R0. 10230 */ 10231 err = 0; 10232 } 10233 if (err) { 10234 verbose(env, "func %s#%d reference has not been acquired before\n", 10235 func_id_name(func_id), func_id); 10236 return err; 10237 } 10238 } 10239 10240 switch (func_id) { 10241 case BPF_FUNC_tail_call: 10242 err = check_reference_leak(env, false); 10243 if (err) { 10244 verbose(env, "tail_call would lead to reference leak\n"); 10245 return err; 10246 } 10247 break; 10248 case BPF_FUNC_get_local_storage: 10249 /* check that flags argument in get_local_storage(map, flags) is 0, 10250 * this is required because get_local_storage() can't return an error. 10251 */ 10252 if (!register_is_null(®s[BPF_REG_2])) { 10253 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10254 return -EINVAL; 10255 } 10256 break; 10257 case BPF_FUNC_for_each_map_elem: 10258 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10259 set_map_elem_callback_state); 10260 break; 10261 case BPF_FUNC_timer_set_callback: 10262 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10263 set_timer_callback_state); 10264 break; 10265 case BPF_FUNC_find_vma: 10266 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10267 set_find_vma_callback_state); 10268 break; 10269 case BPF_FUNC_snprintf: 10270 err = check_bpf_snprintf_call(env, regs); 10271 break; 10272 case BPF_FUNC_loop: 10273 update_loop_inline_state(env, meta.subprogno); 10274 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10275 * is finished, thus mark it precise. 10276 */ 10277 err = mark_chain_precision(env, BPF_REG_1); 10278 if (err) 10279 return err; 10280 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) { 10281 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10282 set_loop_callback_state); 10283 } else { 10284 cur_func(env)->callback_depth = 0; 10285 if (env->log.level & BPF_LOG_LEVEL2) 10286 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10287 env->cur_state->curframe); 10288 } 10289 break; 10290 case BPF_FUNC_dynptr_from_mem: 10291 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10292 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10293 reg_type_str(env, regs[BPF_REG_1].type)); 10294 return -EACCES; 10295 } 10296 break; 10297 case BPF_FUNC_set_retval: 10298 if (prog_type == BPF_PROG_TYPE_LSM && 10299 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10300 if (!env->prog->aux->attach_func_proto->type) { 10301 /* Make sure programs that attach to void 10302 * hooks don't try to modify return value. 10303 */ 10304 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10305 return -EINVAL; 10306 } 10307 } 10308 break; 10309 case BPF_FUNC_dynptr_data: 10310 { 10311 struct bpf_reg_state *reg; 10312 int id, ref_obj_id; 10313 10314 reg = get_dynptr_arg_reg(env, fn, regs); 10315 if (!reg) 10316 return -EFAULT; 10317 10318 10319 if (meta.dynptr_id) { 10320 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 10321 return -EFAULT; 10322 } 10323 if (meta.ref_obj_id) { 10324 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 10325 return -EFAULT; 10326 } 10327 10328 id = dynptr_id(env, reg); 10329 if (id < 0) { 10330 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 10331 return id; 10332 } 10333 10334 ref_obj_id = dynptr_ref_obj_id(env, reg); 10335 if (ref_obj_id < 0) { 10336 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 10337 return ref_obj_id; 10338 } 10339 10340 meta.dynptr_id = id; 10341 meta.ref_obj_id = ref_obj_id; 10342 10343 break; 10344 } 10345 case BPF_FUNC_dynptr_write: 10346 { 10347 enum bpf_dynptr_type dynptr_type; 10348 struct bpf_reg_state *reg; 10349 10350 reg = get_dynptr_arg_reg(env, fn, regs); 10351 if (!reg) 10352 return -EFAULT; 10353 10354 dynptr_type = dynptr_get_type(env, reg); 10355 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10356 return -EFAULT; 10357 10358 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 10359 /* this will trigger clear_all_pkt_pointers(), which will 10360 * invalidate all dynptr slices associated with the skb 10361 */ 10362 changes_data = true; 10363 10364 break; 10365 } 10366 case BPF_FUNC_per_cpu_ptr: 10367 case BPF_FUNC_this_cpu_ptr: 10368 { 10369 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 10370 const struct btf_type *type; 10371 10372 if (reg->type & MEM_RCU) { 10373 type = btf_type_by_id(reg->btf, reg->btf_id); 10374 if (!type || !btf_type_is_struct(type)) { 10375 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 10376 return -EFAULT; 10377 } 10378 returns_cpu_specific_alloc_ptr = true; 10379 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 10380 } 10381 break; 10382 } 10383 case BPF_FUNC_user_ringbuf_drain: 10384 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10385 set_user_ringbuf_callback_state); 10386 break; 10387 } 10388 10389 if (err) 10390 return err; 10391 10392 /* reset caller saved regs */ 10393 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10394 mark_reg_not_init(env, regs, caller_saved[i]); 10395 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10396 } 10397 10398 /* helper call returns 64-bit value. */ 10399 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10400 10401 /* update return register (already marked as written above) */ 10402 ret_type = fn->ret_type; 10403 ret_flag = type_flag(ret_type); 10404 10405 switch (base_type(ret_type)) { 10406 case RET_INTEGER: 10407 /* sets type to SCALAR_VALUE */ 10408 mark_reg_unknown(env, regs, BPF_REG_0); 10409 break; 10410 case RET_VOID: 10411 regs[BPF_REG_0].type = NOT_INIT; 10412 break; 10413 case RET_PTR_TO_MAP_VALUE: 10414 /* There is no offset yet applied, variable or fixed */ 10415 mark_reg_known_zero(env, regs, BPF_REG_0); 10416 /* remember map_ptr, so that check_map_access() 10417 * can check 'value_size' boundary of memory access 10418 * to map element returned from bpf_map_lookup_elem() 10419 */ 10420 if (meta.map_ptr == NULL) { 10421 verbose(env, 10422 "kernel subsystem misconfigured verifier\n"); 10423 return -EINVAL; 10424 } 10425 regs[BPF_REG_0].map_ptr = meta.map_ptr; 10426 regs[BPF_REG_0].map_uid = meta.map_uid; 10427 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10428 if (!type_may_be_null(ret_type) && 10429 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 10430 regs[BPF_REG_0].id = ++env->id_gen; 10431 } 10432 break; 10433 case RET_PTR_TO_SOCKET: 10434 mark_reg_known_zero(env, regs, BPF_REG_0); 10435 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10436 break; 10437 case RET_PTR_TO_SOCK_COMMON: 10438 mark_reg_known_zero(env, regs, BPF_REG_0); 10439 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10440 break; 10441 case RET_PTR_TO_TCP_SOCK: 10442 mark_reg_known_zero(env, regs, BPF_REG_0); 10443 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10444 break; 10445 case RET_PTR_TO_MEM: 10446 mark_reg_known_zero(env, regs, BPF_REG_0); 10447 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10448 regs[BPF_REG_0].mem_size = meta.mem_size; 10449 break; 10450 case RET_PTR_TO_MEM_OR_BTF_ID: 10451 { 10452 const struct btf_type *t; 10453 10454 mark_reg_known_zero(env, regs, BPF_REG_0); 10455 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10456 if (!btf_type_is_struct(t)) { 10457 u32 tsize; 10458 const struct btf_type *ret; 10459 const char *tname; 10460 10461 /* resolve the type size of ksym. */ 10462 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10463 if (IS_ERR(ret)) { 10464 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10465 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10466 tname, PTR_ERR(ret)); 10467 return -EINVAL; 10468 } 10469 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10470 regs[BPF_REG_0].mem_size = tsize; 10471 } else { 10472 if (returns_cpu_specific_alloc_ptr) { 10473 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10474 } else { 10475 /* MEM_RDONLY may be carried from ret_flag, but it 10476 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10477 * it will confuse the check of PTR_TO_BTF_ID in 10478 * check_mem_access(). 10479 */ 10480 ret_flag &= ~MEM_RDONLY; 10481 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10482 } 10483 10484 regs[BPF_REG_0].btf = meta.ret_btf; 10485 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10486 } 10487 break; 10488 } 10489 case RET_PTR_TO_BTF_ID: 10490 { 10491 struct btf *ret_btf; 10492 int ret_btf_id; 10493 10494 mark_reg_known_zero(env, regs, BPF_REG_0); 10495 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10496 if (func_id == BPF_FUNC_kptr_xchg) { 10497 ret_btf = meta.kptr_field->kptr.btf; 10498 ret_btf_id = meta.kptr_field->kptr.btf_id; 10499 if (!btf_is_kernel(ret_btf)) { 10500 regs[BPF_REG_0].type |= MEM_ALLOC; 10501 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10502 regs[BPF_REG_0].type |= MEM_PERCPU; 10503 } 10504 } else { 10505 if (fn->ret_btf_id == BPF_PTR_POISON) { 10506 verbose(env, "verifier internal error:"); 10507 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 10508 func_id_name(func_id)); 10509 return -EINVAL; 10510 } 10511 ret_btf = btf_vmlinux; 10512 ret_btf_id = *fn->ret_btf_id; 10513 } 10514 if (ret_btf_id == 0) { 10515 verbose(env, "invalid return type %u of func %s#%d\n", 10516 base_type(ret_type), func_id_name(func_id), 10517 func_id); 10518 return -EINVAL; 10519 } 10520 regs[BPF_REG_0].btf = ret_btf; 10521 regs[BPF_REG_0].btf_id = ret_btf_id; 10522 break; 10523 } 10524 default: 10525 verbose(env, "unknown return type %u of func %s#%d\n", 10526 base_type(ret_type), func_id_name(func_id), func_id); 10527 return -EINVAL; 10528 } 10529 10530 if (type_may_be_null(regs[BPF_REG_0].type)) 10531 regs[BPF_REG_0].id = ++env->id_gen; 10532 10533 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 10534 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 10535 func_id_name(func_id), func_id); 10536 return -EFAULT; 10537 } 10538 10539 if (is_dynptr_ref_function(func_id)) 10540 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 10541 10542 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 10543 /* For release_reference() */ 10544 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10545 } else if (is_acquire_function(func_id, meta.map_ptr)) { 10546 int id = acquire_reference_state(env, insn_idx); 10547 10548 if (id < 0) 10549 return id; 10550 /* For mark_ptr_or_null_reg() */ 10551 regs[BPF_REG_0].id = id; 10552 /* For release_reference() */ 10553 regs[BPF_REG_0].ref_obj_id = id; 10554 } 10555 10556 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 10557 if (err) 10558 return err; 10559 10560 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 10561 if (err) 10562 return err; 10563 10564 if ((func_id == BPF_FUNC_get_stack || 10565 func_id == BPF_FUNC_get_task_stack) && 10566 !env->prog->has_callchain_buf) { 10567 const char *err_str; 10568 10569 #ifdef CONFIG_PERF_EVENTS 10570 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10571 err_str = "cannot get callchain buffer for func %s#%d\n"; 10572 #else 10573 err = -ENOTSUPP; 10574 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10575 #endif 10576 if (err) { 10577 verbose(env, err_str, func_id_name(func_id), func_id); 10578 return err; 10579 } 10580 10581 env->prog->has_callchain_buf = true; 10582 } 10583 10584 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10585 env->prog->call_get_stack = true; 10586 10587 if (func_id == BPF_FUNC_get_func_ip) { 10588 if (check_get_func_ip(env)) 10589 return -ENOTSUPP; 10590 env->prog->call_get_func_ip = true; 10591 } 10592 10593 if (changes_data) 10594 clear_all_pkt_pointers(env); 10595 return 0; 10596 } 10597 10598 /* mark_btf_func_reg_size() is used when the reg size is determined by 10599 * the BTF func_proto's return value size and argument. 10600 */ 10601 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10602 size_t reg_size) 10603 { 10604 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 10605 10606 if (regno == BPF_REG_0) { 10607 /* Function return value */ 10608 reg->live |= REG_LIVE_WRITTEN; 10609 reg->subreg_def = reg_size == sizeof(u64) ? 10610 DEF_NOT_SUBREG : env->insn_idx + 1; 10611 } else { 10612 /* Function argument */ 10613 if (reg_size == sizeof(u64)) { 10614 mark_insn_zext(env, reg); 10615 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 10616 } else { 10617 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 10618 } 10619 } 10620 } 10621 10622 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10623 { 10624 return meta->kfunc_flags & KF_ACQUIRE; 10625 } 10626 10627 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10628 { 10629 return meta->kfunc_flags & KF_RELEASE; 10630 } 10631 10632 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 10633 { 10634 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 10635 } 10636 10637 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 10638 { 10639 return meta->kfunc_flags & KF_SLEEPABLE; 10640 } 10641 10642 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10643 { 10644 return meta->kfunc_flags & KF_DESTRUCTIVE; 10645 } 10646 10647 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10648 { 10649 return meta->kfunc_flags & KF_RCU; 10650 } 10651 10652 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 10653 { 10654 return meta->kfunc_flags & KF_RCU_PROTECTED; 10655 } 10656 10657 static bool __kfunc_param_match_suffix(const struct btf *btf, 10658 const struct btf_param *arg, 10659 const char *suffix) 10660 { 10661 int suffix_len = strlen(suffix), len; 10662 const char *param_name; 10663 10664 /* In the future, this can be ported to use BTF tagging */ 10665 param_name = btf_name_by_offset(btf, arg->name_off); 10666 if (str_is_empty(param_name)) 10667 return false; 10668 len = strlen(param_name); 10669 if (len < suffix_len) 10670 return false; 10671 param_name += len - suffix_len; 10672 return !strncmp(param_name, suffix, suffix_len); 10673 } 10674 10675 static bool is_kfunc_arg_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, "__sz"); 10686 } 10687 10688 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10689 const struct btf_param *arg, 10690 const struct bpf_reg_state *reg) 10691 { 10692 const struct btf_type *t; 10693 10694 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10695 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10696 return false; 10697 10698 return __kfunc_param_match_suffix(btf, arg, "__szk"); 10699 } 10700 10701 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 10702 { 10703 return __kfunc_param_match_suffix(btf, arg, "__opt"); 10704 } 10705 10706 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10707 { 10708 return __kfunc_param_match_suffix(btf, arg, "__k"); 10709 } 10710 10711 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10712 { 10713 return __kfunc_param_match_suffix(btf, arg, "__ign"); 10714 } 10715 10716 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10717 { 10718 return __kfunc_param_match_suffix(btf, arg, "__alloc"); 10719 } 10720 10721 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10722 { 10723 return __kfunc_param_match_suffix(btf, arg, "__uninit"); 10724 } 10725 10726 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10727 { 10728 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr"); 10729 } 10730 10731 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 10732 { 10733 return __kfunc_param_match_suffix(btf, arg, "__nullable"); 10734 } 10735 10736 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 10737 { 10738 return __kfunc_param_match_suffix(btf, arg, "__str"); 10739 } 10740 10741 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10742 const struct btf_param *arg, 10743 const char *name) 10744 { 10745 int len, target_len = strlen(name); 10746 const char *param_name; 10747 10748 param_name = btf_name_by_offset(btf, arg->name_off); 10749 if (str_is_empty(param_name)) 10750 return false; 10751 len = strlen(param_name); 10752 if (len != target_len) 10753 return false; 10754 if (strcmp(param_name, name)) 10755 return false; 10756 10757 return true; 10758 } 10759 10760 enum { 10761 KF_ARG_DYNPTR_ID, 10762 KF_ARG_LIST_HEAD_ID, 10763 KF_ARG_LIST_NODE_ID, 10764 KF_ARG_RB_ROOT_ID, 10765 KF_ARG_RB_NODE_ID, 10766 }; 10767 10768 BTF_ID_LIST(kf_arg_btf_ids) 10769 BTF_ID(struct, bpf_dynptr_kern) 10770 BTF_ID(struct, bpf_list_head) 10771 BTF_ID(struct, bpf_list_node) 10772 BTF_ID(struct, bpf_rb_root) 10773 BTF_ID(struct, bpf_rb_node) 10774 10775 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10776 const struct btf_param *arg, int type) 10777 { 10778 const struct btf_type *t; 10779 u32 res_id; 10780 10781 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10782 if (!t) 10783 return false; 10784 if (!btf_type_is_ptr(t)) 10785 return false; 10786 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10787 if (!t) 10788 return false; 10789 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10790 } 10791 10792 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10793 { 10794 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10795 } 10796 10797 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10798 { 10799 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10800 } 10801 10802 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10803 { 10804 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10805 } 10806 10807 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10808 { 10809 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10810 } 10811 10812 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10813 { 10814 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10815 } 10816 10817 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10818 const struct btf_param *arg) 10819 { 10820 const struct btf_type *t; 10821 10822 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10823 if (!t) 10824 return false; 10825 10826 return true; 10827 } 10828 10829 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10830 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10831 const struct btf *btf, 10832 const struct btf_type *t, int rec) 10833 { 10834 const struct btf_type *member_type; 10835 const struct btf_member *member; 10836 u32 i; 10837 10838 if (!btf_type_is_struct(t)) 10839 return false; 10840 10841 for_each_member(i, t, member) { 10842 const struct btf_array *array; 10843 10844 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 10845 if (btf_type_is_struct(member_type)) { 10846 if (rec >= 3) { 10847 verbose(env, "max struct nesting depth exceeded\n"); 10848 return false; 10849 } 10850 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 10851 return false; 10852 continue; 10853 } 10854 if (btf_type_is_array(member_type)) { 10855 array = btf_array(member_type); 10856 if (!array->nelems) 10857 return false; 10858 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 10859 if (!btf_type_is_scalar(member_type)) 10860 return false; 10861 continue; 10862 } 10863 if (!btf_type_is_scalar(member_type)) 10864 return false; 10865 } 10866 return true; 10867 } 10868 10869 enum kfunc_ptr_arg_type { 10870 KF_ARG_PTR_TO_CTX, 10871 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 10872 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 10873 KF_ARG_PTR_TO_DYNPTR, 10874 KF_ARG_PTR_TO_ITER, 10875 KF_ARG_PTR_TO_LIST_HEAD, 10876 KF_ARG_PTR_TO_LIST_NODE, 10877 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 10878 KF_ARG_PTR_TO_MEM, 10879 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 10880 KF_ARG_PTR_TO_CALLBACK, 10881 KF_ARG_PTR_TO_RB_ROOT, 10882 KF_ARG_PTR_TO_RB_NODE, 10883 KF_ARG_PTR_TO_NULL, 10884 KF_ARG_PTR_TO_CONST_STR, 10885 }; 10886 10887 enum special_kfunc_type { 10888 KF_bpf_obj_new_impl, 10889 KF_bpf_obj_drop_impl, 10890 KF_bpf_refcount_acquire_impl, 10891 KF_bpf_list_push_front_impl, 10892 KF_bpf_list_push_back_impl, 10893 KF_bpf_list_pop_front, 10894 KF_bpf_list_pop_back, 10895 KF_bpf_cast_to_kern_ctx, 10896 KF_bpf_rdonly_cast, 10897 KF_bpf_rcu_read_lock, 10898 KF_bpf_rcu_read_unlock, 10899 KF_bpf_rbtree_remove, 10900 KF_bpf_rbtree_add_impl, 10901 KF_bpf_rbtree_first, 10902 KF_bpf_dynptr_from_skb, 10903 KF_bpf_dynptr_from_xdp, 10904 KF_bpf_dynptr_slice, 10905 KF_bpf_dynptr_slice_rdwr, 10906 KF_bpf_dynptr_clone, 10907 KF_bpf_percpu_obj_new_impl, 10908 KF_bpf_percpu_obj_drop_impl, 10909 KF_bpf_throw, 10910 KF_bpf_iter_css_task_new, 10911 }; 10912 10913 BTF_SET_START(special_kfunc_set) 10914 BTF_ID(func, bpf_obj_new_impl) 10915 BTF_ID(func, bpf_obj_drop_impl) 10916 BTF_ID(func, bpf_refcount_acquire_impl) 10917 BTF_ID(func, bpf_list_push_front_impl) 10918 BTF_ID(func, bpf_list_push_back_impl) 10919 BTF_ID(func, bpf_list_pop_front) 10920 BTF_ID(func, bpf_list_pop_back) 10921 BTF_ID(func, bpf_cast_to_kern_ctx) 10922 BTF_ID(func, bpf_rdonly_cast) 10923 BTF_ID(func, bpf_rbtree_remove) 10924 BTF_ID(func, bpf_rbtree_add_impl) 10925 BTF_ID(func, bpf_rbtree_first) 10926 BTF_ID(func, bpf_dynptr_from_skb) 10927 BTF_ID(func, bpf_dynptr_from_xdp) 10928 BTF_ID(func, bpf_dynptr_slice) 10929 BTF_ID(func, bpf_dynptr_slice_rdwr) 10930 BTF_ID(func, bpf_dynptr_clone) 10931 BTF_ID(func, bpf_percpu_obj_new_impl) 10932 BTF_ID(func, bpf_percpu_obj_drop_impl) 10933 BTF_ID(func, bpf_throw) 10934 #ifdef CONFIG_CGROUPS 10935 BTF_ID(func, bpf_iter_css_task_new) 10936 #endif 10937 BTF_SET_END(special_kfunc_set) 10938 10939 BTF_ID_LIST(special_kfunc_list) 10940 BTF_ID(func, bpf_obj_new_impl) 10941 BTF_ID(func, bpf_obj_drop_impl) 10942 BTF_ID(func, bpf_refcount_acquire_impl) 10943 BTF_ID(func, bpf_list_push_front_impl) 10944 BTF_ID(func, bpf_list_push_back_impl) 10945 BTF_ID(func, bpf_list_pop_front) 10946 BTF_ID(func, bpf_list_pop_back) 10947 BTF_ID(func, bpf_cast_to_kern_ctx) 10948 BTF_ID(func, bpf_rdonly_cast) 10949 BTF_ID(func, bpf_rcu_read_lock) 10950 BTF_ID(func, bpf_rcu_read_unlock) 10951 BTF_ID(func, bpf_rbtree_remove) 10952 BTF_ID(func, bpf_rbtree_add_impl) 10953 BTF_ID(func, bpf_rbtree_first) 10954 BTF_ID(func, bpf_dynptr_from_skb) 10955 BTF_ID(func, bpf_dynptr_from_xdp) 10956 BTF_ID(func, bpf_dynptr_slice) 10957 BTF_ID(func, bpf_dynptr_slice_rdwr) 10958 BTF_ID(func, bpf_dynptr_clone) 10959 BTF_ID(func, bpf_percpu_obj_new_impl) 10960 BTF_ID(func, bpf_percpu_obj_drop_impl) 10961 BTF_ID(func, bpf_throw) 10962 #ifdef CONFIG_CGROUPS 10963 BTF_ID(func, bpf_iter_css_task_new) 10964 #else 10965 BTF_ID_UNUSED 10966 #endif 10967 10968 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 10969 { 10970 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 10971 meta->arg_owning_ref) { 10972 return false; 10973 } 10974 10975 return meta->kfunc_flags & KF_RET_NULL; 10976 } 10977 10978 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 10979 { 10980 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 10981 } 10982 10983 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 10984 { 10985 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 10986 } 10987 10988 static enum kfunc_ptr_arg_type 10989 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 10990 struct bpf_kfunc_call_arg_meta *meta, 10991 const struct btf_type *t, const struct btf_type *ref_t, 10992 const char *ref_tname, const struct btf_param *args, 10993 int argno, int nargs) 10994 { 10995 u32 regno = argno + 1; 10996 struct bpf_reg_state *regs = cur_regs(env); 10997 struct bpf_reg_state *reg = ®s[regno]; 10998 bool arg_mem_size = false; 10999 11000 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 11001 return KF_ARG_PTR_TO_CTX; 11002 11003 /* In this function, we verify the kfunc's BTF as per the argument type, 11004 * leaving the rest of the verification with respect to the register 11005 * type to our caller. When a set of conditions hold in the BTF type of 11006 * arguments, we resolve it to a known kfunc_ptr_arg_type. 11007 */ 11008 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 11009 return KF_ARG_PTR_TO_CTX; 11010 11011 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 11012 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 11013 11014 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 11015 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 11016 11017 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 11018 return KF_ARG_PTR_TO_DYNPTR; 11019 11020 if (is_kfunc_arg_iter(meta, argno)) 11021 return KF_ARG_PTR_TO_ITER; 11022 11023 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 11024 return KF_ARG_PTR_TO_LIST_HEAD; 11025 11026 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 11027 return KF_ARG_PTR_TO_LIST_NODE; 11028 11029 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 11030 return KF_ARG_PTR_TO_RB_ROOT; 11031 11032 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 11033 return KF_ARG_PTR_TO_RB_NODE; 11034 11035 if (is_kfunc_arg_const_str(meta->btf, &args[argno])) 11036 return KF_ARG_PTR_TO_CONST_STR; 11037 11038 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 11039 if (!btf_type_is_struct(ref_t)) { 11040 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 11041 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 11042 return -EINVAL; 11043 } 11044 return KF_ARG_PTR_TO_BTF_ID; 11045 } 11046 11047 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 11048 return KF_ARG_PTR_TO_CALLBACK; 11049 11050 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg)) 11051 return KF_ARG_PTR_TO_NULL; 11052 11053 if (argno + 1 < nargs && 11054 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 11055 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 11056 arg_mem_size = true; 11057 11058 /* This is the catch all argument type of register types supported by 11059 * check_helper_mem_access. However, we only allow when argument type is 11060 * pointer to scalar, or struct composed (recursively) of scalars. When 11061 * arg_mem_size is true, the pointer can be void *. 11062 */ 11063 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 11064 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 11065 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 11066 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 11067 return -EINVAL; 11068 } 11069 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 11070 } 11071 11072 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 11073 struct bpf_reg_state *reg, 11074 const struct btf_type *ref_t, 11075 const char *ref_tname, u32 ref_id, 11076 struct bpf_kfunc_call_arg_meta *meta, 11077 int argno) 11078 { 11079 const struct btf_type *reg_ref_t; 11080 bool strict_type_match = false; 11081 const struct btf *reg_btf; 11082 const char *reg_ref_tname; 11083 u32 reg_ref_id; 11084 11085 if (base_type(reg->type) == PTR_TO_BTF_ID) { 11086 reg_btf = reg->btf; 11087 reg_ref_id = reg->btf_id; 11088 } else { 11089 reg_btf = btf_vmlinux; 11090 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 11091 } 11092 11093 /* Enforce strict type matching for calls to kfuncs that are acquiring 11094 * or releasing a reference, or are no-cast aliases. We do _not_ 11095 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 11096 * as we want to enable BPF programs to pass types that are bitwise 11097 * equivalent without forcing them to explicitly cast with something 11098 * like bpf_cast_to_kern_ctx(). 11099 * 11100 * For example, say we had a type like the following: 11101 * 11102 * struct bpf_cpumask { 11103 * cpumask_t cpumask; 11104 * refcount_t usage; 11105 * }; 11106 * 11107 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 11108 * to a struct cpumask, so it would be safe to pass a struct 11109 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 11110 * 11111 * The philosophy here is similar to how we allow scalars of different 11112 * types to be passed to kfuncs as long as the size is the same. The 11113 * only difference here is that we're simply allowing 11114 * btf_struct_ids_match() to walk the struct at the 0th offset, and 11115 * resolve types. 11116 */ 11117 if (is_kfunc_acquire(meta) || 11118 (is_kfunc_release(meta) && reg->ref_obj_id) || 11119 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 11120 strict_type_match = true; 11121 11122 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 11123 11124 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 11125 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 11126 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 11127 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 11128 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 11129 btf_type_str(reg_ref_t), reg_ref_tname); 11130 return -EINVAL; 11131 } 11132 return 0; 11133 } 11134 11135 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11136 { 11137 struct bpf_verifier_state *state = env->cur_state; 11138 struct btf_record *rec = reg_btf_record(reg); 11139 11140 if (!state->active_lock.ptr) { 11141 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 11142 return -EFAULT; 11143 } 11144 11145 if (type_flag(reg->type) & NON_OWN_REF) { 11146 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 11147 return -EFAULT; 11148 } 11149 11150 reg->type |= NON_OWN_REF; 11151 if (rec->refcount_off >= 0) 11152 reg->type |= MEM_RCU; 11153 11154 return 0; 11155 } 11156 11157 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 11158 { 11159 struct bpf_func_state *state, *unused; 11160 struct bpf_reg_state *reg; 11161 int i; 11162 11163 state = cur_func(env); 11164 11165 if (!ref_obj_id) { 11166 verbose(env, "verifier internal error: ref_obj_id is zero for " 11167 "owning -> non-owning conversion\n"); 11168 return -EFAULT; 11169 } 11170 11171 for (i = 0; i < state->acquired_refs; i++) { 11172 if (state->refs[i].id != ref_obj_id) 11173 continue; 11174 11175 /* Clear ref_obj_id here so release_reference doesn't clobber 11176 * the whole reg 11177 */ 11178 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11179 if (reg->ref_obj_id == ref_obj_id) { 11180 reg->ref_obj_id = 0; 11181 ref_set_non_owning(env, reg); 11182 } 11183 })); 11184 return 0; 11185 } 11186 11187 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 11188 return -EFAULT; 11189 } 11190 11191 /* Implementation details: 11192 * 11193 * Each register points to some region of memory, which we define as an 11194 * allocation. Each allocation may embed a bpf_spin_lock which protects any 11195 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 11196 * allocation. The lock and the data it protects are colocated in the same 11197 * memory region. 11198 * 11199 * Hence, everytime a register holds a pointer value pointing to such 11200 * allocation, the verifier preserves a unique reg->id for it. 11201 * 11202 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 11203 * bpf_spin_lock is called. 11204 * 11205 * To enable this, lock state in the verifier captures two values: 11206 * active_lock.ptr = Register's type specific pointer 11207 * active_lock.id = A unique ID for each register pointer value 11208 * 11209 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11210 * supported register types. 11211 * 11212 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11213 * allocated objects is the reg->btf pointer. 11214 * 11215 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11216 * can establish the provenance of the map value statically for each distinct 11217 * lookup into such maps. They always contain a single map value hence unique 11218 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11219 * 11220 * So, in case of global variables, they use array maps with max_entries = 1, 11221 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11222 * into the same map value as max_entries is 1, as described above). 11223 * 11224 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11225 * outer map pointer (in verifier context), but each lookup into an inner map 11226 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11227 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11228 * will get different reg->id assigned to each lookup, hence different 11229 * active_lock.id. 11230 * 11231 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11232 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11233 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11234 */ 11235 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11236 { 11237 void *ptr; 11238 u32 id; 11239 11240 switch ((int)reg->type) { 11241 case PTR_TO_MAP_VALUE: 11242 ptr = reg->map_ptr; 11243 break; 11244 case PTR_TO_BTF_ID | MEM_ALLOC: 11245 ptr = reg->btf; 11246 break; 11247 default: 11248 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 11249 return -EFAULT; 11250 } 11251 id = reg->id; 11252 11253 if (!env->cur_state->active_lock.ptr) 11254 return -EINVAL; 11255 if (env->cur_state->active_lock.ptr != ptr || 11256 env->cur_state->active_lock.id != id) { 11257 verbose(env, "held lock and object are not in the same allocation\n"); 11258 return -EINVAL; 11259 } 11260 return 0; 11261 } 11262 11263 static bool is_bpf_list_api_kfunc(u32 btf_id) 11264 { 11265 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11266 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11267 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11268 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 11269 } 11270 11271 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11272 { 11273 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 11274 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11275 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 11276 } 11277 11278 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11279 { 11280 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 11281 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11282 } 11283 11284 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11285 { 11286 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11287 } 11288 11289 static bool is_bpf_throw_kfunc(struct bpf_insn *insn) 11290 { 11291 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 11292 insn->imm == special_kfunc_list[KF_bpf_throw]; 11293 } 11294 11295 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11296 { 11297 return is_bpf_rbtree_api_kfunc(btf_id); 11298 } 11299 11300 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11301 enum btf_field_type head_field_type, 11302 u32 kfunc_btf_id) 11303 { 11304 bool ret; 11305 11306 switch (head_field_type) { 11307 case BPF_LIST_HEAD: 11308 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11309 break; 11310 case BPF_RB_ROOT: 11311 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11312 break; 11313 default: 11314 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11315 btf_field_type_name(head_field_type)); 11316 return false; 11317 } 11318 11319 if (!ret) 11320 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11321 btf_field_type_name(head_field_type)); 11322 return ret; 11323 } 11324 11325 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11326 enum btf_field_type node_field_type, 11327 u32 kfunc_btf_id) 11328 { 11329 bool ret; 11330 11331 switch (node_field_type) { 11332 case BPF_LIST_NODE: 11333 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11334 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 11335 break; 11336 case BPF_RB_NODE: 11337 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11338 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 11339 break; 11340 default: 11341 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11342 btf_field_type_name(node_field_type)); 11343 return false; 11344 } 11345 11346 if (!ret) 11347 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11348 btf_field_type_name(node_field_type)); 11349 return ret; 11350 } 11351 11352 static int 11353 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11354 struct bpf_reg_state *reg, u32 regno, 11355 struct bpf_kfunc_call_arg_meta *meta, 11356 enum btf_field_type head_field_type, 11357 struct btf_field **head_field) 11358 { 11359 const char *head_type_name; 11360 struct btf_field *field; 11361 struct btf_record *rec; 11362 u32 head_off; 11363 11364 if (meta->btf != btf_vmlinux) { 11365 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11366 return -EFAULT; 11367 } 11368 11369 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11370 return -EFAULT; 11371 11372 head_type_name = btf_field_type_name(head_field_type); 11373 if (!tnum_is_const(reg->var_off)) { 11374 verbose(env, 11375 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11376 regno, head_type_name); 11377 return -EINVAL; 11378 } 11379 11380 rec = reg_btf_record(reg); 11381 head_off = reg->off + reg->var_off.value; 11382 field = btf_record_find(rec, head_off, head_field_type); 11383 if (!field) { 11384 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11385 return -EINVAL; 11386 } 11387 11388 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11389 if (check_reg_allocation_locked(env, reg)) { 11390 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11391 rec->spin_lock_off, head_type_name); 11392 return -EINVAL; 11393 } 11394 11395 if (*head_field) { 11396 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 11397 return -EFAULT; 11398 } 11399 *head_field = field; 11400 return 0; 11401 } 11402 11403 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11404 struct bpf_reg_state *reg, u32 regno, 11405 struct bpf_kfunc_call_arg_meta *meta) 11406 { 11407 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 11408 &meta->arg_list_head.field); 11409 } 11410 11411 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11412 struct bpf_reg_state *reg, u32 regno, 11413 struct bpf_kfunc_call_arg_meta *meta) 11414 { 11415 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 11416 &meta->arg_rbtree_root.field); 11417 } 11418 11419 static int 11420 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11421 struct bpf_reg_state *reg, u32 regno, 11422 struct bpf_kfunc_call_arg_meta *meta, 11423 enum btf_field_type head_field_type, 11424 enum btf_field_type node_field_type, 11425 struct btf_field **node_field) 11426 { 11427 const char *node_type_name; 11428 const struct btf_type *et, *t; 11429 struct btf_field *field; 11430 u32 node_off; 11431 11432 if (meta->btf != btf_vmlinux) { 11433 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11434 return -EFAULT; 11435 } 11436 11437 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11438 return -EFAULT; 11439 11440 node_type_name = btf_field_type_name(node_field_type); 11441 if (!tnum_is_const(reg->var_off)) { 11442 verbose(env, 11443 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11444 regno, node_type_name); 11445 return -EINVAL; 11446 } 11447 11448 node_off = reg->off + reg->var_off.value; 11449 field = reg_find_field_offset(reg, node_off, node_field_type); 11450 if (!field || field->offset != node_off) { 11451 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11452 return -EINVAL; 11453 } 11454 11455 field = *node_field; 11456 11457 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11458 t = btf_type_by_id(reg->btf, reg->btf_id); 11459 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11460 field->graph_root.value_btf_id, true)) { 11461 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11462 "in struct %s, but arg is at offset=%d in struct %s\n", 11463 btf_field_type_name(head_field_type), 11464 btf_field_type_name(node_field_type), 11465 field->graph_root.node_offset, 11466 btf_name_by_offset(field->graph_root.btf, et->name_off), 11467 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11468 return -EINVAL; 11469 } 11470 meta->arg_btf = reg->btf; 11471 meta->arg_btf_id = reg->btf_id; 11472 11473 if (node_off != field->graph_root.node_offset) { 11474 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11475 node_off, btf_field_type_name(node_field_type), 11476 field->graph_root.node_offset, 11477 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11478 return -EINVAL; 11479 } 11480 11481 return 0; 11482 } 11483 11484 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11485 struct bpf_reg_state *reg, u32 regno, 11486 struct bpf_kfunc_call_arg_meta *meta) 11487 { 11488 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11489 BPF_LIST_HEAD, BPF_LIST_NODE, 11490 &meta->arg_list_head.field); 11491 } 11492 11493 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11494 struct bpf_reg_state *reg, u32 regno, 11495 struct bpf_kfunc_call_arg_meta *meta) 11496 { 11497 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11498 BPF_RB_ROOT, BPF_RB_NODE, 11499 &meta->arg_rbtree_root.field); 11500 } 11501 11502 /* 11503 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 11504 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 11505 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 11506 * them can only be attached to some specific hook points. 11507 */ 11508 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 11509 { 11510 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11511 11512 switch (prog_type) { 11513 case BPF_PROG_TYPE_LSM: 11514 return true; 11515 case BPF_PROG_TYPE_TRACING: 11516 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 11517 return true; 11518 fallthrough; 11519 default: 11520 return env->prog->aux->sleepable; 11521 } 11522 } 11523 11524 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11525 int insn_idx) 11526 { 11527 const char *func_name = meta->func_name, *ref_tname; 11528 const struct btf *btf = meta->btf; 11529 const struct btf_param *args; 11530 struct btf_record *rec; 11531 u32 i, nargs; 11532 int ret; 11533 11534 args = (const struct btf_param *)(meta->func_proto + 1); 11535 nargs = btf_type_vlen(meta->func_proto); 11536 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 11537 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11538 MAX_BPF_FUNC_REG_ARGS); 11539 return -EINVAL; 11540 } 11541 11542 /* Check that BTF function arguments match actual types that the 11543 * verifier sees. 11544 */ 11545 for (i = 0; i < nargs; i++) { 11546 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 11547 const struct btf_type *t, *ref_t, *resolve_ret; 11548 enum bpf_arg_type arg_type = ARG_DONTCARE; 11549 u32 regno = i + 1, ref_id, type_size; 11550 bool is_ret_buf_sz = false; 11551 int kf_arg_type; 11552 11553 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11554 11555 if (is_kfunc_arg_ignore(btf, &args[i])) 11556 continue; 11557 11558 if (btf_type_is_scalar(t)) { 11559 if (reg->type != SCALAR_VALUE) { 11560 verbose(env, "R%d is not a scalar\n", regno); 11561 return -EINVAL; 11562 } 11563 11564 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11565 if (meta->arg_constant.found) { 11566 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11567 return -EFAULT; 11568 } 11569 if (!tnum_is_const(reg->var_off)) { 11570 verbose(env, "R%d must be a known constant\n", regno); 11571 return -EINVAL; 11572 } 11573 ret = mark_chain_precision(env, regno); 11574 if (ret < 0) 11575 return ret; 11576 meta->arg_constant.found = true; 11577 meta->arg_constant.value = reg->var_off.value; 11578 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 11579 meta->r0_rdonly = true; 11580 is_ret_buf_sz = true; 11581 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 11582 is_ret_buf_sz = true; 11583 } 11584 11585 if (is_ret_buf_sz) { 11586 if (meta->r0_size) { 11587 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 11588 return -EINVAL; 11589 } 11590 11591 if (!tnum_is_const(reg->var_off)) { 11592 verbose(env, "R%d is not a const\n", regno); 11593 return -EINVAL; 11594 } 11595 11596 meta->r0_size = reg->var_off.value; 11597 ret = mark_chain_precision(env, regno); 11598 if (ret) 11599 return ret; 11600 } 11601 continue; 11602 } 11603 11604 if (!btf_type_is_ptr(t)) { 11605 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 11606 return -EINVAL; 11607 } 11608 11609 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 11610 (register_is_null(reg) || type_may_be_null(reg->type)) && 11611 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 11612 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 11613 return -EACCES; 11614 } 11615 11616 if (reg->ref_obj_id) { 11617 if (is_kfunc_release(meta) && meta->ref_obj_id) { 11618 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 11619 regno, reg->ref_obj_id, 11620 meta->ref_obj_id); 11621 return -EFAULT; 11622 } 11623 meta->ref_obj_id = reg->ref_obj_id; 11624 if (is_kfunc_release(meta)) 11625 meta->release_regno = regno; 11626 } 11627 11628 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 11629 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 11630 11631 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 11632 if (kf_arg_type < 0) 11633 return kf_arg_type; 11634 11635 switch (kf_arg_type) { 11636 case KF_ARG_PTR_TO_NULL: 11637 continue; 11638 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11639 case KF_ARG_PTR_TO_BTF_ID: 11640 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 11641 break; 11642 11643 if (!is_trusted_reg(reg)) { 11644 if (!is_kfunc_rcu(meta)) { 11645 verbose(env, "R%d must be referenced or trusted\n", regno); 11646 return -EINVAL; 11647 } 11648 if (!is_rcu_reg(reg)) { 11649 verbose(env, "R%d must be a rcu pointer\n", regno); 11650 return -EINVAL; 11651 } 11652 } 11653 11654 fallthrough; 11655 case KF_ARG_PTR_TO_CTX: 11656 /* Trusted arguments have the same offset checks as release arguments */ 11657 arg_type |= OBJ_RELEASE; 11658 break; 11659 case KF_ARG_PTR_TO_DYNPTR: 11660 case KF_ARG_PTR_TO_ITER: 11661 case KF_ARG_PTR_TO_LIST_HEAD: 11662 case KF_ARG_PTR_TO_LIST_NODE: 11663 case KF_ARG_PTR_TO_RB_ROOT: 11664 case KF_ARG_PTR_TO_RB_NODE: 11665 case KF_ARG_PTR_TO_MEM: 11666 case KF_ARG_PTR_TO_MEM_SIZE: 11667 case KF_ARG_PTR_TO_CALLBACK: 11668 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11669 case KF_ARG_PTR_TO_CONST_STR: 11670 /* Trusted by default */ 11671 break; 11672 default: 11673 WARN_ON_ONCE(1); 11674 return -EFAULT; 11675 } 11676 11677 if (is_kfunc_release(meta) && reg->ref_obj_id) 11678 arg_type |= OBJ_RELEASE; 11679 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 11680 if (ret < 0) 11681 return ret; 11682 11683 switch (kf_arg_type) { 11684 case KF_ARG_PTR_TO_CTX: 11685 if (reg->type != PTR_TO_CTX) { 11686 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 11687 return -EINVAL; 11688 } 11689 11690 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11691 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 11692 if (ret < 0) 11693 return -EINVAL; 11694 meta->ret_btf_id = ret; 11695 } 11696 break; 11697 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11698 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 11699 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) { 11700 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i); 11701 return -EINVAL; 11702 } 11703 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 11704 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 11705 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i); 11706 return -EINVAL; 11707 } 11708 } else { 11709 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11710 return -EINVAL; 11711 } 11712 if (!reg->ref_obj_id) { 11713 verbose(env, "allocated object must be referenced\n"); 11714 return -EINVAL; 11715 } 11716 if (meta->btf == btf_vmlinux) { 11717 meta->arg_btf = reg->btf; 11718 meta->arg_btf_id = reg->btf_id; 11719 } 11720 break; 11721 case KF_ARG_PTR_TO_DYNPTR: 11722 { 11723 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 11724 int clone_ref_obj_id = 0; 11725 11726 if (reg->type != PTR_TO_STACK && 11727 reg->type != CONST_PTR_TO_DYNPTR) { 11728 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 11729 return -EINVAL; 11730 } 11731 11732 if (reg->type == CONST_PTR_TO_DYNPTR) 11733 dynptr_arg_type |= MEM_RDONLY; 11734 11735 if (is_kfunc_arg_uninit(btf, &args[i])) 11736 dynptr_arg_type |= MEM_UNINIT; 11737 11738 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 11739 dynptr_arg_type |= DYNPTR_TYPE_SKB; 11740 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 11741 dynptr_arg_type |= DYNPTR_TYPE_XDP; 11742 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 11743 (dynptr_arg_type & MEM_UNINIT)) { 11744 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 11745 11746 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 11747 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 11748 return -EFAULT; 11749 } 11750 11751 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 11752 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 11753 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 11754 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 11755 return -EFAULT; 11756 } 11757 } 11758 11759 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 11760 if (ret < 0) 11761 return ret; 11762 11763 if (!(dynptr_arg_type & MEM_UNINIT)) { 11764 int id = dynptr_id(env, reg); 11765 11766 if (id < 0) { 11767 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 11768 return id; 11769 } 11770 meta->initialized_dynptr.id = id; 11771 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 11772 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 11773 } 11774 11775 break; 11776 } 11777 case KF_ARG_PTR_TO_ITER: 11778 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 11779 if (!check_css_task_iter_allowlist(env)) { 11780 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 11781 return -EINVAL; 11782 } 11783 } 11784 ret = process_iter_arg(env, regno, insn_idx, meta); 11785 if (ret < 0) 11786 return ret; 11787 break; 11788 case KF_ARG_PTR_TO_LIST_HEAD: 11789 if (reg->type != PTR_TO_MAP_VALUE && 11790 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11791 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11792 return -EINVAL; 11793 } 11794 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11795 verbose(env, "allocated object must be referenced\n"); 11796 return -EINVAL; 11797 } 11798 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 11799 if (ret < 0) 11800 return ret; 11801 break; 11802 case KF_ARG_PTR_TO_RB_ROOT: 11803 if (reg->type != PTR_TO_MAP_VALUE && 11804 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11805 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11806 return -EINVAL; 11807 } 11808 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11809 verbose(env, "allocated object must be referenced\n"); 11810 return -EINVAL; 11811 } 11812 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 11813 if (ret < 0) 11814 return ret; 11815 break; 11816 case KF_ARG_PTR_TO_LIST_NODE: 11817 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11818 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11819 return -EINVAL; 11820 } 11821 if (!reg->ref_obj_id) { 11822 verbose(env, "allocated object must be referenced\n"); 11823 return -EINVAL; 11824 } 11825 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 11826 if (ret < 0) 11827 return ret; 11828 break; 11829 case KF_ARG_PTR_TO_RB_NODE: 11830 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 11831 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 11832 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 11833 return -EINVAL; 11834 } 11835 if (in_rbtree_lock_required_cb(env)) { 11836 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 11837 return -EINVAL; 11838 } 11839 } else { 11840 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11841 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11842 return -EINVAL; 11843 } 11844 if (!reg->ref_obj_id) { 11845 verbose(env, "allocated object must be referenced\n"); 11846 return -EINVAL; 11847 } 11848 } 11849 11850 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 11851 if (ret < 0) 11852 return ret; 11853 break; 11854 case KF_ARG_PTR_TO_BTF_ID: 11855 /* Only base_type is checked, further checks are done here */ 11856 if ((base_type(reg->type) != PTR_TO_BTF_ID || 11857 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 11858 !reg2btf_ids[base_type(reg->type)]) { 11859 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 11860 verbose(env, "expected %s or socket\n", 11861 reg_type_str(env, base_type(reg->type) | 11862 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 11863 return -EINVAL; 11864 } 11865 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 11866 if (ret < 0) 11867 return ret; 11868 break; 11869 case KF_ARG_PTR_TO_MEM: 11870 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 11871 if (IS_ERR(resolve_ret)) { 11872 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 11873 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 11874 return -EINVAL; 11875 } 11876 ret = check_mem_reg(env, reg, regno, type_size); 11877 if (ret < 0) 11878 return ret; 11879 break; 11880 case KF_ARG_PTR_TO_MEM_SIZE: 11881 { 11882 struct bpf_reg_state *buff_reg = ®s[regno]; 11883 const struct btf_param *buff_arg = &args[i]; 11884 struct bpf_reg_state *size_reg = ®s[regno + 1]; 11885 const struct btf_param *size_arg = &args[i + 1]; 11886 11887 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 11888 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 11889 if (ret < 0) { 11890 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 11891 return ret; 11892 } 11893 } 11894 11895 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 11896 if (meta->arg_constant.found) { 11897 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11898 return -EFAULT; 11899 } 11900 if (!tnum_is_const(size_reg->var_off)) { 11901 verbose(env, "R%d must be a known constant\n", regno + 1); 11902 return -EINVAL; 11903 } 11904 meta->arg_constant.found = true; 11905 meta->arg_constant.value = size_reg->var_off.value; 11906 } 11907 11908 /* Skip next '__sz' or '__szk' argument */ 11909 i++; 11910 break; 11911 } 11912 case KF_ARG_PTR_TO_CALLBACK: 11913 if (reg->type != PTR_TO_FUNC) { 11914 verbose(env, "arg%d expected pointer to func\n", i); 11915 return -EINVAL; 11916 } 11917 meta->subprogno = reg->subprogno; 11918 break; 11919 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11920 if (!type_is_ptr_alloc_obj(reg->type)) { 11921 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 11922 return -EINVAL; 11923 } 11924 if (!type_is_non_owning_ref(reg->type)) 11925 meta->arg_owning_ref = true; 11926 11927 rec = reg_btf_record(reg); 11928 if (!rec) { 11929 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 11930 return -EFAULT; 11931 } 11932 11933 if (rec->refcount_off < 0) { 11934 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 11935 return -EINVAL; 11936 } 11937 11938 meta->arg_btf = reg->btf; 11939 meta->arg_btf_id = reg->btf_id; 11940 break; 11941 case KF_ARG_PTR_TO_CONST_STR: 11942 if (reg->type != PTR_TO_MAP_VALUE) { 11943 verbose(env, "arg#%d doesn't point to a const string\n", i); 11944 return -EINVAL; 11945 } 11946 ret = check_reg_const_str(env, reg, regno); 11947 if (ret) 11948 return ret; 11949 break; 11950 } 11951 } 11952 11953 if (is_kfunc_release(meta) && !meta->release_regno) { 11954 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 11955 func_name); 11956 return -EINVAL; 11957 } 11958 11959 return 0; 11960 } 11961 11962 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 11963 struct bpf_insn *insn, 11964 struct bpf_kfunc_call_arg_meta *meta, 11965 const char **kfunc_name) 11966 { 11967 const struct btf_type *func, *func_proto; 11968 u32 func_id, *kfunc_flags; 11969 const char *func_name; 11970 struct btf *desc_btf; 11971 11972 if (kfunc_name) 11973 *kfunc_name = NULL; 11974 11975 if (!insn->imm) 11976 return -EINVAL; 11977 11978 desc_btf = find_kfunc_desc_btf(env, insn->off); 11979 if (IS_ERR(desc_btf)) 11980 return PTR_ERR(desc_btf); 11981 11982 func_id = insn->imm; 11983 func = btf_type_by_id(desc_btf, func_id); 11984 func_name = btf_name_by_offset(desc_btf, func->name_off); 11985 if (kfunc_name) 11986 *kfunc_name = func_name; 11987 func_proto = btf_type_by_id(desc_btf, func->type); 11988 11989 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 11990 if (!kfunc_flags) { 11991 return -EACCES; 11992 } 11993 11994 memset(meta, 0, sizeof(*meta)); 11995 meta->btf = desc_btf; 11996 meta->func_id = func_id; 11997 meta->kfunc_flags = *kfunc_flags; 11998 meta->func_proto = func_proto; 11999 meta->func_name = func_name; 12000 12001 return 0; 12002 } 12003 12004 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 12005 12006 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 12007 int *insn_idx_p) 12008 { 12009 const struct btf_type *t, *ptr_type; 12010 u32 i, nargs, ptr_type_id, release_ref_obj_id; 12011 struct bpf_reg_state *regs = cur_regs(env); 12012 const char *func_name, *ptr_type_name; 12013 bool sleepable, rcu_lock, rcu_unlock; 12014 struct bpf_kfunc_call_arg_meta meta; 12015 struct bpf_insn_aux_data *insn_aux; 12016 int err, insn_idx = *insn_idx_p; 12017 const struct btf_param *args; 12018 const struct btf_type *ret_t; 12019 struct btf *desc_btf; 12020 12021 /* skip for now, but return error when we find this in fixup_kfunc_call */ 12022 if (!insn->imm) 12023 return 0; 12024 12025 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 12026 if (err == -EACCES && func_name) 12027 verbose(env, "calling kernel function %s is not allowed\n", func_name); 12028 if (err) 12029 return err; 12030 desc_btf = meta.btf; 12031 insn_aux = &env->insn_aux_data[insn_idx]; 12032 12033 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 12034 12035 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 12036 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 12037 return -EACCES; 12038 } 12039 12040 sleepable = is_kfunc_sleepable(&meta); 12041 if (sleepable && !env->prog->aux->sleepable) { 12042 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 12043 return -EACCES; 12044 } 12045 12046 /* Check the arguments */ 12047 err = check_kfunc_args(env, &meta, insn_idx); 12048 if (err < 0) 12049 return err; 12050 12051 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12052 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12053 set_rbtree_add_callback_state); 12054 if (err) { 12055 verbose(env, "kfunc %s#%d failed callback verification\n", 12056 func_name, meta.func_id); 12057 return err; 12058 } 12059 } 12060 12061 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 12062 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 12063 12064 if (env->cur_state->active_rcu_lock) { 12065 struct bpf_func_state *state; 12066 struct bpf_reg_state *reg; 12067 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 12068 12069 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 12070 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 12071 return -EACCES; 12072 } 12073 12074 if (rcu_lock) { 12075 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 12076 return -EINVAL; 12077 } else if (rcu_unlock) { 12078 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({ 12079 if (reg->type & MEM_RCU) { 12080 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 12081 reg->type |= PTR_UNTRUSTED; 12082 } 12083 })); 12084 env->cur_state->active_rcu_lock = false; 12085 } else if (sleepable) { 12086 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 12087 return -EACCES; 12088 } 12089 } else if (rcu_lock) { 12090 env->cur_state->active_rcu_lock = true; 12091 } else if (rcu_unlock) { 12092 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 12093 return -EINVAL; 12094 } 12095 12096 /* In case of release function, we get register number of refcounted 12097 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 12098 */ 12099 if (meta.release_regno) { 12100 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 12101 if (err) { 12102 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12103 func_name, meta.func_id); 12104 return err; 12105 } 12106 } 12107 12108 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 12109 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 12110 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12111 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 12112 insn_aux->insert_off = regs[BPF_REG_2].off; 12113 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 12114 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 12115 if (err) { 12116 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 12117 func_name, meta.func_id); 12118 return err; 12119 } 12120 12121 err = release_reference(env, release_ref_obj_id); 12122 if (err) { 12123 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12124 func_name, meta.func_id); 12125 return err; 12126 } 12127 } 12128 12129 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 12130 if (!bpf_jit_supports_exceptions()) { 12131 verbose(env, "JIT does not support calling kfunc %s#%d\n", 12132 func_name, meta.func_id); 12133 return -ENOTSUPP; 12134 } 12135 env->seen_exception = true; 12136 12137 /* In the case of the default callback, the cookie value passed 12138 * to bpf_throw becomes the return value of the program. 12139 */ 12140 if (!env->exception_callback_subprog) { 12141 err = check_return_code(env, BPF_REG_1, "R1"); 12142 if (err < 0) 12143 return err; 12144 } 12145 } 12146 12147 for (i = 0; i < CALLER_SAVED_REGS; i++) 12148 mark_reg_not_init(env, regs, caller_saved[i]); 12149 12150 /* Check return type */ 12151 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 12152 12153 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 12154 /* Only exception is bpf_obj_new_impl */ 12155 if (meta.btf != btf_vmlinux || 12156 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 12157 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] && 12158 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 12159 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 12160 return -EINVAL; 12161 } 12162 } 12163 12164 if (btf_type_is_scalar(t)) { 12165 mark_reg_unknown(env, regs, BPF_REG_0); 12166 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 12167 } else if (btf_type_is_ptr(t)) { 12168 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 12169 12170 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12171 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 12172 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12173 struct btf_struct_meta *struct_meta; 12174 struct btf *ret_btf; 12175 u32 ret_btf_id; 12176 12177 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set) 12178 return -ENOMEM; 12179 12180 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 12181 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 12182 return -EINVAL; 12183 } 12184 12185 ret_btf = env->prog->aux->btf; 12186 ret_btf_id = meta.arg_constant.value; 12187 12188 /* This may be NULL due to user not supplying a BTF */ 12189 if (!ret_btf) { 12190 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 12191 return -EINVAL; 12192 } 12193 12194 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 12195 if (!ret_t || !__btf_type_is_struct(ret_t)) { 12196 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 12197 return -EINVAL; 12198 } 12199 12200 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12201 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 12202 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 12203 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 12204 return -EINVAL; 12205 } 12206 12207 if (!bpf_global_percpu_ma_set) { 12208 mutex_lock(&bpf_percpu_ma_lock); 12209 if (!bpf_global_percpu_ma_set) { 12210 /* Charge memory allocated with bpf_global_percpu_ma to 12211 * root memcg. The obj_cgroup for root memcg is NULL. 12212 */ 12213 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 12214 if (!err) 12215 bpf_global_percpu_ma_set = true; 12216 } 12217 mutex_unlock(&bpf_percpu_ma_lock); 12218 if (err) 12219 return err; 12220 } 12221 12222 mutex_lock(&bpf_percpu_ma_lock); 12223 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 12224 mutex_unlock(&bpf_percpu_ma_lock); 12225 if (err) 12226 return err; 12227 } 12228 12229 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 12230 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12231 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 12232 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 12233 return -EINVAL; 12234 } 12235 12236 if (struct_meta) { 12237 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 12238 return -EINVAL; 12239 } 12240 } 12241 12242 mark_reg_known_zero(env, regs, BPF_REG_0); 12243 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12244 regs[BPF_REG_0].btf = ret_btf; 12245 regs[BPF_REG_0].btf_id = ret_btf_id; 12246 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) 12247 regs[BPF_REG_0].type |= MEM_PERCPU; 12248 12249 insn_aux->obj_new_size = ret_t->size; 12250 insn_aux->kptr_struct_meta = struct_meta; 12251 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 12252 mark_reg_known_zero(env, regs, BPF_REG_0); 12253 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12254 regs[BPF_REG_0].btf = meta.arg_btf; 12255 regs[BPF_REG_0].btf_id = meta.arg_btf_id; 12256 12257 insn_aux->kptr_struct_meta = 12258 btf_find_struct_meta(meta.arg_btf, 12259 meta.arg_btf_id); 12260 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 12261 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 12262 struct btf_field *field = meta.arg_list_head.field; 12263 12264 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12265 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12266 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12267 struct btf_field *field = meta.arg_rbtree_root.field; 12268 12269 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12270 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12271 mark_reg_known_zero(env, regs, BPF_REG_0); 12272 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 12273 regs[BPF_REG_0].btf = desc_btf; 12274 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 12275 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 12276 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 12277 if (!ret_t || !btf_type_is_struct(ret_t)) { 12278 verbose(env, 12279 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 12280 return -EINVAL; 12281 } 12282 12283 mark_reg_known_zero(env, regs, BPF_REG_0); 12284 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 12285 regs[BPF_REG_0].btf = desc_btf; 12286 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 12287 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 12288 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 12289 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 12290 12291 mark_reg_known_zero(env, regs, BPF_REG_0); 12292 12293 if (!meta.arg_constant.found) { 12294 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 12295 return -EFAULT; 12296 } 12297 12298 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 12299 12300 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 12301 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 12302 12303 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 12304 regs[BPF_REG_0].type |= MEM_RDONLY; 12305 } else { 12306 /* this will set env->seen_direct_write to true */ 12307 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 12308 verbose(env, "the prog does not allow writes to packet data\n"); 12309 return -EINVAL; 12310 } 12311 } 12312 12313 if (!meta.initialized_dynptr.id) { 12314 verbose(env, "verifier internal error: no dynptr id\n"); 12315 return -EFAULT; 12316 } 12317 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 12318 12319 /* we don't need to set BPF_REG_0's ref obj id 12320 * because packet slices are not refcounted (see 12321 * dynptr_type_refcounted) 12322 */ 12323 } else { 12324 verbose(env, "kernel function %s unhandled dynamic return type\n", 12325 meta.func_name); 12326 return -EFAULT; 12327 } 12328 } else if (!__btf_type_is_struct(ptr_type)) { 12329 if (!meta.r0_size) { 12330 __u32 sz; 12331 12332 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 12333 meta.r0_size = sz; 12334 meta.r0_rdonly = true; 12335 } 12336 } 12337 if (!meta.r0_size) { 12338 ptr_type_name = btf_name_by_offset(desc_btf, 12339 ptr_type->name_off); 12340 verbose(env, 12341 "kernel function %s returns pointer type %s %s is not supported\n", 12342 func_name, 12343 btf_type_str(ptr_type), 12344 ptr_type_name); 12345 return -EINVAL; 12346 } 12347 12348 mark_reg_known_zero(env, regs, BPF_REG_0); 12349 regs[BPF_REG_0].type = PTR_TO_MEM; 12350 regs[BPF_REG_0].mem_size = meta.r0_size; 12351 12352 if (meta.r0_rdonly) 12353 regs[BPF_REG_0].type |= MEM_RDONLY; 12354 12355 /* Ensures we don't access the memory after a release_reference() */ 12356 if (meta.ref_obj_id) 12357 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 12358 } else { 12359 mark_reg_known_zero(env, regs, BPF_REG_0); 12360 regs[BPF_REG_0].btf = desc_btf; 12361 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 12362 regs[BPF_REG_0].btf_id = ptr_type_id; 12363 } 12364 12365 if (is_kfunc_ret_null(&meta)) { 12366 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 12367 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 12368 regs[BPF_REG_0].id = ++env->id_gen; 12369 } 12370 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 12371 if (is_kfunc_acquire(&meta)) { 12372 int id = acquire_reference_state(env, insn_idx); 12373 12374 if (id < 0) 12375 return id; 12376 if (is_kfunc_ret_null(&meta)) 12377 regs[BPF_REG_0].id = id; 12378 regs[BPF_REG_0].ref_obj_id = id; 12379 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12380 ref_set_non_owning(env, ®s[BPF_REG_0]); 12381 } 12382 12383 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 12384 regs[BPF_REG_0].id = ++env->id_gen; 12385 } else if (btf_type_is_void(t)) { 12386 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12387 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 12388 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 12389 insn_aux->kptr_struct_meta = 12390 btf_find_struct_meta(meta.arg_btf, 12391 meta.arg_btf_id); 12392 } 12393 } 12394 } 12395 12396 nargs = btf_type_vlen(meta.func_proto); 12397 args = (const struct btf_param *)(meta.func_proto + 1); 12398 for (i = 0; i < nargs; i++) { 12399 u32 regno = i + 1; 12400 12401 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 12402 if (btf_type_is_ptr(t)) 12403 mark_btf_func_reg_size(env, regno, sizeof(void *)); 12404 else 12405 /* scalar. ensured by btf_check_kfunc_arg_match() */ 12406 mark_btf_func_reg_size(env, regno, t->size); 12407 } 12408 12409 if (is_iter_next_kfunc(&meta)) { 12410 err = process_iter_next_call(env, insn_idx, &meta); 12411 if (err) 12412 return err; 12413 } 12414 12415 return 0; 12416 } 12417 12418 static bool signed_add_overflows(s64 a, s64 b) 12419 { 12420 /* Do the add in u64, where overflow is well-defined */ 12421 s64 res = (s64)((u64)a + (u64)b); 12422 12423 if (b < 0) 12424 return res > a; 12425 return res < a; 12426 } 12427 12428 static bool signed_add32_overflows(s32 a, s32 b) 12429 { 12430 /* Do the add in u32, where overflow is well-defined */ 12431 s32 res = (s32)((u32)a + (u32)b); 12432 12433 if (b < 0) 12434 return res > a; 12435 return res < a; 12436 } 12437 12438 static bool signed_sub_overflows(s64 a, s64 b) 12439 { 12440 /* Do the sub in u64, where overflow is well-defined */ 12441 s64 res = (s64)((u64)a - (u64)b); 12442 12443 if (b < 0) 12444 return res < a; 12445 return res > a; 12446 } 12447 12448 static bool signed_sub32_overflows(s32 a, s32 b) 12449 { 12450 /* Do the sub in u32, where overflow is well-defined */ 12451 s32 res = (s32)((u32)a - (u32)b); 12452 12453 if (b < 0) 12454 return res < a; 12455 return res > a; 12456 } 12457 12458 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 12459 const struct bpf_reg_state *reg, 12460 enum bpf_reg_type type) 12461 { 12462 bool known = tnum_is_const(reg->var_off); 12463 s64 val = reg->var_off.value; 12464 s64 smin = reg->smin_value; 12465 12466 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 12467 verbose(env, "math between %s pointer and %lld is not allowed\n", 12468 reg_type_str(env, type), val); 12469 return false; 12470 } 12471 12472 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 12473 verbose(env, "%s pointer offset %d is not allowed\n", 12474 reg_type_str(env, type), reg->off); 12475 return false; 12476 } 12477 12478 if (smin == S64_MIN) { 12479 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 12480 reg_type_str(env, type)); 12481 return false; 12482 } 12483 12484 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 12485 verbose(env, "value %lld makes %s pointer be out of bounds\n", 12486 smin, reg_type_str(env, type)); 12487 return false; 12488 } 12489 12490 return true; 12491 } 12492 12493 enum { 12494 REASON_BOUNDS = -1, 12495 REASON_TYPE = -2, 12496 REASON_PATHS = -3, 12497 REASON_LIMIT = -4, 12498 REASON_STACK = -5, 12499 }; 12500 12501 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 12502 u32 *alu_limit, bool mask_to_left) 12503 { 12504 u32 max = 0, ptr_limit = 0; 12505 12506 switch (ptr_reg->type) { 12507 case PTR_TO_STACK: 12508 /* Offset 0 is out-of-bounds, but acceptable start for the 12509 * left direction, see BPF_REG_FP. Also, unknown scalar 12510 * offset where we would need to deal with min/max bounds is 12511 * currently prohibited for unprivileged. 12512 */ 12513 max = MAX_BPF_STACK + mask_to_left; 12514 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 12515 break; 12516 case PTR_TO_MAP_VALUE: 12517 max = ptr_reg->map_ptr->value_size; 12518 ptr_limit = (mask_to_left ? 12519 ptr_reg->smin_value : 12520 ptr_reg->umax_value) + ptr_reg->off; 12521 break; 12522 default: 12523 return REASON_TYPE; 12524 } 12525 12526 if (ptr_limit >= max) 12527 return REASON_LIMIT; 12528 *alu_limit = ptr_limit; 12529 return 0; 12530 } 12531 12532 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 12533 const struct bpf_insn *insn) 12534 { 12535 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 12536 } 12537 12538 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 12539 u32 alu_state, u32 alu_limit) 12540 { 12541 /* If we arrived here from different branches with different 12542 * state or limits to sanitize, then this won't work. 12543 */ 12544 if (aux->alu_state && 12545 (aux->alu_state != alu_state || 12546 aux->alu_limit != alu_limit)) 12547 return REASON_PATHS; 12548 12549 /* Corresponding fixup done in do_misc_fixups(). */ 12550 aux->alu_state = alu_state; 12551 aux->alu_limit = alu_limit; 12552 return 0; 12553 } 12554 12555 static int sanitize_val_alu(struct bpf_verifier_env *env, 12556 struct bpf_insn *insn) 12557 { 12558 struct bpf_insn_aux_data *aux = cur_aux(env); 12559 12560 if (can_skip_alu_sanitation(env, insn)) 12561 return 0; 12562 12563 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 12564 } 12565 12566 static bool sanitize_needed(u8 opcode) 12567 { 12568 return opcode == BPF_ADD || opcode == BPF_SUB; 12569 } 12570 12571 struct bpf_sanitize_info { 12572 struct bpf_insn_aux_data aux; 12573 bool mask_to_left; 12574 }; 12575 12576 static struct bpf_verifier_state * 12577 sanitize_speculative_path(struct bpf_verifier_env *env, 12578 const struct bpf_insn *insn, 12579 u32 next_idx, u32 curr_idx) 12580 { 12581 struct bpf_verifier_state *branch; 12582 struct bpf_reg_state *regs; 12583 12584 branch = push_stack(env, next_idx, curr_idx, true); 12585 if (branch && insn) { 12586 regs = branch->frame[branch->curframe]->regs; 12587 if (BPF_SRC(insn->code) == BPF_K) { 12588 mark_reg_unknown(env, regs, insn->dst_reg); 12589 } else if (BPF_SRC(insn->code) == BPF_X) { 12590 mark_reg_unknown(env, regs, insn->dst_reg); 12591 mark_reg_unknown(env, regs, insn->src_reg); 12592 } 12593 } 12594 return branch; 12595 } 12596 12597 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 12598 struct bpf_insn *insn, 12599 const struct bpf_reg_state *ptr_reg, 12600 const struct bpf_reg_state *off_reg, 12601 struct bpf_reg_state *dst_reg, 12602 struct bpf_sanitize_info *info, 12603 const bool commit_window) 12604 { 12605 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 12606 struct bpf_verifier_state *vstate = env->cur_state; 12607 bool off_is_imm = tnum_is_const(off_reg->var_off); 12608 bool off_is_neg = off_reg->smin_value < 0; 12609 bool ptr_is_dst_reg = ptr_reg == dst_reg; 12610 u8 opcode = BPF_OP(insn->code); 12611 u32 alu_state, alu_limit; 12612 struct bpf_reg_state tmp; 12613 bool ret; 12614 int err; 12615 12616 if (can_skip_alu_sanitation(env, insn)) 12617 return 0; 12618 12619 /* We already marked aux for masking from non-speculative 12620 * paths, thus we got here in the first place. We only care 12621 * to explore bad access from here. 12622 */ 12623 if (vstate->speculative) 12624 goto do_sim; 12625 12626 if (!commit_window) { 12627 if (!tnum_is_const(off_reg->var_off) && 12628 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 12629 return REASON_BOUNDS; 12630 12631 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 12632 (opcode == BPF_SUB && !off_is_neg); 12633 } 12634 12635 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 12636 if (err < 0) 12637 return err; 12638 12639 if (commit_window) { 12640 /* In commit phase we narrow the masking window based on 12641 * the observed pointer move after the simulated operation. 12642 */ 12643 alu_state = info->aux.alu_state; 12644 alu_limit = abs(info->aux.alu_limit - alu_limit); 12645 } else { 12646 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 12647 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 12648 alu_state |= ptr_is_dst_reg ? 12649 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 12650 12651 /* Limit pruning on unknown scalars to enable deep search for 12652 * potential masking differences from other program paths. 12653 */ 12654 if (!off_is_imm) 12655 env->explore_alu_limits = true; 12656 } 12657 12658 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 12659 if (err < 0) 12660 return err; 12661 do_sim: 12662 /* If we're in commit phase, we're done here given we already 12663 * pushed the truncated dst_reg into the speculative verification 12664 * stack. 12665 * 12666 * Also, when register is a known constant, we rewrite register-based 12667 * operation to immediate-based, and thus do not need masking (and as 12668 * a consequence, do not need to simulate the zero-truncation either). 12669 */ 12670 if (commit_window || off_is_imm) 12671 return 0; 12672 12673 /* Simulate and find potential out-of-bounds access under 12674 * speculative execution from truncation as a result of 12675 * masking when off was not within expected range. If off 12676 * sits in dst, then we temporarily need to move ptr there 12677 * to simulate dst (== 0) +/-= ptr. Needed, for example, 12678 * for cases where we use K-based arithmetic in one direction 12679 * and truncated reg-based in the other in order to explore 12680 * bad access. 12681 */ 12682 if (!ptr_is_dst_reg) { 12683 tmp = *dst_reg; 12684 copy_register_state(dst_reg, ptr_reg); 12685 } 12686 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 12687 env->insn_idx); 12688 if (!ptr_is_dst_reg && ret) 12689 *dst_reg = tmp; 12690 return !ret ? REASON_STACK : 0; 12691 } 12692 12693 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 12694 { 12695 struct bpf_verifier_state *vstate = env->cur_state; 12696 12697 /* If we simulate paths under speculation, we don't update the 12698 * insn as 'seen' such that when we verify unreachable paths in 12699 * the non-speculative domain, sanitize_dead_code() can still 12700 * rewrite/sanitize them. 12701 */ 12702 if (!vstate->speculative) 12703 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 12704 } 12705 12706 static int sanitize_err(struct bpf_verifier_env *env, 12707 const struct bpf_insn *insn, int reason, 12708 const struct bpf_reg_state *off_reg, 12709 const struct bpf_reg_state *dst_reg) 12710 { 12711 static const char *err = "pointer arithmetic with it prohibited for !root"; 12712 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 12713 u32 dst = insn->dst_reg, src = insn->src_reg; 12714 12715 switch (reason) { 12716 case REASON_BOUNDS: 12717 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 12718 off_reg == dst_reg ? dst : src, err); 12719 break; 12720 case REASON_TYPE: 12721 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 12722 off_reg == dst_reg ? src : dst, err); 12723 break; 12724 case REASON_PATHS: 12725 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 12726 dst, op, err); 12727 break; 12728 case REASON_LIMIT: 12729 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 12730 dst, op, err); 12731 break; 12732 case REASON_STACK: 12733 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 12734 dst, err); 12735 break; 12736 default: 12737 verbose(env, "verifier internal error: unknown reason (%d)\n", 12738 reason); 12739 break; 12740 } 12741 12742 return -EACCES; 12743 } 12744 12745 /* check that stack access falls within stack limits and that 'reg' doesn't 12746 * have a variable offset. 12747 * 12748 * Variable offset is prohibited for unprivileged mode for simplicity since it 12749 * requires corresponding support in Spectre masking for stack ALU. See also 12750 * retrieve_ptr_limit(). 12751 * 12752 * 12753 * 'off' includes 'reg->off'. 12754 */ 12755 static int check_stack_access_for_ptr_arithmetic( 12756 struct bpf_verifier_env *env, 12757 int regno, 12758 const struct bpf_reg_state *reg, 12759 int off) 12760 { 12761 if (!tnum_is_const(reg->var_off)) { 12762 char tn_buf[48]; 12763 12764 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 12765 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 12766 regno, tn_buf, off); 12767 return -EACCES; 12768 } 12769 12770 if (off >= 0 || off < -MAX_BPF_STACK) { 12771 verbose(env, "R%d stack pointer arithmetic goes out of range, " 12772 "prohibited for !root; off=%d\n", regno, off); 12773 return -EACCES; 12774 } 12775 12776 return 0; 12777 } 12778 12779 static int sanitize_check_bounds(struct bpf_verifier_env *env, 12780 const struct bpf_insn *insn, 12781 const struct bpf_reg_state *dst_reg) 12782 { 12783 u32 dst = insn->dst_reg; 12784 12785 /* For unprivileged we require that resulting offset must be in bounds 12786 * in order to be able to sanitize access later on. 12787 */ 12788 if (env->bypass_spec_v1) 12789 return 0; 12790 12791 switch (dst_reg->type) { 12792 case PTR_TO_STACK: 12793 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 12794 dst_reg->off + dst_reg->var_off.value)) 12795 return -EACCES; 12796 break; 12797 case PTR_TO_MAP_VALUE: 12798 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 12799 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 12800 "prohibited for !root\n", dst); 12801 return -EACCES; 12802 } 12803 break; 12804 default: 12805 break; 12806 } 12807 12808 return 0; 12809 } 12810 12811 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 12812 * Caller should also handle BPF_MOV case separately. 12813 * If we return -EACCES, caller may want to try again treating pointer as a 12814 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 12815 */ 12816 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 12817 struct bpf_insn *insn, 12818 const struct bpf_reg_state *ptr_reg, 12819 const struct bpf_reg_state *off_reg) 12820 { 12821 struct bpf_verifier_state *vstate = env->cur_state; 12822 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 12823 struct bpf_reg_state *regs = state->regs, *dst_reg; 12824 bool known = tnum_is_const(off_reg->var_off); 12825 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 12826 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 12827 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 12828 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 12829 struct bpf_sanitize_info info = {}; 12830 u8 opcode = BPF_OP(insn->code); 12831 u32 dst = insn->dst_reg; 12832 int ret; 12833 12834 dst_reg = ®s[dst]; 12835 12836 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 12837 smin_val > smax_val || umin_val > umax_val) { 12838 /* Taint dst register if offset had invalid bounds derived from 12839 * e.g. dead branches. 12840 */ 12841 __mark_reg_unknown(env, dst_reg); 12842 return 0; 12843 } 12844 12845 if (BPF_CLASS(insn->code) != BPF_ALU64) { 12846 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 12847 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 12848 __mark_reg_unknown(env, dst_reg); 12849 return 0; 12850 } 12851 12852 verbose(env, 12853 "R%d 32-bit pointer arithmetic prohibited\n", 12854 dst); 12855 return -EACCES; 12856 } 12857 12858 if (ptr_reg->type & PTR_MAYBE_NULL) { 12859 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 12860 dst, reg_type_str(env, ptr_reg->type)); 12861 return -EACCES; 12862 } 12863 12864 switch (base_type(ptr_reg->type)) { 12865 case PTR_TO_CTX: 12866 case PTR_TO_MAP_VALUE: 12867 case PTR_TO_MAP_KEY: 12868 case PTR_TO_STACK: 12869 case PTR_TO_PACKET_META: 12870 case PTR_TO_PACKET: 12871 case PTR_TO_TP_BUFFER: 12872 case PTR_TO_BTF_ID: 12873 case PTR_TO_MEM: 12874 case PTR_TO_BUF: 12875 case PTR_TO_FUNC: 12876 case CONST_PTR_TO_DYNPTR: 12877 break; 12878 case PTR_TO_FLOW_KEYS: 12879 if (known) 12880 break; 12881 fallthrough; 12882 case CONST_PTR_TO_MAP: 12883 /* smin_val represents the known value */ 12884 if (known && smin_val == 0 && opcode == BPF_ADD) 12885 break; 12886 fallthrough; 12887 default: 12888 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 12889 dst, reg_type_str(env, ptr_reg->type)); 12890 return -EACCES; 12891 } 12892 12893 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 12894 * The id may be overwritten later if we create a new variable offset. 12895 */ 12896 dst_reg->type = ptr_reg->type; 12897 dst_reg->id = ptr_reg->id; 12898 12899 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 12900 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 12901 return -EINVAL; 12902 12903 /* pointer types do not carry 32-bit bounds at the moment. */ 12904 __mark_reg32_unbounded(dst_reg); 12905 12906 if (sanitize_needed(opcode)) { 12907 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 12908 &info, false); 12909 if (ret < 0) 12910 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12911 } 12912 12913 switch (opcode) { 12914 case BPF_ADD: 12915 /* We can take a fixed offset as long as it doesn't overflow 12916 * the s32 'off' field 12917 */ 12918 if (known && (ptr_reg->off + smin_val == 12919 (s64)(s32)(ptr_reg->off + smin_val))) { 12920 /* pointer += K. Accumulate it into fixed offset */ 12921 dst_reg->smin_value = smin_ptr; 12922 dst_reg->smax_value = smax_ptr; 12923 dst_reg->umin_value = umin_ptr; 12924 dst_reg->umax_value = umax_ptr; 12925 dst_reg->var_off = ptr_reg->var_off; 12926 dst_reg->off = ptr_reg->off + smin_val; 12927 dst_reg->raw = ptr_reg->raw; 12928 break; 12929 } 12930 /* A new variable offset is created. Note that off_reg->off 12931 * == 0, since it's a scalar. 12932 * dst_reg gets the pointer type and since some positive 12933 * integer value was added to the pointer, give it a new 'id' 12934 * if it's a PTR_TO_PACKET. 12935 * this creates a new 'base' pointer, off_reg (variable) gets 12936 * added into the variable offset, and we copy the fixed offset 12937 * from ptr_reg. 12938 */ 12939 if (signed_add_overflows(smin_ptr, smin_val) || 12940 signed_add_overflows(smax_ptr, smax_val)) { 12941 dst_reg->smin_value = S64_MIN; 12942 dst_reg->smax_value = S64_MAX; 12943 } else { 12944 dst_reg->smin_value = smin_ptr + smin_val; 12945 dst_reg->smax_value = smax_ptr + smax_val; 12946 } 12947 if (umin_ptr + umin_val < umin_ptr || 12948 umax_ptr + umax_val < umax_ptr) { 12949 dst_reg->umin_value = 0; 12950 dst_reg->umax_value = U64_MAX; 12951 } else { 12952 dst_reg->umin_value = umin_ptr + umin_val; 12953 dst_reg->umax_value = umax_ptr + umax_val; 12954 } 12955 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 12956 dst_reg->off = ptr_reg->off; 12957 dst_reg->raw = ptr_reg->raw; 12958 if (reg_is_pkt_pointer(ptr_reg)) { 12959 dst_reg->id = ++env->id_gen; 12960 /* something was added to pkt_ptr, set range to zero */ 12961 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12962 } 12963 break; 12964 case BPF_SUB: 12965 if (dst_reg == off_reg) { 12966 /* scalar -= pointer. Creates an unknown scalar */ 12967 verbose(env, "R%d tried to subtract pointer from scalar\n", 12968 dst); 12969 return -EACCES; 12970 } 12971 /* We don't allow subtraction from FP, because (according to 12972 * test_verifier.c test "invalid fp arithmetic", JITs might not 12973 * be able to deal with it. 12974 */ 12975 if (ptr_reg->type == PTR_TO_STACK) { 12976 verbose(env, "R%d subtraction from stack pointer prohibited\n", 12977 dst); 12978 return -EACCES; 12979 } 12980 if (known && (ptr_reg->off - smin_val == 12981 (s64)(s32)(ptr_reg->off - smin_val))) { 12982 /* pointer -= K. Subtract it from fixed offset */ 12983 dst_reg->smin_value = smin_ptr; 12984 dst_reg->smax_value = smax_ptr; 12985 dst_reg->umin_value = umin_ptr; 12986 dst_reg->umax_value = umax_ptr; 12987 dst_reg->var_off = ptr_reg->var_off; 12988 dst_reg->id = ptr_reg->id; 12989 dst_reg->off = ptr_reg->off - smin_val; 12990 dst_reg->raw = ptr_reg->raw; 12991 break; 12992 } 12993 /* A new variable offset is created. If the subtrahend is known 12994 * nonnegative, then any reg->range we had before is still good. 12995 */ 12996 if (signed_sub_overflows(smin_ptr, smax_val) || 12997 signed_sub_overflows(smax_ptr, smin_val)) { 12998 /* Overflow possible, we know nothing */ 12999 dst_reg->smin_value = S64_MIN; 13000 dst_reg->smax_value = S64_MAX; 13001 } else { 13002 dst_reg->smin_value = smin_ptr - smax_val; 13003 dst_reg->smax_value = smax_ptr - smin_val; 13004 } 13005 if (umin_ptr < umax_val) { 13006 /* Overflow possible, we know nothing */ 13007 dst_reg->umin_value = 0; 13008 dst_reg->umax_value = U64_MAX; 13009 } else { 13010 /* Cannot overflow (as long as bounds are consistent) */ 13011 dst_reg->umin_value = umin_ptr - umax_val; 13012 dst_reg->umax_value = umax_ptr - umin_val; 13013 } 13014 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 13015 dst_reg->off = ptr_reg->off; 13016 dst_reg->raw = ptr_reg->raw; 13017 if (reg_is_pkt_pointer(ptr_reg)) { 13018 dst_reg->id = ++env->id_gen; 13019 /* something was added to pkt_ptr, set range to zero */ 13020 if (smin_val < 0) 13021 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13022 } 13023 break; 13024 case BPF_AND: 13025 case BPF_OR: 13026 case BPF_XOR: 13027 /* bitwise ops on pointers are troublesome, prohibit. */ 13028 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 13029 dst, bpf_alu_string[opcode >> 4]); 13030 return -EACCES; 13031 default: 13032 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 13033 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 13034 dst, bpf_alu_string[opcode >> 4]); 13035 return -EACCES; 13036 } 13037 13038 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 13039 return -EINVAL; 13040 reg_bounds_sync(dst_reg); 13041 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 13042 return -EACCES; 13043 if (sanitize_needed(opcode)) { 13044 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 13045 &info, true); 13046 if (ret < 0) 13047 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13048 } 13049 13050 return 0; 13051 } 13052 13053 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 13054 struct bpf_reg_state *src_reg) 13055 { 13056 s32 smin_val = src_reg->s32_min_value; 13057 s32 smax_val = src_reg->s32_max_value; 13058 u32 umin_val = src_reg->u32_min_value; 13059 u32 umax_val = src_reg->u32_max_value; 13060 13061 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 13062 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 13063 dst_reg->s32_min_value = S32_MIN; 13064 dst_reg->s32_max_value = S32_MAX; 13065 } else { 13066 dst_reg->s32_min_value += smin_val; 13067 dst_reg->s32_max_value += smax_val; 13068 } 13069 if (dst_reg->u32_min_value + umin_val < umin_val || 13070 dst_reg->u32_max_value + umax_val < umax_val) { 13071 dst_reg->u32_min_value = 0; 13072 dst_reg->u32_max_value = U32_MAX; 13073 } else { 13074 dst_reg->u32_min_value += umin_val; 13075 dst_reg->u32_max_value += umax_val; 13076 } 13077 } 13078 13079 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 13080 struct bpf_reg_state *src_reg) 13081 { 13082 s64 smin_val = src_reg->smin_value; 13083 s64 smax_val = src_reg->smax_value; 13084 u64 umin_val = src_reg->umin_value; 13085 u64 umax_val = src_reg->umax_value; 13086 13087 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 13088 signed_add_overflows(dst_reg->smax_value, smax_val)) { 13089 dst_reg->smin_value = S64_MIN; 13090 dst_reg->smax_value = S64_MAX; 13091 } else { 13092 dst_reg->smin_value += smin_val; 13093 dst_reg->smax_value += smax_val; 13094 } 13095 if (dst_reg->umin_value + umin_val < umin_val || 13096 dst_reg->umax_value + umax_val < umax_val) { 13097 dst_reg->umin_value = 0; 13098 dst_reg->umax_value = U64_MAX; 13099 } else { 13100 dst_reg->umin_value += umin_val; 13101 dst_reg->umax_value += umax_val; 13102 } 13103 } 13104 13105 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 13106 struct bpf_reg_state *src_reg) 13107 { 13108 s32 smin_val = src_reg->s32_min_value; 13109 s32 smax_val = src_reg->s32_max_value; 13110 u32 umin_val = src_reg->u32_min_value; 13111 u32 umax_val = src_reg->u32_max_value; 13112 13113 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 13114 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 13115 /* Overflow possible, we know nothing */ 13116 dst_reg->s32_min_value = S32_MIN; 13117 dst_reg->s32_max_value = S32_MAX; 13118 } else { 13119 dst_reg->s32_min_value -= smax_val; 13120 dst_reg->s32_max_value -= smin_val; 13121 } 13122 if (dst_reg->u32_min_value < umax_val) { 13123 /* Overflow possible, we know nothing */ 13124 dst_reg->u32_min_value = 0; 13125 dst_reg->u32_max_value = U32_MAX; 13126 } else { 13127 /* Cannot overflow (as long as bounds are consistent) */ 13128 dst_reg->u32_min_value -= umax_val; 13129 dst_reg->u32_max_value -= umin_val; 13130 } 13131 } 13132 13133 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 13134 struct bpf_reg_state *src_reg) 13135 { 13136 s64 smin_val = src_reg->smin_value; 13137 s64 smax_val = src_reg->smax_value; 13138 u64 umin_val = src_reg->umin_value; 13139 u64 umax_val = src_reg->umax_value; 13140 13141 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 13142 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 13143 /* Overflow possible, we know nothing */ 13144 dst_reg->smin_value = S64_MIN; 13145 dst_reg->smax_value = S64_MAX; 13146 } else { 13147 dst_reg->smin_value -= smax_val; 13148 dst_reg->smax_value -= smin_val; 13149 } 13150 if (dst_reg->umin_value < umax_val) { 13151 /* Overflow possible, we know nothing */ 13152 dst_reg->umin_value = 0; 13153 dst_reg->umax_value = U64_MAX; 13154 } else { 13155 /* Cannot overflow (as long as bounds are consistent) */ 13156 dst_reg->umin_value -= umax_val; 13157 dst_reg->umax_value -= umin_val; 13158 } 13159 } 13160 13161 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 13162 struct bpf_reg_state *src_reg) 13163 { 13164 s32 smin_val = src_reg->s32_min_value; 13165 u32 umin_val = src_reg->u32_min_value; 13166 u32 umax_val = src_reg->u32_max_value; 13167 13168 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 13169 /* Ain't nobody got time to multiply that sign */ 13170 __mark_reg32_unbounded(dst_reg); 13171 return; 13172 } 13173 /* Both values are positive, so we can work with unsigned and 13174 * copy the result to signed (unless it exceeds S32_MAX). 13175 */ 13176 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 13177 /* Potential overflow, we know nothing */ 13178 __mark_reg32_unbounded(dst_reg); 13179 return; 13180 } 13181 dst_reg->u32_min_value *= umin_val; 13182 dst_reg->u32_max_value *= umax_val; 13183 if (dst_reg->u32_max_value > S32_MAX) { 13184 /* Overflow possible, we know nothing */ 13185 dst_reg->s32_min_value = S32_MIN; 13186 dst_reg->s32_max_value = S32_MAX; 13187 } else { 13188 dst_reg->s32_min_value = dst_reg->u32_min_value; 13189 dst_reg->s32_max_value = dst_reg->u32_max_value; 13190 } 13191 } 13192 13193 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 13194 struct bpf_reg_state *src_reg) 13195 { 13196 s64 smin_val = src_reg->smin_value; 13197 u64 umin_val = src_reg->umin_value; 13198 u64 umax_val = src_reg->umax_value; 13199 13200 if (smin_val < 0 || dst_reg->smin_value < 0) { 13201 /* Ain't nobody got time to multiply that sign */ 13202 __mark_reg64_unbounded(dst_reg); 13203 return; 13204 } 13205 /* Both values are positive, so we can work with unsigned and 13206 * copy the result to signed (unless it exceeds S64_MAX). 13207 */ 13208 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 13209 /* Potential overflow, we know nothing */ 13210 __mark_reg64_unbounded(dst_reg); 13211 return; 13212 } 13213 dst_reg->umin_value *= umin_val; 13214 dst_reg->umax_value *= umax_val; 13215 if (dst_reg->umax_value > S64_MAX) { 13216 /* Overflow possible, we know nothing */ 13217 dst_reg->smin_value = S64_MIN; 13218 dst_reg->smax_value = S64_MAX; 13219 } else { 13220 dst_reg->smin_value = dst_reg->umin_value; 13221 dst_reg->smax_value = dst_reg->umax_value; 13222 } 13223 } 13224 13225 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 13226 struct bpf_reg_state *src_reg) 13227 { 13228 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13229 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13230 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13231 s32 smin_val = src_reg->s32_min_value; 13232 u32 umax_val = src_reg->u32_max_value; 13233 13234 if (src_known && dst_known) { 13235 __mark_reg32_known(dst_reg, var32_off.value); 13236 return; 13237 } 13238 13239 /* We get our minimum from the var_off, since that's inherently 13240 * bitwise. Our maximum is the minimum of the operands' maxima. 13241 */ 13242 dst_reg->u32_min_value = var32_off.value; 13243 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 13244 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 13245 /* Lose signed bounds when ANDing negative numbers, 13246 * ain't nobody got time for that. 13247 */ 13248 dst_reg->s32_min_value = S32_MIN; 13249 dst_reg->s32_max_value = S32_MAX; 13250 } else { 13251 /* ANDing two positives gives a positive, so safe to 13252 * cast result into s64. 13253 */ 13254 dst_reg->s32_min_value = dst_reg->u32_min_value; 13255 dst_reg->s32_max_value = dst_reg->u32_max_value; 13256 } 13257 } 13258 13259 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 13260 struct bpf_reg_state *src_reg) 13261 { 13262 bool src_known = tnum_is_const(src_reg->var_off); 13263 bool dst_known = tnum_is_const(dst_reg->var_off); 13264 s64 smin_val = src_reg->smin_value; 13265 u64 umax_val = src_reg->umax_value; 13266 13267 if (src_known && dst_known) { 13268 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13269 return; 13270 } 13271 13272 /* We get our minimum from the var_off, since that's inherently 13273 * bitwise. Our maximum is the minimum of the operands' maxima. 13274 */ 13275 dst_reg->umin_value = dst_reg->var_off.value; 13276 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 13277 if (dst_reg->smin_value < 0 || smin_val < 0) { 13278 /* Lose signed bounds when ANDing negative numbers, 13279 * ain't nobody got time for that. 13280 */ 13281 dst_reg->smin_value = S64_MIN; 13282 dst_reg->smax_value = S64_MAX; 13283 } else { 13284 /* ANDing two positives gives a positive, so safe to 13285 * cast result into s64. 13286 */ 13287 dst_reg->smin_value = dst_reg->umin_value; 13288 dst_reg->smax_value = dst_reg->umax_value; 13289 } 13290 /* We may learn something more from the var_off */ 13291 __update_reg_bounds(dst_reg); 13292 } 13293 13294 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 13295 struct bpf_reg_state *src_reg) 13296 { 13297 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13298 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13299 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13300 s32 smin_val = src_reg->s32_min_value; 13301 u32 umin_val = src_reg->u32_min_value; 13302 13303 if (src_known && dst_known) { 13304 __mark_reg32_known(dst_reg, var32_off.value); 13305 return; 13306 } 13307 13308 /* We get our maximum from the var_off, and our minimum is the 13309 * maximum of the operands' minima 13310 */ 13311 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 13312 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13313 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 13314 /* Lose signed bounds when ORing negative numbers, 13315 * ain't nobody got time for that. 13316 */ 13317 dst_reg->s32_min_value = S32_MIN; 13318 dst_reg->s32_max_value = S32_MAX; 13319 } else { 13320 /* ORing two positives gives a positive, so safe to 13321 * cast result into s64. 13322 */ 13323 dst_reg->s32_min_value = dst_reg->u32_min_value; 13324 dst_reg->s32_max_value = dst_reg->u32_max_value; 13325 } 13326 } 13327 13328 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 13329 struct bpf_reg_state *src_reg) 13330 { 13331 bool src_known = tnum_is_const(src_reg->var_off); 13332 bool dst_known = tnum_is_const(dst_reg->var_off); 13333 s64 smin_val = src_reg->smin_value; 13334 u64 umin_val = src_reg->umin_value; 13335 13336 if (src_known && dst_known) { 13337 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13338 return; 13339 } 13340 13341 /* We get our maximum from the var_off, and our minimum is the 13342 * maximum of the operands' minima 13343 */ 13344 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 13345 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13346 if (dst_reg->smin_value < 0 || smin_val < 0) { 13347 /* Lose signed bounds when ORing negative numbers, 13348 * ain't nobody got time for that. 13349 */ 13350 dst_reg->smin_value = S64_MIN; 13351 dst_reg->smax_value = S64_MAX; 13352 } else { 13353 /* ORing two positives gives a positive, so safe to 13354 * cast result into s64. 13355 */ 13356 dst_reg->smin_value = dst_reg->umin_value; 13357 dst_reg->smax_value = dst_reg->umax_value; 13358 } 13359 /* We may learn something more from the var_off */ 13360 __update_reg_bounds(dst_reg); 13361 } 13362 13363 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 13364 struct bpf_reg_state *src_reg) 13365 { 13366 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13367 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13368 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13369 s32 smin_val = src_reg->s32_min_value; 13370 13371 if (src_known && dst_known) { 13372 __mark_reg32_known(dst_reg, var32_off.value); 13373 return; 13374 } 13375 13376 /* We get both minimum and maximum from the var32_off. */ 13377 dst_reg->u32_min_value = var32_off.value; 13378 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13379 13380 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 13381 /* XORing two positive sign numbers gives a positive, 13382 * so safe to cast u32 result into s32. 13383 */ 13384 dst_reg->s32_min_value = dst_reg->u32_min_value; 13385 dst_reg->s32_max_value = dst_reg->u32_max_value; 13386 } else { 13387 dst_reg->s32_min_value = S32_MIN; 13388 dst_reg->s32_max_value = S32_MAX; 13389 } 13390 } 13391 13392 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 13393 struct bpf_reg_state *src_reg) 13394 { 13395 bool src_known = tnum_is_const(src_reg->var_off); 13396 bool dst_known = tnum_is_const(dst_reg->var_off); 13397 s64 smin_val = src_reg->smin_value; 13398 13399 if (src_known && dst_known) { 13400 /* dst_reg->var_off.value has been updated earlier */ 13401 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13402 return; 13403 } 13404 13405 /* We get both minimum and maximum from the var_off. */ 13406 dst_reg->umin_value = dst_reg->var_off.value; 13407 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13408 13409 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 13410 /* XORing two positive sign numbers gives a positive, 13411 * so safe to cast u64 result into s64. 13412 */ 13413 dst_reg->smin_value = dst_reg->umin_value; 13414 dst_reg->smax_value = dst_reg->umax_value; 13415 } else { 13416 dst_reg->smin_value = S64_MIN; 13417 dst_reg->smax_value = S64_MAX; 13418 } 13419 13420 __update_reg_bounds(dst_reg); 13421 } 13422 13423 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13424 u64 umin_val, u64 umax_val) 13425 { 13426 /* We lose all sign bit information (except what we can pick 13427 * up from var_off) 13428 */ 13429 dst_reg->s32_min_value = S32_MIN; 13430 dst_reg->s32_max_value = S32_MAX; 13431 /* If we might shift our top bit out, then we know nothing */ 13432 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 13433 dst_reg->u32_min_value = 0; 13434 dst_reg->u32_max_value = U32_MAX; 13435 } else { 13436 dst_reg->u32_min_value <<= umin_val; 13437 dst_reg->u32_max_value <<= umax_val; 13438 } 13439 } 13440 13441 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13442 struct bpf_reg_state *src_reg) 13443 { 13444 u32 umax_val = src_reg->u32_max_value; 13445 u32 umin_val = src_reg->u32_min_value; 13446 /* u32 alu operation will zext upper bits */ 13447 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13448 13449 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13450 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 13451 /* Not required but being careful mark reg64 bounds as unknown so 13452 * that we are forced to pick them up from tnum and zext later and 13453 * if some path skips this step we are still safe. 13454 */ 13455 __mark_reg64_unbounded(dst_reg); 13456 __update_reg32_bounds(dst_reg); 13457 } 13458 13459 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 13460 u64 umin_val, u64 umax_val) 13461 { 13462 /* Special case <<32 because it is a common compiler pattern to sign 13463 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 13464 * positive we know this shift will also be positive so we can track 13465 * bounds correctly. Otherwise we lose all sign bit information except 13466 * what we can pick up from var_off. Perhaps we can generalize this 13467 * later to shifts of any length. 13468 */ 13469 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 13470 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 13471 else 13472 dst_reg->smax_value = S64_MAX; 13473 13474 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 13475 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 13476 else 13477 dst_reg->smin_value = S64_MIN; 13478 13479 /* If we might shift our top bit out, then we know nothing */ 13480 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 13481 dst_reg->umin_value = 0; 13482 dst_reg->umax_value = U64_MAX; 13483 } else { 13484 dst_reg->umin_value <<= umin_val; 13485 dst_reg->umax_value <<= umax_val; 13486 } 13487 } 13488 13489 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 13490 struct bpf_reg_state *src_reg) 13491 { 13492 u64 umax_val = src_reg->umax_value; 13493 u64 umin_val = src_reg->umin_value; 13494 13495 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 13496 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 13497 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13498 13499 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 13500 /* We may learn something more from the var_off */ 13501 __update_reg_bounds(dst_reg); 13502 } 13503 13504 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 13505 struct bpf_reg_state *src_reg) 13506 { 13507 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13508 u32 umax_val = src_reg->u32_max_value; 13509 u32 umin_val = src_reg->u32_min_value; 13510 13511 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13512 * be negative, then either: 13513 * 1) src_reg might be zero, so the sign bit of the result is 13514 * unknown, so we lose our signed bounds 13515 * 2) it's known negative, thus the unsigned bounds capture the 13516 * signed bounds 13517 * 3) the signed bounds cross zero, so they tell us nothing 13518 * about the result 13519 * If the value in dst_reg is known nonnegative, then again the 13520 * unsigned bounds capture the signed bounds. 13521 * Thus, in all cases it suffices to blow away our signed bounds 13522 * and rely on inferring new ones from the unsigned bounds and 13523 * var_off of the result. 13524 */ 13525 dst_reg->s32_min_value = S32_MIN; 13526 dst_reg->s32_max_value = S32_MAX; 13527 13528 dst_reg->var_off = tnum_rshift(subreg, umin_val); 13529 dst_reg->u32_min_value >>= umax_val; 13530 dst_reg->u32_max_value >>= umin_val; 13531 13532 __mark_reg64_unbounded(dst_reg); 13533 __update_reg32_bounds(dst_reg); 13534 } 13535 13536 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 13537 struct bpf_reg_state *src_reg) 13538 { 13539 u64 umax_val = src_reg->umax_value; 13540 u64 umin_val = src_reg->umin_value; 13541 13542 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13543 * be negative, then either: 13544 * 1) src_reg might be zero, so the sign bit of the result is 13545 * unknown, so we lose our signed bounds 13546 * 2) it's known negative, thus the unsigned bounds capture the 13547 * signed bounds 13548 * 3) the signed bounds cross zero, so they tell us nothing 13549 * about the result 13550 * If the value in dst_reg is known nonnegative, then again the 13551 * unsigned bounds capture the signed bounds. 13552 * Thus, in all cases it suffices to blow away our signed bounds 13553 * and rely on inferring new ones from the unsigned bounds and 13554 * var_off of the result. 13555 */ 13556 dst_reg->smin_value = S64_MIN; 13557 dst_reg->smax_value = S64_MAX; 13558 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 13559 dst_reg->umin_value >>= umax_val; 13560 dst_reg->umax_value >>= umin_val; 13561 13562 /* Its not easy to operate on alu32 bounds here because it depends 13563 * on bits being shifted in. Take easy way out and mark unbounded 13564 * so we can recalculate later from tnum. 13565 */ 13566 __mark_reg32_unbounded(dst_reg); 13567 __update_reg_bounds(dst_reg); 13568 } 13569 13570 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 13571 struct bpf_reg_state *src_reg) 13572 { 13573 u64 umin_val = src_reg->u32_min_value; 13574 13575 /* Upon reaching here, src_known is true and 13576 * umax_val is equal to umin_val. 13577 */ 13578 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 13579 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 13580 13581 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 13582 13583 /* blow away the dst_reg umin_value/umax_value and rely on 13584 * dst_reg var_off to refine the result. 13585 */ 13586 dst_reg->u32_min_value = 0; 13587 dst_reg->u32_max_value = U32_MAX; 13588 13589 __mark_reg64_unbounded(dst_reg); 13590 __update_reg32_bounds(dst_reg); 13591 } 13592 13593 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 13594 struct bpf_reg_state *src_reg) 13595 { 13596 u64 umin_val = src_reg->umin_value; 13597 13598 /* Upon reaching here, src_known is true and umax_val is equal 13599 * to umin_val. 13600 */ 13601 dst_reg->smin_value >>= umin_val; 13602 dst_reg->smax_value >>= umin_val; 13603 13604 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 13605 13606 /* blow away the dst_reg umin_value/umax_value and rely on 13607 * dst_reg var_off to refine the result. 13608 */ 13609 dst_reg->umin_value = 0; 13610 dst_reg->umax_value = U64_MAX; 13611 13612 /* Its not easy to operate on alu32 bounds here because it depends 13613 * on bits being shifted in from upper 32-bits. Take easy way out 13614 * and mark unbounded so we can recalculate later from tnum. 13615 */ 13616 __mark_reg32_unbounded(dst_reg); 13617 __update_reg_bounds(dst_reg); 13618 } 13619 13620 /* WARNING: This function does calculations on 64-bit values, but the actual 13621 * execution may occur on 32-bit values. Therefore, things like bitshifts 13622 * need extra checks in the 32-bit case. 13623 */ 13624 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 13625 struct bpf_insn *insn, 13626 struct bpf_reg_state *dst_reg, 13627 struct bpf_reg_state src_reg) 13628 { 13629 struct bpf_reg_state *regs = cur_regs(env); 13630 u8 opcode = BPF_OP(insn->code); 13631 bool src_known; 13632 s64 smin_val, smax_val; 13633 u64 umin_val, umax_val; 13634 s32 s32_min_val, s32_max_val; 13635 u32 u32_min_val, u32_max_val; 13636 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 13637 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 13638 int ret; 13639 13640 smin_val = src_reg.smin_value; 13641 smax_val = src_reg.smax_value; 13642 umin_val = src_reg.umin_value; 13643 umax_val = src_reg.umax_value; 13644 13645 s32_min_val = src_reg.s32_min_value; 13646 s32_max_val = src_reg.s32_max_value; 13647 u32_min_val = src_reg.u32_min_value; 13648 u32_max_val = src_reg.u32_max_value; 13649 13650 if (alu32) { 13651 src_known = tnum_subreg_is_const(src_reg.var_off); 13652 if ((src_known && 13653 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 13654 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 13655 /* Taint dst register if offset had invalid bounds 13656 * derived from e.g. dead branches. 13657 */ 13658 __mark_reg_unknown(env, dst_reg); 13659 return 0; 13660 } 13661 } else { 13662 src_known = tnum_is_const(src_reg.var_off); 13663 if ((src_known && 13664 (smin_val != smax_val || umin_val != umax_val)) || 13665 smin_val > smax_val || umin_val > umax_val) { 13666 /* Taint dst register if offset had invalid bounds 13667 * derived from e.g. dead branches. 13668 */ 13669 __mark_reg_unknown(env, dst_reg); 13670 return 0; 13671 } 13672 } 13673 13674 if (!src_known && 13675 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 13676 __mark_reg_unknown(env, dst_reg); 13677 return 0; 13678 } 13679 13680 if (sanitize_needed(opcode)) { 13681 ret = sanitize_val_alu(env, insn); 13682 if (ret < 0) 13683 return sanitize_err(env, insn, ret, NULL, NULL); 13684 } 13685 13686 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 13687 * There are two classes of instructions: The first class we track both 13688 * alu32 and alu64 sign/unsigned bounds independently this provides the 13689 * greatest amount of precision when alu operations are mixed with jmp32 13690 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 13691 * and BPF_OR. This is possible because these ops have fairly easy to 13692 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 13693 * See alu32 verifier tests for examples. The second class of 13694 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 13695 * with regards to tracking sign/unsigned bounds because the bits may 13696 * cross subreg boundaries in the alu64 case. When this happens we mark 13697 * the reg unbounded in the subreg bound space and use the resulting 13698 * tnum to calculate an approximation of the sign/unsigned bounds. 13699 */ 13700 switch (opcode) { 13701 case BPF_ADD: 13702 scalar32_min_max_add(dst_reg, &src_reg); 13703 scalar_min_max_add(dst_reg, &src_reg); 13704 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 13705 break; 13706 case BPF_SUB: 13707 scalar32_min_max_sub(dst_reg, &src_reg); 13708 scalar_min_max_sub(dst_reg, &src_reg); 13709 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 13710 break; 13711 case BPF_MUL: 13712 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 13713 scalar32_min_max_mul(dst_reg, &src_reg); 13714 scalar_min_max_mul(dst_reg, &src_reg); 13715 break; 13716 case BPF_AND: 13717 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 13718 scalar32_min_max_and(dst_reg, &src_reg); 13719 scalar_min_max_and(dst_reg, &src_reg); 13720 break; 13721 case BPF_OR: 13722 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 13723 scalar32_min_max_or(dst_reg, &src_reg); 13724 scalar_min_max_or(dst_reg, &src_reg); 13725 break; 13726 case BPF_XOR: 13727 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 13728 scalar32_min_max_xor(dst_reg, &src_reg); 13729 scalar_min_max_xor(dst_reg, &src_reg); 13730 break; 13731 case BPF_LSH: 13732 if (umax_val >= insn_bitness) { 13733 /* Shifts greater than 31 or 63 are undefined. 13734 * This includes shifts by a negative number. 13735 */ 13736 mark_reg_unknown(env, regs, insn->dst_reg); 13737 break; 13738 } 13739 if (alu32) 13740 scalar32_min_max_lsh(dst_reg, &src_reg); 13741 else 13742 scalar_min_max_lsh(dst_reg, &src_reg); 13743 break; 13744 case BPF_RSH: 13745 if (umax_val >= insn_bitness) { 13746 /* Shifts greater than 31 or 63 are undefined. 13747 * This includes shifts by a negative number. 13748 */ 13749 mark_reg_unknown(env, regs, insn->dst_reg); 13750 break; 13751 } 13752 if (alu32) 13753 scalar32_min_max_rsh(dst_reg, &src_reg); 13754 else 13755 scalar_min_max_rsh(dst_reg, &src_reg); 13756 break; 13757 case BPF_ARSH: 13758 if (umax_val >= insn_bitness) { 13759 /* Shifts greater than 31 or 63 are undefined. 13760 * This includes shifts by a negative number. 13761 */ 13762 mark_reg_unknown(env, regs, insn->dst_reg); 13763 break; 13764 } 13765 if (alu32) 13766 scalar32_min_max_arsh(dst_reg, &src_reg); 13767 else 13768 scalar_min_max_arsh(dst_reg, &src_reg); 13769 break; 13770 default: 13771 mark_reg_unknown(env, regs, insn->dst_reg); 13772 break; 13773 } 13774 13775 /* ALU32 ops are zero extended into 64bit register */ 13776 if (alu32) 13777 zext_32_to_64(dst_reg); 13778 reg_bounds_sync(dst_reg); 13779 return 0; 13780 } 13781 13782 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 13783 * and var_off. 13784 */ 13785 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 13786 struct bpf_insn *insn) 13787 { 13788 struct bpf_verifier_state *vstate = env->cur_state; 13789 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13790 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 13791 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 13792 u8 opcode = BPF_OP(insn->code); 13793 int err; 13794 13795 dst_reg = ®s[insn->dst_reg]; 13796 src_reg = NULL; 13797 if (dst_reg->type != SCALAR_VALUE) 13798 ptr_reg = dst_reg; 13799 else 13800 /* Make sure ID is cleared otherwise dst_reg min/max could be 13801 * incorrectly propagated into other registers by find_equal_scalars() 13802 */ 13803 dst_reg->id = 0; 13804 if (BPF_SRC(insn->code) == BPF_X) { 13805 src_reg = ®s[insn->src_reg]; 13806 if (src_reg->type != SCALAR_VALUE) { 13807 if (dst_reg->type != SCALAR_VALUE) { 13808 /* Combining two pointers by any ALU op yields 13809 * an arbitrary scalar. Disallow all math except 13810 * pointer subtraction 13811 */ 13812 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13813 mark_reg_unknown(env, regs, insn->dst_reg); 13814 return 0; 13815 } 13816 verbose(env, "R%d pointer %s pointer prohibited\n", 13817 insn->dst_reg, 13818 bpf_alu_string[opcode >> 4]); 13819 return -EACCES; 13820 } else { 13821 /* scalar += pointer 13822 * This is legal, but we have to reverse our 13823 * src/dest handling in computing the range 13824 */ 13825 err = mark_chain_precision(env, insn->dst_reg); 13826 if (err) 13827 return err; 13828 return adjust_ptr_min_max_vals(env, insn, 13829 src_reg, dst_reg); 13830 } 13831 } else if (ptr_reg) { 13832 /* pointer += scalar */ 13833 err = mark_chain_precision(env, insn->src_reg); 13834 if (err) 13835 return err; 13836 return adjust_ptr_min_max_vals(env, insn, 13837 dst_reg, src_reg); 13838 } else if (dst_reg->precise) { 13839 /* if dst_reg is precise, src_reg should be precise as well */ 13840 err = mark_chain_precision(env, insn->src_reg); 13841 if (err) 13842 return err; 13843 } 13844 } else { 13845 /* Pretend the src is a reg with a known value, since we only 13846 * need to be able to read from this state. 13847 */ 13848 off_reg.type = SCALAR_VALUE; 13849 __mark_reg_known(&off_reg, insn->imm); 13850 src_reg = &off_reg; 13851 if (ptr_reg) /* pointer += K */ 13852 return adjust_ptr_min_max_vals(env, insn, 13853 ptr_reg, src_reg); 13854 } 13855 13856 /* Got here implies adding two SCALAR_VALUEs */ 13857 if (WARN_ON_ONCE(ptr_reg)) { 13858 print_verifier_state(env, state, true); 13859 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 13860 return -EINVAL; 13861 } 13862 if (WARN_ON(!src_reg)) { 13863 print_verifier_state(env, state, true); 13864 verbose(env, "verifier internal error: no src_reg\n"); 13865 return -EINVAL; 13866 } 13867 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 13868 } 13869 13870 /* check validity of 32-bit and 64-bit arithmetic operations */ 13871 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 13872 { 13873 struct bpf_reg_state *regs = cur_regs(env); 13874 u8 opcode = BPF_OP(insn->code); 13875 int err; 13876 13877 if (opcode == BPF_END || opcode == BPF_NEG) { 13878 if (opcode == BPF_NEG) { 13879 if (BPF_SRC(insn->code) != BPF_K || 13880 insn->src_reg != BPF_REG_0 || 13881 insn->off != 0 || insn->imm != 0) { 13882 verbose(env, "BPF_NEG uses reserved fields\n"); 13883 return -EINVAL; 13884 } 13885 } else { 13886 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 13887 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 13888 (BPF_CLASS(insn->code) == BPF_ALU64 && 13889 BPF_SRC(insn->code) != BPF_TO_LE)) { 13890 verbose(env, "BPF_END uses reserved fields\n"); 13891 return -EINVAL; 13892 } 13893 } 13894 13895 /* check src operand */ 13896 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13897 if (err) 13898 return err; 13899 13900 if (is_pointer_value(env, insn->dst_reg)) { 13901 verbose(env, "R%d pointer arithmetic prohibited\n", 13902 insn->dst_reg); 13903 return -EACCES; 13904 } 13905 13906 /* check dest operand */ 13907 err = check_reg_arg(env, insn->dst_reg, DST_OP); 13908 if (err) 13909 return err; 13910 13911 } else if (opcode == BPF_MOV) { 13912 13913 if (BPF_SRC(insn->code) == BPF_X) { 13914 if (insn->imm != 0) { 13915 verbose(env, "BPF_MOV uses reserved fields\n"); 13916 return -EINVAL; 13917 } 13918 13919 if (BPF_CLASS(insn->code) == BPF_ALU) { 13920 if (insn->off != 0 && insn->off != 8 && insn->off != 16) { 13921 verbose(env, "BPF_MOV uses reserved fields\n"); 13922 return -EINVAL; 13923 } 13924 } else { 13925 if (insn->off != 0 && insn->off != 8 && insn->off != 16 && 13926 insn->off != 32) { 13927 verbose(env, "BPF_MOV uses reserved fields\n"); 13928 return -EINVAL; 13929 } 13930 } 13931 13932 /* check src operand */ 13933 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13934 if (err) 13935 return err; 13936 } else { 13937 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 13938 verbose(env, "BPF_MOV uses reserved fields\n"); 13939 return -EINVAL; 13940 } 13941 } 13942 13943 /* check dest operand, mark as required later */ 13944 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13945 if (err) 13946 return err; 13947 13948 if (BPF_SRC(insn->code) == BPF_X) { 13949 struct bpf_reg_state *src_reg = regs + insn->src_reg; 13950 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 13951 13952 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13953 if (insn->off == 0) { 13954 /* case: R1 = R2 13955 * copy register state to dest reg 13956 */ 13957 assign_scalar_id_before_mov(env, src_reg); 13958 copy_register_state(dst_reg, src_reg); 13959 dst_reg->live |= REG_LIVE_WRITTEN; 13960 dst_reg->subreg_def = DEF_NOT_SUBREG; 13961 } else { 13962 /* case: R1 = (s8, s16 s32)R2 */ 13963 if (is_pointer_value(env, insn->src_reg)) { 13964 verbose(env, 13965 "R%d sign-extension part of pointer\n", 13966 insn->src_reg); 13967 return -EACCES; 13968 } else if (src_reg->type == SCALAR_VALUE) { 13969 bool no_sext; 13970 13971 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13972 if (no_sext) 13973 assign_scalar_id_before_mov(env, src_reg); 13974 copy_register_state(dst_reg, src_reg); 13975 if (!no_sext) 13976 dst_reg->id = 0; 13977 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 13978 dst_reg->live |= REG_LIVE_WRITTEN; 13979 dst_reg->subreg_def = DEF_NOT_SUBREG; 13980 } else { 13981 mark_reg_unknown(env, regs, insn->dst_reg); 13982 } 13983 } 13984 } else { 13985 /* R1 = (u32) R2 */ 13986 if (is_pointer_value(env, insn->src_reg)) { 13987 verbose(env, 13988 "R%d partial copy of pointer\n", 13989 insn->src_reg); 13990 return -EACCES; 13991 } else if (src_reg->type == SCALAR_VALUE) { 13992 if (insn->off == 0) { 13993 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 13994 13995 if (is_src_reg_u32) 13996 assign_scalar_id_before_mov(env, src_reg); 13997 copy_register_state(dst_reg, src_reg); 13998 /* Make sure ID is cleared if src_reg is not in u32 13999 * range otherwise dst_reg min/max could be incorrectly 14000 * propagated into src_reg by find_equal_scalars() 14001 */ 14002 if (!is_src_reg_u32) 14003 dst_reg->id = 0; 14004 dst_reg->live |= REG_LIVE_WRITTEN; 14005 dst_reg->subreg_def = env->insn_idx + 1; 14006 } else { 14007 /* case: W1 = (s8, s16)W2 */ 14008 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 14009 14010 if (no_sext) 14011 assign_scalar_id_before_mov(env, src_reg); 14012 copy_register_state(dst_reg, src_reg); 14013 if (!no_sext) 14014 dst_reg->id = 0; 14015 dst_reg->live |= REG_LIVE_WRITTEN; 14016 dst_reg->subreg_def = env->insn_idx + 1; 14017 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 14018 } 14019 } else { 14020 mark_reg_unknown(env, regs, 14021 insn->dst_reg); 14022 } 14023 zext_32_to_64(dst_reg); 14024 reg_bounds_sync(dst_reg); 14025 } 14026 } else { 14027 /* case: R = imm 14028 * remember the value we stored into this reg 14029 */ 14030 /* clear any state __mark_reg_known doesn't set */ 14031 mark_reg_unknown(env, regs, insn->dst_reg); 14032 regs[insn->dst_reg].type = SCALAR_VALUE; 14033 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14034 __mark_reg_known(regs + insn->dst_reg, 14035 insn->imm); 14036 } else { 14037 __mark_reg_known(regs + insn->dst_reg, 14038 (u32)insn->imm); 14039 } 14040 } 14041 14042 } else if (opcode > BPF_END) { 14043 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 14044 return -EINVAL; 14045 14046 } else { /* all other ALU ops: and, sub, xor, add, ... */ 14047 14048 if (BPF_SRC(insn->code) == BPF_X) { 14049 if (insn->imm != 0 || insn->off > 1 || 14050 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14051 verbose(env, "BPF_ALU uses reserved fields\n"); 14052 return -EINVAL; 14053 } 14054 /* check src1 operand */ 14055 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14056 if (err) 14057 return err; 14058 } else { 14059 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 14060 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14061 verbose(env, "BPF_ALU uses reserved fields\n"); 14062 return -EINVAL; 14063 } 14064 } 14065 14066 /* check src2 operand */ 14067 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14068 if (err) 14069 return err; 14070 14071 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 14072 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 14073 verbose(env, "div by zero\n"); 14074 return -EINVAL; 14075 } 14076 14077 if ((opcode == BPF_LSH || opcode == BPF_RSH || 14078 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 14079 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 14080 14081 if (insn->imm < 0 || insn->imm >= size) { 14082 verbose(env, "invalid shift %d\n", insn->imm); 14083 return -EINVAL; 14084 } 14085 } 14086 14087 /* check dest operand */ 14088 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14089 err = err ?: adjust_reg_min_max_vals(env, insn); 14090 if (err) 14091 return err; 14092 } 14093 14094 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 14095 } 14096 14097 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 14098 struct bpf_reg_state *dst_reg, 14099 enum bpf_reg_type type, 14100 bool range_right_open) 14101 { 14102 struct bpf_func_state *state; 14103 struct bpf_reg_state *reg; 14104 int new_range; 14105 14106 if (dst_reg->off < 0 || 14107 (dst_reg->off == 0 && range_right_open)) 14108 /* This doesn't give us any range */ 14109 return; 14110 14111 if (dst_reg->umax_value > MAX_PACKET_OFF || 14112 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 14113 /* Risk of overflow. For instance, ptr + (1<<63) may be less 14114 * than pkt_end, but that's because it's also less than pkt. 14115 */ 14116 return; 14117 14118 new_range = dst_reg->off; 14119 if (range_right_open) 14120 new_range++; 14121 14122 /* Examples for register markings: 14123 * 14124 * pkt_data in dst register: 14125 * 14126 * r2 = r3; 14127 * r2 += 8; 14128 * if (r2 > pkt_end) goto <handle exception> 14129 * <access okay> 14130 * 14131 * r2 = r3; 14132 * r2 += 8; 14133 * if (r2 < pkt_end) goto <access okay> 14134 * <handle exception> 14135 * 14136 * Where: 14137 * r2 == dst_reg, pkt_end == src_reg 14138 * r2=pkt(id=n,off=8,r=0) 14139 * r3=pkt(id=n,off=0,r=0) 14140 * 14141 * pkt_data in src register: 14142 * 14143 * r2 = r3; 14144 * r2 += 8; 14145 * if (pkt_end >= r2) goto <access okay> 14146 * <handle exception> 14147 * 14148 * r2 = r3; 14149 * r2 += 8; 14150 * if (pkt_end <= r2) goto <handle exception> 14151 * <access okay> 14152 * 14153 * Where: 14154 * pkt_end == dst_reg, r2 == src_reg 14155 * r2=pkt(id=n,off=8,r=0) 14156 * r3=pkt(id=n,off=0,r=0) 14157 * 14158 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 14159 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 14160 * and [r3, r3 + 8-1) respectively is safe to access depending on 14161 * the check. 14162 */ 14163 14164 /* If our ids match, then we must have the same max_value. And we 14165 * don't care about the other reg's fixed offset, since if it's too big 14166 * the range won't allow anything. 14167 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 14168 */ 14169 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14170 if (reg->type == type && reg->id == dst_reg->id) 14171 /* keep the maximum range already checked */ 14172 reg->range = max(reg->range, new_range); 14173 })); 14174 } 14175 14176 /* 14177 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 14178 */ 14179 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14180 u8 opcode, bool is_jmp32) 14181 { 14182 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 14183 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 14184 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value; 14185 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value; 14186 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value; 14187 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value; 14188 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value; 14189 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value; 14190 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value; 14191 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value; 14192 14193 switch (opcode) { 14194 case BPF_JEQ: 14195 /* constants, umin/umax and smin/smax checks would be 14196 * redundant in this case because they all should match 14197 */ 14198 if (tnum_is_const(t1) && tnum_is_const(t2)) 14199 return t1.value == t2.value; 14200 /* non-overlapping ranges */ 14201 if (umin1 > umax2 || umax1 < umin2) 14202 return 0; 14203 if (smin1 > smax2 || smax1 < smin2) 14204 return 0; 14205 if (!is_jmp32) { 14206 /* if 64-bit ranges are inconclusive, see if we can 14207 * utilize 32-bit subrange knowledge to eliminate 14208 * branches that can't be taken a priori 14209 */ 14210 if (reg1->u32_min_value > reg2->u32_max_value || 14211 reg1->u32_max_value < reg2->u32_min_value) 14212 return 0; 14213 if (reg1->s32_min_value > reg2->s32_max_value || 14214 reg1->s32_max_value < reg2->s32_min_value) 14215 return 0; 14216 } 14217 break; 14218 case BPF_JNE: 14219 /* constants, umin/umax and smin/smax checks would be 14220 * redundant in this case because they all should match 14221 */ 14222 if (tnum_is_const(t1) && tnum_is_const(t2)) 14223 return t1.value != t2.value; 14224 /* non-overlapping ranges */ 14225 if (umin1 > umax2 || umax1 < umin2) 14226 return 1; 14227 if (smin1 > smax2 || smax1 < smin2) 14228 return 1; 14229 if (!is_jmp32) { 14230 /* if 64-bit ranges are inconclusive, see if we can 14231 * utilize 32-bit subrange knowledge to eliminate 14232 * branches that can't be taken a priori 14233 */ 14234 if (reg1->u32_min_value > reg2->u32_max_value || 14235 reg1->u32_max_value < reg2->u32_min_value) 14236 return 1; 14237 if (reg1->s32_min_value > reg2->s32_max_value || 14238 reg1->s32_max_value < reg2->s32_min_value) 14239 return 1; 14240 } 14241 break; 14242 case BPF_JSET: 14243 if (!is_reg_const(reg2, is_jmp32)) { 14244 swap(reg1, reg2); 14245 swap(t1, t2); 14246 } 14247 if (!is_reg_const(reg2, is_jmp32)) 14248 return -1; 14249 if ((~t1.mask & t1.value) & t2.value) 14250 return 1; 14251 if (!((t1.mask | t1.value) & t2.value)) 14252 return 0; 14253 break; 14254 case BPF_JGT: 14255 if (umin1 > umax2) 14256 return 1; 14257 else if (umax1 <= umin2) 14258 return 0; 14259 break; 14260 case BPF_JSGT: 14261 if (smin1 > smax2) 14262 return 1; 14263 else if (smax1 <= smin2) 14264 return 0; 14265 break; 14266 case BPF_JLT: 14267 if (umax1 < umin2) 14268 return 1; 14269 else if (umin1 >= umax2) 14270 return 0; 14271 break; 14272 case BPF_JSLT: 14273 if (smax1 < smin2) 14274 return 1; 14275 else if (smin1 >= smax2) 14276 return 0; 14277 break; 14278 case BPF_JGE: 14279 if (umin1 >= umax2) 14280 return 1; 14281 else if (umax1 < umin2) 14282 return 0; 14283 break; 14284 case BPF_JSGE: 14285 if (smin1 >= smax2) 14286 return 1; 14287 else if (smax1 < smin2) 14288 return 0; 14289 break; 14290 case BPF_JLE: 14291 if (umax1 <= umin2) 14292 return 1; 14293 else if (umin1 > umax2) 14294 return 0; 14295 break; 14296 case BPF_JSLE: 14297 if (smax1 <= smin2) 14298 return 1; 14299 else if (smin1 > smax2) 14300 return 0; 14301 break; 14302 } 14303 14304 return -1; 14305 } 14306 14307 static int flip_opcode(u32 opcode) 14308 { 14309 /* How can we transform "a <op> b" into "b <op> a"? */ 14310 static const u8 opcode_flip[16] = { 14311 /* these stay the same */ 14312 [BPF_JEQ >> 4] = BPF_JEQ, 14313 [BPF_JNE >> 4] = BPF_JNE, 14314 [BPF_JSET >> 4] = BPF_JSET, 14315 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 14316 [BPF_JGE >> 4] = BPF_JLE, 14317 [BPF_JGT >> 4] = BPF_JLT, 14318 [BPF_JLE >> 4] = BPF_JGE, 14319 [BPF_JLT >> 4] = BPF_JGT, 14320 [BPF_JSGE >> 4] = BPF_JSLE, 14321 [BPF_JSGT >> 4] = BPF_JSLT, 14322 [BPF_JSLE >> 4] = BPF_JSGE, 14323 [BPF_JSLT >> 4] = BPF_JSGT 14324 }; 14325 return opcode_flip[opcode >> 4]; 14326 } 14327 14328 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 14329 struct bpf_reg_state *src_reg, 14330 u8 opcode) 14331 { 14332 struct bpf_reg_state *pkt; 14333 14334 if (src_reg->type == PTR_TO_PACKET_END) { 14335 pkt = dst_reg; 14336 } else if (dst_reg->type == PTR_TO_PACKET_END) { 14337 pkt = src_reg; 14338 opcode = flip_opcode(opcode); 14339 } else { 14340 return -1; 14341 } 14342 14343 if (pkt->range >= 0) 14344 return -1; 14345 14346 switch (opcode) { 14347 case BPF_JLE: 14348 /* pkt <= pkt_end */ 14349 fallthrough; 14350 case BPF_JGT: 14351 /* pkt > pkt_end */ 14352 if (pkt->range == BEYOND_PKT_END) 14353 /* pkt has at last one extra byte beyond pkt_end */ 14354 return opcode == BPF_JGT; 14355 break; 14356 case BPF_JLT: 14357 /* pkt < pkt_end */ 14358 fallthrough; 14359 case BPF_JGE: 14360 /* pkt >= pkt_end */ 14361 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 14362 return opcode == BPF_JGE; 14363 break; 14364 } 14365 return -1; 14366 } 14367 14368 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 14369 * and return: 14370 * 1 - branch will be taken and "goto target" will be executed 14371 * 0 - branch will not be taken and fall-through to next insn 14372 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 14373 * range [0,10] 14374 */ 14375 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14376 u8 opcode, bool is_jmp32) 14377 { 14378 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 14379 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 14380 14381 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 14382 u64 val; 14383 14384 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 14385 if (!is_reg_const(reg2, is_jmp32)) { 14386 opcode = flip_opcode(opcode); 14387 swap(reg1, reg2); 14388 } 14389 /* and ensure that reg2 is a constant */ 14390 if (!is_reg_const(reg2, is_jmp32)) 14391 return -1; 14392 14393 if (!reg_not_null(reg1)) 14394 return -1; 14395 14396 /* If pointer is valid tests against zero will fail so we can 14397 * use this to direct branch taken. 14398 */ 14399 val = reg_const_value(reg2, is_jmp32); 14400 if (val != 0) 14401 return -1; 14402 14403 switch (opcode) { 14404 case BPF_JEQ: 14405 return 0; 14406 case BPF_JNE: 14407 return 1; 14408 default: 14409 return -1; 14410 } 14411 } 14412 14413 /* now deal with two scalars, but not necessarily constants */ 14414 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32); 14415 } 14416 14417 /* Opcode that corresponds to a *false* branch condition. 14418 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 14419 */ 14420 static u8 rev_opcode(u8 opcode) 14421 { 14422 switch (opcode) { 14423 case BPF_JEQ: return BPF_JNE; 14424 case BPF_JNE: return BPF_JEQ; 14425 /* JSET doesn't have it's reverse opcode in BPF, so add 14426 * BPF_X flag to denote the reverse of that operation 14427 */ 14428 case BPF_JSET: return BPF_JSET | BPF_X; 14429 case BPF_JSET | BPF_X: return BPF_JSET; 14430 case BPF_JGE: return BPF_JLT; 14431 case BPF_JGT: return BPF_JLE; 14432 case BPF_JLE: return BPF_JGT; 14433 case BPF_JLT: return BPF_JGE; 14434 case BPF_JSGE: return BPF_JSLT; 14435 case BPF_JSGT: return BPF_JSLE; 14436 case BPF_JSLE: return BPF_JSGT; 14437 case BPF_JSLT: return BPF_JSGE; 14438 default: return 0; 14439 } 14440 } 14441 14442 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 14443 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14444 u8 opcode, bool is_jmp32) 14445 { 14446 struct tnum t; 14447 u64 val; 14448 14449 again: 14450 switch (opcode) { 14451 case BPF_JEQ: 14452 if (is_jmp32) { 14453 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14454 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14455 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14456 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14457 reg2->u32_min_value = reg1->u32_min_value; 14458 reg2->u32_max_value = reg1->u32_max_value; 14459 reg2->s32_min_value = reg1->s32_min_value; 14460 reg2->s32_max_value = reg1->s32_max_value; 14461 14462 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 14463 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14464 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 14465 } else { 14466 reg1->umin_value = max(reg1->umin_value, reg2->umin_value); 14467 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14468 reg1->smin_value = max(reg1->smin_value, reg2->smin_value); 14469 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14470 reg2->umin_value = reg1->umin_value; 14471 reg2->umax_value = reg1->umax_value; 14472 reg2->smin_value = reg1->smin_value; 14473 reg2->smax_value = reg1->smax_value; 14474 14475 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 14476 reg2->var_off = reg1->var_off; 14477 } 14478 break; 14479 case BPF_JNE: 14480 if (!is_reg_const(reg2, is_jmp32)) 14481 swap(reg1, reg2); 14482 if (!is_reg_const(reg2, is_jmp32)) 14483 break; 14484 14485 /* try to recompute the bound of reg1 if reg2 is a const and 14486 * is exactly the edge of reg1. 14487 */ 14488 val = reg_const_value(reg2, is_jmp32); 14489 if (is_jmp32) { 14490 /* u32_min_value is not equal to 0xffffffff at this point, 14491 * because otherwise u32_max_value is 0xffffffff as well, 14492 * in such a case both reg1 and reg2 would be constants, 14493 * jump would be predicted and reg_set_min_max() won't 14494 * be called. 14495 * 14496 * Same reasoning works for all {u,s}{min,max}{32,64} cases 14497 * below. 14498 */ 14499 if (reg1->u32_min_value == (u32)val) 14500 reg1->u32_min_value++; 14501 if (reg1->u32_max_value == (u32)val) 14502 reg1->u32_max_value--; 14503 if (reg1->s32_min_value == (s32)val) 14504 reg1->s32_min_value++; 14505 if (reg1->s32_max_value == (s32)val) 14506 reg1->s32_max_value--; 14507 } else { 14508 if (reg1->umin_value == (u64)val) 14509 reg1->umin_value++; 14510 if (reg1->umax_value == (u64)val) 14511 reg1->umax_value--; 14512 if (reg1->smin_value == (s64)val) 14513 reg1->smin_value++; 14514 if (reg1->smax_value == (s64)val) 14515 reg1->smax_value--; 14516 } 14517 break; 14518 case BPF_JSET: 14519 if (!is_reg_const(reg2, is_jmp32)) 14520 swap(reg1, reg2); 14521 if (!is_reg_const(reg2, is_jmp32)) 14522 break; 14523 val = reg_const_value(reg2, is_jmp32); 14524 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 14525 * requires single bit to learn something useful. E.g., if we 14526 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 14527 * are actually set? We can learn something definite only if 14528 * it's a single-bit value to begin with. 14529 * 14530 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 14531 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 14532 * bit 1 is set, which we can readily use in adjustments. 14533 */ 14534 if (!is_power_of_2(val)) 14535 break; 14536 if (is_jmp32) { 14537 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 14538 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14539 } else { 14540 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 14541 } 14542 break; 14543 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 14544 if (!is_reg_const(reg2, is_jmp32)) 14545 swap(reg1, reg2); 14546 if (!is_reg_const(reg2, is_jmp32)) 14547 break; 14548 val = reg_const_value(reg2, is_jmp32); 14549 if (is_jmp32) { 14550 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 14551 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14552 } else { 14553 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 14554 } 14555 break; 14556 case BPF_JLE: 14557 if (is_jmp32) { 14558 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14559 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14560 } else { 14561 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14562 reg2->umin_value = max(reg1->umin_value, reg2->umin_value); 14563 } 14564 break; 14565 case BPF_JLT: 14566 if (is_jmp32) { 14567 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1); 14568 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value); 14569 } else { 14570 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1); 14571 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value); 14572 } 14573 break; 14574 case BPF_JSLE: 14575 if (is_jmp32) { 14576 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14577 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14578 } else { 14579 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14580 reg2->smin_value = max(reg1->smin_value, reg2->smin_value); 14581 } 14582 break; 14583 case BPF_JSLT: 14584 if (is_jmp32) { 14585 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1); 14586 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value); 14587 } else { 14588 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1); 14589 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value); 14590 } 14591 break; 14592 case BPF_JGE: 14593 case BPF_JGT: 14594 case BPF_JSGE: 14595 case BPF_JSGT: 14596 /* just reuse LE/LT logic above */ 14597 opcode = flip_opcode(opcode); 14598 swap(reg1, reg2); 14599 goto again; 14600 default: 14601 return; 14602 } 14603 } 14604 14605 /* Adjusts the register min/max values in the case that the dst_reg and 14606 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K 14607 * check, in which case we havea fake SCALAR_VALUE representing insn->imm). 14608 * Technically we can do similar adjustments for pointers to the same object, 14609 * but we don't support that right now. 14610 */ 14611 static int reg_set_min_max(struct bpf_verifier_env *env, 14612 struct bpf_reg_state *true_reg1, 14613 struct bpf_reg_state *true_reg2, 14614 struct bpf_reg_state *false_reg1, 14615 struct bpf_reg_state *false_reg2, 14616 u8 opcode, bool is_jmp32) 14617 { 14618 int err; 14619 14620 /* If either register is a pointer, we can't learn anything about its 14621 * variable offset from the compare (unless they were a pointer into 14622 * the same object, but we don't bother with that). 14623 */ 14624 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE) 14625 return 0; 14626 14627 /* fallthrough (FALSE) branch */ 14628 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32); 14629 reg_bounds_sync(false_reg1); 14630 reg_bounds_sync(false_reg2); 14631 14632 /* jump (TRUE) branch */ 14633 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32); 14634 reg_bounds_sync(true_reg1); 14635 reg_bounds_sync(true_reg2); 14636 14637 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1"); 14638 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2"); 14639 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1"); 14640 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2"); 14641 return err; 14642 } 14643 14644 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 14645 struct bpf_reg_state *reg, u32 id, 14646 bool is_null) 14647 { 14648 if (type_may_be_null(reg->type) && reg->id == id && 14649 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 14650 /* Old offset (both fixed and variable parts) should have been 14651 * known-zero, because we don't allow pointer arithmetic on 14652 * pointers that might be NULL. If we see this happening, don't 14653 * convert the register. 14654 * 14655 * But in some cases, some helpers that return local kptrs 14656 * advance offset for the returned pointer. In those cases, it 14657 * is fine to expect to see reg->off. 14658 */ 14659 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 14660 return; 14661 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 14662 WARN_ON_ONCE(reg->off)) 14663 return; 14664 14665 if (is_null) { 14666 reg->type = SCALAR_VALUE; 14667 /* We don't need id and ref_obj_id from this point 14668 * onwards anymore, thus we should better reset it, 14669 * so that state pruning has chances to take effect. 14670 */ 14671 reg->id = 0; 14672 reg->ref_obj_id = 0; 14673 14674 return; 14675 } 14676 14677 mark_ptr_not_null_reg(reg); 14678 14679 if (!reg_may_point_to_spin_lock(reg)) { 14680 /* For not-NULL ptr, reg->ref_obj_id will be reset 14681 * in release_reference(). 14682 * 14683 * reg->id is still used by spin_lock ptr. Other 14684 * than spin_lock ptr type, reg->id can be reset. 14685 */ 14686 reg->id = 0; 14687 } 14688 } 14689 } 14690 14691 /* The logic is similar to find_good_pkt_pointers(), both could eventually 14692 * be folded together at some point. 14693 */ 14694 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 14695 bool is_null) 14696 { 14697 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14698 struct bpf_reg_state *regs = state->regs, *reg; 14699 u32 ref_obj_id = regs[regno].ref_obj_id; 14700 u32 id = regs[regno].id; 14701 14702 if (ref_obj_id && ref_obj_id == id && is_null) 14703 /* regs[regno] is in the " == NULL" branch. 14704 * No one could have freed the reference state before 14705 * doing the NULL check. 14706 */ 14707 WARN_ON_ONCE(release_reference_state(state, id)); 14708 14709 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14710 mark_ptr_or_null_reg(state, reg, id, is_null); 14711 })); 14712 } 14713 14714 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 14715 struct bpf_reg_state *dst_reg, 14716 struct bpf_reg_state *src_reg, 14717 struct bpf_verifier_state *this_branch, 14718 struct bpf_verifier_state *other_branch) 14719 { 14720 if (BPF_SRC(insn->code) != BPF_X) 14721 return false; 14722 14723 /* Pointers are always 64-bit. */ 14724 if (BPF_CLASS(insn->code) == BPF_JMP32) 14725 return false; 14726 14727 switch (BPF_OP(insn->code)) { 14728 case BPF_JGT: 14729 if ((dst_reg->type == PTR_TO_PACKET && 14730 src_reg->type == PTR_TO_PACKET_END) || 14731 (dst_reg->type == PTR_TO_PACKET_META && 14732 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14733 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 14734 find_good_pkt_pointers(this_branch, dst_reg, 14735 dst_reg->type, false); 14736 mark_pkt_end(other_branch, insn->dst_reg, true); 14737 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14738 src_reg->type == PTR_TO_PACKET) || 14739 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14740 src_reg->type == PTR_TO_PACKET_META)) { 14741 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 14742 find_good_pkt_pointers(other_branch, src_reg, 14743 src_reg->type, true); 14744 mark_pkt_end(this_branch, insn->src_reg, false); 14745 } else { 14746 return false; 14747 } 14748 break; 14749 case BPF_JLT: 14750 if ((dst_reg->type == PTR_TO_PACKET && 14751 src_reg->type == PTR_TO_PACKET_END) || 14752 (dst_reg->type == PTR_TO_PACKET_META && 14753 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14754 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 14755 find_good_pkt_pointers(other_branch, dst_reg, 14756 dst_reg->type, true); 14757 mark_pkt_end(this_branch, insn->dst_reg, false); 14758 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14759 src_reg->type == PTR_TO_PACKET) || 14760 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14761 src_reg->type == PTR_TO_PACKET_META)) { 14762 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 14763 find_good_pkt_pointers(this_branch, src_reg, 14764 src_reg->type, false); 14765 mark_pkt_end(other_branch, insn->src_reg, true); 14766 } else { 14767 return false; 14768 } 14769 break; 14770 case BPF_JGE: 14771 if ((dst_reg->type == PTR_TO_PACKET && 14772 src_reg->type == PTR_TO_PACKET_END) || 14773 (dst_reg->type == PTR_TO_PACKET_META && 14774 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14775 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 14776 find_good_pkt_pointers(this_branch, dst_reg, 14777 dst_reg->type, true); 14778 mark_pkt_end(other_branch, insn->dst_reg, false); 14779 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14780 src_reg->type == PTR_TO_PACKET) || 14781 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14782 src_reg->type == PTR_TO_PACKET_META)) { 14783 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 14784 find_good_pkt_pointers(other_branch, src_reg, 14785 src_reg->type, false); 14786 mark_pkt_end(this_branch, insn->src_reg, true); 14787 } else { 14788 return false; 14789 } 14790 break; 14791 case BPF_JLE: 14792 if ((dst_reg->type == PTR_TO_PACKET && 14793 src_reg->type == PTR_TO_PACKET_END) || 14794 (dst_reg->type == PTR_TO_PACKET_META && 14795 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14796 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 14797 find_good_pkt_pointers(other_branch, dst_reg, 14798 dst_reg->type, false); 14799 mark_pkt_end(this_branch, insn->dst_reg, true); 14800 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14801 src_reg->type == PTR_TO_PACKET) || 14802 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14803 src_reg->type == PTR_TO_PACKET_META)) { 14804 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 14805 find_good_pkt_pointers(this_branch, src_reg, 14806 src_reg->type, true); 14807 mark_pkt_end(other_branch, insn->src_reg, false); 14808 } else { 14809 return false; 14810 } 14811 break; 14812 default: 14813 return false; 14814 } 14815 14816 return true; 14817 } 14818 14819 static void find_equal_scalars(struct bpf_verifier_state *vstate, 14820 struct bpf_reg_state *known_reg) 14821 { 14822 struct bpf_func_state *state; 14823 struct bpf_reg_state *reg; 14824 14825 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14826 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 14827 copy_register_state(reg, known_reg); 14828 })); 14829 } 14830 14831 static int check_cond_jmp_op(struct bpf_verifier_env *env, 14832 struct bpf_insn *insn, int *insn_idx) 14833 { 14834 struct bpf_verifier_state *this_branch = env->cur_state; 14835 struct bpf_verifier_state *other_branch; 14836 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 14837 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 14838 struct bpf_reg_state *eq_branch_regs; 14839 struct bpf_reg_state fake_reg = {}; 14840 u8 opcode = BPF_OP(insn->code); 14841 bool is_jmp32; 14842 int pred = -1; 14843 int err; 14844 14845 /* Only conditional jumps are expected to reach here. */ 14846 if (opcode == BPF_JA || opcode > BPF_JSLE) { 14847 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 14848 return -EINVAL; 14849 } 14850 14851 /* check src2 operand */ 14852 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14853 if (err) 14854 return err; 14855 14856 dst_reg = ®s[insn->dst_reg]; 14857 if (BPF_SRC(insn->code) == BPF_X) { 14858 if (insn->imm != 0) { 14859 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14860 return -EINVAL; 14861 } 14862 14863 /* check src1 operand */ 14864 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14865 if (err) 14866 return err; 14867 14868 src_reg = ®s[insn->src_reg]; 14869 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 14870 is_pointer_value(env, insn->src_reg)) { 14871 verbose(env, "R%d pointer comparison prohibited\n", 14872 insn->src_reg); 14873 return -EACCES; 14874 } 14875 } else { 14876 if (insn->src_reg != BPF_REG_0) { 14877 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14878 return -EINVAL; 14879 } 14880 src_reg = &fake_reg; 14881 src_reg->type = SCALAR_VALUE; 14882 __mark_reg_known(src_reg, insn->imm); 14883 } 14884 14885 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 14886 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32); 14887 if (pred >= 0) { 14888 /* If we get here with a dst_reg pointer type it is because 14889 * above is_branch_taken() special cased the 0 comparison. 14890 */ 14891 if (!__is_pointer_value(false, dst_reg)) 14892 err = mark_chain_precision(env, insn->dst_reg); 14893 if (BPF_SRC(insn->code) == BPF_X && !err && 14894 !__is_pointer_value(false, src_reg)) 14895 err = mark_chain_precision(env, insn->src_reg); 14896 if (err) 14897 return err; 14898 } 14899 14900 if (pred == 1) { 14901 /* Only follow the goto, ignore fall-through. If needed, push 14902 * the fall-through branch for simulation under speculative 14903 * execution. 14904 */ 14905 if (!env->bypass_spec_v1 && 14906 !sanitize_speculative_path(env, insn, *insn_idx + 1, 14907 *insn_idx)) 14908 return -EFAULT; 14909 if (env->log.level & BPF_LOG_LEVEL) 14910 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14911 *insn_idx += insn->off; 14912 return 0; 14913 } else if (pred == 0) { 14914 /* Only follow the fall-through branch, since that's where the 14915 * program will go. If needed, push the goto branch for 14916 * simulation under speculative execution. 14917 */ 14918 if (!env->bypass_spec_v1 && 14919 !sanitize_speculative_path(env, insn, 14920 *insn_idx + insn->off + 1, 14921 *insn_idx)) 14922 return -EFAULT; 14923 if (env->log.level & BPF_LOG_LEVEL) 14924 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14925 return 0; 14926 } 14927 14928 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 14929 false); 14930 if (!other_branch) 14931 return -EFAULT; 14932 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 14933 14934 if (BPF_SRC(insn->code) == BPF_X) { 14935 err = reg_set_min_max(env, 14936 &other_branch_regs[insn->dst_reg], 14937 &other_branch_regs[insn->src_reg], 14938 dst_reg, src_reg, opcode, is_jmp32); 14939 } else /* BPF_SRC(insn->code) == BPF_K */ { 14940 err = reg_set_min_max(env, 14941 &other_branch_regs[insn->dst_reg], 14942 src_reg /* fake one */, 14943 dst_reg, src_reg /* same fake one */, 14944 opcode, is_jmp32); 14945 } 14946 if (err) 14947 return err; 14948 14949 if (BPF_SRC(insn->code) == BPF_X && 14950 src_reg->type == SCALAR_VALUE && src_reg->id && 14951 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 14952 find_equal_scalars(this_branch, src_reg); 14953 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 14954 } 14955 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 14956 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 14957 find_equal_scalars(this_branch, dst_reg); 14958 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 14959 } 14960 14961 /* if one pointer register is compared to another pointer 14962 * register check if PTR_MAYBE_NULL could be lifted. 14963 * E.g. register A - maybe null 14964 * register B - not null 14965 * for JNE A, B, ... - A is not null in the false branch; 14966 * for JEQ A, B, ... - A is not null in the true branch. 14967 * 14968 * Since PTR_TO_BTF_ID points to a kernel struct that does 14969 * not need to be null checked by the BPF program, i.e., 14970 * could be null even without PTR_MAYBE_NULL marking, so 14971 * only propagate nullness when neither reg is that type. 14972 */ 14973 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 14974 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 14975 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 14976 base_type(src_reg->type) != PTR_TO_BTF_ID && 14977 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 14978 eq_branch_regs = NULL; 14979 switch (opcode) { 14980 case BPF_JEQ: 14981 eq_branch_regs = other_branch_regs; 14982 break; 14983 case BPF_JNE: 14984 eq_branch_regs = regs; 14985 break; 14986 default: 14987 /* do nothing */ 14988 break; 14989 } 14990 if (eq_branch_regs) { 14991 if (type_may_be_null(src_reg->type)) 14992 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 14993 else 14994 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 14995 } 14996 } 14997 14998 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 14999 * NOTE: these optimizations below are related with pointer comparison 15000 * which will never be JMP32. 15001 */ 15002 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 15003 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 15004 type_may_be_null(dst_reg->type)) { 15005 /* Mark all identical registers in each branch as either 15006 * safe or unknown depending R == 0 or R != 0 conditional. 15007 */ 15008 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 15009 opcode == BPF_JNE); 15010 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 15011 opcode == BPF_JEQ); 15012 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 15013 this_branch, other_branch) && 15014 is_pointer_value(env, insn->dst_reg)) { 15015 verbose(env, "R%d pointer comparison prohibited\n", 15016 insn->dst_reg); 15017 return -EACCES; 15018 } 15019 if (env->log.level & BPF_LOG_LEVEL) 15020 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15021 return 0; 15022 } 15023 15024 /* verify BPF_LD_IMM64 instruction */ 15025 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 15026 { 15027 struct bpf_insn_aux_data *aux = cur_aux(env); 15028 struct bpf_reg_state *regs = cur_regs(env); 15029 struct bpf_reg_state *dst_reg; 15030 struct bpf_map *map; 15031 int err; 15032 15033 if (BPF_SIZE(insn->code) != BPF_DW) { 15034 verbose(env, "invalid BPF_LD_IMM insn\n"); 15035 return -EINVAL; 15036 } 15037 if (insn->off != 0) { 15038 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 15039 return -EINVAL; 15040 } 15041 15042 err = check_reg_arg(env, insn->dst_reg, DST_OP); 15043 if (err) 15044 return err; 15045 15046 dst_reg = ®s[insn->dst_reg]; 15047 if (insn->src_reg == 0) { 15048 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 15049 15050 dst_reg->type = SCALAR_VALUE; 15051 __mark_reg_known(®s[insn->dst_reg], imm); 15052 return 0; 15053 } 15054 15055 /* All special src_reg cases are listed below. From this point onwards 15056 * we either succeed and assign a corresponding dst_reg->type after 15057 * zeroing the offset, or fail and reject the program. 15058 */ 15059 mark_reg_known_zero(env, regs, insn->dst_reg); 15060 15061 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 15062 dst_reg->type = aux->btf_var.reg_type; 15063 switch (base_type(dst_reg->type)) { 15064 case PTR_TO_MEM: 15065 dst_reg->mem_size = aux->btf_var.mem_size; 15066 break; 15067 case PTR_TO_BTF_ID: 15068 dst_reg->btf = aux->btf_var.btf; 15069 dst_reg->btf_id = aux->btf_var.btf_id; 15070 break; 15071 default: 15072 verbose(env, "bpf verifier is misconfigured\n"); 15073 return -EFAULT; 15074 } 15075 return 0; 15076 } 15077 15078 if (insn->src_reg == BPF_PSEUDO_FUNC) { 15079 struct bpf_prog_aux *aux = env->prog->aux; 15080 u32 subprogno = find_subprog(env, 15081 env->insn_idx + insn->imm + 1); 15082 15083 if (!aux->func_info) { 15084 verbose(env, "missing btf func_info\n"); 15085 return -EINVAL; 15086 } 15087 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 15088 verbose(env, "callback function not static\n"); 15089 return -EINVAL; 15090 } 15091 15092 dst_reg->type = PTR_TO_FUNC; 15093 dst_reg->subprogno = subprogno; 15094 return 0; 15095 } 15096 15097 map = env->used_maps[aux->map_index]; 15098 dst_reg->map_ptr = map; 15099 15100 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 15101 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 15102 dst_reg->type = PTR_TO_MAP_VALUE; 15103 dst_reg->off = aux->map_off; 15104 WARN_ON_ONCE(map->max_entries != 1); 15105 /* We want reg->id to be same (0) as map_value is not distinct */ 15106 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 15107 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 15108 dst_reg->type = CONST_PTR_TO_MAP; 15109 } else { 15110 verbose(env, "bpf verifier is misconfigured\n"); 15111 return -EINVAL; 15112 } 15113 15114 return 0; 15115 } 15116 15117 static bool may_access_skb(enum bpf_prog_type type) 15118 { 15119 switch (type) { 15120 case BPF_PROG_TYPE_SOCKET_FILTER: 15121 case BPF_PROG_TYPE_SCHED_CLS: 15122 case BPF_PROG_TYPE_SCHED_ACT: 15123 return true; 15124 default: 15125 return false; 15126 } 15127 } 15128 15129 /* verify safety of LD_ABS|LD_IND instructions: 15130 * - they can only appear in the programs where ctx == skb 15131 * - since they are wrappers of function calls, they scratch R1-R5 registers, 15132 * preserve R6-R9, and store return value into R0 15133 * 15134 * Implicit input: 15135 * ctx == skb == R6 == CTX 15136 * 15137 * Explicit input: 15138 * SRC == any register 15139 * IMM == 32-bit immediate 15140 * 15141 * Output: 15142 * R0 - 8/16/32-bit skb data converted to cpu endianness 15143 */ 15144 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 15145 { 15146 struct bpf_reg_state *regs = cur_regs(env); 15147 static const int ctx_reg = BPF_REG_6; 15148 u8 mode = BPF_MODE(insn->code); 15149 int i, err; 15150 15151 if (!may_access_skb(resolve_prog_type(env->prog))) { 15152 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 15153 return -EINVAL; 15154 } 15155 15156 if (!env->ops->gen_ld_abs) { 15157 verbose(env, "bpf verifier is misconfigured\n"); 15158 return -EINVAL; 15159 } 15160 15161 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 15162 BPF_SIZE(insn->code) == BPF_DW || 15163 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 15164 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 15165 return -EINVAL; 15166 } 15167 15168 /* check whether implicit source operand (register R6) is readable */ 15169 err = check_reg_arg(env, ctx_reg, SRC_OP); 15170 if (err) 15171 return err; 15172 15173 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 15174 * gen_ld_abs() may terminate the program at runtime, leading to 15175 * reference leak. 15176 */ 15177 err = check_reference_leak(env, false); 15178 if (err) { 15179 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 15180 return err; 15181 } 15182 15183 if (env->cur_state->active_lock.ptr) { 15184 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 15185 return -EINVAL; 15186 } 15187 15188 if (env->cur_state->active_rcu_lock) { 15189 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 15190 return -EINVAL; 15191 } 15192 15193 if (regs[ctx_reg].type != PTR_TO_CTX) { 15194 verbose(env, 15195 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 15196 return -EINVAL; 15197 } 15198 15199 if (mode == BPF_IND) { 15200 /* check explicit source operand */ 15201 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15202 if (err) 15203 return err; 15204 } 15205 15206 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 15207 if (err < 0) 15208 return err; 15209 15210 /* reset caller saved regs to unreadable */ 15211 for (i = 0; i < CALLER_SAVED_REGS; i++) { 15212 mark_reg_not_init(env, regs, caller_saved[i]); 15213 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 15214 } 15215 15216 /* mark destination R0 register as readable, since it contains 15217 * the value fetched from the packet. 15218 * Already marked as written above. 15219 */ 15220 mark_reg_unknown(env, regs, BPF_REG_0); 15221 /* ld_abs load up to 32-bit skb data. */ 15222 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 15223 return 0; 15224 } 15225 15226 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 15227 { 15228 const char *exit_ctx = "At program exit"; 15229 struct tnum enforce_attach_type_range = tnum_unknown; 15230 const struct bpf_prog *prog = env->prog; 15231 struct bpf_reg_state *reg; 15232 struct bpf_retval_range range = retval_range(0, 1); 15233 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 15234 int err; 15235 struct bpf_func_state *frame = env->cur_state->frame[0]; 15236 const bool is_subprog = frame->subprogno; 15237 15238 /* LSM and struct_ops func-ptr's return type could be "void" */ 15239 if (!is_subprog || frame->in_exception_callback_fn) { 15240 switch (prog_type) { 15241 case BPF_PROG_TYPE_LSM: 15242 if (prog->expected_attach_type == BPF_LSM_CGROUP) 15243 /* See below, can be 0 or 0-1 depending on hook. */ 15244 break; 15245 fallthrough; 15246 case BPF_PROG_TYPE_STRUCT_OPS: 15247 if (!prog->aux->attach_func_proto->type) 15248 return 0; 15249 break; 15250 default: 15251 break; 15252 } 15253 } 15254 15255 /* eBPF calling convention is such that R0 is used 15256 * to return the value from eBPF program. 15257 * Make sure that it's readable at this time 15258 * of bpf_exit, which means that program wrote 15259 * something into it earlier 15260 */ 15261 err = check_reg_arg(env, regno, SRC_OP); 15262 if (err) 15263 return err; 15264 15265 if (is_pointer_value(env, regno)) { 15266 verbose(env, "R%d leaks addr as return value\n", regno); 15267 return -EACCES; 15268 } 15269 15270 reg = cur_regs(env) + regno; 15271 15272 if (frame->in_async_callback_fn) { 15273 /* enforce return zero from async callbacks like timer */ 15274 exit_ctx = "At async callback return"; 15275 range = retval_range(0, 0); 15276 goto enforce_retval; 15277 } 15278 15279 if (is_subprog && !frame->in_exception_callback_fn) { 15280 if (reg->type != SCALAR_VALUE) { 15281 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 15282 regno, reg_type_str(env, reg->type)); 15283 return -EINVAL; 15284 } 15285 return 0; 15286 } 15287 15288 switch (prog_type) { 15289 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 15290 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 15291 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 15292 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG || 15293 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 15294 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 15295 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME || 15296 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 15297 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME || 15298 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME) 15299 range = retval_range(1, 1); 15300 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 15301 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 15302 range = retval_range(0, 3); 15303 break; 15304 case BPF_PROG_TYPE_CGROUP_SKB: 15305 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 15306 range = retval_range(0, 3); 15307 enforce_attach_type_range = tnum_range(2, 3); 15308 } 15309 break; 15310 case BPF_PROG_TYPE_CGROUP_SOCK: 15311 case BPF_PROG_TYPE_SOCK_OPS: 15312 case BPF_PROG_TYPE_CGROUP_DEVICE: 15313 case BPF_PROG_TYPE_CGROUP_SYSCTL: 15314 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 15315 break; 15316 case BPF_PROG_TYPE_RAW_TRACEPOINT: 15317 if (!env->prog->aux->attach_btf_id) 15318 return 0; 15319 range = retval_range(0, 0); 15320 break; 15321 case BPF_PROG_TYPE_TRACING: 15322 switch (env->prog->expected_attach_type) { 15323 case BPF_TRACE_FENTRY: 15324 case BPF_TRACE_FEXIT: 15325 range = retval_range(0, 0); 15326 break; 15327 case BPF_TRACE_RAW_TP: 15328 case BPF_MODIFY_RETURN: 15329 return 0; 15330 case BPF_TRACE_ITER: 15331 break; 15332 default: 15333 return -ENOTSUPP; 15334 } 15335 break; 15336 case BPF_PROG_TYPE_SK_LOOKUP: 15337 range = retval_range(SK_DROP, SK_PASS); 15338 break; 15339 15340 case BPF_PROG_TYPE_LSM: 15341 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 15342 /* Regular BPF_PROG_TYPE_LSM programs can return 15343 * any value. 15344 */ 15345 return 0; 15346 } 15347 if (!env->prog->aux->attach_func_proto->type) { 15348 /* Make sure programs that attach to void 15349 * hooks don't try to modify return value. 15350 */ 15351 range = retval_range(1, 1); 15352 } 15353 break; 15354 15355 case BPF_PROG_TYPE_NETFILTER: 15356 range = retval_range(NF_DROP, NF_ACCEPT); 15357 break; 15358 case BPF_PROG_TYPE_EXT: 15359 /* freplace program can return anything as its return value 15360 * depends on the to-be-replaced kernel func or bpf program. 15361 */ 15362 default: 15363 return 0; 15364 } 15365 15366 enforce_retval: 15367 if (reg->type != SCALAR_VALUE) { 15368 verbose(env, "%s the register R%d is not a known value (%s)\n", 15369 exit_ctx, regno, reg_type_str(env, reg->type)); 15370 return -EINVAL; 15371 } 15372 15373 err = mark_chain_precision(env, regno); 15374 if (err) 15375 return err; 15376 15377 if (!retval_range_within(range, reg)) { 15378 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 15379 if (!is_subprog && 15380 prog->expected_attach_type == BPF_LSM_CGROUP && 15381 prog_type == BPF_PROG_TYPE_LSM && 15382 !prog->aux->attach_func_proto->type) 15383 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 15384 return -EINVAL; 15385 } 15386 15387 if (!tnum_is_unknown(enforce_attach_type_range) && 15388 tnum_in(enforce_attach_type_range, reg->var_off)) 15389 env->prog->enforce_expected_attach_type = 1; 15390 return 0; 15391 } 15392 15393 /* non-recursive DFS pseudo code 15394 * 1 procedure DFS-iterative(G,v): 15395 * 2 label v as discovered 15396 * 3 let S be a stack 15397 * 4 S.push(v) 15398 * 5 while S is not empty 15399 * 6 t <- S.peek() 15400 * 7 if t is what we're looking for: 15401 * 8 return t 15402 * 9 for all edges e in G.adjacentEdges(t) do 15403 * 10 if edge e is already labelled 15404 * 11 continue with the next edge 15405 * 12 w <- G.adjacentVertex(t,e) 15406 * 13 if vertex w is not discovered and not explored 15407 * 14 label e as tree-edge 15408 * 15 label w as discovered 15409 * 16 S.push(w) 15410 * 17 continue at 5 15411 * 18 else if vertex w is discovered 15412 * 19 label e as back-edge 15413 * 20 else 15414 * 21 // vertex w is explored 15415 * 22 label e as forward- or cross-edge 15416 * 23 label t as explored 15417 * 24 S.pop() 15418 * 15419 * convention: 15420 * 0x10 - discovered 15421 * 0x11 - discovered and fall-through edge labelled 15422 * 0x12 - discovered and fall-through and branch edges labelled 15423 * 0x20 - explored 15424 */ 15425 15426 enum { 15427 DISCOVERED = 0x10, 15428 EXPLORED = 0x20, 15429 FALLTHROUGH = 1, 15430 BRANCH = 2, 15431 }; 15432 15433 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 15434 { 15435 env->insn_aux_data[idx].prune_point = true; 15436 } 15437 15438 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 15439 { 15440 return env->insn_aux_data[insn_idx].prune_point; 15441 } 15442 15443 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 15444 { 15445 env->insn_aux_data[idx].force_checkpoint = true; 15446 } 15447 15448 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 15449 { 15450 return env->insn_aux_data[insn_idx].force_checkpoint; 15451 } 15452 15453 static void mark_calls_callback(struct bpf_verifier_env *env, int idx) 15454 { 15455 env->insn_aux_data[idx].calls_callback = true; 15456 } 15457 15458 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx) 15459 { 15460 return env->insn_aux_data[insn_idx].calls_callback; 15461 } 15462 15463 enum { 15464 DONE_EXPLORING = 0, 15465 KEEP_EXPLORING = 1, 15466 }; 15467 15468 /* t, w, e - match pseudo-code above: 15469 * t - index of current instruction 15470 * w - next instruction 15471 * e - edge 15472 */ 15473 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 15474 { 15475 int *insn_stack = env->cfg.insn_stack; 15476 int *insn_state = env->cfg.insn_state; 15477 15478 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 15479 return DONE_EXPLORING; 15480 15481 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 15482 return DONE_EXPLORING; 15483 15484 if (w < 0 || w >= env->prog->len) { 15485 verbose_linfo(env, t, "%d: ", t); 15486 verbose(env, "jump out of range from insn %d to %d\n", t, w); 15487 return -EINVAL; 15488 } 15489 15490 if (e == BRANCH) { 15491 /* mark branch target for state pruning */ 15492 mark_prune_point(env, w); 15493 mark_jmp_point(env, w); 15494 } 15495 15496 if (insn_state[w] == 0) { 15497 /* tree-edge */ 15498 insn_state[t] = DISCOVERED | e; 15499 insn_state[w] = DISCOVERED; 15500 if (env->cfg.cur_stack >= env->prog->len) 15501 return -E2BIG; 15502 insn_stack[env->cfg.cur_stack++] = w; 15503 return KEEP_EXPLORING; 15504 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 15505 if (env->bpf_capable) 15506 return DONE_EXPLORING; 15507 verbose_linfo(env, t, "%d: ", t); 15508 verbose_linfo(env, w, "%d: ", w); 15509 verbose(env, "back-edge from insn %d to %d\n", t, w); 15510 return -EINVAL; 15511 } else if (insn_state[w] == EXPLORED) { 15512 /* forward- or cross-edge */ 15513 insn_state[t] = DISCOVERED | e; 15514 } else { 15515 verbose(env, "insn state internal bug\n"); 15516 return -EFAULT; 15517 } 15518 return DONE_EXPLORING; 15519 } 15520 15521 static int visit_func_call_insn(int t, struct bpf_insn *insns, 15522 struct bpf_verifier_env *env, 15523 bool visit_callee) 15524 { 15525 int ret, insn_sz; 15526 15527 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 15528 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 15529 if (ret) 15530 return ret; 15531 15532 mark_prune_point(env, t + insn_sz); 15533 /* when we exit from subprog, we need to record non-linear history */ 15534 mark_jmp_point(env, t + insn_sz); 15535 15536 if (visit_callee) { 15537 mark_prune_point(env, t); 15538 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env); 15539 } 15540 return ret; 15541 } 15542 15543 /* Visits the instruction at index t and returns one of the following: 15544 * < 0 - an error occurred 15545 * DONE_EXPLORING - the instruction was fully explored 15546 * KEEP_EXPLORING - there is still work to be done before it is fully explored 15547 */ 15548 static int visit_insn(int t, struct bpf_verifier_env *env) 15549 { 15550 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 15551 int ret, off, insn_sz; 15552 15553 if (bpf_pseudo_func(insn)) 15554 return visit_func_call_insn(t, insns, env, true); 15555 15556 /* All non-branch instructions have a single fall-through edge. */ 15557 if (BPF_CLASS(insn->code) != BPF_JMP && 15558 BPF_CLASS(insn->code) != BPF_JMP32) { 15559 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 15560 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 15561 } 15562 15563 switch (BPF_OP(insn->code)) { 15564 case BPF_EXIT: 15565 return DONE_EXPLORING; 15566 15567 case BPF_CALL: 15568 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback) 15569 /* Mark this call insn as a prune point to trigger 15570 * is_state_visited() check before call itself is 15571 * processed by __check_func_call(). Otherwise new 15572 * async state will be pushed for further exploration. 15573 */ 15574 mark_prune_point(env, t); 15575 /* For functions that invoke callbacks it is not known how many times 15576 * callback would be called. Verifier models callback calling functions 15577 * by repeatedly visiting callback bodies and returning to origin call 15578 * instruction. 15579 * In order to stop such iteration verifier needs to identify when a 15580 * state identical some state from a previous iteration is reached. 15581 * Check below forces creation of checkpoint before callback calling 15582 * instruction to allow search for such identical states. 15583 */ 15584 if (is_sync_callback_calling_insn(insn)) { 15585 mark_calls_callback(env, t); 15586 mark_force_checkpoint(env, t); 15587 mark_prune_point(env, t); 15588 mark_jmp_point(env, t); 15589 } 15590 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 15591 struct bpf_kfunc_call_arg_meta meta; 15592 15593 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 15594 if (ret == 0 && is_iter_next_kfunc(&meta)) { 15595 mark_prune_point(env, t); 15596 /* Checking and saving state checkpoints at iter_next() call 15597 * is crucial for fast convergence of open-coded iterator loop 15598 * logic, so we need to force it. If we don't do that, 15599 * is_state_visited() might skip saving a checkpoint, causing 15600 * unnecessarily long sequence of not checkpointed 15601 * instructions and jumps, leading to exhaustion of jump 15602 * history buffer, and potentially other undesired outcomes. 15603 * It is expected that with correct open-coded iterators 15604 * convergence will happen quickly, so we don't run a risk of 15605 * exhausting memory. 15606 */ 15607 mark_force_checkpoint(env, t); 15608 } 15609 } 15610 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 15611 15612 case BPF_JA: 15613 if (BPF_SRC(insn->code) != BPF_K) 15614 return -EINVAL; 15615 15616 if (BPF_CLASS(insn->code) == BPF_JMP) 15617 off = insn->off; 15618 else 15619 off = insn->imm; 15620 15621 /* unconditional jump with single edge */ 15622 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 15623 if (ret) 15624 return ret; 15625 15626 mark_prune_point(env, t + off + 1); 15627 mark_jmp_point(env, t + off + 1); 15628 15629 return ret; 15630 15631 default: 15632 /* conditional jump with two edges */ 15633 mark_prune_point(env, t); 15634 15635 ret = push_insn(t, t + 1, FALLTHROUGH, env); 15636 if (ret) 15637 return ret; 15638 15639 return push_insn(t, t + insn->off + 1, BRANCH, env); 15640 } 15641 } 15642 15643 /* non-recursive depth-first-search to detect loops in BPF program 15644 * loop == back-edge in directed graph 15645 */ 15646 static int check_cfg(struct bpf_verifier_env *env) 15647 { 15648 int insn_cnt = env->prog->len; 15649 int *insn_stack, *insn_state; 15650 int ex_insn_beg, i, ret = 0; 15651 bool ex_done = false; 15652 15653 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15654 if (!insn_state) 15655 return -ENOMEM; 15656 15657 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15658 if (!insn_stack) { 15659 kvfree(insn_state); 15660 return -ENOMEM; 15661 } 15662 15663 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 15664 insn_stack[0] = 0; /* 0 is the first instruction */ 15665 env->cfg.cur_stack = 1; 15666 15667 walk_cfg: 15668 while (env->cfg.cur_stack > 0) { 15669 int t = insn_stack[env->cfg.cur_stack - 1]; 15670 15671 ret = visit_insn(t, env); 15672 switch (ret) { 15673 case DONE_EXPLORING: 15674 insn_state[t] = EXPLORED; 15675 env->cfg.cur_stack--; 15676 break; 15677 case KEEP_EXPLORING: 15678 break; 15679 default: 15680 if (ret > 0) { 15681 verbose(env, "visit_insn internal bug\n"); 15682 ret = -EFAULT; 15683 } 15684 goto err_free; 15685 } 15686 } 15687 15688 if (env->cfg.cur_stack < 0) { 15689 verbose(env, "pop stack internal bug\n"); 15690 ret = -EFAULT; 15691 goto err_free; 15692 } 15693 15694 if (env->exception_callback_subprog && !ex_done) { 15695 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start; 15696 15697 insn_state[ex_insn_beg] = DISCOVERED; 15698 insn_stack[0] = ex_insn_beg; 15699 env->cfg.cur_stack = 1; 15700 ex_done = true; 15701 goto walk_cfg; 15702 } 15703 15704 for (i = 0; i < insn_cnt; i++) { 15705 struct bpf_insn *insn = &env->prog->insnsi[i]; 15706 15707 if (insn_state[i] != EXPLORED) { 15708 verbose(env, "unreachable insn %d\n", i); 15709 ret = -EINVAL; 15710 goto err_free; 15711 } 15712 if (bpf_is_ldimm64(insn)) { 15713 if (insn_state[i + 1] != 0) { 15714 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 15715 ret = -EINVAL; 15716 goto err_free; 15717 } 15718 i++; /* skip second half of ldimm64 */ 15719 } 15720 } 15721 ret = 0; /* cfg looks good */ 15722 15723 err_free: 15724 kvfree(insn_state); 15725 kvfree(insn_stack); 15726 env->cfg.insn_state = env->cfg.insn_stack = NULL; 15727 return ret; 15728 } 15729 15730 static int check_abnormal_return(struct bpf_verifier_env *env) 15731 { 15732 int i; 15733 15734 for (i = 1; i < env->subprog_cnt; i++) { 15735 if (env->subprog_info[i].has_ld_abs) { 15736 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 15737 return -EINVAL; 15738 } 15739 if (env->subprog_info[i].has_tail_call) { 15740 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 15741 return -EINVAL; 15742 } 15743 } 15744 return 0; 15745 } 15746 15747 /* The minimum supported BTF func info size */ 15748 #define MIN_BPF_FUNCINFO_SIZE 8 15749 #define MAX_FUNCINFO_REC_SIZE 252 15750 15751 static int check_btf_func_early(struct bpf_verifier_env *env, 15752 const union bpf_attr *attr, 15753 bpfptr_t uattr) 15754 { 15755 u32 krec_size = sizeof(struct bpf_func_info); 15756 const struct btf_type *type, *func_proto; 15757 u32 i, nfuncs, urec_size, min_size; 15758 struct bpf_func_info *krecord; 15759 struct bpf_prog *prog; 15760 const struct btf *btf; 15761 u32 prev_offset = 0; 15762 bpfptr_t urecord; 15763 int ret = -ENOMEM; 15764 15765 nfuncs = attr->func_info_cnt; 15766 if (!nfuncs) { 15767 if (check_abnormal_return(env)) 15768 return -EINVAL; 15769 return 0; 15770 } 15771 15772 urec_size = attr->func_info_rec_size; 15773 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 15774 urec_size > MAX_FUNCINFO_REC_SIZE || 15775 urec_size % sizeof(u32)) { 15776 verbose(env, "invalid func info rec size %u\n", urec_size); 15777 return -EINVAL; 15778 } 15779 15780 prog = env->prog; 15781 btf = prog->aux->btf; 15782 15783 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15784 min_size = min_t(u32, krec_size, urec_size); 15785 15786 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 15787 if (!krecord) 15788 return -ENOMEM; 15789 15790 for (i = 0; i < nfuncs; i++) { 15791 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 15792 if (ret) { 15793 if (ret == -E2BIG) { 15794 verbose(env, "nonzero tailing record in func info"); 15795 /* set the size kernel expects so loader can zero 15796 * out the rest of the record. 15797 */ 15798 if (copy_to_bpfptr_offset(uattr, 15799 offsetof(union bpf_attr, func_info_rec_size), 15800 &min_size, sizeof(min_size))) 15801 ret = -EFAULT; 15802 } 15803 goto err_free; 15804 } 15805 15806 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 15807 ret = -EFAULT; 15808 goto err_free; 15809 } 15810 15811 /* check insn_off */ 15812 ret = -EINVAL; 15813 if (i == 0) { 15814 if (krecord[i].insn_off) { 15815 verbose(env, 15816 "nonzero insn_off %u for the first func info record", 15817 krecord[i].insn_off); 15818 goto err_free; 15819 } 15820 } else if (krecord[i].insn_off <= prev_offset) { 15821 verbose(env, 15822 "same or smaller insn offset (%u) than previous func info record (%u)", 15823 krecord[i].insn_off, prev_offset); 15824 goto err_free; 15825 } 15826 15827 /* check type_id */ 15828 type = btf_type_by_id(btf, krecord[i].type_id); 15829 if (!type || !btf_type_is_func(type)) { 15830 verbose(env, "invalid type id %d in func info", 15831 krecord[i].type_id); 15832 goto err_free; 15833 } 15834 15835 func_proto = btf_type_by_id(btf, type->type); 15836 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 15837 /* btf_func_check() already verified it during BTF load */ 15838 goto err_free; 15839 15840 prev_offset = krecord[i].insn_off; 15841 bpfptr_add(&urecord, urec_size); 15842 } 15843 15844 prog->aux->func_info = krecord; 15845 prog->aux->func_info_cnt = nfuncs; 15846 return 0; 15847 15848 err_free: 15849 kvfree(krecord); 15850 return ret; 15851 } 15852 15853 static int check_btf_func(struct bpf_verifier_env *env, 15854 const union bpf_attr *attr, 15855 bpfptr_t uattr) 15856 { 15857 const struct btf_type *type, *func_proto, *ret_type; 15858 u32 i, nfuncs, urec_size; 15859 struct bpf_func_info *krecord; 15860 struct bpf_func_info_aux *info_aux = NULL; 15861 struct bpf_prog *prog; 15862 const struct btf *btf; 15863 bpfptr_t urecord; 15864 bool scalar_return; 15865 int ret = -ENOMEM; 15866 15867 nfuncs = attr->func_info_cnt; 15868 if (!nfuncs) { 15869 if (check_abnormal_return(env)) 15870 return -EINVAL; 15871 return 0; 15872 } 15873 if (nfuncs != env->subprog_cnt) { 15874 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 15875 return -EINVAL; 15876 } 15877 15878 urec_size = attr->func_info_rec_size; 15879 15880 prog = env->prog; 15881 btf = prog->aux->btf; 15882 15883 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15884 15885 krecord = prog->aux->func_info; 15886 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 15887 if (!info_aux) 15888 return -ENOMEM; 15889 15890 for (i = 0; i < nfuncs; i++) { 15891 /* check insn_off */ 15892 ret = -EINVAL; 15893 15894 if (env->subprog_info[i].start != krecord[i].insn_off) { 15895 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 15896 goto err_free; 15897 } 15898 15899 /* Already checked type_id */ 15900 type = btf_type_by_id(btf, krecord[i].type_id); 15901 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 15902 /* Already checked func_proto */ 15903 func_proto = btf_type_by_id(btf, type->type); 15904 15905 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 15906 scalar_return = 15907 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 15908 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 15909 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 15910 goto err_free; 15911 } 15912 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 15913 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 15914 goto err_free; 15915 } 15916 15917 bpfptr_add(&urecord, urec_size); 15918 } 15919 15920 prog->aux->func_info_aux = info_aux; 15921 return 0; 15922 15923 err_free: 15924 kfree(info_aux); 15925 return ret; 15926 } 15927 15928 static void adjust_btf_func(struct bpf_verifier_env *env) 15929 { 15930 struct bpf_prog_aux *aux = env->prog->aux; 15931 int i; 15932 15933 if (!aux->func_info) 15934 return; 15935 15936 /* func_info is not available for hidden subprogs */ 15937 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 15938 aux->func_info[i].insn_off = env->subprog_info[i].start; 15939 } 15940 15941 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 15942 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 15943 15944 static int check_btf_line(struct bpf_verifier_env *env, 15945 const union bpf_attr *attr, 15946 bpfptr_t uattr) 15947 { 15948 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 15949 struct bpf_subprog_info *sub; 15950 struct bpf_line_info *linfo; 15951 struct bpf_prog *prog; 15952 const struct btf *btf; 15953 bpfptr_t ulinfo; 15954 int err; 15955 15956 nr_linfo = attr->line_info_cnt; 15957 if (!nr_linfo) 15958 return 0; 15959 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 15960 return -EINVAL; 15961 15962 rec_size = attr->line_info_rec_size; 15963 if (rec_size < MIN_BPF_LINEINFO_SIZE || 15964 rec_size > MAX_LINEINFO_REC_SIZE || 15965 rec_size & (sizeof(u32) - 1)) 15966 return -EINVAL; 15967 15968 /* Need to zero it in case the userspace may 15969 * pass in a smaller bpf_line_info object. 15970 */ 15971 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 15972 GFP_KERNEL | __GFP_NOWARN); 15973 if (!linfo) 15974 return -ENOMEM; 15975 15976 prog = env->prog; 15977 btf = prog->aux->btf; 15978 15979 s = 0; 15980 sub = env->subprog_info; 15981 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 15982 expected_size = sizeof(struct bpf_line_info); 15983 ncopy = min_t(u32, expected_size, rec_size); 15984 for (i = 0; i < nr_linfo; i++) { 15985 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 15986 if (err) { 15987 if (err == -E2BIG) { 15988 verbose(env, "nonzero tailing record in line_info"); 15989 if (copy_to_bpfptr_offset(uattr, 15990 offsetof(union bpf_attr, line_info_rec_size), 15991 &expected_size, sizeof(expected_size))) 15992 err = -EFAULT; 15993 } 15994 goto err_free; 15995 } 15996 15997 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 15998 err = -EFAULT; 15999 goto err_free; 16000 } 16001 16002 /* 16003 * Check insn_off to ensure 16004 * 1) strictly increasing AND 16005 * 2) bounded by prog->len 16006 * 16007 * The linfo[0].insn_off == 0 check logically falls into 16008 * the later "missing bpf_line_info for func..." case 16009 * because the first linfo[0].insn_off must be the 16010 * first sub also and the first sub must have 16011 * subprog_info[0].start == 0. 16012 */ 16013 if ((i && linfo[i].insn_off <= prev_offset) || 16014 linfo[i].insn_off >= prog->len) { 16015 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 16016 i, linfo[i].insn_off, prev_offset, 16017 prog->len); 16018 err = -EINVAL; 16019 goto err_free; 16020 } 16021 16022 if (!prog->insnsi[linfo[i].insn_off].code) { 16023 verbose(env, 16024 "Invalid insn code at line_info[%u].insn_off\n", 16025 i); 16026 err = -EINVAL; 16027 goto err_free; 16028 } 16029 16030 if (!btf_name_by_offset(btf, linfo[i].line_off) || 16031 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 16032 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 16033 err = -EINVAL; 16034 goto err_free; 16035 } 16036 16037 if (s != env->subprog_cnt) { 16038 if (linfo[i].insn_off == sub[s].start) { 16039 sub[s].linfo_idx = i; 16040 s++; 16041 } else if (sub[s].start < linfo[i].insn_off) { 16042 verbose(env, "missing bpf_line_info for func#%u\n", s); 16043 err = -EINVAL; 16044 goto err_free; 16045 } 16046 } 16047 16048 prev_offset = linfo[i].insn_off; 16049 bpfptr_add(&ulinfo, rec_size); 16050 } 16051 16052 if (s != env->subprog_cnt) { 16053 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 16054 env->subprog_cnt - s, s); 16055 err = -EINVAL; 16056 goto err_free; 16057 } 16058 16059 prog->aux->linfo = linfo; 16060 prog->aux->nr_linfo = nr_linfo; 16061 16062 return 0; 16063 16064 err_free: 16065 kvfree(linfo); 16066 return err; 16067 } 16068 16069 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 16070 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 16071 16072 static int check_core_relo(struct bpf_verifier_env *env, 16073 const union bpf_attr *attr, 16074 bpfptr_t uattr) 16075 { 16076 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 16077 struct bpf_core_relo core_relo = {}; 16078 struct bpf_prog *prog = env->prog; 16079 const struct btf *btf = prog->aux->btf; 16080 struct bpf_core_ctx ctx = { 16081 .log = &env->log, 16082 .btf = btf, 16083 }; 16084 bpfptr_t u_core_relo; 16085 int err; 16086 16087 nr_core_relo = attr->core_relo_cnt; 16088 if (!nr_core_relo) 16089 return 0; 16090 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 16091 return -EINVAL; 16092 16093 rec_size = attr->core_relo_rec_size; 16094 if (rec_size < MIN_CORE_RELO_SIZE || 16095 rec_size > MAX_CORE_RELO_SIZE || 16096 rec_size % sizeof(u32)) 16097 return -EINVAL; 16098 16099 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 16100 expected_size = sizeof(struct bpf_core_relo); 16101 ncopy = min_t(u32, expected_size, rec_size); 16102 16103 /* Unlike func_info and line_info, copy and apply each CO-RE 16104 * relocation record one at a time. 16105 */ 16106 for (i = 0; i < nr_core_relo; i++) { 16107 /* future proofing when sizeof(bpf_core_relo) changes */ 16108 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 16109 if (err) { 16110 if (err == -E2BIG) { 16111 verbose(env, "nonzero tailing record in core_relo"); 16112 if (copy_to_bpfptr_offset(uattr, 16113 offsetof(union bpf_attr, core_relo_rec_size), 16114 &expected_size, sizeof(expected_size))) 16115 err = -EFAULT; 16116 } 16117 break; 16118 } 16119 16120 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 16121 err = -EFAULT; 16122 break; 16123 } 16124 16125 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 16126 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 16127 i, core_relo.insn_off, prog->len); 16128 err = -EINVAL; 16129 break; 16130 } 16131 16132 err = bpf_core_apply(&ctx, &core_relo, i, 16133 &prog->insnsi[core_relo.insn_off / 8]); 16134 if (err) 16135 break; 16136 bpfptr_add(&u_core_relo, rec_size); 16137 } 16138 return err; 16139 } 16140 16141 static int check_btf_info_early(struct bpf_verifier_env *env, 16142 const union bpf_attr *attr, 16143 bpfptr_t uattr) 16144 { 16145 struct btf *btf; 16146 int err; 16147 16148 if (!attr->func_info_cnt && !attr->line_info_cnt) { 16149 if (check_abnormal_return(env)) 16150 return -EINVAL; 16151 return 0; 16152 } 16153 16154 btf = btf_get_by_fd(attr->prog_btf_fd); 16155 if (IS_ERR(btf)) 16156 return PTR_ERR(btf); 16157 if (btf_is_kernel(btf)) { 16158 btf_put(btf); 16159 return -EACCES; 16160 } 16161 env->prog->aux->btf = btf; 16162 16163 err = check_btf_func_early(env, attr, uattr); 16164 if (err) 16165 return err; 16166 return 0; 16167 } 16168 16169 static int check_btf_info(struct bpf_verifier_env *env, 16170 const union bpf_attr *attr, 16171 bpfptr_t uattr) 16172 { 16173 int err; 16174 16175 if (!attr->func_info_cnt && !attr->line_info_cnt) { 16176 if (check_abnormal_return(env)) 16177 return -EINVAL; 16178 return 0; 16179 } 16180 16181 err = check_btf_func(env, attr, uattr); 16182 if (err) 16183 return err; 16184 16185 err = check_btf_line(env, attr, uattr); 16186 if (err) 16187 return err; 16188 16189 err = check_core_relo(env, attr, uattr); 16190 if (err) 16191 return err; 16192 16193 return 0; 16194 } 16195 16196 /* check %cur's range satisfies %old's */ 16197 static bool range_within(struct bpf_reg_state *old, 16198 struct bpf_reg_state *cur) 16199 { 16200 return old->umin_value <= cur->umin_value && 16201 old->umax_value >= cur->umax_value && 16202 old->smin_value <= cur->smin_value && 16203 old->smax_value >= cur->smax_value && 16204 old->u32_min_value <= cur->u32_min_value && 16205 old->u32_max_value >= cur->u32_max_value && 16206 old->s32_min_value <= cur->s32_min_value && 16207 old->s32_max_value >= cur->s32_max_value; 16208 } 16209 16210 /* If in the old state two registers had the same id, then they need to have 16211 * the same id in the new state as well. But that id could be different from 16212 * the old state, so we need to track the mapping from old to new ids. 16213 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 16214 * regs with old id 5 must also have new id 9 for the new state to be safe. But 16215 * regs with a different old id could still have new id 9, we don't care about 16216 * that. 16217 * So we look through our idmap to see if this old id has been seen before. If 16218 * so, we require the new id to match; otherwise, we add the id pair to the map. 16219 */ 16220 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 16221 { 16222 struct bpf_id_pair *map = idmap->map; 16223 unsigned int i; 16224 16225 /* either both IDs should be set or both should be zero */ 16226 if (!!old_id != !!cur_id) 16227 return false; 16228 16229 if (old_id == 0) /* cur_id == 0 as well */ 16230 return true; 16231 16232 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 16233 if (!map[i].old) { 16234 /* Reached an empty slot; haven't seen this id before */ 16235 map[i].old = old_id; 16236 map[i].cur = cur_id; 16237 return true; 16238 } 16239 if (map[i].old == old_id) 16240 return map[i].cur == cur_id; 16241 if (map[i].cur == cur_id) 16242 return false; 16243 } 16244 /* We ran out of idmap slots, which should be impossible */ 16245 WARN_ON_ONCE(1); 16246 return false; 16247 } 16248 16249 /* Similar to check_ids(), but allocate a unique temporary ID 16250 * for 'old_id' or 'cur_id' of zero. 16251 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 16252 */ 16253 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 16254 { 16255 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 16256 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 16257 16258 return check_ids(old_id, cur_id, idmap); 16259 } 16260 16261 static void clean_func_state(struct bpf_verifier_env *env, 16262 struct bpf_func_state *st) 16263 { 16264 enum bpf_reg_liveness live; 16265 int i, j; 16266 16267 for (i = 0; i < BPF_REG_FP; i++) { 16268 live = st->regs[i].live; 16269 /* liveness must not touch this register anymore */ 16270 st->regs[i].live |= REG_LIVE_DONE; 16271 if (!(live & REG_LIVE_READ)) 16272 /* since the register is unused, clear its state 16273 * to make further comparison simpler 16274 */ 16275 __mark_reg_not_init(env, &st->regs[i]); 16276 } 16277 16278 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 16279 live = st->stack[i].spilled_ptr.live; 16280 /* liveness must not touch this stack slot anymore */ 16281 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 16282 if (!(live & REG_LIVE_READ)) { 16283 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 16284 for (j = 0; j < BPF_REG_SIZE; j++) 16285 st->stack[i].slot_type[j] = STACK_INVALID; 16286 } 16287 } 16288 } 16289 16290 static void clean_verifier_state(struct bpf_verifier_env *env, 16291 struct bpf_verifier_state *st) 16292 { 16293 int i; 16294 16295 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 16296 /* all regs in this state in all frames were already marked */ 16297 return; 16298 16299 for (i = 0; i <= st->curframe; i++) 16300 clean_func_state(env, st->frame[i]); 16301 } 16302 16303 /* the parentage chains form a tree. 16304 * the verifier states are added to state lists at given insn and 16305 * pushed into state stack for future exploration. 16306 * when the verifier reaches bpf_exit insn some of the verifer states 16307 * stored in the state lists have their final liveness state already, 16308 * but a lot of states will get revised from liveness point of view when 16309 * the verifier explores other branches. 16310 * Example: 16311 * 1: r0 = 1 16312 * 2: if r1 == 100 goto pc+1 16313 * 3: r0 = 2 16314 * 4: exit 16315 * when the verifier reaches exit insn the register r0 in the state list of 16316 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 16317 * of insn 2 and goes exploring further. At the insn 4 it will walk the 16318 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 16319 * 16320 * Since the verifier pushes the branch states as it sees them while exploring 16321 * the program the condition of walking the branch instruction for the second 16322 * time means that all states below this branch were already explored and 16323 * their final liveness marks are already propagated. 16324 * Hence when the verifier completes the search of state list in is_state_visited() 16325 * we can call this clean_live_states() function to mark all liveness states 16326 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 16327 * will not be used. 16328 * This function also clears the registers and stack for states that !READ 16329 * to simplify state merging. 16330 * 16331 * Important note here that walking the same branch instruction in the callee 16332 * doesn't meant that the states are DONE. The verifier has to compare 16333 * the callsites 16334 */ 16335 static void clean_live_states(struct bpf_verifier_env *env, int insn, 16336 struct bpf_verifier_state *cur) 16337 { 16338 struct bpf_verifier_state_list *sl; 16339 16340 sl = *explored_state(env, insn); 16341 while (sl) { 16342 if (sl->state.branches) 16343 goto next; 16344 if (sl->state.insn_idx != insn || 16345 !same_callsites(&sl->state, cur)) 16346 goto next; 16347 clean_verifier_state(env, &sl->state); 16348 next: 16349 sl = sl->next; 16350 } 16351 } 16352 16353 static bool regs_exact(const struct bpf_reg_state *rold, 16354 const struct bpf_reg_state *rcur, 16355 struct bpf_idmap *idmap) 16356 { 16357 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16358 check_ids(rold->id, rcur->id, idmap) && 16359 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16360 } 16361 16362 /* Returns true if (rold safe implies rcur safe) */ 16363 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 16364 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact) 16365 { 16366 if (exact) 16367 return regs_exact(rold, rcur, idmap); 16368 16369 if (!(rold->live & REG_LIVE_READ)) 16370 /* explored state didn't use this */ 16371 return true; 16372 if (rold->type == NOT_INIT) 16373 /* explored state can't have used this */ 16374 return true; 16375 if (rcur->type == NOT_INIT) 16376 return false; 16377 16378 /* Enforce that register types have to match exactly, including their 16379 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 16380 * rule. 16381 * 16382 * One can make a point that using a pointer register as unbounded 16383 * SCALAR would be technically acceptable, but this could lead to 16384 * pointer leaks because scalars are allowed to leak while pointers 16385 * are not. We could make this safe in special cases if root is 16386 * calling us, but it's probably not worth the hassle. 16387 * 16388 * Also, register types that are *not* MAYBE_NULL could technically be 16389 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 16390 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 16391 * to the same map). 16392 * However, if the old MAYBE_NULL register then got NULL checked, 16393 * doing so could have affected others with the same id, and we can't 16394 * check for that because we lost the id when we converted to 16395 * a non-MAYBE_NULL variant. 16396 * So, as a general rule we don't allow mixing MAYBE_NULL and 16397 * non-MAYBE_NULL registers as well. 16398 */ 16399 if (rold->type != rcur->type) 16400 return false; 16401 16402 switch (base_type(rold->type)) { 16403 case SCALAR_VALUE: 16404 if (env->explore_alu_limits) { 16405 /* explore_alu_limits disables tnum_in() and range_within() 16406 * logic and requires everything to be strict 16407 */ 16408 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16409 check_scalar_ids(rold->id, rcur->id, idmap); 16410 } 16411 if (!rold->precise) 16412 return true; 16413 /* Why check_ids() for scalar registers? 16414 * 16415 * Consider the following BPF code: 16416 * 1: r6 = ... unbound scalar, ID=a ... 16417 * 2: r7 = ... unbound scalar, ID=b ... 16418 * 3: if (r6 > r7) goto +1 16419 * 4: r6 = r7 16420 * 5: if (r6 > X) goto ... 16421 * 6: ... memory operation using r7 ... 16422 * 16423 * First verification path is [1-6]: 16424 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 16425 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark 16426 * r7 <= X, because r6 and r7 share same id. 16427 * Next verification path is [1-4, 6]. 16428 * 16429 * Instruction (6) would be reached in two states: 16430 * I. r6{.id=b}, r7{.id=b} via path 1-6; 16431 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 16432 * 16433 * Use check_ids() to distinguish these states. 16434 * --- 16435 * Also verify that new value satisfies old value range knowledge. 16436 */ 16437 return range_within(rold, rcur) && 16438 tnum_in(rold->var_off, rcur->var_off) && 16439 check_scalar_ids(rold->id, rcur->id, idmap); 16440 case PTR_TO_MAP_KEY: 16441 case PTR_TO_MAP_VALUE: 16442 case PTR_TO_MEM: 16443 case PTR_TO_BUF: 16444 case PTR_TO_TP_BUFFER: 16445 /* If the new min/max/var_off satisfy the old ones and 16446 * everything else matches, we are OK. 16447 */ 16448 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 16449 range_within(rold, rcur) && 16450 tnum_in(rold->var_off, rcur->var_off) && 16451 check_ids(rold->id, rcur->id, idmap) && 16452 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16453 case PTR_TO_PACKET_META: 16454 case PTR_TO_PACKET: 16455 /* We must have at least as much range as the old ptr 16456 * did, so that any accesses which were safe before are 16457 * still safe. This is true even if old range < old off, 16458 * since someone could have accessed through (ptr - k), or 16459 * even done ptr -= k in a register, to get a safe access. 16460 */ 16461 if (rold->range > rcur->range) 16462 return false; 16463 /* If the offsets don't match, we can't trust our alignment; 16464 * nor can we be sure that we won't fall out of range. 16465 */ 16466 if (rold->off != rcur->off) 16467 return false; 16468 /* id relations must be preserved */ 16469 if (!check_ids(rold->id, rcur->id, idmap)) 16470 return false; 16471 /* new val must satisfy old val knowledge */ 16472 return range_within(rold, rcur) && 16473 tnum_in(rold->var_off, rcur->var_off); 16474 case PTR_TO_STACK: 16475 /* two stack pointers are equal only if they're pointing to 16476 * the same stack frame, since fp-8 in foo != fp-8 in bar 16477 */ 16478 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 16479 default: 16480 return regs_exact(rold, rcur, idmap); 16481 } 16482 } 16483 16484 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 16485 struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact) 16486 { 16487 int i, spi; 16488 16489 /* walk slots of the explored stack and ignore any additional 16490 * slots in the current stack, since explored(safe) state 16491 * didn't use them 16492 */ 16493 for (i = 0; i < old->allocated_stack; i++) { 16494 struct bpf_reg_state *old_reg, *cur_reg; 16495 16496 spi = i / BPF_REG_SIZE; 16497 16498 if (exact && 16499 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16500 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16501 return false; 16502 16503 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) { 16504 i += BPF_REG_SIZE - 1; 16505 /* explored state didn't use this */ 16506 continue; 16507 } 16508 16509 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 16510 continue; 16511 16512 if (env->allow_uninit_stack && 16513 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 16514 continue; 16515 16516 /* explored stack has more populated slots than current stack 16517 * and these slots were used 16518 */ 16519 if (i >= cur->allocated_stack) 16520 return false; 16521 16522 /* if old state was safe with misc data in the stack 16523 * it will be safe with zero-initialized stack. 16524 * The opposite is not true 16525 */ 16526 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 16527 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 16528 continue; 16529 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16530 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16531 /* Ex: old explored (safe) state has STACK_SPILL in 16532 * this stack slot, but current has STACK_MISC -> 16533 * this verifier states are not equivalent, 16534 * return false to continue verification of this path 16535 */ 16536 return false; 16537 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 16538 continue; 16539 /* Both old and cur are having same slot_type */ 16540 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 16541 case STACK_SPILL: 16542 /* when explored and current stack slot are both storing 16543 * spilled registers, check that stored pointers types 16544 * are the same as well. 16545 * Ex: explored safe path could have stored 16546 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 16547 * but current path has stored: 16548 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 16549 * such verifier states are not equivalent. 16550 * return false to continue verification of this path 16551 */ 16552 if (!regsafe(env, &old->stack[spi].spilled_ptr, 16553 &cur->stack[spi].spilled_ptr, idmap, exact)) 16554 return false; 16555 break; 16556 case STACK_DYNPTR: 16557 old_reg = &old->stack[spi].spilled_ptr; 16558 cur_reg = &cur->stack[spi].spilled_ptr; 16559 if (old_reg->dynptr.type != cur_reg->dynptr.type || 16560 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 16561 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16562 return false; 16563 break; 16564 case STACK_ITER: 16565 old_reg = &old->stack[spi].spilled_ptr; 16566 cur_reg = &cur->stack[spi].spilled_ptr; 16567 /* iter.depth is not compared between states as it 16568 * doesn't matter for correctness and would otherwise 16569 * prevent convergence; we maintain it only to prevent 16570 * infinite loop check triggering, see 16571 * iter_active_depths_differ() 16572 */ 16573 if (old_reg->iter.btf != cur_reg->iter.btf || 16574 old_reg->iter.btf_id != cur_reg->iter.btf_id || 16575 old_reg->iter.state != cur_reg->iter.state || 16576 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 16577 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16578 return false; 16579 break; 16580 case STACK_MISC: 16581 case STACK_ZERO: 16582 case STACK_INVALID: 16583 continue; 16584 /* Ensure that new unhandled slot types return false by default */ 16585 default: 16586 return false; 16587 } 16588 } 16589 return true; 16590 } 16591 16592 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 16593 struct bpf_idmap *idmap) 16594 { 16595 int i; 16596 16597 if (old->acquired_refs != cur->acquired_refs) 16598 return false; 16599 16600 for (i = 0; i < old->acquired_refs; i++) { 16601 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 16602 return false; 16603 } 16604 16605 return true; 16606 } 16607 16608 /* compare two verifier states 16609 * 16610 * all states stored in state_list are known to be valid, since 16611 * verifier reached 'bpf_exit' instruction through them 16612 * 16613 * this function is called when verifier exploring different branches of 16614 * execution popped from the state stack. If it sees an old state that has 16615 * more strict register state and more strict stack state then this execution 16616 * branch doesn't need to be explored further, since verifier already 16617 * concluded that more strict state leads to valid finish. 16618 * 16619 * Therefore two states are equivalent if register state is more conservative 16620 * and explored stack state is more conservative than the current one. 16621 * Example: 16622 * explored current 16623 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 16624 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 16625 * 16626 * In other words if current stack state (one being explored) has more 16627 * valid slots than old one that already passed validation, it means 16628 * the verifier can stop exploring and conclude that current state is valid too 16629 * 16630 * Similarly with registers. If explored state has register type as invalid 16631 * whereas register type in current state is meaningful, it means that 16632 * the current state will reach 'bpf_exit' instruction safely 16633 */ 16634 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 16635 struct bpf_func_state *cur, bool exact) 16636 { 16637 int i; 16638 16639 for (i = 0; i < MAX_BPF_REG; i++) 16640 if (!regsafe(env, &old->regs[i], &cur->regs[i], 16641 &env->idmap_scratch, exact)) 16642 return false; 16643 16644 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 16645 return false; 16646 16647 if (!refsafe(old, cur, &env->idmap_scratch)) 16648 return false; 16649 16650 return true; 16651 } 16652 16653 static void reset_idmap_scratch(struct bpf_verifier_env *env) 16654 { 16655 env->idmap_scratch.tmp_id_gen = env->id_gen; 16656 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 16657 } 16658 16659 static bool states_equal(struct bpf_verifier_env *env, 16660 struct bpf_verifier_state *old, 16661 struct bpf_verifier_state *cur, 16662 bool exact) 16663 { 16664 int i; 16665 16666 if (old->curframe != cur->curframe) 16667 return false; 16668 16669 reset_idmap_scratch(env); 16670 16671 /* Verification state from speculative execution simulation 16672 * must never prune a non-speculative execution one. 16673 */ 16674 if (old->speculative && !cur->speculative) 16675 return false; 16676 16677 if (old->active_lock.ptr != cur->active_lock.ptr) 16678 return false; 16679 16680 /* Old and cur active_lock's have to be either both present 16681 * or both absent. 16682 */ 16683 if (!!old->active_lock.id != !!cur->active_lock.id) 16684 return false; 16685 16686 if (old->active_lock.id && 16687 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch)) 16688 return false; 16689 16690 if (old->active_rcu_lock != cur->active_rcu_lock) 16691 return false; 16692 16693 /* for states to be equal callsites have to be the same 16694 * and all frame states need to be equivalent 16695 */ 16696 for (i = 0; i <= old->curframe; i++) { 16697 if (old->frame[i]->callsite != cur->frame[i]->callsite) 16698 return false; 16699 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact)) 16700 return false; 16701 } 16702 return true; 16703 } 16704 16705 /* Return 0 if no propagation happened. Return negative error code if error 16706 * happened. Otherwise, return the propagated bit. 16707 */ 16708 static int propagate_liveness_reg(struct bpf_verifier_env *env, 16709 struct bpf_reg_state *reg, 16710 struct bpf_reg_state *parent_reg) 16711 { 16712 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 16713 u8 flag = reg->live & REG_LIVE_READ; 16714 int err; 16715 16716 /* When comes here, read flags of PARENT_REG or REG could be any of 16717 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 16718 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 16719 */ 16720 if (parent_flag == REG_LIVE_READ64 || 16721 /* Or if there is no read flag from REG. */ 16722 !flag || 16723 /* Or if the read flag from REG is the same as PARENT_REG. */ 16724 parent_flag == flag) 16725 return 0; 16726 16727 err = mark_reg_read(env, reg, parent_reg, flag); 16728 if (err) 16729 return err; 16730 16731 return flag; 16732 } 16733 16734 /* A write screens off any subsequent reads; but write marks come from the 16735 * straight-line code between a state and its parent. When we arrive at an 16736 * equivalent state (jump target or such) we didn't arrive by the straight-line 16737 * code, so read marks in the state must propagate to the parent regardless 16738 * of the state's write marks. That's what 'parent == state->parent' comparison 16739 * in mark_reg_read() is for. 16740 */ 16741 static int propagate_liveness(struct bpf_verifier_env *env, 16742 const struct bpf_verifier_state *vstate, 16743 struct bpf_verifier_state *vparent) 16744 { 16745 struct bpf_reg_state *state_reg, *parent_reg; 16746 struct bpf_func_state *state, *parent; 16747 int i, frame, err = 0; 16748 16749 if (vparent->curframe != vstate->curframe) { 16750 WARN(1, "propagate_live: parent frame %d current frame %d\n", 16751 vparent->curframe, vstate->curframe); 16752 return -EFAULT; 16753 } 16754 /* Propagate read liveness of registers... */ 16755 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 16756 for (frame = 0; frame <= vstate->curframe; frame++) { 16757 parent = vparent->frame[frame]; 16758 state = vstate->frame[frame]; 16759 parent_reg = parent->regs; 16760 state_reg = state->regs; 16761 /* We don't need to worry about FP liveness, it's read-only */ 16762 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 16763 err = propagate_liveness_reg(env, &state_reg[i], 16764 &parent_reg[i]); 16765 if (err < 0) 16766 return err; 16767 if (err == REG_LIVE_READ64) 16768 mark_insn_zext(env, &parent_reg[i]); 16769 } 16770 16771 /* Propagate stack slots. */ 16772 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 16773 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 16774 parent_reg = &parent->stack[i].spilled_ptr; 16775 state_reg = &state->stack[i].spilled_ptr; 16776 err = propagate_liveness_reg(env, state_reg, 16777 parent_reg); 16778 if (err < 0) 16779 return err; 16780 } 16781 } 16782 return 0; 16783 } 16784 16785 /* find precise scalars in the previous equivalent state and 16786 * propagate them into the current state 16787 */ 16788 static int propagate_precision(struct bpf_verifier_env *env, 16789 const struct bpf_verifier_state *old) 16790 { 16791 struct bpf_reg_state *state_reg; 16792 struct bpf_func_state *state; 16793 int i, err = 0, fr; 16794 bool first; 16795 16796 for (fr = old->curframe; fr >= 0; fr--) { 16797 state = old->frame[fr]; 16798 state_reg = state->regs; 16799 first = true; 16800 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 16801 if (state_reg->type != SCALAR_VALUE || 16802 !state_reg->precise || 16803 !(state_reg->live & REG_LIVE_READ)) 16804 continue; 16805 if (env->log.level & BPF_LOG_LEVEL2) { 16806 if (first) 16807 verbose(env, "frame %d: propagating r%d", fr, i); 16808 else 16809 verbose(env, ",r%d", i); 16810 } 16811 bt_set_frame_reg(&env->bt, fr, i); 16812 first = false; 16813 } 16814 16815 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16816 if (!is_spilled_reg(&state->stack[i])) 16817 continue; 16818 state_reg = &state->stack[i].spilled_ptr; 16819 if (state_reg->type != SCALAR_VALUE || 16820 !state_reg->precise || 16821 !(state_reg->live & REG_LIVE_READ)) 16822 continue; 16823 if (env->log.level & BPF_LOG_LEVEL2) { 16824 if (first) 16825 verbose(env, "frame %d: propagating fp%d", 16826 fr, (-i - 1) * BPF_REG_SIZE); 16827 else 16828 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 16829 } 16830 bt_set_frame_slot(&env->bt, fr, i); 16831 first = false; 16832 } 16833 if (!first) 16834 verbose(env, "\n"); 16835 } 16836 16837 err = mark_chain_precision_batch(env); 16838 if (err < 0) 16839 return err; 16840 16841 return 0; 16842 } 16843 16844 static bool states_maybe_looping(struct bpf_verifier_state *old, 16845 struct bpf_verifier_state *cur) 16846 { 16847 struct bpf_func_state *fold, *fcur; 16848 int i, fr = cur->curframe; 16849 16850 if (old->curframe != fr) 16851 return false; 16852 16853 fold = old->frame[fr]; 16854 fcur = cur->frame[fr]; 16855 for (i = 0; i < MAX_BPF_REG; i++) 16856 if (memcmp(&fold->regs[i], &fcur->regs[i], 16857 offsetof(struct bpf_reg_state, parent))) 16858 return false; 16859 return true; 16860 } 16861 16862 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 16863 { 16864 return env->insn_aux_data[insn_idx].is_iter_next; 16865 } 16866 16867 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 16868 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 16869 * states to match, which otherwise would look like an infinite loop. So while 16870 * iter_next() calls are taken care of, we still need to be careful and 16871 * prevent erroneous and too eager declaration of "ininite loop", when 16872 * iterators are involved. 16873 * 16874 * Here's a situation in pseudo-BPF assembly form: 16875 * 16876 * 0: again: ; set up iter_next() call args 16877 * 1: r1 = &it ; <CHECKPOINT HERE> 16878 * 2: call bpf_iter_num_next ; this is iter_next() call 16879 * 3: if r0 == 0 goto done 16880 * 4: ... something useful here ... 16881 * 5: goto again ; another iteration 16882 * 6: done: 16883 * 7: r1 = &it 16884 * 8: call bpf_iter_num_destroy ; clean up iter state 16885 * 9: exit 16886 * 16887 * This is a typical loop. Let's assume that we have a prune point at 1:, 16888 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 16889 * again`, assuming other heuristics don't get in a way). 16890 * 16891 * When we first time come to 1:, let's say we have some state X. We proceed 16892 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 16893 * Now we come back to validate that forked ACTIVE state. We proceed through 16894 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 16895 * are converging. But the problem is that we don't know that yet, as this 16896 * convergence has to happen at iter_next() call site only. So if nothing is 16897 * done, at 1: verifier will use bounded loop logic and declare infinite 16898 * looping (and would be *technically* correct, if not for iterator's 16899 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 16900 * don't want that. So what we do in process_iter_next_call() when we go on 16901 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 16902 * a different iteration. So when we suspect an infinite loop, we additionally 16903 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 16904 * pretend we are not looping and wait for next iter_next() call. 16905 * 16906 * This only applies to ACTIVE state. In DRAINED state we don't expect to 16907 * loop, because that would actually mean infinite loop, as DRAINED state is 16908 * "sticky", and so we'll keep returning into the same instruction with the 16909 * same state (at least in one of possible code paths). 16910 * 16911 * This approach allows to keep infinite loop heuristic even in the face of 16912 * active iterator. E.g., C snippet below is and will be detected as 16913 * inifintely looping: 16914 * 16915 * struct bpf_iter_num it; 16916 * int *p, x; 16917 * 16918 * bpf_iter_num_new(&it, 0, 10); 16919 * while ((p = bpf_iter_num_next(&t))) { 16920 * x = p; 16921 * while (x--) {} // <<-- infinite loop here 16922 * } 16923 * 16924 */ 16925 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 16926 { 16927 struct bpf_reg_state *slot, *cur_slot; 16928 struct bpf_func_state *state; 16929 int i, fr; 16930 16931 for (fr = old->curframe; fr >= 0; fr--) { 16932 state = old->frame[fr]; 16933 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16934 if (state->stack[i].slot_type[0] != STACK_ITER) 16935 continue; 16936 16937 slot = &state->stack[i].spilled_ptr; 16938 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 16939 continue; 16940 16941 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 16942 if (cur_slot->iter.depth != slot->iter.depth) 16943 return true; 16944 } 16945 } 16946 return false; 16947 } 16948 16949 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 16950 { 16951 struct bpf_verifier_state_list *new_sl; 16952 struct bpf_verifier_state_list *sl, **pprev; 16953 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry; 16954 int i, j, n, err, states_cnt = 0; 16955 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx); 16956 bool add_new_state = force_new_state; 16957 bool force_exact; 16958 16959 /* bpf progs typically have pruning point every 4 instructions 16960 * http://vger.kernel.org/bpfconf2019.html#session-1 16961 * Do not add new state for future pruning if the verifier hasn't seen 16962 * at least 2 jumps and at least 8 instructions. 16963 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 16964 * In tests that amounts to up to 50% reduction into total verifier 16965 * memory consumption and 20% verifier time speedup. 16966 */ 16967 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 16968 env->insn_processed - env->prev_insn_processed >= 8) 16969 add_new_state = true; 16970 16971 pprev = explored_state(env, insn_idx); 16972 sl = *pprev; 16973 16974 clean_live_states(env, insn_idx, cur); 16975 16976 while (sl) { 16977 states_cnt++; 16978 if (sl->state.insn_idx != insn_idx) 16979 goto next; 16980 16981 if (sl->state.branches) { 16982 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 16983 16984 if (frame->in_async_callback_fn && 16985 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 16986 /* Different async_entry_cnt means that the verifier is 16987 * processing another entry into async callback. 16988 * Seeing the same state is not an indication of infinite 16989 * loop or infinite recursion. 16990 * But finding the same state doesn't mean that it's safe 16991 * to stop processing the current state. The previous state 16992 * hasn't yet reached bpf_exit, since state.branches > 0. 16993 * Checking in_async_callback_fn alone is not enough either. 16994 * Since the verifier still needs to catch infinite loops 16995 * inside async callbacks. 16996 */ 16997 goto skip_inf_loop_check; 16998 } 16999 /* BPF open-coded iterators loop detection is special. 17000 * states_maybe_looping() logic is too simplistic in detecting 17001 * states that *might* be equivalent, because it doesn't know 17002 * about ID remapping, so don't even perform it. 17003 * See process_iter_next_call() and iter_active_depths_differ() 17004 * for overview of the logic. When current and one of parent 17005 * states are detected as equivalent, it's a good thing: we prove 17006 * convergence and can stop simulating further iterations. 17007 * It's safe to assume that iterator loop will finish, taking into 17008 * account iter_next() contract of eventually returning 17009 * sticky NULL result. 17010 * 17011 * Note, that states have to be compared exactly in this case because 17012 * read and precision marks might not be finalized inside the loop. 17013 * E.g. as in the program below: 17014 * 17015 * 1. r7 = -16 17016 * 2. r6 = bpf_get_prandom_u32() 17017 * 3. while (bpf_iter_num_next(&fp[-8])) { 17018 * 4. if (r6 != 42) { 17019 * 5. r7 = -32 17020 * 6. r6 = bpf_get_prandom_u32() 17021 * 7. continue 17022 * 8. } 17023 * 9. r0 = r10 17024 * 10. r0 += r7 17025 * 11. r8 = *(u64 *)(r0 + 0) 17026 * 12. r6 = bpf_get_prandom_u32() 17027 * 13. } 17028 * 17029 * Here verifier would first visit path 1-3, create a checkpoint at 3 17030 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 17031 * not have read or precision mark for r7 yet, thus inexact states 17032 * comparison would discard current state with r7=-32 17033 * => unsafe memory access at 11 would not be caught. 17034 */ 17035 if (is_iter_next_insn(env, insn_idx)) { 17036 if (states_equal(env, &sl->state, cur, true)) { 17037 struct bpf_func_state *cur_frame; 17038 struct bpf_reg_state *iter_state, *iter_reg; 17039 int spi; 17040 17041 cur_frame = cur->frame[cur->curframe]; 17042 /* btf_check_iter_kfuncs() enforces that 17043 * iter state pointer is always the first arg 17044 */ 17045 iter_reg = &cur_frame->regs[BPF_REG_1]; 17046 /* current state is valid due to states_equal(), 17047 * so we can assume valid iter and reg state, 17048 * no need for extra (re-)validations 17049 */ 17050 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 17051 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 17052 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 17053 update_loop_entry(cur, &sl->state); 17054 goto hit; 17055 } 17056 } 17057 goto skip_inf_loop_check; 17058 } 17059 if (calls_callback(env, insn_idx)) { 17060 if (states_equal(env, &sl->state, cur, true)) 17061 goto hit; 17062 goto skip_inf_loop_check; 17063 } 17064 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 17065 if (states_maybe_looping(&sl->state, cur) && 17066 states_equal(env, &sl->state, cur, true) && 17067 !iter_active_depths_differ(&sl->state, cur) && 17068 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 17069 verbose_linfo(env, insn_idx, "; "); 17070 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 17071 verbose(env, "cur state:"); 17072 print_verifier_state(env, cur->frame[cur->curframe], true); 17073 verbose(env, "old state:"); 17074 print_verifier_state(env, sl->state.frame[cur->curframe], true); 17075 return -EINVAL; 17076 } 17077 /* if the verifier is processing a loop, avoid adding new state 17078 * too often, since different loop iterations have distinct 17079 * states and may not help future pruning. 17080 * This threshold shouldn't be too low to make sure that 17081 * a loop with large bound will be rejected quickly. 17082 * The most abusive loop will be: 17083 * r1 += 1 17084 * if r1 < 1000000 goto pc-2 17085 * 1M insn_procssed limit / 100 == 10k peak states. 17086 * This threshold shouldn't be too high either, since states 17087 * at the end of the loop are likely to be useful in pruning. 17088 */ 17089 skip_inf_loop_check: 17090 if (!force_new_state && 17091 env->jmps_processed - env->prev_jmps_processed < 20 && 17092 env->insn_processed - env->prev_insn_processed < 100) 17093 add_new_state = false; 17094 goto miss; 17095 } 17096 /* If sl->state is a part of a loop and this loop's entry is a part of 17097 * current verification path then states have to be compared exactly. 17098 * 'force_exact' is needed to catch the following case: 17099 * 17100 * initial Here state 'succ' was processed first, 17101 * | it was eventually tracked to produce a 17102 * V state identical to 'hdr'. 17103 * .---------> hdr All branches from 'succ' had been explored 17104 * | | and thus 'succ' has its .branches == 0. 17105 * | V 17106 * | .------... Suppose states 'cur' and 'succ' correspond 17107 * | | | to the same instruction + callsites. 17108 * | V V In such case it is necessary to check 17109 * | ... ... if 'succ' and 'cur' are states_equal(). 17110 * | | | If 'succ' and 'cur' are a part of the 17111 * | V V same loop exact flag has to be set. 17112 * | succ <- cur To check if that is the case, verify 17113 * | | if loop entry of 'succ' is in current 17114 * | V DFS path. 17115 * | ... 17116 * | | 17117 * '----' 17118 * 17119 * Additional details are in the comment before get_loop_entry(). 17120 */ 17121 loop_entry = get_loop_entry(&sl->state); 17122 force_exact = loop_entry && loop_entry->branches > 0; 17123 if (states_equal(env, &sl->state, cur, force_exact)) { 17124 if (force_exact) 17125 update_loop_entry(cur, loop_entry); 17126 hit: 17127 sl->hit_cnt++; 17128 /* reached equivalent register/stack state, 17129 * prune the search. 17130 * Registers read by the continuation are read by us. 17131 * If we have any write marks in env->cur_state, they 17132 * will prevent corresponding reads in the continuation 17133 * from reaching our parent (an explored_state). Our 17134 * own state will get the read marks recorded, but 17135 * they'll be immediately forgotten as we're pruning 17136 * this state and will pop a new one. 17137 */ 17138 err = propagate_liveness(env, &sl->state, cur); 17139 17140 /* if previous state reached the exit with precision and 17141 * current state is equivalent to it (except precsion marks) 17142 * the precision needs to be propagated back in 17143 * the current state. 17144 */ 17145 if (is_jmp_point(env, env->insn_idx)) 17146 err = err ? : push_jmp_history(env, cur, 0); 17147 err = err ? : propagate_precision(env, &sl->state); 17148 if (err) 17149 return err; 17150 return 1; 17151 } 17152 miss: 17153 /* when new state is not going to be added do not increase miss count. 17154 * Otherwise several loop iterations will remove the state 17155 * recorded earlier. The goal of these heuristics is to have 17156 * states from some iterations of the loop (some in the beginning 17157 * and some at the end) to help pruning. 17158 */ 17159 if (add_new_state) 17160 sl->miss_cnt++; 17161 /* heuristic to determine whether this state is beneficial 17162 * to keep checking from state equivalence point of view. 17163 * Higher numbers increase max_states_per_insn and verification time, 17164 * but do not meaningfully decrease insn_processed. 17165 * 'n' controls how many times state could miss before eviction. 17166 * Use bigger 'n' for checkpoints because evicting checkpoint states 17167 * too early would hinder iterator convergence. 17168 */ 17169 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 17170 if (sl->miss_cnt > sl->hit_cnt * n + n) { 17171 /* the state is unlikely to be useful. Remove it to 17172 * speed up verification 17173 */ 17174 *pprev = sl->next; 17175 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE && 17176 !sl->state.used_as_loop_entry) { 17177 u32 br = sl->state.branches; 17178 17179 WARN_ONCE(br, 17180 "BUG live_done but branches_to_explore %d\n", 17181 br); 17182 free_verifier_state(&sl->state, false); 17183 kfree(sl); 17184 env->peak_states--; 17185 } else { 17186 /* cannot free this state, since parentage chain may 17187 * walk it later. Add it for free_list instead to 17188 * be freed at the end of verification 17189 */ 17190 sl->next = env->free_list; 17191 env->free_list = sl; 17192 } 17193 sl = *pprev; 17194 continue; 17195 } 17196 next: 17197 pprev = &sl->next; 17198 sl = *pprev; 17199 } 17200 17201 if (env->max_states_per_insn < states_cnt) 17202 env->max_states_per_insn = states_cnt; 17203 17204 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 17205 return 0; 17206 17207 if (!add_new_state) 17208 return 0; 17209 17210 /* There were no equivalent states, remember the current one. 17211 * Technically the current state is not proven to be safe yet, 17212 * but it will either reach outer most bpf_exit (which means it's safe) 17213 * or it will be rejected. When there are no loops the verifier won't be 17214 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 17215 * again on the way to bpf_exit. 17216 * When looping the sl->state.branches will be > 0 and this state 17217 * will not be considered for equivalence until branches == 0. 17218 */ 17219 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 17220 if (!new_sl) 17221 return -ENOMEM; 17222 env->total_states++; 17223 env->peak_states++; 17224 env->prev_jmps_processed = env->jmps_processed; 17225 env->prev_insn_processed = env->insn_processed; 17226 17227 /* forget precise markings we inherited, see __mark_chain_precision */ 17228 if (env->bpf_capable) 17229 mark_all_scalars_imprecise(env, cur); 17230 17231 /* add new state to the head of linked list */ 17232 new = &new_sl->state; 17233 err = copy_verifier_state(new, cur); 17234 if (err) { 17235 free_verifier_state(new, false); 17236 kfree(new_sl); 17237 return err; 17238 } 17239 new->insn_idx = insn_idx; 17240 WARN_ONCE(new->branches != 1, 17241 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 17242 17243 cur->parent = new; 17244 cur->first_insn_idx = insn_idx; 17245 cur->dfs_depth = new->dfs_depth + 1; 17246 clear_jmp_history(cur); 17247 new_sl->next = *explored_state(env, insn_idx); 17248 *explored_state(env, insn_idx) = new_sl; 17249 /* connect new state to parentage chain. Current frame needs all 17250 * registers connected. Only r6 - r9 of the callers are alive (pushed 17251 * to the stack implicitly by JITs) so in callers' frames connect just 17252 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 17253 * the state of the call instruction (with WRITTEN set), and r0 comes 17254 * from callee with its full parentage chain, anyway. 17255 */ 17256 /* clear write marks in current state: the writes we did are not writes 17257 * our child did, so they don't screen off its reads from us. 17258 * (There are no read marks in current state, because reads always mark 17259 * their parent and current state never has children yet. Only 17260 * explored_states can get read marks.) 17261 */ 17262 for (j = 0; j <= cur->curframe; j++) { 17263 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 17264 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 17265 for (i = 0; i < BPF_REG_FP; i++) 17266 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 17267 } 17268 17269 /* all stack frames are accessible from callee, clear them all */ 17270 for (j = 0; j <= cur->curframe; j++) { 17271 struct bpf_func_state *frame = cur->frame[j]; 17272 struct bpf_func_state *newframe = new->frame[j]; 17273 17274 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 17275 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 17276 frame->stack[i].spilled_ptr.parent = 17277 &newframe->stack[i].spilled_ptr; 17278 } 17279 } 17280 return 0; 17281 } 17282 17283 /* Return true if it's OK to have the same insn return a different type. */ 17284 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 17285 { 17286 switch (base_type(type)) { 17287 case PTR_TO_CTX: 17288 case PTR_TO_SOCKET: 17289 case PTR_TO_SOCK_COMMON: 17290 case PTR_TO_TCP_SOCK: 17291 case PTR_TO_XDP_SOCK: 17292 case PTR_TO_BTF_ID: 17293 return false; 17294 default: 17295 return true; 17296 } 17297 } 17298 17299 /* If an instruction was previously used with particular pointer types, then we 17300 * need to be careful to avoid cases such as the below, where it may be ok 17301 * for one branch accessing the pointer, but not ok for the other branch: 17302 * 17303 * R1 = sock_ptr 17304 * goto X; 17305 * ... 17306 * R1 = some_other_valid_ptr; 17307 * goto X; 17308 * ... 17309 * R2 = *(u32 *)(R1 + 0); 17310 */ 17311 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 17312 { 17313 return src != prev && (!reg_type_mismatch_ok(src) || 17314 !reg_type_mismatch_ok(prev)); 17315 } 17316 17317 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 17318 bool allow_trust_missmatch) 17319 { 17320 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 17321 17322 if (*prev_type == NOT_INIT) { 17323 /* Saw a valid insn 17324 * dst_reg = *(u32 *)(src_reg + off) 17325 * save type to validate intersecting paths 17326 */ 17327 *prev_type = type; 17328 } else if (reg_type_mismatch(type, *prev_type)) { 17329 /* Abuser program is trying to use the same insn 17330 * dst_reg = *(u32*) (src_reg + off) 17331 * with different pointer types: 17332 * src_reg == ctx in one branch and 17333 * src_reg == stack|map in some other branch. 17334 * Reject it. 17335 */ 17336 if (allow_trust_missmatch && 17337 base_type(type) == PTR_TO_BTF_ID && 17338 base_type(*prev_type) == PTR_TO_BTF_ID) { 17339 /* 17340 * Have to support a use case when one path through 17341 * the program yields TRUSTED pointer while another 17342 * is UNTRUSTED. Fallback to UNTRUSTED to generate 17343 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 17344 */ 17345 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 17346 } else { 17347 verbose(env, "same insn cannot be used with different pointers\n"); 17348 return -EINVAL; 17349 } 17350 } 17351 17352 return 0; 17353 } 17354 17355 static int do_check(struct bpf_verifier_env *env) 17356 { 17357 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17358 struct bpf_verifier_state *state = env->cur_state; 17359 struct bpf_insn *insns = env->prog->insnsi; 17360 struct bpf_reg_state *regs; 17361 int insn_cnt = env->prog->len; 17362 bool do_print_state = false; 17363 int prev_insn_idx = -1; 17364 17365 for (;;) { 17366 bool exception_exit = false; 17367 struct bpf_insn *insn; 17368 u8 class; 17369 int err; 17370 17371 /* reset current history entry on each new instruction */ 17372 env->cur_hist_ent = NULL; 17373 17374 env->prev_insn_idx = prev_insn_idx; 17375 if (env->insn_idx >= insn_cnt) { 17376 verbose(env, "invalid insn idx %d insn_cnt %d\n", 17377 env->insn_idx, insn_cnt); 17378 return -EFAULT; 17379 } 17380 17381 insn = &insns[env->insn_idx]; 17382 class = BPF_CLASS(insn->code); 17383 17384 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 17385 verbose(env, 17386 "BPF program is too large. Processed %d insn\n", 17387 env->insn_processed); 17388 return -E2BIG; 17389 } 17390 17391 state->last_insn_idx = env->prev_insn_idx; 17392 17393 if (is_prune_point(env, env->insn_idx)) { 17394 err = is_state_visited(env, env->insn_idx); 17395 if (err < 0) 17396 return err; 17397 if (err == 1) { 17398 /* found equivalent state, can prune the search */ 17399 if (env->log.level & BPF_LOG_LEVEL) { 17400 if (do_print_state) 17401 verbose(env, "\nfrom %d to %d%s: safe\n", 17402 env->prev_insn_idx, env->insn_idx, 17403 env->cur_state->speculative ? 17404 " (speculative execution)" : ""); 17405 else 17406 verbose(env, "%d: safe\n", env->insn_idx); 17407 } 17408 goto process_bpf_exit; 17409 } 17410 } 17411 17412 if (is_jmp_point(env, env->insn_idx)) { 17413 err = push_jmp_history(env, state, 0); 17414 if (err) 17415 return err; 17416 } 17417 17418 if (signal_pending(current)) 17419 return -EAGAIN; 17420 17421 if (need_resched()) 17422 cond_resched(); 17423 17424 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17425 verbose(env, "\nfrom %d to %d%s:", 17426 env->prev_insn_idx, env->insn_idx, 17427 env->cur_state->speculative ? 17428 " (speculative execution)" : ""); 17429 print_verifier_state(env, state->frame[state->curframe], true); 17430 do_print_state = false; 17431 } 17432 17433 if (env->log.level & BPF_LOG_LEVEL) { 17434 const struct bpf_insn_cbs cbs = { 17435 .cb_call = disasm_kfunc_name, 17436 .cb_print = verbose, 17437 .private_data = env, 17438 }; 17439 17440 if (verifier_state_scratched(env)) 17441 print_insn_state(env, state->frame[state->curframe]); 17442 17443 verbose_linfo(env, env->insn_idx, "; "); 17444 env->prev_log_pos = env->log.end_pos; 17445 verbose(env, "%d: ", env->insn_idx); 17446 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 17447 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17448 env->prev_log_pos = env->log.end_pos; 17449 } 17450 17451 if (bpf_prog_is_offloaded(env->prog->aux)) { 17452 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17453 env->prev_insn_idx); 17454 if (err) 17455 return err; 17456 } 17457 17458 regs = cur_regs(env); 17459 sanitize_mark_insn_seen(env); 17460 prev_insn_idx = env->insn_idx; 17461 17462 if (class == BPF_ALU || class == BPF_ALU64) { 17463 err = check_alu_op(env, insn); 17464 if (err) 17465 return err; 17466 17467 } else if (class == BPF_LDX) { 17468 enum bpf_reg_type src_reg_type; 17469 17470 /* check for reserved fields is already done */ 17471 17472 /* check src operand */ 17473 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17474 if (err) 17475 return err; 17476 17477 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 17478 if (err) 17479 return err; 17480 17481 src_reg_type = regs[insn->src_reg].type; 17482 17483 /* check that memory (src_reg + off) is readable, 17484 * the state of dst_reg will be updated by this func 17485 */ 17486 err = check_mem_access(env, env->insn_idx, insn->src_reg, 17487 insn->off, BPF_SIZE(insn->code), 17488 BPF_READ, insn->dst_reg, false, 17489 BPF_MODE(insn->code) == BPF_MEMSX); 17490 err = err ?: save_aux_ptr_type(env, src_reg_type, true); 17491 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], "ldx"); 17492 if (err) 17493 return err; 17494 } else if (class == BPF_STX) { 17495 enum bpf_reg_type dst_reg_type; 17496 17497 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 17498 err = check_atomic(env, env->insn_idx, insn); 17499 if (err) 17500 return err; 17501 env->insn_idx++; 17502 continue; 17503 } 17504 17505 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 17506 verbose(env, "BPF_STX uses reserved fields\n"); 17507 return -EINVAL; 17508 } 17509 17510 /* check src1 operand */ 17511 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17512 if (err) 17513 return err; 17514 /* check src2 operand */ 17515 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17516 if (err) 17517 return err; 17518 17519 dst_reg_type = regs[insn->dst_reg].type; 17520 17521 /* check that memory (dst_reg + off) is writeable */ 17522 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17523 insn->off, BPF_SIZE(insn->code), 17524 BPF_WRITE, insn->src_reg, false, false); 17525 if (err) 17526 return err; 17527 17528 err = save_aux_ptr_type(env, dst_reg_type, false); 17529 if (err) 17530 return err; 17531 } else if (class == BPF_ST) { 17532 enum bpf_reg_type dst_reg_type; 17533 17534 if (BPF_MODE(insn->code) != BPF_MEM || 17535 insn->src_reg != BPF_REG_0) { 17536 verbose(env, "BPF_ST uses reserved fields\n"); 17537 return -EINVAL; 17538 } 17539 /* check src operand */ 17540 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17541 if (err) 17542 return err; 17543 17544 dst_reg_type = regs[insn->dst_reg].type; 17545 17546 /* check that memory (dst_reg + off) is writeable */ 17547 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17548 insn->off, BPF_SIZE(insn->code), 17549 BPF_WRITE, -1, false, false); 17550 if (err) 17551 return err; 17552 17553 err = save_aux_ptr_type(env, dst_reg_type, false); 17554 if (err) 17555 return err; 17556 } else if (class == BPF_JMP || class == BPF_JMP32) { 17557 u8 opcode = BPF_OP(insn->code); 17558 17559 env->jmps_processed++; 17560 if (opcode == BPF_CALL) { 17561 if (BPF_SRC(insn->code) != BPF_K || 17562 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 17563 && insn->off != 0) || 17564 (insn->src_reg != BPF_REG_0 && 17565 insn->src_reg != BPF_PSEUDO_CALL && 17566 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 17567 insn->dst_reg != BPF_REG_0 || 17568 class == BPF_JMP32) { 17569 verbose(env, "BPF_CALL uses reserved fields\n"); 17570 return -EINVAL; 17571 } 17572 17573 if (env->cur_state->active_lock.ptr) { 17574 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 17575 (insn->src_reg == BPF_PSEUDO_CALL) || 17576 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17577 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 17578 verbose(env, "function calls are not allowed while holding a lock\n"); 17579 return -EINVAL; 17580 } 17581 } 17582 if (insn->src_reg == BPF_PSEUDO_CALL) { 17583 err = check_func_call(env, insn, &env->insn_idx); 17584 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 17585 err = check_kfunc_call(env, insn, &env->insn_idx); 17586 if (!err && is_bpf_throw_kfunc(insn)) { 17587 exception_exit = true; 17588 goto process_bpf_exit_full; 17589 } 17590 } else { 17591 err = check_helper_call(env, insn, &env->insn_idx); 17592 } 17593 if (err) 17594 return err; 17595 17596 mark_reg_scratched(env, BPF_REG_0); 17597 } else if (opcode == BPF_JA) { 17598 if (BPF_SRC(insn->code) != BPF_K || 17599 insn->src_reg != BPF_REG_0 || 17600 insn->dst_reg != BPF_REG_0 || 17601 (class == BPF_JMP && insn->imm != 0) || 17602 (class == BPF_JMP32 && insn->off != 0)) { 17603 verbose(env, "BPF_JA uses reserved fields\n"); 17604 return -EINVAL; 17605 } 17606 17607 if (class == BPF_JMP) 17608 env->insn_idx += insn->off + 1; 17609 else 17610 env->insn_idx += insn->imm + 1; 17611 continue; 17612 17613 } else if (opcode == BPF_EXIT) { 17614 if (BPF_SRC(insn->code) != BPF_K || 17615 insn->imm != 0 || 17616 insn->src_reg != BPF_REG_0 || 17617 insn->dst_reg != BPF_REG_0 || 17618 class == BPF_JMP32) { 17619 verbose(env, "BPF_EXIT uses reserved fields\n"); 17620 return -EINVAL; 17621 } 17622 process_bpf_exit_full: 17623 if (env->cur_state->active_lock.ptr && 17624 !in_rbtree_lock_required_cb(env)) { 17625 verbose(env, "bpf_spin_unlock is missing\n"); 17626 return -EINVAL; 17627 } 17628 17629 if (env->cur_state->active_rcu_lock && 17630 !in_rbtree_lock_required_cb(env)) { 17631 verbose(env, "bpf_rcu_read_unlock is missing\n"); 17632 return -EINVAL; 17633 } 17634 17635 /* We must do check_reference_leak here before 17636 * prepare_func_exit to handle the case when 17637 * state->curframe > 0, it may be a callback 17638 * function, for which reference_state must 17639 * match caller reference state when it exits. 17640 */ 17641 err = check_reference_leak(env, exception_exit); 17642 if (err) 17643 return err; 17644 17645 /* The side effect of the prepare_func_exit 17646 * which is being skipped is that it frees 17647 * bpf_func_state. Typically, process_bpf_exit 17648 * will only be hit with outermost exit. 17649 * copy_verifier_state in pop_stack will handle 17650 * freeing of any extra bpf_func_state left over 17651 * from not processing all nested function 17652 * exits. We also skip return code checks as 17653 * they are not needed for exceptional exits. 17654 */ 17655 if (exception_exit) 17656 goto process_bpf_exit; 17657 17658 if (state->curframe) { 17659 /* exit from nested function */ 17660 err = prepare_func_exit(env, &env->insn_idx); 17661 if (err) 17662 return err; 17663 do_print_state = true; 17664 continue; 17665 } 17666 17667 err = check_return_code(env, BPF_REG_0, "R0"); 17668 if (err) 17669 return err; 17670 process_bpf_exit: 17671 mark_verifier_state_scratched(env); 17672 update_branch_counts(env, env->cur_state); 17673 err = pop_stack(env, &prev_insn_idx, 17674 &env->insn_idx, pop_log); 17675 if (err < 0) { 17676 if (err != -ENOENT) 17677 return err; 17678 break; 17679 } else { 17680 do_print_state = true; 17681 continue; 17682 } 17683 } else { 17684 err = check_cond_jmp_op(env, insn, &env->insn_idx); 17685 if (err) 17686 return err; 17687 } 17688 } else if (class == BPF_LD) { 17689 u8 mode = BPF_MODE(insn->code); 17690 17691 if (mode == BPF_ABS || mode == BPF_IND) { 17692 err = check_ld_abs(env, insn); 17693 if (err) 17694 return err; 17695 17696 } else if (mode == BPF_IMM) { 17697 err = check_ld_imm(env, insn); 17698 if (err) 17699 return err; 17700 17701 env->insn_idx++; 17702 sanitize_mark_insn_seen(env); 17703 } else { 17704 verbose(env, "invalid BPF_LD mode\n"); 17705 return -EINVAL; 17706 } 17707 } else { 17708 verbose(env, "unknown insn class %d\n", class); 17709 return -EINVAL; 17710 } 17711 17712 env->insn_idx++; 17713 } 17714 17715 return 0; 17716 } 17717 17718 static int find_btf_percpu_datasec(struct btf *btf) 17719 { 17720 const struct btf_type *t; 17721 const char *tname; 17722 int i, n; 17723 17724 /* 17725 * Both vmlinux and module each have their own ".data..percpu" 17726 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17727 * types to look at only module's own BTF types. 17728 */ 17729 n = btf_nr_types(btf); 17730 if (btf_is_module(btf)) 17731 i = btf_nr_types(btf_vmlinux); 17732 else 17733 i = 1; 17734 17735 for(; i < n; i++) { 17736 t = btf_type_by_id(btf, i); 17737 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17738 continue; 17739 17740 tname = btf_name_by_offset(btf, t->name_off); 17741 if (!strcmp(tname, ".data..percpu")) 17742 return i; 17743 } 17744 17745 return -ENOENT; 17746 } 17747 17748 /* replace pseudo btf_id with kernel symbol address */ 17749 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 17750 struct bpf_insn *insn, 17751 struct bpf_insn_aux_data *aux) 17752 { 17753 const struct btf_var_secinfo *vsi; 17754 const struct btf_type *datasec; 17755 struct btf_mod_pair *btf_mod; 17756 const struct btf_type *t; 17757 const char *sym_name; 17758 bool percpu = false; 17759 u32 type, id = insn->imm; 17760 struct btf *btf; 17761 s32 datasec_id; 17762 u64 addr; 17763 int i, btf_fd, err; 17764 17765 btf_fd = insn[1].imm; 17766 if (btf_fd) { 17767 btf = btf_get_by_fd(btf_fd); 17768 if (IS_ERR(btf)) { 17769 verbose(env, "invalid module BTF object FD specified.\n"); 17770 return -EINVAL; 17771 } 17772 } else { 17773 if (!btf_vmlinux) { 17774 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 17775 return -EINVAL; 17776 } 17777 btf = btf_vmlinux; 17778 btf_get(btf); 17779 } 17780 17781 t = btf_type_by_id(btf, id); 17782 if (!t) { 17783 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17784 err = -ENOENT; 17785 goto err_put; 17786 } 17787 17788 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 17789 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 17790 err = -EINVAL; 17791 goto err_put; 17792 } 17793 17794 sym_name = btf_name_by_offset(btf, t->name_off); 17795 addr = kallsyms_lookup_name(sym_name); 17796 if (!addr) { 17797 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 17798 sym_name); 17799 err = -ENOENT; 17800 goto err_put; 17801 } 17802 insn[0].imm = (u32)addr; 17803 insn[1].imm = addr >> 32; 17804 17805 if (btf_type_is_func(t)) { 17806 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17807 aux->btf_var.mem_size = 0; 17808 goto check_btf; 17809 } 17810 17811 datasec_id = find_btf_percpu_datasec(btf); 17812 if (datasec_id > 0) { 17813 datasec = btf_type_by_id(btf, datasec_id); 17814 for_each_vsi(i, datasec, vsi) { 17815 if (vsi->type == id) { 17816 percpu = true; 17817 break; 17818 } 17819 } 17820 } 17821 17822 type = t->type; 17823 t = btf_type_skip_modifiers(btf, type, NULL); 17824 if (percpu) { 17825 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 17826 aux->btf_var.btf = btf; 17827 aux->btf_var.btf_id = type; 17828 } else if (!btf_type_is_struct(t)) { 17829 const struct btf_type *ret; 17830 const char *tname; 17831 u32 tsize; 17832 17833 /* resolve the type size of ksym. */ 17834 ret = btf_resolve_size(btf, t, &tsize); 17835 if (IS_ERR(ret)) { 17836 tname = btf_name_by_offset(btf, t->name_off); 17837 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 17838 tname, PTR_ERR(ret)); 17839 err = -EINVAL; 17840 goto err_put; 17841 } 17842 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17843 aux->btf_var.mem_size = tsize; 17844 } else { 17845 aux->btf_var.reg_type = PTR_TO_BTF_ID; 17846 aux->btf_var.btf = btf; 17847 aux->btf_var.btf_id = type; 17848 } 17849 check_btf: 17850 /* check whether we recorded this BTF (and maybe module) already */ 17851 for (i = 0; i < env->used_btf_cnt; i++) { 17852 if (env->used_btfs[i].btf == btf) { 17853 btf_put(btf); 17854 return 0; 17855 } 17856 } 17857 17858 if (env->used_btf_cnt >= MAX_USED_BTFS) { 17859 err = -E2BIG; 17860 goto err_put; 17861 } 17862 17863 btf_mod = &env->used_btfs[env->used_btf_cnt]; 17864 btf_mod->btf = btf; 17865 btf_mod->module = NULL; 17866 17867 /* if we reference variables from kernel module, bump its refcount */ 17868 if (btf_is_module(btf)) { 17869 btf_mod->module = btf_try_get_module(btf); 17870 if (!btf_mod->module) { 17871 err = -ENXIO; 17872 goto err_put; 17873 } 17874 } 17875 17876 env->used_btf_cnt++; 17877 17878 return 0; 17879 err_put: 17880 btf_put(btf); 17881 return err; 17882 } 17883 17884 static bool is_tracing_prog_type(enum bpf_prog_type type) 17885 { 17886 switch (type) { 17887 case BPF_PROG_TYPE_KPROBE: 17888 case BPF_PROG_TYPE_TRACEPOINT: 17889 case BPF_PROG_TYPE_PERF_EVENT: 17890 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17891 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 17892 return true; 17893 default: 17894 return false; 17895 } 17896 } 17897 17898 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 17899 struct bpf_map *map, 17900 struct bpf_prog *prog) 17901 17902 { 17903 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17904 17905 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 17906 btf_record_has_field(map->record, BPF_RB_ROOT)) { 17907 if (is_tracing_prog_type(prog_type)) { 17908 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 17909 return -EINVAL; 17910 } 17911 } 17912 17913 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 17914 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 17915 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 17916 return -EINVAL; 17917 } 17918 17919 if (is_tracing_prog_type(prog_type)) { 17920 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 17921 return -EINVAL; 17922 } 17923 } 17924 17925 if (btf_record_has_field(map->record, BPF_TIMER)) { 17926 if (is_tracing_prog_type(prog_type)) { 17927 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 17928 return -EINVAL; 17929 } 17930 } 17931 17932 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 17933 !bpf_offload_prog_map_match(prog, map)) { 17934 verbose(env, "offload device mismatch between prog and map\n"); 17935 return -EINVAL; 17936 } 17937 17938 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 17939 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 17940 return -EINVAL; 17941 } 17942 17943 if (prog->aux->sleepable) 17944 switch (map->map_type) { 17945 case BPF_MAP_TYPE_HASH: 17946 case BPF_MAP_TYPE_LRU_HASH: 17947 case BPF_MAP_TYPE_ARRAY: 17948 case BPF_MAP_TYPE_PERCPU_HASH: 17949 case BPF_MAP_TYPE_PERCPU_ARRAY: 17950 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 17951 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 17952 case BPF_MAP_TYPE_HASH_OF_MAPS: 17953 case BPF_MAP_TYPE_RINGBUF: 17954 case BPF_MAP_TYPE_USER_RINGBUF: 17955 case BPF_MAP_TYPE_INODE_STORAGE: 17956 case BPF_MAP_TYPE_SK_STORAGE: 17957 case BPF_MAP_TYPE_TASK_STORAGE: 17958 case BPF_MAP_TYPE_CGRP_STORAGE: 17959 break; 17960 default: 17961 verbose(env, 17962 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 17963 return -EINVAL; 17964 } 17965 17966 return 0; 17967 } 17968 17969 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 17970 { 17971 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 17972 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 17973 } 17974 17975 /* find and rewrite pseudo imm in ld_imm64 instructions: 17976 * 17977 * 1. if it accesses map FD, replace it with actual map pointer. 17978 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 17979 * 17980 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 17981 */ 17982 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 17983 { 17984 struct bpf_insn *insn = env->prog->insnsi; 17985 int insn_cnt = env->prog->len; 17986 int i, j, err; 17987 17988 err = bpf_prog_calc_tag(env->prog); 17989 if (err) 17990 return err; 17991 17992 for (i = 0; i < insn_cnt; i++, insn++) { 17993 if (BPF_CLASS(insn->code) == BPF_LDX && 17994 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 17995 insn->imm != 0)) { 17996 verbose(env, "BPF_LDX uses reserved fields\n"); 17997 return -EINVAL; 17998 } 17999 18000 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 18001 struct bpf_insn_aux_data *aux; 18002 struct bpf_map *map; 18003 struct fd f; 18004 u64 addr; 18005 u32 fd; 18006 18007 if (i == insn_cnt - 1 || insn[1].code != 0 || 18008 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 18009 insn[1].off != 0) { 18010 verbose(env, "invalid bpf_ld_imm64 insn\n"); 18011 return -EINVAL; 18012 } 18013 18014 if (insn[0].src_reg == 0) 18015 /* valid generic load 64-bit imm */ 18016 goto next_insn; 18017 18018 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 18019 aux = &env->insn_aux_data[i]; 18020 err = check_pseudo_btf_id(env, insn, aux); 18021 if (err) 18022 return err; 18023 goto next_insn; 18024 } 18025 18026 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 18027 aux = &env->insn_aux_data[i]; 18028 aux->ptr_type = PTR_TO_FUNC; 18029 goto next_insn; 18030 } 18031 18032 /* In final convert_pseudo_ld_imm64() step, this is 18033 * converted into regular 64-bit imm load insn. 18034 */ 18035 switch (insn[0].src_reg) { 18036 case BPF_PSEUDO_MAP_VALUE: 18037 case BPF_PSEUDO_MAP_IDX_VALUE: 18038 break; 18039 case BPF_PSEUDO_MAP_FD: 18040 case BPF_PSEUDO_MAP_IDX: 18041 if (insn[1].imm == 0) 18042 break; 18043 fallthrough; 18044 default: 18045 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 18046 return -EINVAL; 18047 } 18048 18049 switch (insn[0].src_reg) { 18050 case BPF_PSEUDO_MAP_IDX_VALUE: 18051 case BPF_PSEUDO_MAP_IDX: 18052 if (bpfptr_is_null(env->fd_array)) { 18053 verbose(env, "fd_idx without fd_array is invalid\n"); 18054 return -EPROTO; 18055 } 18056 if (copy_from_bpfptr_offset(&fd, env->fd_array, 18057 insn[0].imm * sizeof(fd), 18058 sizeof(fd))) 18059 return -EFAULT; 18060 break; 18061 default: 18062 fd = insn[0].imm; 18063 break; 18064 } 18065 18066 f = fdget(fd); 18067 map = __bpf_map_get(f); 18068 if (IS_ERR(map)) { 18069 verbose(env, "fd %d is not pointing to valid bpf_map\n", 18070 insn[0].imm); 18071 return PTR_ERR(map); 18072 } 18073 18074 err = check_map_prog_compatibility(env, map, env->prog); 18075 if (err) { 18076 fdput(f); 18077 return err; 18078 } 18079 18080 aux = &env->insn_aux_data[i]; 18081 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 18082 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 18083 addr = (unsigned long)map; 18084 } else { 18085 u32 off = insn[1].imm; 18086 18087 if (off >= BPF_MAX_VAR_OFF) { 18088 verbose(env, "direct value offset of %u is not allowed\n", off); 18089 fdput(f); 18090 return -EINVAL; 18091 } 18092 18093 if (!map->ops->map_direct_value_addr) { 18094 verbose(env, "no direct value access support for this map type\n"); 18095 fdput(f); 18096 return -EINVAL; 18097 } 18098 18099 err = map->ops->map_direct_value_addr(map, &addr, off); 18100 if (err) { 18101 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 18102 map->value_size, off); 18103 fdput(f); 18104 return err; 18105 } 18106 18107 aux->map_off = off; 18108 addr += off; 18109 } 18110 18111 insn[0].imm = (u32)addr; 18112 insn[1].imm = addr >> 32; 18113 18114 /* check whether we recorded this map already */ 18115 for (j = 0; j < env->used_map_cnt; j++) { 18116 if (env->used_maps[j] == map) { 18117 aux->map_index = j; 18118 fdput(f); 18119 goto next_insn; 18120 } 18121 } 18122 18123 if (env->used_map_cnt >= MAX_USED_MAPS) { 18124 fdput(f); 18125 return -E2BIG; 18126 } 18127 18128 if (env->prog->aux->sleepable) 18129 atomic64_inc(&map->sleepable_refcnt); 18130 /* hold the map. If the program is rejected by verifier, 18131 * the map will be released by release_maps() or it 18132 * will be used by the valid program until it's unloaded 18133 * and all maps are released in bpf_free_used_maps() 18134 */ 18135 bpf_map_inc(map); 18136 18137 aux->map_index = env->used_map_cnt; 18138 env->used_maps[env->used_map_cnt++] = map; 18139 18140 if (bpf_map_is_cgroup_storage(map) && 18141 bpf_cgroup_storage_assign(env->prog->aux, map)) { 18142 verbose(env, "only one cgroup storage of each type is allowed\n"); 18143 fdput(f); 18144 return -EBUSY; 18145 } 18146 18147 fdput(f); 18148 next_insn: 18149 insn++; 18150 i++; 18151 continue; 18152 } 18153 18154 /* Basic sanity check before we invest more work here. */ 18155 if (!bpf_opcode_in_insntable(insn->code)) { 18156 verbose(env, "unknown opcode %02x\n", insn->code); 18157 return -EINVAL; 18158 } 18159 } 18160 18161 /* now all pseudo BPF_LD_IMM64 instructions load valid 18162 * 'struct bpf_map *' into a register instead of user map_fd. 18163 * These pointers will be used later by verifier to validate map access. 18164 */ 18165 return 0; 18166 } 18167 18168 /* drop refcnt of maps used by the rejected program */ 18169 static void release_maps(struct bpf_verifier_env *env) 18170 { 18171 __bpf_free_used_maps(env->prog->aux, env->used_maps, 18172 env->used_map_cnt); 18173 } 18174 18175 /* drop refcnt of maps used by the rejected program */ 18176 static void release_btfs(struct bpf_verifier_env *env) 18177 { 18178 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 18179 env->used_btf_cnt); 18180 } 18181 18182 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 18183 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 18184 { 18185 struct bpf_insn *insn = env->prog->insnsi; 18186 int insn_cnt = env->prog->len; 18187 int i; 18188 18189 for (i = 0; i < insn_cnt; i++, insn++) { 18190 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 18191 continue; 18192 if (insn->src_reg == BPF_PSEUDO_FUNC) 18193 continue; 18194 insn->src_reg = 0; 18195 } 18196 } 18197 18198 /* single env->prog->insni[off] instruction was replaced with the range 18199 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 18200 * [0, off) and [off, end) to new locations, so the patched range stays zero 18201 */ 18202 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 18203 struct bpf_insn_aux_data *new_data, 18204 struct bpf_prog *new_prog, u32 off, u32 cnt) 18205 { 18206 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 18207 struct bpf_insn *insn = new_prog->insnsi; 18208 u32 old_seen = old_data[off].seen; 18209 u32 prog_len; 18210 int i; 18211 18212 /* aux info at OFF always needs adjustment, no matter fast path 18213 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 18214 * original insn at old prog. 18215 */ 18216 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 18217 18218 if (cnt == 1) 18219 return; 18220 prog_len = new_prog->len; 18221 18222 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 18223 memcpy(new_data + off + cnt - 1, old_data + off, 18224 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 18225 for (i = off; i < off + cnt - 1; i++) { 18226 /* Expand insni[off]'s seen count to the patched range. */ 18227 new_data[i].seen = old_seen; 18228 new_data[i].zext_dst = insn_has_def32(env, insn + i); 18229 } 18230 env->insn_aux_data = new_data; 18231 vfree(old_data); 18232 } 18233 18234 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 18235 { 18236 int i; 18237 18238 if (len == 1) 18239 return; 18240 /* NOTE: fake 'exit' subprog should be updated as well. */ 18241 for (i = 0; i <= env->subprog_cnt; i++) { 18242 if (env->subprog_info[i].start <= off) 18243 continue; 18244 env->subprog_info[i].start += len - 1; 18245 } 18246 } 18247 18248 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 18249 { 18250 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 18251 int i, sz = prog->aux->size_poke_tab; 18252 struct bpf_jit_poke_descriptor *desc; 18253 18254 for (i = 0; i < sz; i++) { 18255 desc = &tab[i]; 18256 if (desc->insn_idx <= off) 18257 continue; 18258 desc->insn_idx += len - 1; 18259 } 18260 } 18261 18262 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 18263 const struct bpf_insn *patch, u32 len) 18264 { 18265 struct bpf_prog *new_prog; 18266 struct bpf_insn_aux_data *new_data = NULL; 18267 18268 if (len > 1) { 18269 new_data = vzalloc(array_size(env->prog->len + len - 1, 18270 sizeof(struct bpf_insn_aux_data))); 18271 if (!new_data) 18272 return NULL; 18273 } 18274 18275 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 18276 if (IS_ERR(new_prog)) { 18277 if (PTR_ERR(new_prog) == -ERANGE) 18278 verbose(env, 18279 "insn %d cannot be patched due to 16-bit range\n", 18280 env->insn_aux_data[off].orig_idx); 18281 vfree(new_data); 18282 return NULL; 18283 } 18284 adjust_insn_aux_data(env, new_data, new_prog, off, len); 18285 adjust_subprog_starts(env, off, len); 18286 adjust_poke_descs(new_prog, off, len); 18287 return new_prog; 18288 } 18289 18290 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 18291 u32 off, u32 cnt) 18292 { 18293 int i, j; 18294 18295 /* find first prog starting at or after off (first to remove) */ 18296 for (i = 0; i < env->subprog_cnt; i++) 18297 if (env->subprog_info[i].start >= off) 18298 break; 18299 /* find first prog starting at or after off + cnt (first to stay) */ 18300 for (j = i; j < env->subprog_cnt; j++) 18301 if (env->subprog_info[j].start >= off + cnt) 18302 break; 18303 /* if j doesn't start exactly at off + cnt, we are just removing 18304 * the front of previous prog 18305 */ 18306 if (env->subprog_info[j].start != off + cnt) 18307 j--; 18308 18309 if (j > i) { 18310 struct bpf_prog_aux *aux = env->prog->aux; 18311 int move; 18312 18313 /* move fake 'exit' subprog as well */ 18314 move = env->subprog_cnt + 1 - j; 18315 18316 memmove(env->subprog_info + i, 18317 env->subprog_info + j, 18318 sizeof(*env->subprog_info) * move); 18319 env->subprog_cnt -= j - i; 18320 18321 /* remove func_info */ 18322 if (aux->func_info) { 18323 move = aux->func_info_cnt - j; 18324 18325 memmove(aux->func_info + i, 18326 aux->func_info + j, 18327 sizeof(*aux->func_info) * move); 18328 aux->func_info_cnt -= j - i; 18329 /* func_info->insn_off is set after all code rewrites, 18330 * in adjust_btf_func() - no need to adjust 18331 */ 18332 } 18333 } else { 18334 /* convert i from "first prog to remove" to "first to adjust" */ 18335 if (env->subprog_info[i].start == off) 18336 i++; 18337 } 18338 18339 /* update fake 'exit' subprog as well */ 18340 for (; i <= env->subprog_cnt; i++) 18341 env->subprog_info[i].start -= cnt; 18342 18343 return 0; 18344 } 18345 18346 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 18347 u32 cnt) 18348 { 18349 struct bpf_prog *prog = env->prog; 18350 u32 i, l_off, l_cnt, nr_linfo; 18351 struct bpf_line_info *linfo; 18352 18353 nr_linfo = prog->aux->nr_linfo; 18354 if (!nr_linfo) 18355 return 0; 18356 18357 linfo = prog->aux->linfo; 18358 18359 /* find first line info to remove, count lines to be removed */ 18360 for (i = 0; i < nr_linfo; i++) 18361 if (linfo[i].insn_off >= off) 18362 break; 18363 18364 l_off = i; 18365 l_cnt = 0; 18366 for (; i < nr_linfo; i++) 18367 if (linfo[i].insn_off < off + cnt) 18368 l_cnt++; 18369 else 18370 break; 18371 18372 /* First live insn doesn't match first live linfo, it needs to "inherit" 18373 * last removed linfo. prog is already modified, so prog->len == off 18374 * means no live instructions after (tail of the program was removed). 18375 */ 18376 if (prog->len != off && l_cnt && 18377 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 18378 l_cnt--; 18379 linfo[--i].insn_off = off + cnt; 18380 } 18381 18382 /* remove the line info which refer to the removed instructions */ 18383 if (l_cnt) { 18384 memmove(linfo + l_off, linfo + i, 18385 sizeof(*linfo) * (nr_linfo - i)); 18386 18387 prog->aux->nr_linfo -= l_cnt; 18388 nr_linfo = prog->aux->nr_linfo; 18389 } 18390 18391 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 18392 for (i = l_off; i < nr_linfo; i++) 18393 linfo[i].insn_off -= cnt; 18394 18395 /* fix up all subprogs (incl. 'exit') which start >= off */ 18396 for (i = 0; i <= env->subprog_cnt; i++) 18397 if (env->subprog_info[i].linfo_idx > l_off) { 18398 /* program may have started in the removed region but 18399 * may not be fully removed 18400 */ 18401 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 18402 env->subprog_info[i].linfo_idx -= l_cnt; 18403 else 18404 env->subprog_info[i].linfo_idx = l_off; 18405 } 18406 18407 return 0; 18408 } 18409 18410 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 18411 { 18412 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18413 unsigned int orig_prog_len = env->prog->len; 18414 int err; 18415 18416 if (bpf_prog_is_offloaded(env->prog->aux)) 18417 bpf_prog_offload_remove_insns(env, off, cnt); 18418 18419 err = bpf_remove_insns(env->prog, off, cnt); 18420 if (err) 18421 return err; 18422 18423 err = adjust_subprog_starts_after_remove(env, off, cnt); 18424 if (err) 18425 return err; 18426 18427 err = bpf_adj_linfo_after_remove(env, off, cnt); 18428 if (err) 18429 return err; 18430 18431 memmove(aux_data + off, aux_data + off + cnt, 18432 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 18433 18434 return 0; 18435 } 18436 18437 /* The verifier does more data flow analysis than llvm and will not 18438 * explore branches that are dead at run time. Malicious programs can 18439 * have dead code too. Therefore replace all dead at-run-time code 18440 * with 'ja -1'. 18441 * 18442 * Just nops are not optimal, e.g. if they would sit at the end of the 18443 * program and through another bug we would manage to jump there, then 18444 * we'd execute beyond program memory otherwise. Returning exception 18445 * code also wouldn't work since we can have subprogs where the dead 18446 * code could be located. 18447 */ 18448 static void sanitize_dead_code(struct bpf_verifier_env *env) 18449 { 18450 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18451 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18452 struct bpf_insn *insn = env->prog->insnsi; 18453 const int insn_cnt = env->prog->len; 18454 int i; 18455 18456 for (i = 0; i < insn_cnt; i++) { 18457 if (aux_data[i].seen) 18458 continue; 18459 memcpy(insn + i, &trap, sizeof(trap)); 18460 aux_data[i].zext_dst = false; 18461 } 18462 } 18463 18464 static bool insn_is_cond_jump(u8 code) 18465 { 18466 u8 op; 18467 18468 op = BPF_OP(code); 18469 if (BPF_CLASS(code) == BPF_JMP32) 18470 return op != BPF_JA; 18471 18472 if (BPF_CLASS(code) != BPF_JMP) 18473 return false; 18474 18475 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 18476 } 18477 18478 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 18479 { 18480 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18481 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18482 struct bpf_insn *insn = env->prog->insnsi; 18483 const int insn_cnt = env->prog->len; 18484 int i; 18485 18486 for (i = 0; i < insn_cnt; i++, insn++) { 18487 if (!insn_is_cond_jump(insn->code)) 18488 continue; 18489 18490 if (!aux_data[i + 1].seen) 18491 ja.off = insn->off; 18492 else if (!aux_data[i + 1 + insn->off].seen) 18493 ja.off = 0; 18494 else 18495 continue; 18496 18497 if (bpf_prog_is_offloaded(env->prog->aux)) 18498 bpf_prog_offload_replace_insn(env, i, &ja); 18499 18500 memcpy(insn, &ja, sizeof(ja)); 18501 } 18502 } 18503 18504 static int opt_remove_dead_code(struct bpf_verifier_env *env) 18505 { 18506 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18507 int insn_cnt = env->prog->len; 18508 int i, err; 18509 18510 for (i = 0; i < insn_cnt; i++) { 18511 int j; 18512 18513 j = 0; 18514 while (i + j < insn_cnt && !aux_data[i + j].seen) 18515 j++; 18516 if (!j) 18517 continue; 18518 18519 err = verifier_remove_insns(env, i, j); 18520 if (err) 18521 return err; 18522 insn_cnt = env->prog->len; 18523 } 18524 18525 return 0; 18526 } 18527 18528 static int opt_remove_nops(struct bpf_verifier_env *env) 18529 { 18530 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18531 struct bpf_insn *insn = env->prog->insnsi; 18532 int insn_cnt = env->prog->len; 18533 int i, err; 18534 18535 for (i = 0; i < insn_cnt; i++) { 18536 if (memcmp(&insn[i], &ja, sizeof(ja))) 18537 continue; 18538 18539 err = verifier_remove_insns(env, i, 1); 18540 if (err) 18541 return err; 18542 insn_cnt--; 18543 i--; 18544 } 18545 18546 return 0; 18547 } 18548 18549 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 18550 const union bpf_attr *attr) 18551 { 18552 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 18553 struct bpf_insn_aux_data *aux = env->insn_aux_data; 18554 int i, patch_len, delta = 0, len = env->prog->len; 18555 struct bpf_insn *insns = env->prog->insnsi; 18556 struct bpf_prog *new_prog; 18557 bool rnd_hi32; 18558 18559 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 18560 zext_patch[1] = BPF_ZEXT_REG(0); 18561 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 18562 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 18563 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 18564 for (i = 0; i < len; i++) { 18565 int adj_idx = i + delta; 18566 struct bpf_insn insn; 18567 int load_reg; 18568 18569 insn = insns[adj_idx]; 18570 load_reg = insn_def_regno(&insn); 18571 if (!aux[adj_idx].zext_dst) { 18572 u8 code, class; 18573 u32 imm_rnd; 18574 18575 if (!rnd_hi32) 18576 continue; 18577 18578 code = insn.code; 18579 class = BPF_CLASS(code); 18580 if (load_reg == -1) 18581 continue; 18582 18583 /* NOTE: arg "reg" (the fourth one) is only used for 18584 * BPF_STX + SRC_OP, so it is safe to pass NULL 18585 * here. 18586 */ 18587 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 18588 if (class == BPF_LD && 18589 BPF_MODE(code) == BPF_IMM) 18590 i++; 18591 continue; 18592 } 18593 18594 /* ctx load could be transformed into wider load. */ 18595 if (class == BPF_LDX && 18596 aux[adj_idx].ptr_type == PTR_TO_CTX) 18597 continue; 18598 18599 imm_rnd = get_random_u32(); 18600 rnd_hi32_patch[0] = insn; 18601 rnd_hi32_patch[1].imm = imm_rnd; 18602 rnd_hi32_patch[3].dst_reg = load_reg; 18603 patch = rnd_hi32_patch; 18604 patch_len = 4; 18605 goto apply_patch_buffer; 18606 } 18607 18608 /* Add in an zero-extend instruction if a) the JIT has requested 18609 * it or b) it's a CMPXCHG. 18610 * 18611 * The latter is because: BPF_CMPXCHG always loads a value into 18612 * R0, therefore always zero-extends. However some archs' 18613 * equivalent instruction only does this load when the 18614 * comparison is successful. This detail of CMPXCHG is 18615 * orthogonal to the general zero-extension behaviour of the 18616 * CPU, so it's treated independently of bpf_jit_needs_zext. 18617 */ 18618 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 18619 continue; 18620 18621 /* Zero-extension is done by the caller. */ 18622 if (bpf_pseudo_kfunc_call(&insn)) 18623 continue; 18624 18625 if (WARN_ON(load_reg == -1)) { 18626 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 18627 return -EFAULT; 18628 } 18629 18630 zext_patch[0] = insn; 18631 zext_patch[1].dst_reg = load_reg; 18632 zext_patch[1].src_reg = load_reg; 18633 patch = zext_patch; 18634 patch_len = 2; 18635 apply_patch_buffer: 18636 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 18637 if (!new_prog) 18638 return -ENOMEM; 18639 env->prog = new_prog; 18640 insns = new_prog->insnsi; 18641 aux = env->insn_aux_data; 18642 delta += patch_len - 1; 18643 } 18644 18645 return 0; 18646 } 18647 18648 /* convert load instructions that access fields of a context type into a 18649 * sequence of instructions that access fields of the underlying structure: 18650 * struct __sk_buff -> struct sk_buff 18651 * struct bpf_sock_ops -> struct sock 18652 */ 18653 static int convert_ctx_accesses(struct bpf_verifier_env *env) 18654 { 18655 const struct bpf_verifier_ops *ops = env->ops; 18656 int i, cnt, size, ctx_field_size, delta = 0; 18657 const int insn_cnt = env->prog->len; 18658 struct bpf_insn insn_buf[16], *insn; 18659 u32 target_size, size_default, off; 18660 struct bpf_prog *new_prog; 18661 enum bpf_access_type type; 18662 bool is_narrower_load; 18663 18664 if (ops->gen_prologue || env->seen_direct_write) { 18665 if (!ops->gen_prologue) { 18666 verbose(env, "bpf verifier is misconfigured\n"); 18667 return -EINVAL; 18668 } 18669 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 18670 env->prog); 18671 if (cnt >= ARRAY_SIZE(insn_buf)) { 18672 verbose(env, "bpf verifier is misconfigured\n"); 18673 return -EINVAL; 18674 } else if (cnt) { 18675 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 18676 if (!new_prog) 18677 return -ENOMEM; 18678 18679 env->prog = new_prog; 18680 delta += cnt - 1; 18681 } 18682 } 18683 18684 if (bpf_prog_is_offloaded(env->prog->aux)) 18685 return 0; 18686 18687 insn = env->prog->insnsi + delta; 18688 18689 for (i = 0; i < insn_cnt; i++, insn++) { 18690 bpf_convert_ctx_access_t convert_ctx_access; 18691 u8 mode; 18692 18693 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 18694 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 18695 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 18696 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 18697 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 18698 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 18699 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 18700 type = BPF_READ; 18701 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 18702 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 18703 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 18704 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 18705 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 18706 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 18707 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 18708 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 18709 type = BPF_WRITE; 18710 } else { 18711 continue; 18712 } 18713 18714 if (type == BPF_WRITE && 18715 env->insn_aux_data[i + delta].sanitize_stack_spill) { 18716 struct bpf_insn patch[] = { 18717 *insn, 18718 BPF_ST_NOSPEC(), 18719 }; 18720 18721 cnt = ARRAY_SIZE(patch); 18722 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 18723 if (!new_prog) 18724 return -ENOMEM; 18725 18726 delta += cnt - 1; 18727 env->prog = new_prog; 18728 insn = new_prog->insnsi + i + delta; 18729 continue; 18730 } 18731 18732 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 18733 case PTR_TO_CTX: 18734 if (!ops->convert_ctx_access) 18735 continue; 18736 convert_ctx_access = ops->convert_ctx_access; 18737 break; 18738 case PTR_TO_SOCKET: 18739 case PTR_TO_SOCK_COMMON: 18740 convert_ctx_access = bpf_sock_convert_ctx_access; 18741 break; 18742 case PTR_TO_TCP_SOCK: 18743 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 18744 break; 18745 case PTR_TO_XDP_SOCK: 18746 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 18747 break; 18748 case PTR_TO_BTF_ID: 18749 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 18750 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 18751 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 18752 * be said once it is marked PTR_UNTRUSTED, hence we must handle 18753 * any faults for loads into such types. BPF_WRITE is disallowed 18754 * for this case. 18755 */ 18756 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 18757 if (type == BPF_READ) { 18758 if (BPF_MODE(insn->code) == BPF_MEM) 18759 insn->code = BPF_LDX | BPF_PROBE_MEM | 18760 BPF_SIZE((insn)->code); 18761 else 18762 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 18763 BPF_SIZE((insn)->code); 18764 env->prog->aux->num_exentries++; 18765 } 18766 continue; 18767 default: 18768 continue; 18769 } 18770 18771 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 18772 size = BPF_LDST_BYTES(insn); 18773 mode = BPF_MODE(insn->code); 18774 18775 /* If the read access is a narrower load of the field, 18776 * convert to a 4/8-byte load, to minimum program type specific 18777 * convert_ctx_access changes. If conversion is successful, 18778 * we will apply proper mask to the result. 18779 */ 18780 is_narrower_load = size < ctx_field_size; 18781 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 18782 off = insn->off; 18783 if (is_narrower_load) { 18784 u8 size_code; 18785 18786 if (type == BPF_WRITE) { 18787 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 18788 return -EINVAL; 18789 } 18790 18791 size_code = BPF_H; 18792 if (ctx_field_size == 4) 18793 size_code = BPF_W; 18794 else if (ctx_field_size == 8) 18795 size_code = BPF_DW; 18796 18797 insn->off = off & ~(size_default - 1); 18798 insn->code = BPF_LDX | BPF_MEM | size_code; 18799 } 18800 18801 target_size = 0; 18802 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 18803 &target_size); 18804 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 18805 (ctx_field_size && !target_size)) { 18806 verbose(env, "bpf verifier is misconfigured\n"); 18807 return -EINVAL; 18808 } 18809 18810 if (is_narrower_load && size < target_size) { 18811 u8 shift = bpf_ctx_narrow_access_offset( 18812 off, size, size_default) * 8; 18813 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 18814 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 18815 return -EINVAL; 18816 } 18817 if (ctx_field_size <= 4) { 18818 if (shift) 18819 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 18820 insn->dst_reg, 18821 shift); 18822 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18823 (1 << size * 8) - 1); 18824 } else { 18825 if (shift) 18826 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 18827 insn->dst_reg, 18828 shift); 18829 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18830 (1ULL << size * 8) - 1); 18831 } 18832 } 18833 if (mode == BPF_MEMSX) 18834 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 18835 insn->dst_reg, insn->dst_reg, 18836 size * 8, 0); 18837 18838 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18839 if (!new_prog) 18840 return -ENOMEM; 18841 18842 delta += cnt - 1; 18843 18844 /* keep walking new program and skip insns we just inserted */ 18845 env->prog = new_prog; 18846 insn = new_prog->insnsi + i + delta; 18847 } 18848 18849 return 0; 18850 } 18851 18852 static int jit_subprogs(struct bpf_verifier_env *env) 18853 { 18854 struct bpf_prog *prog = env->prog, **func, *tmp; 18855 int i, j, subprog_start, subprog_end = 0, len, subprog; 18856 struct bpf_map *map_ptr; 18857 struct bpf_insn *insn; 18858 void *old_bpf_func; 18859 int err, num_exentries; 18860 18861 if (env->subprog_cnt <= 1) 18862 return 0; 18863 18864 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18865 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 18866 continue; 18867 18868 /* Upon error here we cannot fall back to interpreter but 18869 * need a hard reject of the program. Thus -EFAULT is 18870 * propagated in any case. 18871 */ 18872 subprog = find_subprog(env, i + insn->imm + 1); 18873 if (subprog < 0) { 18874 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 18875 i + insn->imm + 1); 18876 return -EFAULT; 18877 } 18878 /* temporarily remember subprog id inside insn instead of 18879 * aux_data, since next loop will split up all insns into funcs 18880 */ 18881 insn->off = subprog; 18882 /* remember original imm in case JIT fails and fallback 18883 * to interpreter will be needed 18884 */ 18885 env->insn_aux_data[i].call_imm = insn->imm; 18886 /* point imm to __bpf_call_base+1 from JITs point of view */ 18887 insn->imm = 1; 18888 if (bpf_pseudo_func(insn)) 18889 /* jit (e.g. x86_64) may emit fewer instructions 18890 * if it learns a u32 imm is the same as a u64 imm. 18891 * Force a non zero here. 18892 */ 18893 insn[1].imm = 1; 18894 } 18895 18896 err = bpf_prog_alloc_jited_linfo(prog); 18897 if (err) 18898 goto out_undo_insn; 18899 18900 err = -ENOMEM; 18901 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 18902 if (!func) 18903 goto out_undo_insn; 18904 18905 for (i = 0; i < env->subprog_cnt; i++) { 18906 subprog_start = subprog_end; 18907 subprog_end = env->subprog_info[i + 1].start; 18908 18909 len = subprog_end - subprog_start; 18910 /* bpf_prog_run() doesn't call subprogs directly, 18911 * hence main prog stats include the runtime of subprogs. 18912 * subprogs don't have IDs and not reachable via prog_get_next_id 18913 * func[i]->stats will never be accessed and stays NULL 18914 */ 18915 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 18916 if (!func[i]) 18917 goto out_free; 18918 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 18919 len * sizeof(struct bpf_insn)); 18920 func[i]->type = prog->type; 18921 func[i]->len = len; 18922 if (bpf_prog_calc_tag(func[i])) 18923 goto out_free; 18924 func[i]->is_func = 1; 18925 func[i]->aux->func_idx = i; 18926 /* Below members will be freed only at prog->aux */ 18927 func[i]->aux->btf = prog->aux->btf; 18928 func[i]->aux->func_info = prog->aux->func_info; 18929 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 18930 func[i]->aux->poke_tab = prog->aux->poke_tab; 18931 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 18932 18933 for (j = 0; j < prog->aux->size_poke_tab; j++) { 18934 struct bpf_jit_poke_descriptor *poke; 18935 18936 poke = &prog->aux->poke_tab[j]; 18937 if (poke->insn_idx < subprog_end && 18938 poke->insn_idx >= subprog_start) 18939 poke->aux = func[i]->aux; 18940 } 18941 18942 func[i]->aux->name[0] = 'F'; 18943 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 18944 func[i]->jit_requested = 1; 18945 func[i]->blinding_requested = prog->blinding_requested; 18946 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 18947 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 18948 func[i]->aux->linfo = prog->aux->linfo; 18949 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 18950 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 18951 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 18952 num_exentries = 0; 18953 insn = func[i]->insnsi; 18954 for (j = 0; j < func[i]->len; j++, insn++) { 18955 if (BPF_CLASS(insn->code) == BPF_LDX && 18956 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 18957 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 18958 num_exentries++; 18959 } 18960 func[i]->aux->num_exentries = num_exentries; 18961 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 18962 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb; 18963 if (!i) 18964 func[i]->aux->exception_boundary = env->seen_exception; 18965 func[i] = bpf_int_jit_compile(func[i]); 18966 if (!func[i]->jited) { 18967 err = -ENOTSUPP; 18968 goto out_free; 18969 } 18970 cond_resched(); 18971 } 18972 18973 /* at this point all bpf functions were successfully JITed 18974 * now populate all bpf_calls with correct addresses and 18975 * run last pass of JIT 18976 */ 18977 for (i = 0; i < env->subprog_cnt; i++) { 18978 insn = func[i]->insnsi; 18979 for (j = 0; j < func[i]->len; j++, insn++) { 18980 if (bpf_pseudo_func(insn)) { 18981 subprog = insn->off; 18982 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 18983 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 18984 continue; 18985 } 18986 if (!bpf_pseudo_call(insn)) 18987 continue; 18988 subprog = insn->off; 18989 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 18990 } 18991 18992 /* we use the aux data to keep a list of the start addresses 18993 * of the JITed images for each function in the program 18994 * 18995 * for some architectures, such as powerpc64, the imm field 18996 * might not be large enough to hold the offset of the start 18997 * address of the callee's JITed image from __bpf_call_base 18998 * 18999 * in such cases, we can lookup the start address of a callee 19000 * by using its subprog id, available from the off field of 19001 * the call instruction, as an index for this list 19002 */ 19003 func[i]->aux->func = func; 19004 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 19005 func[i]->aux->real_func_cnt = env->subprog_cnt; 19006 } 19007 for (i = 0; i < env->subprog_cnt; i++) { 19008 old_bpf_func = func[i]->bpf_func; 19009 tmp = bpf_int_jit_compile(func[i]); 19010 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 19011 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 19012 err = -ENOTSUPP; 19013 goto out_free; 19014 } 19015 cond_resched(); 19016 } 19017 19018 /* finally lock prog and jit images for all functions and 19019 * populate kallsysm. Begin at the first subprogram, since 19020 * bpf_prog_load will add the kallsyms for the main program. 19021 */ 19022 for (i = 1; i < env->subprog_cnt; i++) { 19023 bpf_prog_lock_ro(func[i]); 19024 bpf_prog_kallsyms_add(func[i]); 19025 } 19026 19027 /* Last step: make now unused interpreter insns from main 19028 * prog consistent for later dump requests, so they can 19029 * later look the same as if they were interpreted only. 19030 */ 19031 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 19032 if (bpf_pseudo_func(insn)) { 19033 insn[0].imm = env->insn_aux_data[i].call_imm; 19034 insn[1].imm = insn->off; 19035 insn->off = 0; 19036 continue; 19037 } 19038 if (!bpf_pseudo_call(insn)) 19039 continue; 19040 insn->off = env->insn_aux_data[i].call_imm; 19041 subprog = find_subprog(env, i + insn->off + 1); 19042 insn->imm = subprog; 19043 } 19044 19045 prog->jited = 1; 19046 prog->bpf_func = func[0]->bpf_func; 19047 prog->jited_len = func[0]->jited_len; 19048 prog->aux->extable = func[0]->aux->extable; 19049 prog->aux->num_exentries = func[0]->aux->num_exentries; 19050 prog->aux->func = func; 19051 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 19052 prog->aux->real_func_cnt = env->subprog_cnt; 19053 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func; 19054 prog->aux->exception_boundary = func[0]->aux->exception_boundary; 19055 bpf_prog_jit_attempt_done(prog); 19056 return 0; 19057 out_free: 19058 /* We failed JIT'ing, so at this point we need to unregister poke 19059 * descriptors from subprogs, so that kernel is not attempting to 19060 * patch it anymore as we're freeing the subprog JIT memory. 19061 */ 19062 for (i = 0; i < prog->aux->size_poke_tab; i++) { 19063 map_ptr = prog->aux->poke_tab[i].tail_call.map; 19064 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 19065 } 19066 /* At this point we're guaranteed that poke descriptors are not 19067 * live anymore. We can just unlink its descriptor table as it's 19068 * released with the main prog. 19069 */ 19070 for (i = 0; i < env->subprog_cnt; i++) { 19071 if (!func[i]) 19072 continue; 19073 func[i]->aux->poke_tab = NULL; 19074 bpf_jit_free(func[i]); 19075 } 19076 kfree(func); 19077 out_undo_insn: 19078 /* cleanup main prog to be interpreted */ 19079 prog->jit_requested = 0; 19080 prog->blinding_requested = 0; 19081 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 19082 if (!bpf_pseudo_call(insn)) 19083 continue; 19084 insn->off = 0; 19085 insn->imm = env->insn_aux_data[i].call_imm; 19086 } 19087 bpf_prog_jit_attempt_done(prog); 19088 return err; 19089 } 19090 19091 static int fixup_call_args(struct bpf_verifier_env *env) 19092 { 19093 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 19094 struct bpf_prog *prog = env->prog; 19095 struct bpf_insn *insn = prog->insnsi; 19096 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 19097 int i, depth; 19098 #endif 19099 int err = 0; 19100 19101 if (env->prog->jit_requested && 19102 !bpf_prog_is_offloaded(env->prog->aux)) { 19103 err = jit_subprogs(env); 19104 if (err == 0) 19105 return 0; 19106 if (err == -EFAULT) 19107 return err; 19108 } 19109 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 19110 if (has_kfunc_call) { 19111 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 19112 return -EINVAL; 19113 } 19114 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 19115 /* When JIT fails the progs with bpf2bpf calls and tail_calls 19116 * have to be rejected, since interpreter doesn't support them yet. 19117 */ 19118 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 19119 return -EINVAL; 19120 } 19121 for (i = 0; i < prog->len; i++, insn++) { 19122 if (bpf_pseudo_func(insn)) { 19123 /* When JIT fails the progs with callback calls 19124 * have to be rejected, since interpreter doesn't support them yet. 19125 */ 19126 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 19127 return -EINVAL; 19128 } 19129 19130 if (!bpf_pseudo_call(insn)) 19131 continue; 19132 depth = get_callee_stack_depth(env, insn, i); 19133 if (depth < 0) 19134 return depth; 19135 bpf_patch_call_args(insn, depth); 19136 } 19137 err = 0; 19138 #endif 19139 return err; 19140 } 19141 19142 /* replace a generic kfunc with a specialized version if necessary */ 19143 static void specialize_kfunc(struct bpf_verifier_env *env, 19144 u32 func_id, u16 offset, unsigned long *addr) 19145 { 19146 struct bpf_prog *prog = env->prog; 19147 bool seen_direct_write; 19148 void *xdp_kfunc; 19149 bool is_rdonly; 19150 19151 if (bpf_dev_bound_kfunc_id(func_id)) { 19152 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 19153 if (xdp_kfunc) { 19154 *addr = (unsigned long)xdp_kfunc; 19155 return; 19156 } 19157 /* fallback to default kfunc when not supported by netdev */ 19158 } 19159 19160 if (offset) 19161 return; 19162 19163 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 19164 seen_direct_write = env->seen_direct_write; 19165 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 19166 19167 if (is_rdonly) 19168 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 19169 19170 /* restore env->seen_direct_write to its original value, since 19171 * may_access_direct_pkt_data mutates it 19172 */ 19173 env->seen_direct_write = seen_direct_write; 19174 } 19175 } 19176 19177 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 19178 u16 struct_meta_reg, 19179 u16 node_offset_reg, 19180 struct bpf_insn *insn, 19181 struct bpf_insn *insn_buf, 19182 int *cnt) 19183 { 19184 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 19185 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 19186 19187 insn_buf[0] = addr[0]; 19188 insn_buf[1] = addr[1]; 19189 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 19190 insn_buf[3] = *insn; 19191 *cnt = 4; 19192 } 19193 19194 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 19195 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 19196 { 19197 const struct bpf_kfunc_desc *desc; 19198 19199 if (!insn->imm) { 19200 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 19201 return -EINVAL; 19202 } 19203 19204 *cnt = 0; 19205 19206 /* insn->imm has the btf func_id. Replace it with an offset relative to 19207 * __bpf_call_base, unless the JIT needs to call functions that are 19208 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 19209 */ 19210 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 19211 if (!desc) { 19212 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 19213 insn->imm); 19214 return -EFAULT; 19215 } 19216 19217 if (!bpf_jit_supports_far_kfunc_call()) 19218 insn->imm = BPF_CALL_IMM(desc->addr); 19219 if (insn->off) 19220 return 0; 19221 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 19222 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 19223 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19224 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19225 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 19226 19227 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) { 19228 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 19229 insn_idx); 19230 return -EFAULT; 19231 } 19232 19233 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 19234 insn_buf[1] = addr[0]; 19235 insn_buf[2] = addr[1]; 19236 insn_buf[3] = *insn; 19237 *cnt = 4; 19238 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 19239 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] || 19240 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 19241 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19242 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19243 19244 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) { 19245 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 19246 insn_idx); 19247 return -EFAULT; 19248 } 19249 19250 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 19251 !kptr_struct_meta) { 19252 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 19253 insn_idx); 19254 return -EFAULT; 19255 } 19256 19257 insn_buf[0] = addr[0]; 19258 insn_buf[1] = addr[1]; 19259 insn_buf[2] = *insn; 19260 *cnt = 3; 19261 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 19262 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 19263 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 19264 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19265 int struct_meta_reg = BPF_REG_3; 19266 int node_offset_reg = BPF_REG_4; 19267 19268 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 19269 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 19270 struct_meta_reg = BPF_REG_4; 19271 node_offset_reg = BPF_REG_5; 19272 } 19273 19274 if (!kptr_struct_meta) { 19275 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 19276 insn_idx); 19277 return -EFAULT; 19278 } 19279 19280 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 19281 node_offset_reg, insn, insn_buf, cnt); 19282 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 19283 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 19284 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 19285 *cnt = 1; 19286 } 19287 return 0; 19288 } 19289 19290 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */ 19291 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len) 19292 { 19293 struct bpf_subprog_info *info = env->subprog_info; 19294 int cnt = env->subprog_cnt; 19295 struct bpf_prog *prog; 19296 19297 /* We only reserve one slot for hidden subprogs in subprog_info. */ 19298 if (env->hidden_subprog_cnt) { 19299 verbose(env, "verifier internal error: only one hidden subprog supported\n"); 19300 return -EFAULT; 19301 } 19302 /* We're not patching any existing instruction, just appending the new 19303 * ones for the hidden subprog. Hence all of the adjustment operations 19304 * in bpf_patch_insn_data are no-ops. 19305 */ 19306 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len); 19307 if (!prog) 19308 return -ENOMEM; 19309 env->prog = prog; 19310 info[cnt + 1].start = info[cnt].start; 19311 info[cnt].start = prog->len - len + 1; 19312 env->subprog_cnt++; 19313 env->hidden_subprog_cnt++; 19314 return 0; 19315 } 19316 19317 /* Do various post-verification rewrites in a single program pass. 19318 * These rewrites simplify JIT and interpreter implementations. 19319 */ 19320 static int do_misc_fixups(struct bpf_verifier_env *env) 19321 { 19322 struct bpf_prog *prog = env->prog; 19323 enum bpf_attach_type eatype = prog->expected_attach_type; 19324 enum bpf_prog_type prog_type = resolve_prog_type(prog); 19325 struct bpf_insn *insn = prog->insnsi; 19326 const struct bpf_func_proto *fn; 19327 const int insn_cnt = prog->len; 19328 const struct bpf_map_ops *ops; 19329 struct bpf_insn_aux_data *aux; 19330 struct bpf_insn insn_buf[16]; 19331 struct bpf_prog *new_prog; 19332 struct bpf_map *map_ptr; 19333 int i, ret, cnt, delta = 0; 19334 19335 if (env->seen_exception && !env->exception_callback_subprog) { 19336 struct bpf_insn patch[] = { 19337 env->prog->insnsi[insn_cnt - 1], 19338 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1), 19339 BPF_EXIT_INSN(), 19340 }; 19341 19342 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch)); 19343 if (ret < 0) 19344 return ret; 19345 prog = env->prog; 19346 insn = prog->insnsi; 19347 19348 env->exception_callback_subprog = env->subprog_cnt - 1; 19349 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */ 19350 mark_subprog_exc_cb(env, env->exception_callback_subprog); 19351 } 19352 19353 for (i = 0; i < insn_cnt; i++, insn++) { 19354 /* Make divide-by-zero exceptions impossible. */ 19355 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 19356 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 19357 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 19358 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 19359 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 19360 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 19361 struct bpf_insn *patchlet; 19362 struct bpf_insn chk_and_div[] = { 19363 /* [R,W]x div 0 -> 0 */ 19364 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 19365 BPF_JNE | BPF_K, insn->src_reg, 19366 0, 2, 0), 19367 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 19368 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 19369 *insn, 19370 }; 19371 struct bpf_insn chk_and_mod[] = { 19372 /* [R,W]x mod 0 -> [R,W]x */ 19373 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 19374 BPF_JEQ | BPF_K, insn->src_reg, 19375 0, 1 + (is64 ? 0 : 1), 0), 19376 *insn, 19377 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 19378 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 19379 }; 19380 19381 patchlet = isdiv ? chk_and_div : chk_and_mod; 19382 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 19383 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 19384 19385 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, 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 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 19396 if (BPF_CLASS(insn->code) == BPF_LD && 19397 (BPF_MODE(insn->code) == BPF_ABS || 19398 BPF_MODE(insn->code) == BPF_IND)) { 19399 cnt = env->ops->gen_ld_abs(insn, insn_buf); 19400 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19401 verbose(env, "bpf verifier is misconfigured\n"); 19402 return -EINVAL; 19403 } 19404 19405 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19406 if (!new_prog) 19407 return -ENOMEM; 19408 19409 delta += cnt - 1; 19410 env->prog = prog = new_prog; 19411 insn = new_prog->insnsi + i + delta; 19412 continue; 19413 } 19414 19415 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 19416 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 19417 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 19418 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 19419 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 19420 struct bpf_insn *patch = &insn_buf[0]; 19421 bool issrc, isneg, isimm; 19422 u32 off_reg; 19423 19424 aux = &env->insn_aux_data[i + delta]; 19425 if (!aux->alu_state || 19426 aux->alu_state == BPF_ALU_NON_POINTER) 19427 continue; 19428 19429 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 19430 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 19431 BPF_ALU_SANITIZE_SRC; 19432 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 19433 19434 off_reg = issrc ? insn->src_reg : insn->dst_reg; 19435 if (isimm) { 19436 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19437 } else { 19438 if (isneg) 19439 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19440 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19441 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 19442 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 19443 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 19444 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 19445 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 19446 } 19447 if (!issrc) 19448 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 19449 insn->src_reg = BPF_REG_AX; 19450 if (isneg) 19451 insn->code = insn->code == code_add ? 19452 code_sub : code_add; 19453 *patch++ = *insn; 19454 if (issrc && isneg && !isimm) 19455 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19456 cnt = patch - insn_buf; 19457 19458 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19459 if (!new_prog) 19460 return -ENOMEM; 19461 19462 delta += cnt - 1; 19463 env->prog = prog = new_prog; 19464 insn = new_prog->insnsi + i + delta; 19465 continue; 19466 } 19467 19468 if (insn->code != (BPF_JMP | BPF_CALL)) 19469 continue; 19470 if (insn->src_reg == BPF_PSEUDO_CALL) 19471 continue; 19472 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 19473 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 19474 if (ret) 19475 return ret; 19476 if (cnt == 0) 19477 continue; 19478 19479 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19480 if (!new_prog) 19481 return -ENOMEM; 19482 19483 delta += cnt - 1; 19484 env->prog = prog = new_prog; 19485 insn = new_prog->insnsi + i + delta; 19486 continue; 19487 } 19488 19489 if (insn->imm == BPF_FUNC_get_route_realm) 19490 prog->dst_needed = 1; 19491 if (insn->imm == BPF_FUNC_get_prandom_u32) 19492 bpf_user_rnd_init_once(); 19493 if (insn->imm == BPF_FUNC_override_return) 19494 prog->kprobe_override = 1; 19495 if (insn->imm == BPF_FUNC_tail_call) { 19496 /* If we tail call into other programs, we 19497 * cannot make any assumptions since they can 19498 * be replaced dynamically during runtime in 19499 * the program array. 19500 */ 19501 prog->cb_access = 1; 19502 if (!allow_tail_call_in_subprogs(env)) 19503 prog->aux->stack_depth = MAX_BPF_STACK; 19504 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 19505 19506 /* mark bpf_tail_call as different opcode to avoid 19507 * conditional branch in the interpreter for every normal 19508 * call and to prevent accidental JITing by JIT compiler 19509 * that doesn't support bpf_tail_call yet 19510 */ 19511 insn->imm = 0; 19512 insn->code = BPF_JMP | BPF_TAIL_CALL; 19513 19514 aux = &env->insn_aux_data[i + delta]; 19515 if (env->bpf_capable && !prog->blinding_requested && 19516 prog->jit_requested && 19517 !bpf_map_key_poisoned(aux) && 19518 !bpf_map_ptr_poisoned(aux) && 19519 !bpf_map_ptr_unpriv(aux)) { 19520 struct bpf_jit_poke_descriptor desc = { 19521 .reason = BPF_POKE_REASON_TAIL_CALL, 19522 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 19523 .tail_call.key = bpf_map_key_immediate(aux), 19524 .insn_idx = i + delta, 19525 }; 19526 19527 ret = bpf_jit_add_poke_descriptor(prog, &desc); 19528 if (ret < 0) { 19529 verbose(env, "adding tail call poke descriptor failed\n"); 19530 return ret; 19531 } 19532 19533 insn->imm = ret + 1; 19534 continue; 19535 } 19536 19537 if (!bpf_map_ptr_unpriv(aux)) 19538 continue; 19539 19540 /* instead of changing every JIT dealing with tail_call 19541 * emit two extra insns: 19542 * if (index >= max_entries) goto out; 19543 * index &= array->index_mask; 19544 * to avoid out-of-bounds cpu speculation 19545 */ 19546 if (bpf_map_ptr_poisoned(aux)) { 19547 verbose(env, "tail_call abusing map_ptr\n"); 19548 return -EINVAL; 19549 } 19550 19551 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19552 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 19553 map_ptr->max_entries, 2); 19554 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 19555 container_of(map_ptr, 19556 struct bpf_array, 19557 map)->index_mask); 19558 insn_buf[2] = *insn; 19559 cnt = 3; 19560 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19561 if (!new_prog) 19562 return -ENOMEM; 19563 19564 delta += cnt - 1; 19565 env->prog = prog = new_prog; 19566 insn = new_prog->insnsi + i + delta; 19567 continue; 19568 } 19569 19570 if (insn->imm == BPF_FUNC_timer_set_callback) { 19571 /* The verifier will process callback_fn as many times as necessary 19572 * with different maps and the register states prepared by 19573 * set_timer_callback_state will be accurate. 19574 * 19575 * The following use case is valid: 19576 * map1 is shared by prog1, prog2, prog3. 19577 * prog1 calls bpf_timer_init for some map1 elements 19578 * prog2 calls bpf_timer_set_callback for some map1 elements. 19579 * Those that were not bpf_timer_init-ed will return -EINVAL. 19580 * prog3 calls bpf_timer_start for some map1 elements. 19581 * Those that were not both bpf_timer_init-ed and 19582 * bpf_timer_set_callback-ed will return -EINVAL. 19583 */ 19584 struct bpf_insn ld_addrs[2] = { 19585 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 19586 }; 19587 19588 insn_buf[0] = ld_addrs[0]; 19589 insn_buf[1] = ld_addrs[1]; 19590 insn_buf[2] = *insn; 19591 cnt = 3; 19592 19593 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19594 if (!new_prog) 19595 return -ENOMEM; 19596 19597 delta += cnt - 1; 19598 env->prog = prog = new_prog; 19599 insn = new_prog->insnsi + i + delta; 19600 goto patch_call_imm; 19601 } 19602 19603 if (is_storage_get_function(insn->imm)) { 19604 if (!env->prog->aux->sleepable || 19605 env->insn_aux_data[i + delta].storage_get_func_atomic) 19606 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 19607 else 19608 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 19609 insn_buf[1] = *insn; 19610 cnt = 2; 19611 19612 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19613 if (!new_prog) 19614 return -ENOMEM; 19615 19616 delta += cnt - 1; 19617 env->prog = prog = new_prog; 19618 insn = new_prog->insnsi + i + delta; 19619 goto patch_call_imm; 19620 } 19621 19622 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */ 19623 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) { 19624 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data, 19625 * bpf_mem_alloc() returns a ptr to the percpu data ptr. 19626 */ 19627 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0); 19628 insn_buf[1] = *insn; 19629 cnt = 2; 19630 19631 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19632 if (!new_prog) 19633 return -ENOMEM; 19634 19635 delta += cnt - 1; 19636 env->prog = prog = new_prog; 19637 insn = new_prog->insnsi + i + delta; 19638 goto patch_call_imm; 19639 } 19640 19641 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 19642 * and other inlining handlers are currently limited to 64 bit 19643 * only. 19644 */ 19645 if (prog->jit_requested && BITS_PER_LONG == 64 && 19646 (insn->imm == BPF_FUNC_map_lookup_elem || 19647 insn->imm == BPF_FUNC_map_update_elem || 19648 insn->imm == BPF_FUNC_map_delete_elem || 19649 insn->imm == BPF_FUNC_map_push_elem || 19650 insn->imm == BPF_FUNC_map_pop_elem || 19651 insn->imm == BPF_FUNC_map_peek_elem || 19652 insn->imm == BPF_FUNC_redirect_map || 19653 insn->imm == BPF_FUNC_for_each_map_elem || 19654 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 19655 aux = &env->insn_aux_data[i + delta]; 19656 if (bpf_map_ptr_poisoned(aux)) 19657 goto patch_call_imm; 19658 19659 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19660 ops = map_ptr->ops; 19661 if (insn->imm == BPF_FUNC_map_lookup_elem && 19662 ops->map_gen_lookup) { 19663 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 19664 if (cnt == -EOPNOTSUPP) 19665 goto patch_map_ops_generic; 19666 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19667 verbose(env, "bpf verifier is misconfigured\n"); 19668 return -EINVAL; 19669 } 19670 19671 new_prog = bpf_patch_insn_data(env, i + delta, 19672 insn_buf, cnt); 19673 if (!new_prog) 19674 return -ENOMEM; 19675 19676 delta += cnt - 1; 19677 env->prog = prog = new_prog; 19678 insn = new_prog->insnsi + i + delta; 19679 continue; 19680 } 19681 19682 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 19683 (void *(*)(struct bpf_map *map, void *key))NULL)); 19684 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 19685 (long (*)(struct bpf_map *map, void *key))NULL)); 19686 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 19687 (long (*)(struct bpf_map *map, void *key, void *value, 19688 u64 flags))NULL)); 19689 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 19690 (long (*)(struct bpf_map *map, void *value, 19691 u64 flags))NULL)); 19692 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 19693 (long (*)(struct bpf_map *map, void *value))NULL)); 19694 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 19695 (long (*)(struct bpf_map *map, void *value))NULL)); 19696 BUILD_BUG_ON(!__same_type(ops->map_redirect, 19697 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 19698 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 19699 (long (*)(struct bpf_map *map, 19700 bpf_callback_t callback_fn, 19701 void *callback_ctx, 19702 u64 flags))NULL)); 19703 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 19704 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 19705 19706 patch_map_ops_generic: 19707 switch (insn->imm) { 19708 case BPF_FUNC_map_lookup_elem: 19709 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 19710 continue; 19711 case BPF_FUNC_map_update_elem: 19712 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 19713 continue; 19714 case BPF_FUNC_map_delete_elem: 19715 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 19716 continue; 19717 case BPF_FUNC_map_push_elem: 19718 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 19719 continue; 19720 case BPF_FUNC_map_pop_elem: 19721 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 19722 continue; 19723 case BPF_FUNC_map_peek_elem: 19724 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 19725 continue; 19726 case BPF_FUNC_redirect_map: 19727 insn->imm = BPF_CALL_IMM(ops->map_redirect); 19728 continue; 19729 case BPF_FUNC_for_each_map_elem: 19730 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 19731 continue; 19732 case BPF_FUNC_map_lookup_percpu_elem: 19733 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 19734 continue; 19735 } 19736 19737 goto patch_call_imm; 19738 } 19739 19740 /* Implement bpf_jiffies64 inline. */ 19741 if (prog->jit_requested && BITS_PER_LONG == 64 && 19742 insn->imm == BPF_FUNC_jiffies64) { 19743 struct bpf_insn ld_jiffies_addr[2] = { 19744 BPF_LD_IMM64(BPF_REG_0, 19745 (unsigned long)&jiffies), 19746 }; 19747 19748 insn_buf[0] = ld_jiffies_addr[0]; 19749 insn_buf[1] = ld_jiffies_addr[1]; 19750 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 19751 BPF_REG_0, 0); 19752 cnt = 3; 19753 19754 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 19755 cnt); 19756 if (!new_prog) 19757 return -ENOMEM; 19758 19759 delta += cnt - 1; 19760 env->prog = prog = new_prog; 19761 insn = new_prog->insnsi + i + delta; 19762 continue; 19763 } 19764 19765 /* Implement bpf_get_func_arg inline. */ 19766 if (prog_type == BPF_PROG_TYPE_TRACING && 19767 insn->imm == BPF_FUNC_get_func_arg) { 19768 /* Load nr_args from ctx - 8 */ 19769 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19770 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 19771 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 19772 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 19773 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 19774 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19775 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 19776 insn_buf[7] = BPF_JMP_A(1); 19777 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 19778 cnt = 9; 19779 19780 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19781 if (!new_prog) 19782 return -ENOMEM; 19783 19784 delta += cnt - 1; 19785 env->prog = prog = new_prog; 19786 insn = new_prog->insnsi + i + delta; 19787 continue; 19788 } 19789 19790 /* Implement bpf_get_func_ret inline. */ 19791 if (prog_type == BPF_PROG_TYPE_TRACING && 19792 insn->imm == BPF_FUNC_get_func_ret) { 19793 if (eatype == BPF_TRACE_FEXIT || 19794 eatype == BPF_MODIFY_RETURN) { 19795 /* Load nr_args from ctx - 8 */ 19796 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19797 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 19798 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 19799 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19800 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 19801 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 19802 cnt = 6; 19803 } else { 19804 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 19805 cnt = 1; 19806 } 19807 19808 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19809 if (!new_prog) 19810 return -ENOMEM; 19811 19812 delta += cnt - 1; 19813 env->prog = prog = new_prog; 19814 insn = new_prog->insnsi + i + delta; 19815 continue; 19816 } 19817 19818 /* Implement get_func_arg_cnt inline. */ 19819 if (prog_type == BPF_PROG_TYPE_TRACING && 19820 insn->imm == BPF_FUNC_get_func_arg_cnt) { 19821 /* Load nr_args from ctx - 8 */ 19822 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19823 19824 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19825 if (!new_prog) 19826 return -ENOMEM; 19827 19828 env->prog = prog = new_prog; 19829 insn = new_prog->insnsi + i + delta; 19830 continue; 19831 } 19832 19833 /* Implement bpf_get_func_ip inline. */ 19834 if (prog_type == BPF_PROG_TYPE_TRACING && 19835 insn->imm == BPF_FUNC_get_func_ip) { 19836 /* Load IP address from ctx - 16 */ 19837 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 19838 19839 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19840 if (!new_prog) 19841 return -ENOMEM; 19842 19843 env->prog = prog = new_prog; 19844 insn = new_prog->insnsi + i + delta; 19845 continue; 19846 } 19847 19848 /* Implement bpf_kptr_xchg inline */ 19849 if (prog->jit_requested && BITS_PER_LONG == 64 && 19850 insn->imm == BPF_FUNC_kptr_xchg && 19851 bpf_jit_supports_ptr_xchg()) { 19852 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2); 19853 insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0); 19854 cnt = 2; 19855 19856 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19857 if (!new_prog) 19858 return -ENOMEM; 19859 19860 delta += cnt - 1; 19861 env->prog = prog = new_prog; 19862 insn = new_prog->insnsi + i + delta; 19863 continue; 19864 } 19865 patch_call_imm: 19866 fn = env->ops->get_func_proto(insn->imm, env->prog); 19867 /* all functions that have prototype and verifier allowed 19868 * programs to call them, must be real in-kernel functions 19869 */ 19870 if (!fn->func) { 19871 verbose(env, 19872 "kernel subsystem misconfigured func %s#%d\n", 19873 func_id_name(insn->imm), insn->imm); 19874 return -EFAULT; 19875 } 19876 insn->imm = fn->func - __bpf_call_base; 19877 } 19878 19879 /* Since poke tab is now finalized, publish aux to tracker. */ 19880 for (i = 0; i < prog->aux->size_poke_tab; i++) { 19881 map_ptr = prog->aux->poke_tab[i].tail_call.map; 19882 if (!map_ptr->ops->map_poke_track || 19883 !map_ptr->ops->map_poke_untrack || 19884 !map_ptr->ops->map_poke_run) { 19885 verbose(env, "bpf verifier is misconfigured\n"); 19886 return -EINVAL; 19887 } 19888 19889 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 19890 if (ret < 0) { 19891 verbose(env, "tracking tail call prog failed\n"); 19892 return ret; 19893 } 19894 } 19895 19896 sort_kfunc_descs_by_imm_off(env->prog); 19897 19898 return 0; 19899 } 19900 19901 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 19902 int position, 19903 s32 stack_base, 19904 u32 callback_subprogno, 19905 u32 *cnt) 19906 { 19907 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 19908 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 19909 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 19910 int reg_loop_max = BPF_REG_6; 19911 int reg_loop_cnt = BPF_REG_7; 19912 int reg_loop_ctx = BPF_REG_8; 19913 19914 struct bpf_prog *new_prog; 19915 u32 callback_start; 19916 u32 call_insn_offset; 19917 s32 callback_offset; 19918 19919 /* This represents an inlined version of bpf_iter.c:bpf_loop, 19920 * be careful to modify this code in sync. 19921 */ 19922 struct bpf_insn insn_buf[] = { 19923 /* Return error and jump to the end of the patch if 19924 * expected number of iterations is too big. 19925 */ 19926 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 19927 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 19928 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 19929 /* spill R6, R7, R8 to use these as loop vars */ 19930 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 19931 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 19932 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 19933 /* initialize loop vars */ 19934 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 19935 BPF_MOV32_IMM(reg_loop_cnt, 0), 19936 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 19937 /* loop header, 19938 * if reg_loop_cnt >= reg_loop_max skip the loop body 19939 */ 19940 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 19941 /* callback call, 19942 * correct callback offset would be set after patching 19943 */ 19944 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 19945 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 19946 BPF_CALL_REL(0), 19947 /* increment loop counter */ 19948 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 19949 /* jump to loop header if callback returned 0 */ 19950 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 19951 /* return value of bpf_loop, 19952 * set R0 to the number of iterations 19953 */ 19954 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 19955 /* restore original values of R6, R7, R8 */ 19956 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 19957 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 19958 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 19959 }; 19960 19961 *cnt = ARRAY_SIZE(insn_buf); 19962 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 19963 if (!new_prog) 19964 return new_prog; 19965 19966 /* callback start is known only after patching */ 19967 callback_start = env->subprog_info[callback_subprogno].start; 19968 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 19969 call_insn_offset = position + 12; 19970 callback_offset = callback_start - call_insn_offset - 1; 19971 new_prog->insnsi[call_insn_offset].imm = callback_offset; 19972 19973 return new_prog; 19974 } 19975 19976 static bool is_bpf_loop_call(struct bpf_insn *insn) 19977 { 19978 return insn->code == (BPF_JMP | BPF_CALL) && 19979 insn->src_reg == 0 && 19980 insn->imm == BPF_FUNC_loop; 19981 } 19982 19983 /* For all sub-programs in the program (including main) check 19984 * insn_aux_data to see if there are bpf_loop calls that require 19985 * inlining. If such calls are found the calls are replaced with a 19986 * sequence of instructions produced by `inline_bpf_loop` function and 19987 * subprog stack_depth is increased by the size of 3 registers. 19988 * This stack space is used to spill values of the R6, R7, R8. These 19989 * registers are used to store the loop bound, counter and context 19990 * variables. 19991 */ 19992 static int optimize_bpf_loop(struct bpf_verifier_env *env) 19993 { 19994 struct bpf_subprog_info *subprogs = env->subprog_info; 19995 int i, cur_subprog = 0, cnt, delta = 0; 19996 struct bpf_insn *insn = env->prog->insnsi; 19997 int insn_cnt = env->prog->len; 19998 u16 stack_depth = subprogs[cur_subprog].stack_depth; 19999 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 20000 u16 stack_depth_extra = 0; 20001 20002 for (i = 0; i < insn_cnt; i++, insn++) { 20003 struct bpf_loop_inline_state *inline_state = 20004 &env->insn_aux_data[i + delta].loop_inline_state; 20005 20006 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 20007 struct bpf_prog *new_prog; 20008 20009 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 20010 new_prog = inline_bpf_loop(env, 20011 i + delta, 20012 -(stack_depth + stack_depth_extra), 20013 inline_state->callback_subprogno, 20014 &cnt); 20015 if (!new_prog) 20016 return -ENOMEM; 20017 20018 delta += cnt - 1; 20019 env->prog = new_prog; 20020 insn = new_prog->insnsi + i + delta; 20021 } 20022 20023 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 20024 subprogs[cur_subprog].stack_depth += stack_depth_extra; 20025 cur_subprog++; 20026 stack_depth = subprogs[cur_subprog].stack_depth; 20027 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 20028 stack_depth_extra = 0; 20029 } 20030 } 20031 20032 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 20033 20034 return 0; 20035 } 20036 20037 static void free_states(struct bpf_verifier_env *env) 20038 { 20039 struct bpf_verifier_state_list *sl, *sln; 20040 int i; 20041 20042 sl = env->free_list; 20043 while (sl) { 20044 sln = sl->next; 20045 free_verifier_state(&sl->state, false); 20046 kfree(sl); 20047 sl = sln; 20048 } 20049 env->free_list = NULL; 20050 20051 if (!env->explored_states) 20052 return; 20053 20054 for (i = 0; i < state_htab_size(env); i++) { 20055 sl = env->explored_states[i]; 20056 20057 while (sl) { 20058 sln = sl->next; 20059 free_verifier_state(&sl->state, false); 20060 kfree(sl); 20061 sl = sln; 20062 } 20063 env->explored_states[i] = NULL; 20064 } 20065 } 20066 20067 static int do_check_common(struct bpf_verifier_env *env, int subprog) 20068 { 20069 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 20070 struct bpf_subprog_info *sub = subprog_info(env, subprog); 20071 struct bpf_verifier_state *state; 20072 struct bpf_reg_state *regs; 20073 int ret, i; 20074 20075 env->prev_linfo = NULL; 20076 env->pass_cnt++; 20077 20078 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 20079 if (!state) 20080 return -ENOMEM; 20081 state->curframe = 0; 20082 state->speculative = false; 20083 state->branches = 1; 20084 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 20085 if (!state->frame[0]) { 20086 kfree(state); 20087 return -ENOMEM; 20088 } 20089 env->cur_state = state; 20090 init_func_state(env, state->frame[0], 20091 BPF_MAIN_FUNC /* callsite */, 20092 0 /* frameno */, 20093 subprog); 20094 state->first_insn_idx = env->subprog_info[subprog].start; 20095 state->last_insn_idx = -1; 20096 20097 regs = state->frame[state->curframe]->regs; 20098 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 20099 const char *sub_name = subprog_name(env, subprog); 20100 struct bpf_subprog_arg_info *arg; 20101 struct bpf_reg_state *reg; 20102 20103 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 20104 ret = btf_prepare_func_args(env, subprog); 20105 if (ret) 20106 goto out; 20107 20108 if (subprog_is_exc_cb(env, subprog)) { 20109 state->frame[0]->in_exception_callback_fn = true; 20110 /* We have already ensured that the callback returns an integer, just 20111 * like all global subprogs. We need to determine it only has a single 20112 * scalar argument. 20113 */ 20114 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 20115 verbose(env, "exception cb only supports single integer argument\n"); 20116 ret = -EINVAL; 20117 goto out; 20118 } 20119 } 20120 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) { 20121 arg = &sub->args[i - BPF_REG_1]; 20122 reg = ®s[i]; 20123 20124 if (arg->arg_type == ARG_PTR_TO_CTX) { 20125 reg->type = PTR_TO_CTX; 20126 mark_reg_known_zero(env, regs, i); 20127 } else if (arg->arg_type == ARG_ANYTHING) { 20128 reg->type = SCALAR_VALUE; 20129 mark_reg_unknown(env, regs, i); 20130 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 20131 /* assume unspecial LOCAL dynptr type */ 20132 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen); 20133 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 20134 reg->type = PTR_TO_MEM; 20135 if (arg->arg_type & PTR_MAYBE_NULL) 20136 reg->type |= PTR_MAYBE_NULL; 20137 mark_reg_known_zero(env, regs, i); 20138 reg->mem_size = arg->mem_size; 20139 reg->id = ++env->id_gen; 20140 } else { 20141 WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n", 20142 i - BPF_REG_1, arg->arg_type); 20143 ret = -EFAULT; 20144 goto out; 20145 } 20146 } 20147 } else { 20148 /* if main BPF program has associated BTF info, validate that 20149 * it's matching expected signature, and otherwise mark BTF 20150 * info for main program as unreliable 20151 */ 20152 if (env->prog->aux->func_info_aux) { 20153 ret = btf_prepare_func_args(env, 0); 20154 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) 20155 env->prog->aux->func_info_aux[0].unreliable = true; 20156 } 20157 20158 /* 1st arg to a function */ 20159 regs[BPF_REG_1].type = PTR_TO_CTX; 20160 mark_reg_known_zero(env, regs, BPF_REG_1); 20161 } 20162 20163 ret = do_check(env); 20164 out: 20165 /* check for NULL is necessary, since cur_state can be freed inside 20166 * do_check() under memory pressure. 20167 */ 20168 if (env->cur_state) { 20169 free_verifier_state(env->cur_state, true); 20170 env->cur_state = NULL; 20171 } 20172 while (!pop_stack(env, NULL, NULL, false)); 20173 if (!ret && pop_log) 20174 bpf_vlog_reset(&env->log, 0); 20175 free_states(env); 20176 return ret; 20177 } 20178 20179 /* Lazily verify all global functions based on their BTF, if they are called 20180 * from main BPF program or any of subprograms transitively. 20181 * BPF global subprogs called from dead code are not validated. 20182 * All callable global functions must pass verification. 20183 * Otherwise the whole program is rejected. 20184 * Consider: 20185 * int bar(int); 20186 * int foo(int f) 20187 * { 20188 * return bar(f); 20189 * } 20190 * int bar(int b) 20191 * { 20192 * ... 20193 * } 20194 * foo() will be verified first for R1=any_scalar_value. During verification it 20195 * will be assumed that bar() already verified successfully and call to bar() 20196 * from foo() will be checked for type match only. Later bar() will be verified 20197 * independently to check that it's safe for R1=any_scalar_value. 20198 */ 20199 static int do_check_subprogs(struct bpf_verifier_env *env) 20200 { 20201 struct bpf_prog_aux *aux = env->prog->aux; 20202 struct bpf_func_info_aux *sub_aux; 20203 int i, ret, new_cnt; 20204 20205 if (!aux->func_info) 20206 return 0; 20207 20208 /* exception callback is presumed to be always called */ 20209 if (env->exception_callback_subprog) 20210 subprog_aux(env, env->exception_callback_subprog)->called = true; 20211 20212 again: 20213 new_cnt = 0; 20214 for (i = 1; i < env->subprog_cnt; i++) { 20215 if (!subprog_is_global(env, i)) 20216 continue; 20217 20218 sub_aux = subprog_aux(env, i); 20219 if (!sub_aux->called || sub_aux->verified) 20220 continue; 20221 20222 env->insn_idx = env->subprog_info[i].start; 20223 WARN_ON_ONCE(env->insn_idx == 0); 20224 ret = do_check_common(env, i); 20225 if (ret) { 20226 return ret; 20227 } else if (env->log.level & BPF_LOG_LEVEL) { 20228 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 20229 i, subprog_name(env, i)); 20230 } 20231 20232 /* We verified new global subprog, it might have called some 20233 * more global subprogs that we haven't verified yet, so we 20234 * need to do another pass over subprogs to verify those. 20235 */ 20236 sub_aux->verified = true; 20237 new_cnt++; 20238 } 20239 20240 /* We can't loop forever as we verify at least one global subprog on 20241 * each pass. 20242 */ 20243 if (new_cnt) 20244 goto again; 20245 20246 return 0; 20247 } 20248 20249 static int do_check_main(struct bpf_verifier_env *env) 20250 { 20251 int ret; 20252 20253 env->insn_idx = 0; 20254 ret = do_check_common(env, 0); 20255 if (!ret) 20256 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 20257 return ret; 20258 } 20259 20260 20261 static void print_verification_stats(struct bpf_verifier_env *env) 20262 { 20263 int i; 20264 20265 if (env->log.level & BPF_LOG_STATS) { 20266 verbose(env, "verification time %lld usec\n", 20267 div_u64(env->verification_time, 1000)); 20268 verbose(env, "stack depth "); 20269 for (i = 0; i < env->subprog_cnt; i++) { 20270 u32 depth = env->subprog_info[i].stack_depth; 20271 20272 verbose(env, "%d", depth); 20273 if (i + 1 < env->subprog_cnt) 20274 verbose(env, "+"); 20275 } 20276 verbose(env, "\n"); 20277 } 20278 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 20279 "total_states %d peak_states %d mark_read %d\n", 20280 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 20281 env->max_states_per_insn, env->total_states, 20282 env->peak_states, env->longest_mark_read_walk); 20283 } 20284 20285 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 20286 { 20287 const struct btf_type *t, *func_proto; 20288 const struct bpf_struct_ops_desc *st_ops_desc; 20289 const struct bpf_struct_ops *st_ops; 20290 const struct btf_member *member; 20291 struct bpf_prog *prog = env->prog; 20292 u32 btf_id, member_idx; 20293 struct btf *btf; 20294 const char *mname; 20295 20296 if (!prog->gpl_compatible) { 20297 verbose(env, "struct ops programs must have a GPL compatible license\n"); 20298 return -EINVAL; 20299 } 20300 20301 if (!prog->aux->attach_btf_id) 20302 return -ENOTSUPP; 20303 20304 btf = prog->aux->attach_btf; 20305 if (btf_is_module(btf)) { 20306 /* Make sure st_ops is valid through the lifetime of env */ 20307 env->attach_btf_mod = btf_try_get_module(btf); 20308 if (!env->attach_btf_mod) { 20309 verbose(env, "struct_ops module %s is not found\n", 20310 btf_get_name(btf)); 20311 return -ENOTSUPP; 20312 } 20313 } 20314 20315 btf_id = prog->aux->attach_btf_id; 20316 st_ops_desc = bpf_struct_ops_find(btf, btf_id); 20317 if (!st_ops_desc) { 20318 verbose(env, "attach_btf_id %u is not a supported struct\n", 20319 btf_id); 20320 return -ENOTSUPP; 20321 } 20322 st_ops = st_ops_desc->st_ops; 20323 20324 t = st_ops_desc->type; 20325 member_idx = prog->expected_attach_type; 20326 if (member_idx >= btf_type_vlen(t)) { 20327 verbose(env, "attach to invalid member idx %u of struct %s\n", 20328 member_idx, st_ops->name); 20329 return -EINVAL; 20330 } 20331 20332 member = &btf_type_member(t)[member_idx]; 20333 mname = btf_name_by_offset(btf, member->name_off); 20334 func_proto = btf_type_resolve_func_ptr(btf, member->type, 20335 NULL); 20336 if (!func_proto) { 20337 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 20338 mname, member_idx, st_ops->name); 20339 return -EINVAL; 20340 } 20341 20342 if (st_ops->check_member) { 20343 int err = st_ops->check_member(t, member, prog); 20344 20345 if (err) { 20346 verbose(env, "attach to unsupported member %s of struct %s\n", 20347 mname, st_ops->name); 20348 return err; 20349 } 20350 } 20351 20352 prog->aux->attach_func_proto = func_proto; 20353 prog->aux->attach_func_name = mname; 20354 env->ops = st_ops->verifier_ops; 20355 20356 return 0; 20357 } 20358 #define SECURITY_PREFIX "security_" 20359 20360 static int check_attach_modify_return(unsigned long addr, const char *func_name) 20361 { 20362 if (within_error_injection_list(addr) || 20363 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 20364 return 0; 20365 20366 return -EINVAL; 20367 } 20368 20369 /* list of non-sleepable functions that are otherwise on 20370 * ALLOW_ERROR_INJECTION list 20371 */ 20372 BTF_SET_START(btf_non_sleepable_error_inject) 20373 /* Three functions below can be called from sleepable and non-sleepable context. 20374 * Assume non-sleepable from bpf safety point of view. 20375 */ 20376 BTF_ID(func, __filemap_add_folio) 20377 BTF_ID(func, should_fail_alloc_page) 20378 BTF_ID(func, should_failslab) 20379 BTF_SET_END(btf_non_sleepable_error_inject) 20380 20381 static int check_non_sleepable_error_inject(u32 btf_id) 20382 { 20383 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 20384 } 20385 20386 int bpf_check_attach_target(struct bpf_verifier_log *log, 20387 const struct bpf_prog *prog, 20388 const struct bpf_prog *tgt_prog, 20389 u32 btf_id, 20390 struct bpf_attach_target_info *tgt_info) 20391 { 20392 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 20393 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 20394 const char prefix[] = "btf_trace_"; 20395 int ret = 0, subprog = -1, i; 20396 const struct btf_type *t; 20397 bool conservative = true; 20398 const char *tname; 20399 struct btf *btf; 20400 long addr = 0; 20401 struct module *mod = NULL; 20402 20403 if (!btf_id) { 20404 bpf_log(log, "Tracing programs must provide btf_id\n"); 20405 return -EINVAL; 20406 } 20407 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 20408 if (!btf) { 20409 bpf_log(log, 20410 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 20411 return -EINVAL; 20412 } 20413 t = btf_type_by_id(btf, btf_id); 20414 if (!t) { 20415 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 20416 return -EINVAL; 20417 } 20418 tname = btf_name_by_offset(btf, t->name_off); 20419 if (!tname) { 20420 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 20421 return -EINVAL; 20422 } 20423 if (tgt_prog) { 20424 struct bpf_prog_aux *aux = tgt_prog->aux; 20425 20426 if (bpf_prog_is_dev_bound(prog->aux) && 20427 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 20428 bpf_log(log, "Target program bound device mismatch"); 20429 return -EINVAL; 20430 } 20431 20432 for (i = 0; i < aux->func_info_cnt; i++) 20433 if (aux->func_info[i].type_id == btf_id) { 20434 subprog = i; 20435 break; 20436 } 20437 if (subprog == -1) { 20438 bpf_log(log, "Subprog %s doesn't exist\n", tname); 20439 return -EINVAL; 20440 } 20441 if (aux->func && aux->func[subprog]->aux->exception_cb) { 20442 bpf_log(log, 20443 "%s programs cannot attach to exception callback\n", 20444 prog_extension ? "Extension" : "FENTRY/FEXIT"); 20445 return -EINVAL; 20446 } 20447 conservative = aux->func_info_aux[subprog].unreliable; 20448 if (prog_extension) { 20449 if (conservative) { 20450 bpf_log(log, 20451 "Cannot replace static functions\n"); 20452 return -EINVAL; 20453 } 20454 if (!prog->jit_requested) { 20455 bpf_log(log, 20456 "Extension programs should be JITed\n"); 20457 return -EINVAL; 20458 } 20459 } 20460 if (!tgt_prog->jited) { 20461 bpf_log(log, "Can attach to only JITed progs\n"); 20462 return -EINVAL; 20463 } 20464 if (prog_tracing) { 20465 if (aux->attach_tracing_prog) { 20466 /* 20467 * Target program is an fentry/fexit which is already attached 20468 * to another tracing program. More levels of nesting 20469 * attachment are not allowed. 20470 */ 20471 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 20472 return -EINVAL; 20473 } 20474 } else if (tgt_prog->type == prog->type) { 20475 /* 20476 * To avoid potential call chain cycles, prevent attaching of a 20477 * program extension to another extension. It's ok to attach 20478 * fentry/fexit to extension program. 20479 */ 20480 bpf_log(log, "Cannot recursively attach\n"); 20481 return -EINVAL; 20482 } 20483 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 20484 prog_extension && 20485 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 20486 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 20487 /* Program extensions can extend all program types 20488 * except fentry/fexit. The reason is the following. 20489 * The fentry/fexit programs are used for performance 20490 * analysis, stats and can be attached to any program 20491 * type. When extension program is replacing XDP function 20492 * it is necessary to allow performance analysis of all 20493 * functions. Both original XDP program and its program 20494 * extension. Hence attaching fentry/fexit to 20495 * BPF_PROG_TYPE_EXT is allowed. If extending of 20496 * fentry/fexit was allowed it would be possible to create 20497 * long call chain fentry->extension->fentry->extension 20498 * beyond reasonable stack size. Hence extending fentry 20499 * is not allowed. 20500 */ 20501 bpf_log(log, "Cannot extend fentry/fexit\n"); 20502 return -EINVAL; 20503 } 20504 } else { 20505 if (prog_extension) { 20506 bpf_log(log, "Cannot replace kernel functions\n"); 20507 return -EINVAL; 20508 } 20509 } 20510 20511 switch (prog->expected_attach_type) { 20512 case BPF_TRACE_RAW_TP: 20513 if (tgt_prog) { 20514 bpf_log(log, 20515 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 20516 return -EINVAL; 20517 } 20518 if (!btf_type_is_typedef(t)) { 20519 bpf_log(log, "attach_btf_id %u is not a typedef\n", 20520 btf_id); 20521 return -EINVAL; 20522 } 20523 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 20524 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 20525 btf_id, tname); 20526 return -EINVAL; 20527 } 20528 tname += sizeof(prefix) - 1; 20529 t = btf_type_by_id(btf, t->type); 20530 if (!btf_type_is_ptr(t)) 20531 /* should never happen in valid vmlinux build */ 20532 return -EINVAL; 20533 t = btf_type_by_id(btf, t->type); 20534 if (!btf_type_is_func_proto(t)) 20535 /* should never happen in valid vmlinux build */ 20536 return -EINVAL; 20537 20538 break; 20539 case BPF_TRACE_ITER: 20540 if (!btf_type_is_func(t)) { 20541 bpf_log(log, "attach_btf_id %u is not a function\n", 20542 btf_id); 20543 return -EINVAL; 20544 } 20545 t = btf_type_by_id(btf, t->type); 20546 if (!btf_type_is_func_proto(t)) 20547 return -EINVAL; 20548 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 20549 if (ret) 20550 return ret; 20551 break; 20552 default: 20553 if (!prog_extension) 20554 return -EINVAL; 20555 fallthrough; 20556 case BPF_MODIFY_RETURN: 20557 case BPF_LSM_MAC: 20558 case BPF_LSM_CGROUP: 20559 case BPF_TRACE_FENTRY: 20560 case BPF_TRACE_FEXIT: 20561 if (!btf_type_is_func(t)) { 20562 bpf_log(log, "attach_btf_id %u is not a function\n", 20563 btf_id); 20564 return -EINVAL; 20565 } 20566 if (prog_extension && 20567 btf_check_type_match(log, prog, btf, t)) 20568 return -EINVAL; 20569 t = btf_type_by_id(btf, t->type); 20570 if (!btf_type_is_func_proto(t)) 20571 return -EINVAL; 20572 20573 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 20574 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 20575 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 20576 return -EINVAL; 20577 20578 if (tgt_prog && conservative) 20579 t = NULL; 20580 20581 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 20582 if (ret < 0) 20583 return ret; 20584 20585 if (tgt_prog) { 20586 if (subprog == 0) 20587 addr = (long) tgt_prog->bpf_func; 20588 else 20589 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 20590 } else { 20591 if (btf_is_module(btf)) { 20592 mod = btf_try_get_module(btf); 20593 if (mod) 20594 addr = find_kallsyms_symbol_value(mod, tname); 20595 else 20596 addr = 0; 20597 } else { 20598 addr = kallsyms_lookup_name(tname); 20599 } 20600 if (!addr) { 20601 module_put(mod); 20602 bpf_log(log, 20603 "The address of function %s cannot be found\n", 20604 tname); 20605 return -ENOENT; 20606 } 20607 } 20608 20609 if (prog->aux->sleepable) { 20610 ret = -EINVAL; 20611 switch (prog->type) { 20612 case BPF_PROG_TYPE_TRACING: 20613 20614 /* fentry/fexit/fmod_ret progs can be sleepable if they are 20615 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 20616 */ 20617 if (!check_non_sleepable_error_inject(btf_id) && 20618 within_error_injection_list(addr)) 20619 ret = 0; 20620 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 20621 * in the fmodret id set with the KF_SLEEPABLE flag. 20622 */ 20623 else { 20624 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 20625 prog); 20626 20627 if (flags && (*flags & KF_SLEEPABLE)) 20628 ret = 0; 20629 } 20630 break; 20631 case BPF_PROG_TYPE_LSM: 20632 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 20633 * Only some of them are sleepable. 20634 */ 20635 if (bpf_lsm_is_sleepable_hook(btf_id)) 20636 ret = 0; 20637 break; 20638 default: 20639 break; 20640 } 20641 if (ret) { 20642 module_put(mod); 20643 bpf_log(log, "%s is not sleepable\n", tname); 20644 return ret; 20645 } 20646 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 20647 if (tgt_prog) { 20648 module_put(mod); 20649 bpf_log(log, "can't modify return codes of BPF programs\n"); 20650 return -EINVAL; 20651 } 20652 ret = -EINVAL; 20653 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 20654 !check_attach_modify_return(addr, tname)) 20655 ret = 0; 20656 if (ret) { 20657 module_put(mod); 20658 bpf_log(log, "%s() is not modifiable\n", tname); 20659 return ret; 20660 } 20661 } 20662 20663 break; 20664 } 20665 tgt_info->tgt_addr = addr; 20666 tgt_info->tgt_name = tname; 20667 tgt_info->tgt_type = t; 20668 tgt_info->tgt_mod = mod; 20669 return 0; 20670 } 20671 20672 BTF_SET_START(btf_id_deny) 20673 BTF_ID_UNUSED 20674 #ifdef CONFIG_SMP 20675 BTF_ID(func, migrate_disable) 20676 BTF_ID(func, migrate_enable) 20677 #endif 20678 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 20679 BTF_ID(func, rcu_read_unlock_strict) 20680 #endif 20681 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 20682 BTF_ID(func, preempt_count_add) 20683 BTF_ID(func, preempt_count_sub) 20684 #endif 20685 #ifdef CONFIG_PREEMPT_RCU 20686 BTF_ID(func, __rcu_read_lock) 20687 BTF_ID(func, __rcu_read_unlock) 20688 #endif 20689 BTF_SET_END(btf_id_deny) 20690 20691 static bool can_be_sleepable(struct bpf_prog *prog) 20692 { 20693 if (prog->type == BPF_PROG_TYPE_TRACING) { 20694 switch (prog->expected_attach_type) { 20695 case BPF_TRACE_FENTRY: 20696 case BPF_TRACE_FEXIT: 20697 case BPF_MODIFY_RETURN: 20698 case BPF_TRACE_ITER: 20699 return true; 20700 default: 20701 return false; 20702 } 20703 } 20704 return prog->type == BPF_PROG_TYPE_LSM || 20705 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 20706 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 20707 } 20708 20709 static int check_attach_btf_id(struct bpf_verifier_env *env) 20710 { 20711 struct bpf_prog *prog = env->prog; 20712 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 20713 struct bpf_attach_target_info tgt_info = {}; 20714 u32 btf_id = prog->aux->attach_btf_id; 20715 struct bpf_trampoline *tr; 20716 int ret; 20717 u64 key; 20718 20719 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 20720 if (prog->aux->sleepable) 20721 /* attach_btf_id checked to be zero already */ 20722 return 0; 20723 verbose(env, "Syscall programs can only be sleepable\n"); 20724 return -EINVAL; 20725 } 20726 20727 if (prog->aux->sleepable && !can_be_sleepable(prog)) { 20728 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 20729 return -EINVAL; 20730 } 20731 20732 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 20733 return check_struct_ops_btf_id(env); 20734 20735 if (prog->type != BPF_PROG_TYPE_TRACING && 20736 prog->type != BPF_PROG_TYPE_LSM && 20737 prog->type != BPF_PROG_TYPE_EXT) 20738 return 0; 20739 20740 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 20741 if (ret) 20742 return ret; 20743 20744 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 20745 /* to make freplace equivalent to their targets, they need to 20746 * inherit env->ops and expected_attach_type for the rest of the 20747 * verification 20748 */ 20749 env->ops = bpf_verifier_ops[tgt_prog->type]; 20750 prog->expected_attach_type = tgt_prog->expected_attach_type; 20751 } 20752 20753 /* store info about the attachment target that will be used later */ 20754 prog->aux->attach_func_proto = tgt_info.tgt_type; 20755 prog->aux->attach_func_name = tgt_info.tgt_name; 20756 prog->aux->mod = tgt_info.tgt_mod; 20757 20758 if (tgt_prog) { 20759 prog->aux->saved_dst_prog_type = tgt_prog->type; 20760 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 20761 } 20762 20763 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 20764 prog->aux->attach_btf_trace = true; 20765 return 0; 20766 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 20767 if (!bpf_iter_prog_supported(prog)) 20768 return -EINVAL; 20769 return 0; 20770 } 20771 20772 if (prog->type == BPF_PROG_TYPE_LSM) { 20773 ret = bpf_lsm_verify_prog(&env->log, prog); 20774 if (ret < 0) 20775 return ret; 20776 } else if (prog->type == BPF_PROG_TYPE_TRACING && 20777 btf_id_set_contains(&btf_id_deny, btf_id)) { 20778 return -EINVAL; 20779 } 20780 20781 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 20782 tr = bpf_trampoline_get(key, &tgt_info); 20783 if (!tr) 20784 return -ENOMEM; 20785 20786 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 20787 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 20788 20789 prog->aux->dst_trampoline = tr; 20790 return 0; 20791 } 20792 20793 struct btf *bpf_get_btf_vmlinux(void) 20794 { 20795 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 20796 mutex_lock(&bpf_verifier_lock); 20797 if (!btf_vmlinux) 20798 btf_vmlinux = btf_parse_vmlinux(); 20799 mutex_unlock(&bpf_verifier_lock); 20800 } 20801 return btf_vmlinux; 20802 } 20803 20804 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 20805 { 20806 u64 start_time = ktime_get_ns(); 20807 struct bpf_verifier_env *env; 20808 int i, len, ret = -EINVAL, err; 20809 u32 log_true_size; 20810 bool is_priv; 20811 20812 /* no program is valid */ 20813 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 20814 return -EINVAL; 20815 20816 /* 'struct bpf_verifier_env' can be global, but since it's not small, 20817 * allocate/free it every time bpf_check() is called 20818 */ 20819 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 20820 if (!env) 20821 return -ENOMEM; 20822 20823 env->bt.env = env; 20824 20825 len = (*prog)->len; 20826 env->insn_aux_data = 20827 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 20828 ret = -ENOMEM; 20829 if (!env->insn_aux_data) 20830 goto err_free_env; 20831 for (i = 0; i < len; i++) 20832 env->insn_aux_data[i].orig_idx = i; 20833 env->prog = *prog; 20834 env->ops = bpf_verifier_ops[env->prog->type]; 20835 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 20836 20837 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 20838 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 20839 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 20840 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 20841 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 20842 20843 bpf_get_btf_vmlinux(); 20844 20845 /* grab the mutex to protect few globals used by verifier */ 20846 if (!is_priv) 20847 mutex_lock(&bpf_verifier_lock); 20848 20849 /* user could have requested verbose verifier output 20850 * and supplied buffer to store the verification trace 20851 */ 20852 ret = bpf_vlog_init(&env->log, attr->log_level, 20853 (char __user *) (unsigned long) attr->log_buf, 20854 attr->log_size); 20855 if (ret) 20856 goto err_unlock; 20857 20858 mark_verifier_state_clean(env); 20859 20860 if (IS_ERR(btf_vmlinux)) { 20861 /* Either gcc or pahole or kernel are broken. */ 20862 verbose(env, "in-kernel BTF is malformed\n"); 20863 ret = PTR_ERR(btf_vmlinux); 20864 goto skip_full_check; 20865 } 20866 20867 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 20868 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 20869 env->strict_alignment = true; 20870 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 20871 env->strict_alignment = false; 20872 20873 if (is_priv) 20874 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 20875 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 20876 20877 env->explored_states = kvcalloc(state_htab_size(env), 20878 sizeof(struct bpf_verifier_state_list *), 20879 GFP_USER); 20880 ret = -ENOMEM; 20881 if (!env->explored_states) 20882 goto skip_full_check; 20883 20884 ret = check_btf_info_early(env, attr, uattr); 20885 if (ret < 0) 20886 goto skip_full_check; 20887 20888 ret = add_subprog_and_kfunc(env); 20889 if (ret < 0) 20890 goto skip_full_check; 20891 20892 ret = check_subprogs(env); 20893 if (ret < 0) 20894 goto skip_full_check; 20895 20896 ret = check_btf_info(env, attr, uattr); 20897 if (ret < 0) 20898 goto skip_full_check; 20899 20900 ret = check_attach_btf_id(env); 20901 if (ret) 20902 goto skip_full_check; 20903 20904 ret = resolve_pseudo_ldimm64(env); 20905 if (ret < 0) 20906 goto skip_full_check; 20907 20908 if (bpf_prog_is_offloaded(env->prog->aux)) { 20909 ret = bpf_prog_offload_verifier_prep(env->prog); 20910 if (ret) 20911 goto skip_full_check; 20912 } 20913 20914 ret = check_cfg(env); 20915 if (ret < 0) 20916 goto skip_full_check; 20917 20918 ret = do_check_main(env); 20919 ret = ret ?: do_check_subprogs(env); 20920 20921 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 20922 ret = bpf_prog_offload_finalize(env); 20923 20924 skip_full_check: 20925 kvfree(env->explored_states); 20926 20927 if (ret == 0) 20928 ret = check_max_stack_depth(env); 20929 20930 /* instruction rewrites happen after this point */ 20931 if (ret == 0) 20932 ret = optimize_bpf_loop(env); 20933 20934 if (is_priv) { 20935 if (ret == 0) 20936 opt_hard_wire_dead_code_branches(env); 20937 if (ret == 0) 20938 ret = opt_remove_dead_code(env); 20939 if (ret == 0) 20940 ret = opt_remove_nops(env); 20941 } else { 20942 if (ret == 0) 20943 sanitize_dead_code(env); 20944 } 20945 20946 if (ret == 0) 20947 /* program is valid, convert *(u32*)(ctx + off) accesses */ 20948 ret = convert_ctx_accesses(env); 20949 20950 if (ret == 0) 20951 ret = do_misc_fixups(env); 20952 20953 /* do 32-bit optimization after insn patching has done so those patched 20954 * insns could be handled correctly. 20955 */ 20956 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 20957 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 20958 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 20959 : false; 20960 } 20961 20962 if (ret == 0) 20963 ret = fixup_call_args(env); 20964 20965 env->verification_time = ktime_get_ns() - start_time; 20966 print_verification_stats(env); 20967 env->prog->aux->verified_insns = env->insn_processed; 20968 20969 /* preserve original error even if log finalization is successful */ 20970 err = bpf_vlog_finalize(&env->log, &log_true_size); 20971 if (err) 20972 ret = err; 20973 20974 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 20975 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 20976 &log_true_size, sizeof(log_true_size))) { 20977 ret = -EFAULT; 20978 goto err_release_maps; 20979 } 20980 20981 if (ret) 20982 goto err_release_maps; 20983 20984 if (env->used_map_cnt) { 20985 /* if program passed verifier, update used_maps in bpf_prog_info */ 20986 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 20987 sizeof(env->used_maps[0]), 20988 GFP_KERNEL); 20989 20990 if (!env->prog->aux->used_maps) { 20991 ret = -ENOMEM; 20992 goto err_release_maps; 20993 } 20994 20995 memcpy(env->prog->aux->used_maps, env->used_maps, 20996 sizeof(env->used_maps[0]) * env->used_map_cnt); 20997 env->prog->aux->used_map_cnt = env->used_map_cnt; 20998 } 20999 if (env->used_btf_cnt) { 21000 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 21001 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 21002 sizeof(env->used_btfs[0]), 21003 GFP_KERNEL); 21004 if (!env->prog->aux->used_btfs) { 21005 ret = -ENOMEM; 21006 goto err_release_maps; 21007 } 21008 21009 memcpy(env->prog->aux->used_btfs, env->used_btfs, 21010 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 21011 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 21012 } 21013 if (env->used_map_cnt || env->used_btf_cnt) { 21014 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 21015 * bpf_ld_imm64 instructions 21016 */ 21017 convert_pseudo_ld_imm64(env); 21018 } 21019 21020 adjust_btf_func(env); 21021 21022 err_release_maps: 21023 if (!env->prog->aux->used_maps) 21024 /* if we didn't copy map pointers into bpf_prog_info, release 21025 * them now. Otherwise free_used_maps() will release them. 21026 */ 21027 release_maps(env); 21028 if (!env->prog->aux->used_btfs) 21029 release_btfs(env); 21030 21031 /* extension progs temporarily inherit the attach_type of their targets 21032 for verification purposes, so set it back to zero before returning 21033 */ 21034 if (env->prog->type == BPF_PROG_TYPE_EXT) 21035 env->prog->expected_attach_type = 0; 21036 21037 *prog = env->prog; 21038 21039 module_put(env->attach_btf_mod); 21040 err_unlock: 21041 if (!is_priv) 21042 mutex_unlock(&bpf_verifier_lock); 21043 vfree(env->insn_aux_data); 21044 err_free_env: 21045 kfree(env); 21046 return ret; 21047 } 21048