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 /* Copy src state preserving dst->parent and dst->live fields */ 4407 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 4408 { 4409 struct bpf_reg_state *parent = dst->parent; 4410 enum bpf_reg_liveness live = dst->live; 4411 4412 *dst = *src; 4413 dst->parent = parent; 4414 dst->live = live; 4415 } 4416 4417 static void save_register_state(struct bpf_verifier_env *env, 4418 struct bpf_func_state *state, 4419 int spi, struct bpf_reg_state *reg, 4420 int size) 4421 { 4422 int i; 4423 4424 copy_register_state(&state->stack[spi].spilled_ptr, reg); 4425 if (size == BPF_REG_SIZE) 4426 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4427 4428 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 4429 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 4430 4431 /* size < 8 bytes spill */ 4432 for (; i; i--) 4433 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]); 4434 } 4435 4436 static bool is_bpf_st_mem(struct bpf_insn *insn) 4437 { 4438 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 4439 } 4440 4441 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 4442 * stack boundary and alignment are checked in check_mem_access() 4443 */ 4444 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 4445 /* stack frame we're writing to */ 4446 struct bpf_func_state *state, 4447 int off, int size, int value_regno, 4448 int insn_idx) 4449 { 4450 struct bpf_func_state *cur; /* state of the current function */ 4451 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 4452 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4453 struct bpf_reg_state *reg = NULL; 4454 int insn_flags = insn_stack_access_flags(state->frameno, spi); 4455 4456 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 4457 * so it's aligned access and [off, off + size) are within stack limits 4458 */ 4459 if (!env->allow_ptr_leaks && 4460 is_spilled_reg(&state->stack[spi]) && 4461 size != BPF_REG_SIZE) { 4462 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 4463 return -EACCES; 4464 } 4465 4466 cur = env->cur_state->frame[env->cur_state->curframe]; 4467 if (value_regno >= 0) 4468 reg = &cur->regs[value_regno]; 4469 if (!env->bypass_spec_v4) { 4470 bool sanitize = reg && is_spillable_regtype(reg->type); 4471 4472 for (i = 0; i < size; i++) { 4473 u8 type = state->stack[spi].slot_type[i]; 4474 4475 if (type != STACK_MISC && type != STACK_ZERO) { 4476 sanitize = true; 4477 break; 4478 } 4479 } 4480 4481 if (sanitize) 4482 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 4483 } 4484 4485 err = destroy_if_dynptr_stack_slot(env, state, spi); 4486 if (err) 4487 return err; 4488 4489 mark_stack_slot_scratched(env, spi); 4490 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && env->bpf_capable) { 4491 save_register_state(env, state, spi, reg, size); 4492 /* Break the relation on a narrowing spill. */ 4493 if (fls64(reg->umax_value) > BITS_PER_BYTE * size) 4494 state->stack[spi].spilled_ptr.id = 0; 4495 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 4496 insn->imm != 0 && env->bpf_capable) { 4497 struct bpf_reg_state fake_reg = {}; 4498 4499 __mark_reg_known(&fake_reg, insn->imm); 4500 fake_reg.type = SCALAR_VALUE; 4501 save_register_state(env, state, spi, &fake_reg, size); 4502 } else if (reg && is_spillable_regtype(reg->type)) { 4503 /* register containing pointer is being spilled into stack */ 4504 if (size != BPF_REG_SIZE) { 4505 verbose_linfo(env, insn_idx, "; "); 4506 verbose(env, "invalid size of register spill\n"); 4507 return -EACCES; 4508 } 4509 if (state != cur && reg->type == PTR_TO_STACK) { 4510 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4511 return -EINVAL; 4512 } 4513 save_register_state(env, state, spi, reg, size); 4514 } else { 4515 u8 type = STACK_MISC; 4516 4517 /* regular write of data into stack destroys any spilled ptr */ 4518 state->stack[spi].spilled_ptr.type = NOT_INIT; 4519 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 4520 if (is_stack_slot_special(&state->stack[spi])) 4521 for (i = 0; i < BPF_REG_SIZE; i++) 4522 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 4523 4524 /* only mark the slot as written if all 8 bytes were written 4525 * otherwise read propagation may incorrectly stop too soon 4526 * when stack slots are partially written. 4527 * This heuristic means that read propagation will be 4528 * conservative, since it will add reg_live_read marks 4529 * to stack slots all the way to first state when programs 4530 * writes+reads less than 8 bytes 4531 */ 4532 if (size == BPF_REG_SIZE) 4533 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4534 4535 /* when we zero initialize stack slots mark them as such */ 4536 if ((reg && register_is_null(reg)) || 4537 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4538 /* STACK_ZERO case happened because register spill 4539 * wasn't properly aligned at the stack slot boundary, 4540 * so it's not a register spill anymore; force 4541 * originating register to be precise to make 4542 * STACK_ZERO correct for subsequent states 4543 */ 4544 err = mark_chain_precision(env, value_regno); 4545 if (err) 4546 return err; 4547 type = STACK_ZERO; 4548 } 4549 4550 /* Mark slots affected by this stack write. */ 4551 for (i = 0; i < size; i++) 4552 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 4553 insn_flags = 0; /* not a register spill */ 4554 } 4555 4556 if (insn_flags) 4557 return push_jmp_history(env, env->cur_state, insn_flags); 4558 return 0; 4559 } 4560 4561 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 4562 * known to contain a variable offset. 4563 * This function checks whether the write is permitted and conservatively 4564 * tracks the effects of the write, considering that each stack slot in the 4565 * dynamic range is potentially written to. 4566 * 4567 * 'off' includes 'regno->off'. 4568 * 'value_regno' can be -1, meaning that an unknown value is being written to 4569 * the stack. 4570 * 4571 * Spilled pointers in range are not marked as written because we don't know 4572 * what's going to be actually written. This means that read propagation for 4573 * future reads cannot be terminated by this write. 4574 * 4575 * For privileged programs, uninitialized stack slots are considered 4576 * initialized by this write (even though we don't know exactly what offsets 4577 * are going to be written to). The idea is that we don't want the verifier to 4578 * reject future reads that access slots written to through variable offsets. 4579 */ 4580 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4581 /* func where register points to */ 4582 struct bpf_func_state *state, 4583 int ptr_regno, int off, int size, 4584 int value_regno, int insn_idx) 4585 { 4586 struct bpf_func_state *cur; /* state of the current function */ 4587 int min_off, max_off; 4588 int i, err; 4589 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 4590 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4591 bool writing_zero = false; 4592 /* set if the fact that we're writing a zero is used to let any 4593 * stack slots remain STACK_ZERO 4594 */ 4595 bool zero_used = false; 4596 4597 cur = env->cur_state->frame[env->cur_state->curframe]; 4598 ptr_reg = &cur->regs[ptr_regno]; 4599 min_off = ptr_reg->smin_value + off; 4600 max_off = ptr_reg->smax_value + off + size; 4601 if (value_regno >= 0) 4602 value_reg = &cur->regs[value_regno]; 4603 if ((value_reg && register_is_null(value_reg)) || 4604 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4605 writing_zero = true; 4606 4607 for (i = min_off; i < max_off; i++) { 4608 int spi; 4609 4610 spi = __get_spi(i); 4611 err = destroy_if_dynptr_stack_slot(env, state, spi); 4612 if (err) 4613 return err; 4614 } 4615 4616 /* Variable offset writes destroy any spilled pointers in range. */ 4617 for (i = min_off; i < max_off; i++) { 4618 u8 new_type, *stype; 4619 int slot, spi; 4620 4621 slot = -i - 1; 4622 spi = slot / BPF_REG_SIZE; 4623 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4624 mark_stack_slot_scratched(env, spi); 4625 4626 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4627 /* Reject the write if range we may write to has not 4628 * been initialized beforehand. If we didn't reject 4629 * here, the ptr status would be erased below (even 4630 * though not all slots are actually overwritten), 4631 * possibly opening the door to leaks. 4632 * 4633 * We do however catch STACK_INVALID case below, and 4634 * only allow reading possibly uninitialized memory 4635 * later for CAP_PERFMON, as the write may not happen to 4636 * that slot. 4637 */ 4638 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4639 insn_idx, i); 4640 return -EINVAL; 4641 } 4642 4643 /* Erase all spilled pointers. */ 4644 state->stack[spi].spilled_ptr.type = NOT_INIT; 4645 4646 /* Update the slot type. */ 4647 new_type = STACK_MISC; 4648 if (writing_zero && *stype == STACK_ZERO) { 4649 new_type = STACK_ZERO; 4650 zero_used = true; 4651 } 4652 /* If the slot is STACK_INVALID, we check whether it's OK to 4653 * pretend that it will be initialized by this write. The slot 4654 * might not actually be written to, and so if we mark it as 4655 * initialized future reads might leak uninitialized memory. 4656 * For privileged programs, we will accept such reads to slots 4657 * that may or may not be written because, if we're reject 4658 * them, the error would be too confusing. 4659 */ 4660 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4661 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4662 insn_idx, i); 4663 return -EINVAL; 4664 } 4665 *stype = new_type; 4666 } 4667 if (zero_used) { 4668 /* backtracking doesn't work for STACK_ZERO yet. */ 4669 err = mark_chain_precision(env, value_regno); 4670 if (err) 4671 return err; 4672 } 4673 return 0; 4674 } 4675 4676 /* When register 'dst_regno' is assigned some values from stack[min_off, 4677 * max_off), we set the register's type according to the types of the 4678 * respective stack slots. If all the stack values are known to be zeros, then 4679 * so is the destination reg. Otherwise, the register is considered to be 4680 * SCALAR. This function does not deal with register filling; the caller must 4681 * ensure that all spilled registers in the stack range have been marked as 4682 * read. 4683 */ 4684 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4685 /* func where src register points to */ 4686 struct bpf_func_state *ptr_state, 4687 int min_off, int max_off, int dst_regno) 4688 { 4689 struct bpf_verifier_state *vstate = env->cur_state; 4690 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4691 int i, slot, spi; 4692 u8 *stype; 4693 int zeros = 0; 4694 4695 for (i = min_off; i < max_off; i++) { 4696 slot = -i - 1; 4697 spi = slot / BPF_REG_SIZE; 4698 mark_stack_slot_scratched(env, spi); 4699 stype = ptr_state->stack[spi].slot_type; 4700 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4701 break; 4702 zeros++; 4703 } 4704 if (zeros == max_off - min_off) { 4705 /* Any access_size read into register is zero extended, 4706 * so the whole register == const_zero. 4707 */ 4708 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4709 } else { 4710 /* have read misc data from the stack */ 4711 mark_reg_unknown(env, state->regs, dst_regno); 4712 } 4713 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4714 } 4715 4716 /* Read the stack at 'off' and put the results into the register indicated by 4717 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4718 * spilled reg. 4719 * 4720 * 'dst_regno' can be -1, meaning that the read value is not going to a 4721 * register. 4722 * 4723 * The access is assumed to be within the current stack bounds. 4724 */ 4725 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4726 /* func where src register points to */ 4727 struct bpf_func_state *reg_state, 4728 int off, int size, int dst_regno) 4729 { 4730 struct bpf_verifier_state *vstate = env->cur_state; 4731 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4732 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4733 struct bpf_reg_state *reg; 4734 u8 *stype, type; 4735 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi); 4736 4737 stype = reg_state->stack[spi].slot_type; 4738 reg = ®_state->stack[spi].spilled_ptr; 4739 4740 mark_stack_slot_scratched(env, spi); 4741 4742 if (is_spilled_reg(®_state->stack[spi])) { 4743 u8 spill_size = 1; 4744 4745 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4746 spill_size++; 4747 4748 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4749 if (reg->type != SCALAR_VALUE) { 4750 verbose_linfo(env, env->insn_idx, "; "); 4751 verbose(env, "invalid size of register fill\n"); 4752 return -EACCES; 4753 } 4754 4755 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4756 if (dst_regno < 0) 4757 return 0; 4758 4759 if (!(off % BPF_REG_SIZE) && size == spill_size) { 4760 /* The earlier check_reg_arg() has decided the 4761 * subreg_def for this insn. Save it first. 4762 */ 4763 s32 subreg_def = state->regs[dst_regno].subreg_def; 4764 4765 copy_register_state(&state->regs[dst_regno], reg); 4766 state->regs[dst_regno].subreg_def = subreg_def; 4767 } else { 4768 int spill_cnt = 0, zero_cnt = 0; 4769 4770 for (i = 0; i < size; i++) { 4771 type = stype[(slot - i) % BPF_REG_SIZE]; 4772 if (type == STACK_SPILL) { 4773 spill_cnt++; 4774 continue; 4775 } 4776 if (type == STACK_MISC) 4777 continue; 4778 if (type == STACK_ZERO) { 4779 zero_cnt++; 4780 continue; 4781 } 4782 if (type == STACK_INVALID && env->allow_uninit_stack) 4783 continue; 4784 verbose(env, "invalid read from stack off %d+%d size %d\n", 4785 off, i, size); 4786 return -EACCES; 4787 } 4788 4789 if (spill_cnt == size && 4790 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 4791 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4792 /* this IS register fill, so keep insn_flags */ 4793 } else if (zero_cnt == size) { 4794 /* similarly to mark_reg_stack_read(), preserve zeroes */ 4795 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4796 insn_flags = 0; /* not restoring original register state */ 4797 } else { 4798 mark_reg_unknown(env, state->regs, dst_regno); 4799 insn_flags = 0; /* not restoring original register state */ 4800 } 4801 } 4802 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4803 } else if (dst_regno >= 0) { 4804 /* restore register state from stack */ 4805 copy_register_state(&state->regs[dst_regno], reg); 4806 /* mark reg as written since spilled pointer state likely 4807 * has its liveness marks cleared by is_state_visited() 4808 * which resets stack/reg liveness for state transitions 4809 */ 4810 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4811 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 4812 /* If dst_regno==-1, the caller is asking us whether 4813 * it is acceptable to use this value as a SCALAR_VALUE 4814 * (e.g. for XADD). 4815 * We must not allow unprivileged callers to do that 4816 * with spilled pointers. 4817 */ 4818 verbose(env, "leaking pointer from stack off %d\n", 4819 off); 4820 return -EACCES; 4821 } 4822 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4823 } else { 4824 for (i = 0; i < size; i++) { 4825 type = stype[(slot - i) % BPF_REG_SIZE]; 4826 if (type == STACK_MISC) 4827 continue; 4828 if (type == STACK_ZERO) 4829 continue; 4830 if (type == STACK_INVALID && env->allow_uninit_stack) 4831 continue; 4832 verbose(env, "invalid read from stack off %d+%d size %d\n", 4833 off, i, size); 4834 return -EACCES; 4835 } 4836 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4837 if (dst_regno >= 0) 4838 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 4839 insn_flags = 0; /* we are not restoring spilled register */ 4840 } 4841 if (insn_flags) 4842 return push_jmp_history(env, env->cur_state, insn_flags); 4843 return 0; 4844 } 4845 4846 enum bpf_access_src { 4847 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 4848 ACCESS_HELPER = 2, /* the access is performed by a helper */ 4849 }; 4850 4851 static int check_stack_range_initialized(struct bpf_verifier_env *env, 4852 int regno, int off, int access_size, 4853 bool zero_size_allowed, 4854 enum bpf_access_src type, 4855 struct bpf_call_arg_meta *meta); 4856 4857 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 4858 { 4859 return cur_regs(env) + regno; 4860 } 4861 4862 /* Read the stack at 'ptr_regno + off' and put the result into the register 4863 * 'dst_regno'. 4864 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 4865 * but not its variable offset. 4866 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 4867 * 4868 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 4869 * filling registers (i.e. reads of spilled register cannot be detected when 4870 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 4871 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 4872 * offset; for a fixed offset check_stack_read_fixed_off should be used 4873 * instead. 4874 */ 4875 static int check_stack_read_var_off(struct bpf_verifier_env *env, 4876 int ptr_regno, int off, int size, int dst_regno) 4877 { 4878 /* The state of the source register. */ 4879 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4880 struct bpf_func_state *ptr_state = func(env, reg); 4881 int err; 4882 int min_off, max_off; 4883 4884 /* Note that we pass a NULL meta, so raw access will not be permitted. 4885 */ 4886 err = check_stack_range_initialized(env, ptr_regno, off, size, 4887 false, ACCESS_DIRECT, NULL); 4888 if (err) 4889 return err; 4890 4891 min_off = reg->smin_value + off; 4892 max_off = reg->smax_value + off; 4893 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 4894 return 0; 4895 } 4896 4897 /* check_stack_read dispatches to check_stack_read_fixed_off or 4898 * check_stack_read_var_off. 4899 * 4900 * The caller must ensure that the offset falls within the allocated stack 4901 * bounds. 4902 * 4903 * 'dst_regno' is a register which will receive the value from the stack. It 4904 * can be -1, meaning that the read value is not going to a register. 4905 */ 4906 static int check_stack_read(struct bpf_verifier_env *env, 4907 int ptr_regno, int off, int size, 4908 int dst_regno) 4909 { 4910 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4911 struct bpf_func_state *state = func(env, reg); 4912 int err; 4913 /* Some accesses are only permitted with a static offset. */ 4914 bool var_off = !tnum_is_const(reg->var_off); 4915 4916 /* The offset is required to be static when reads don't go to a 4917 * register, in order to not leak pointers (see 4918 * check_stack_read_fixed_off). 4919 */ 4920 if (dst_regno < 0 && var_off) { 4921 char tn_buf[48]; 4922 4923 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4924 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 4925 tn_buf, off, size); 4926 return -EACCES; 4927 } 4928 /* Variable offset is prohibited for unprivileged mode for simplicity 4929 * since it requires corresponding support in Spectre masking for stack 4930 * ALU. See also retrieve_ptr_limit(). The check in 4931 * check_stack_access_for_ptr_arithmetic() called by 4932 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 4933 * with variable offsets, therefore no check is required here. Further, 4934 * just checking it here would be insufficient as speculative stack 4935 * writes could still lead to unsafe speculative behaviour. 4936 */ 4937 if (!var_off) { 4938 off += reg->var_off.value; 4939 err = check_stack_read_fixed_off(env, state, off, size, 4940 dst_regno); 4941 } else { 4942 /* Variable offset stack reads need more conservative handling 4943 * than fixed offset ones. Note that dst_regno >= 0 on this 4944 * branch. 4945 */ 4946 err = check_stack_read_var_off(env, ptr_regno, off, size, 4947 dst_regno); 4948 } 4949 return err; 4950 } 4951 4952 4953 /* check_stack_write dispatches to check_stack_write_fixed_off or 4954 * check_stack_write_var_off. 4955 * 4956 * 'ptr_regno' is the register used as a pointer into the stack. 4957 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 4958 * 'value_regno' is the register whose value we're writing to the stack. It can 4959 * be -1, meaning that we're not writing from a register. 4960 * 4961 * The caller must ensure that the offset falls within the maximum stack size. 4962 */ 4963 static int check_stack_write(struct bpf_verifier_env *env, 4964 int ptr_regno, int off, int size, 4965 int value_regno, int insn_idx) 4966 { 4967 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4968 struct bpf_func_state *state = func(env, reg); 4969 int err; 4970 4971 if (tnum_is_const(reg->var_off)) { 4972 off += reg->var_off.value; 4973 err = check_stack_write_fixed_off(env, state, off, size, 4974 value_regno, insn_idx); 4975 } else { 4976 /* Variable offset stack reads need more conservative handling 4977 * than fixed offset ones. 4978 */ 4979 err = check_stack_write_var_off(env, state, 4980 ptr_regno, off, size, 4981 value_regno, insn_idx); 4982 } 4983 return err; 4984 } 4985 4986 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 4987 int off, int size, enum bpf_access_type type) 4988 { 4989 struct bpf_reg_state *regs = cur_regs(env); 4990 struct bpf_map *map = regs[regno].map_ptr; 4991 u32 cap = bpf_map_flags_to_cap(map); 4992 4993 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 4994 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 4995 map->value_size, off, size); 4996 return -EACCES; 4997 } 4998 4999 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 5000 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 5001 map->value_size, off, size); 5002 return -EACCES; 5003 } 5004 5005 return 0; 5006 } 5007 5008 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 5009 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 5010 int off, int size, u32 mem_size, 5011 bool zero_size_allowed) 5012 { 5013 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 5014 struct bpf_reg_state *reg; 5015 5016 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 5017 return 0; 5018 5019 reg = &cur_regs(env)[regno]; 5020 switch (reg->type) { 5021 case PTR_TO_MAP_KEY: 5022 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 5023 mem_size, off, size); 5024 break; 5025 case PTR_TO_MAP_VALUE: 5026 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 5027 mem_size, off, size); 5028 break; 5029 case PTR_TO_PACKET: 5030 case PTR_TO_PACKET_META: 5031 case PTR_TO_PACKET_END: 5032 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 5033 off, size, regno, reg->id, off, mem_size); 5034 break; 5035 case PTR_TO_MEM: 5036 default: 5037 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 5038 mem_size, off, size); 5039 } 5040 5041 return -EACCES; 5042 } 5043 5044 /* check read/write into a memory region with possible variable offset */ 5045 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 5046 int off, int size, u32 mem_size, 5047 bool zero_size_allowed) 5048 { 5049 struct bpf_verifier_state *vstate = env->cur_state; 5050 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5051 struct bpf_reg_state *reg = &state->regs[regno]; 5052 int err; 5053 5054 /* We may have adjusted the register pointing to memory region, so we 5055 * need to try adding each of min_value and max_value to off 5056 * to make sure our theoretical access will be safe. 5057 * 5058 * The minimum value is only important with signed 5059 * comparisons where we can't assume the floor of a 5060 * value is 0. If we are using signed variables for our 5061 * index'es we need to make sure that whatever we use 5062 * will have a set floor within our range. 5063 */ 5064 if (reg->smin_value < 0 && 5065 (reg->smin_value == S64_MIN || 5066 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5067 reg->smin_value + off < 0)) { 5068 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5069 regno); 5070 return -EACCES; 5071 } 5072 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5073 mem_size, zero_size_allowed); 5074 if (err) { 5075 verbose(env, "R%d min value is outside of the allowed memory range\n", 5076 regno); 5077 return err; 5078 } 5079 5080 /* If we haven't set a max value then we need to bail since we can't be 5081 * sure we won't do bad things. 5082 * If reg->umax_value + off could overflow, treat that as unbounded too. 5083 */ 5084 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5085 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5086 regno); 5087 return -EACCES; 5088 } 5089 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5090 mem_size, zero_size_allowed); 5091 if (err) { 5092 verbose(env, "R%d max value is outside of the allowed memory range\n", 5093 regno); 5094 return err; 5095 } 5096 5097 return 0; 5098 } 5099 5100 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5101 const struct bpf_reg_state *reg, int regno, 5102 bool fixed_off_ok) 5103 { 5104 /* Access to this pointer-typed register or passing it to a helper 5105 * is only allowed in its original, unmodified form. 5106 */ 5107 5108 if (reg->off < 0) { 5109 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5110 reg_type_str(env, reg->type), regno, reg->off); 5111 return -EACCES; 5112 } 5113 5114 if (!fixed_off_ok && reg->off) { 5115 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5116 reg_type_str(env, reg->type), regno, reg->off); 5117 return -EACCES; 5118 } 5119 5120 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5121 char tn_buf[48]; 5122 5123 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5124 verbose(env, "variable %s access var_off=%s disallowed\n", 5125 reg_type_str(env, reg->type), tn_buf); 5126 return -EACCES; 5127 } 5128 5129 return 0; 5130 } 5131 5132 static int check_ptr_off_reg(struct bpf_verifier_env *env, 5133 const struct bpf_reg_state *reg, int regno) 5134 { 5135 return __check_ptr_off_reg(env, reg, regno, false); 5136 } 5137 5138 static int map_kptr_match_type(struct bpf_verifier_env *env, 5139 struct btf_field *kptr_field, 5140 struct bpf_reg_state *reg, u32 regno) 5141 { 5142 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5143 int perm_flags; 5144 const char *reg_name = ""; 5145 5146 if (btf_is_kernel(reg->btf)) { 5147 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5148 5149 /* Only unreferenced case accepts untrusted pointers */ 5150 if (kptr_field->type == BPF_KPTR_UNREF) 5151 perm_flags |= PTR_UNTRUSTED; 5152 } else { 5153 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5154 if (kptr_field->type == BPF_KPTR_PERCPU) 5155 perm_flags |= MEM_PERCPU; 5156 } 5157 5158 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5159 goto bad_type; 5160 5161 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5162 reg_name = btf_type_name(reg->btf, reg->btf_id); 5163 5164 /* For ref_ptr case, release function check should ensure we get one 5165 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5166 * normal store of unreferenced kptr, we must ensure var_off is zero. 5167 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5168 * reg->off and reg->ref_obj_id are not needed here. 5169 */ 5170 if (__check_ptr_off_reg(env, reg, regno, true)) 5171 return -EACCES; 5172 5173 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5174 * we also need to take into account the reg->off. 5175 * 5176 * We want to support cases like: 5177 * 5178 * struct foo { 5179 * struct bar br; 5180 * struct baz bz; 5181 * }; 5182 * 5183 * struct foo *v; 5184 * v = func(); // PTR_TO_BTF_ID 5185 * val->foo = v; // reg->off is zero, btf and btf_id match type 5186 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5187 * // first member type of struct after comparison fails 5188 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5189 * // to match type 5190 * 5191 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5192 * is zero. We must also ensure that btf_struct_ids_match does not walk 5193 * the struct to match type against first member of struct, i.e. reject 5194 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5195 * strict mode to true for type match. 5196 */ 5197 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5198 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5199 kptr_field->type != BPF_KPTR_UNREF)) 5200 goto bad_type; 5201 return 0; 5202 bad_type: 5203 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5204 reg_type_str(env, reg->type), reg_name); 5205 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5206 if (kptr_field->type == BPF_KPTR_UNREF) 5207 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5208 targ_name); 5209 else 5210 verbose(env, "\n"); 5211 return -EINVAL; 5212 } 5213 5214 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5215 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5216 */ 5217 static bool in_rcu_cs(struct bpf_verifier_env *env) 5218 { 5219 return env->cur_state->active_rcu_lock || 5220 env->cur_state->active_lock.ptr || 5221 !env->prog->aux->sleepable; 5222 } 5223 5224 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5225 BTF_SET_START(rcu_protected_types) 5226 BTF_ID(struct, prog_test_ref_kfunc) 5227 #ifdef CONFIG_CGROUPS 5228 BTF_ID(struct, cgroup) 5229 #endif 5230 BTF_ID(struct, bpf_cpumask) 5231 BTF_ID(struct, task_struct) 5232 BTF_SET_END(rcu_protected_types) 5233 5234 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5235 { 5236 if (!btf_is_kernel(btf)) 5237 return true; 5238 return btf_id_set_contains(&rcu_protected_types, btf_id); 5239 } 5240 5241 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 5242 { 5243 struct btf_struct_meta *meta; 5244 5245 if (btf_is_kernel(kptr_field->kptr.btf)) 5246 return NULL; 5247 5248 meta = btf_find_struct_meta(kptr_field->kptr.btf, 5249 kptr_field->kptr.btf_id); 5250 5251 return meta ? meta->record : NULL; 5252 } 5253 5254 static bool rcu_safe_kptr(const struct btf_field *field) 5255 { 5256 const struct btf_field_kptr *kptr = &field->kptr; 5257 5258 return field->type == BPF_KPTR_PERCPU || 5259 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 5260 } 5261 5262 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 5263 { 5264 struct btf_record *rec; 5265 u32 ret; 5266 5267 ret = PTR_MAYBE_NULL; 5268 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 5269 ret |= MEM_RCU; 5270 if (kptr_field->type == BPF_KPTR_PERCPU) 5271 ret |= MEM_PERCPU; 5272 else if (!btf_is_kernel(kptr_field->kptr.btf)) 5273 ret |= MEM_ALLOC; 5274 5275 rec = kptr_pointee_btf_record(kptr_field); 5276 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 5277 ret |= NON_OWN_REF; 5278 } else { 5279 ret |= PTR_UNTRUSTED; 5280 } 5281 5282 return ret; 5283 } 5284 5285 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5286 int value_regno, int insn_idx, 5287 struct btf_field *kptr_field) 5288 { 5289 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5290 int class = BPF_CLASS(insn->code); 5291 struct bpf_reg_state *val_reg; 5292 5293 /* Things we already checked for in check_map_access and caller: 5294 * - Reject cases where variable offset may touch kptr 5295 * - size of access (must be BPF_DW) 5296 * - tnum_is_const(reg->var_off) 5297 * - kptr_field->offset == off + reg->var_off.value 5298 */ 5299 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5300 if (BPF_MODE(insn->code) != BPF_MEM) { 5301 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5302 return -EACCES; 5303 } 5304 5305 /* We only allow loading referenced kptr, since it will be marked as 5306 * untrusted, similar to unreferenced kptr. 5307 */ 5308 if (class != BPF_LDX && 5309 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 5310 verbose(env, "store to referenced kptr disallowed\n"); 5311 return -EACCES; 5312 } 5313 5314 if (class == BPF_LDX) { 5315 val_reg = reg_state(env, value_regno); 5316 /* We can simply mark the value_regno receiving the pointer 5317 * value from map as PTR_TO_BTF_ID, with the correct type. 5318 */ 5319 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5320 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field)); 5321 /* For mark_ptr_or_null_reg */ 5322 val_reg->id = ++env->id_gen; 5323 } else if (class == BPF_STX) { 5324 val_reg = reg_state(env, value_regno); 5325 if (!register_is_null(val_reg) && 5326 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5327 return -EACCES; 5328 } else if (class == BPF_ST) { 5329 if (insn->imm) { 5330 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5331 kptr_field->offset); 5332 return -EACCES; 5333 } 5334 } else { 5335 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5336 return -EACCES; 5337 } 5338 return 0; 5339 } 5340 5341 /* check read/write into a map element with possible variable offset */ 5342 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5343 int off, int size, bool zero_size_allowed, 5344 enum bpf_access_src src) 5345 { 5346 struct bpf_verifier_state *vstate = env->cur_state; 5347 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5348 struct bpf_reg_state *reg = &state->regs[regno]; 5349 struct bpf_map *map = reg->map_ptr; 5350 struct btf_record *rec; 5351 int err, i; 5352 5353 err = check_mem_region_access(env, regno, off, size, map->value_size, 5354 zero_size_allowed); 5355 if (err) 5356 return err; 5357 5358 if (IS_ERR_OR_NULL(map->record)) 5359 return 0; 5360 rec = map->record; 5361 for (i = 0; i < rec->cnt; i++) { 5362 struct btf_field *field = &rec->fields[i]; 5363 u32 p = field->offset; 5364 5365 /* If any part of a field can be touched by load/store, reject 5366 * this program. To check that [x1, x2) overlaps with [y1, y2), 5367 * it is sufficient to check x1 < y2 && y1 < x2. 5368 */ 5369 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 5370 p < reg->umax_value + off + size) { 5371 switch (field->type) { 5372 case BPF_KPTR_UNREF: 5373 case BPF_KPTR_REF: 5374 case BPF_KPTR_PERCPU: 5375 if (src != ACCESS_DIRECT) { 5376 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 5377 return -EACCES; 5378 } 5379 if (!tnum_is_const(reg->var_off)) { 5380 verbose(env, "kptr access cannot have variable offset\n"); 5381 return -EACCES; 5382 } 5383 if (p != off + reg->var_off.value) { 5384 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 5385 p, off + reg->var_off.value); 5386 return -EACCES; 5387 } 5388 if (size != bpf_size_to_bytes(BPF_DW)) { 5389 verbose(env, "kptr access size must be BPF_DW\n"); 5390 return -EACCES; 5391 } 5392 break; 5393 default: 5394 verbose(env, "%s cannot be accessed directly by load/store\n", 5395 btf_field_type_name(field->type)); 5396 return -EACCES; 5397 } 5398 } 5399 } 5400 return 0; 5401 } 5402 5403 #define MAX_PACKET_OFF 0xffff 5404 5405 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5406 const struct bpf_call_arg_meta *meta, 5407 enum bpf_access_type t) 5408 { 5409 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5410 5411 switch (prog_type) { 5412 /* Program types only with direct read access go here! */ 5413 case BPF_PROG_TYPE_LWT_IN: 5414 case BPF_PROG_TYPE_LWT_OUT: 5415 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5416 case BPF_PROG_TYPE_SK_REUSEPORT: 5417 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5418 case BPF_PROG_TYPE_CGROUP_SKB: 5419 if (t == BPF_WRITE) 5420 return false; 5421 fallthrough; 5422 5423 /* Program types with direct read + write access go here! */ 5424 case BPF_PROG_TYPE_SCHED_CLS: 5425 case BPF_PROG_TYPE_SCHED_ACT: 5426 case BPF_PROG_TYPE_XDP: 5427 case BPF_PROG_TYPE_LWT_XMIT: 5428 case BPF_PROG_TYPE_SK_SKB: 5429 case BPF_PROG_TYPE_SK_MSG: 5430 if (meta) 5431 return meta->pkt_access; 5432 5433 env->seen_direct_write = true; 5434 return true; 5435 5436 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5437 if (t == BPF_WRITE) 5438 env->seen_direct_write = true; 5439 5440 return true; 5441 5442 default: 5443 return false; 5444 } 5445 } 5446 5447 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5448 int size, bool zero_size_allowed) 5449 { 5450 struct bpf_reg_state *regs = cur_regs(env); 5451 struct bpf_reg_state *reg = ®s[regno]; 5452 int err; 5453 5454 /* We may have added a variable offset to the packet pointer; but any 5455 * reg->range we have comes after that. We are only checking the fixed 5456 * offset. 5457 */ 5458 5459 /* We don't allow negative numbers, because we aren't tracking enough 5460 * detail to prove they're safe. 5461 */ 5462 if (reg->smin_value < 0) { 5463 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5464 regno); 5465 return -EACCES; 5466 } 5467 5468 err = reg->range < 0 ? -EINVAL : 5469 __check_mem_access(env, regno, off, size, reg->range, 5470 zero_size_allowed); 5471 if (err) { 5472 verbose(env, "R%d offset is outside of the packet\n", regno); 5473 return err; 5474 } 5475 5476 /* __check_mem_access has made sure "off + size - 1" is within u16. 5477 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5478 * otherwise find_good_pkt_pointers would have refused to set range info 5479 * that __check_mem_access would have rejected this pkt access. 5480 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5481 */ 5482 env->prog->aux->max_pkt_offset = 5483 max_t(u32, env->prog->aux->max_pkt_offset, 5484 off + reg->umax_value + size - 1); 5485 5486 return err; 5487 } 5488 5489 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5490 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5491 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5492 struct btf **btf, u32 *btf_id) 5493 { 5494 struct bpf_insn_access_aux info = { 5495 .reg_type = *reg_type, 5496 .log = &env->log, 5497 }; 5498 5499 if (env->ops->is_valid_access && 5500 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5501 /* A non zero info.ctx_field_size indicates that this field is a 5502 * candidate for later verifier transformation to load the whole 5503 * field and then apply a mask when accessed with a narrower 5504 * access than actual ctx access size. A zero info.ctx_field_size 5505 * will only allow for whole field access and rejects any other 5506 * type of narrower access. 5507 */ 5508 *reg_type = info.reg_type; 5509 5510 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5511 *btf = info.btf; 5512 *btf_id = info.btf_id; 5513 } else { 5514 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5515 } 5516 /* remember the offset of last byte accessed in ctx */ 5517 if (env->prog->aux->max_ctx_offset < off + size) 5518 env->prog->aux->max_ctx_offset = off + size; 5519 return 0; 5520 } 5521 5522 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5523 return -EACCES; 5524 } 5525 5526 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5527 int size) 5528 { 5529 if (size < 0 || off < 0 || 5530 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5531 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5532 off, size); 5533 return -EACCES; 5534 } 5535 return 0; 5536 } 5537 5538 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5539 u32 regno, int off, int size, 5540 enum bpf_access_type t) 5541 { 5542 struct bpf_reg_state *regs = cur_regs(env); 5543 struct bpf_reg_state *reg = ®s[regno]; 5544 struct bpf_insn_access_aux info = {}; 5545 bool valid; 5546 5547 if (reg->smin_value < 0) { 5548 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5549 regno); 5550 return -EACCES; 5551 } 5552 5553 switch (reg->type) { 5554 case PTR_TO_SOCK_COMMON: 5555 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5556 break; 5557 case PTR_TO_SOCKET: 5558 valid = bpf_sock_is_valid_access(off, size, t, &info); 5559 break; 5560 case PTR_TO_TCP_SOCK: 5561 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5562 break; 5563 case PTR_TO_XDP_SOCK: 5564 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5565 break; 5566 default: 5567 valid = false; 5568 } 5569 5570 5571 if (valid) { 5572 env->insn_aux_data[insn_idx].ctx_field_size = 5573 info.ctx_field_size; 5574 return 0; 5575 } 5576 5577 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5578 regno, reg_type_str(env, reg->type), off, size); 5579 5580 return -EACCES; 5581 } 5582 5583 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5584 { 5585 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5586 } 5587 5588 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5589 { 5590 const struct bpf_reg_state *reg = reg_state(env, regno); 5591 5592 return reg->type == PTR_TO_CTX; 5593 } 5594 5595 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5596 { 5597 const struct bpf_reg_state *reg = reg_state(env, regno); 5598 5599 return type_is_sk_pointer(reg->type); 5600 } 5601 5602 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5603 { 5604 const struct bpf_reg_state *reg = reg_state(env, regno); 5605 5606 return type_is_pkt_pointer(reg->type); 5607 } 5608 5609 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5610 { 5611 const struct bpf_reg_state *reg = reg_state(env, regno); 5612 5613 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5614 return reg->type == PTR_TO_FLOW_KEYS; 5615 } 5616 5617 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5618 #ifdef CONFIG_NET 5619 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5620 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5621 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5622 #endif 5623 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5624 }; 5625 5626 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5627 { 5628 /* A referenced register is always trusted. */ 5629 if (reg->ref_obj_id) 5630 return true; 5631 5632 /* Types listed in the reg2btf_ids are always trusted */ 5633 if (reg2btf_ids[base_type(reg->type)]) 5634 return true; 5635 5636 /* If a register is not referenced, it is trusted if it has the 5637 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5638 * other type modifiers may be safe, but we elect to take an opt-in 5639 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5640 * not. 5641 * 5642 * Eventually, we should make PTR_TRUSTED the single source of truth 5643 * for whether a register is trusted. 5644 */ 5645 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5646 !bpf_type_has_unsafe_modifiers(reg->type); 5647 } 5648 5649 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5650 { 5651 return reg->type & MEM_RCU; 5652 } 5653 5654 static void clear_trusted_flags(enum bpf_type_flag *flag) 5655 { 5656 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5657 } 5658 5659 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5660 const struct bpf_reg_state *reg, 5661 int off, int size, bool strict) 5662 { 5663 struct tnum reg_off; 5664 int ip_align; 5665 5666 /* Byte size accesses are always allowed. */ 5667 if (!strict || size == 1) 5668 return 0; 5669 5670 /* For platforms that do not have a Kconfig enabling 5671 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5672 * NET_IP_ALIGN is universally set to '2'. And on platforms 5673 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5674 * to this code only in strict mode where we want to emulate 5675 * the NET_IP_ALIGN==2 checking. Therefore use an 5676 * unconditional IP align value of '2'. 5677 */ 5678 ip_align = 2; 5679 5680 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5681 if (!tnum_is_aligned(reg_off, size)) { 5682 char tn_buf[48]; 5683 5684 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5685 verbose(env, 5686 "misaligned packet access off %d+%s+%d+%d size %d\n", 5687 ip_align, tn_buf, reg->off, off, size); 5688 return -EACCES; 5689 } 5690 5691 return 0; 5692 } 5693 5694 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5695 const struct bpf_reg_state *reg, 5696 const char *pointer_desc, 5697 int off, int size, bool strict) 5698 { 5699 struct tnum reg_off; 5700 5701 /* Byte size accesses are always allowed. */ 5702 if (!strict || size == 1) 5703 return 0; 5704 5705 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5706 if (!tnum_is_aligned(reg_off, size)) { 5707 char tn_buf[48]; 5708 5709 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5710 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5711 pointer_desc, tn_buf, reg->off, off, size); 5712 return -EACCES; 5713 } 5714 5715 return 0; 5716 } 5717 5718 static int check_ptr_alignment(struct bpf_verifier_env *env, 5719 const struct bpf_reg_state *reg, int off, 5720 int size, bool strict_alignment_once) 5721 { 5722 bool strict = env->strict_alignment || strict_alignment_once; 5723 const char *pointer_desc = ""; 5724 5725 switch (reg->type) { 5726 case PTR_TO_PACKET: 5727 case PTR_TO_PACKET_META: 5728 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5729 * right in front, treat it the very same way. 5730 */ 5731 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5732 case PTR_TO_FLOW_KEYS: 5733 pointer_desc = "flow keys "; 5734 break; 5735 case PTR_TO_MAP_KEY: 5736 pointer_desc = "key "; 5737 break; 5738 case PTR_TO_MAP_VALUE: 5739 pointer_desc = "value "; 5740 break; 5741 case PTR_TO_CTX: 5742 pointer_desc = "context "; 5743 break; 5744 case PTR_TO_STACK: 5745 pointer_desc = "stack "; 5746 /* The stack spill tracking logic in check_stack_write_fixed_off() 5747 * and check_stack_read_fixed_off() relies on stack accesses being 5748 * aligned. 5749 */ 5750 strict = true; 5751 break; 5752 case PTR_TO_SOCKET: 5753 pointer_desc = "sock "; 5754 break; 5755 case PTR_TO_SOCK_COMMON: 5756 pointer_desc = "sock_common "; 5757 break; 5758 case PTR_TO_TCP_SOCK: 5759 pointer_desc = "tcp_sock "; 5760 break; 5761 case PTR_TO_XDP_SOCK: 5762 pointer_desc = "xdp_sock "; 5763 break; 5764 default: 5765 break; 5766 } 5767 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5768 strict); 5769 } 5770 5771 /* starting from main bpf function walk all instructions of the function 5772 * and recursively walk all callees that given function can call. 5773 * Ignore jump and exit insns. 5774 * Since recursion is prevented by check_cfg() this algorithm 5775 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 5776 */ 5777 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx) 5778 { 5779 struct bpf_subprog_info *subprog = env->subprog_info; 5780 struct bpf_insn *insn = env->prog->insnsi; 5781 int depth = 0, frame = 0, i, subprog_end; 5782 bool tail_call_reachable = false; 5783 int ret_insn[MAX_CALL_FRAMES]; 5784 int ret_prog[MAX_CALL_FRAMES]; 5785 int j; 5786 5787 i = subprog[idx].start; 5788 process_func: 5789 /* protect against potential stack overflow that might happen when 5790 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5791 * depth for such case down to 256 so that the worst case scenario 5792 * would result in 8k stack size (32 which is tailcall limit * 256 = 5793 * 8k). 5794 * 5795 * To get the idea what might happen, see an example: 5796 * func1 -> sub rsp, 128 5797 * subfunc1 -> sub rsp, 256 5798 * tailcall1 -> add rsp, 256 5799 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5800 * subfunc2 -> sub rsp, 64 5801 * subfunc22 -> sub rsp, 128 5802 * tailcall2 -> add rsp, 128 5803 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5804 * 5805 * tailcall will unwind the current stack frame but it will not get rid 5806 * of caller's stack as shown on the example above. 5807 */ 5808 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5809 verbose(env, 5810 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5811 depth); 5812 return -EACCES; 5813 } 5814 /* round up to 32-bytes, since this is granularity 5815 * of interpreter stack size 5816 */ 5817 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5818 if (depth > MAX_BPF_STACK) { 5819 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5820 frame + 1, depth); 5821 return -EACCES; 5822 } 5823 continue_func: 5824 subprog_end = subprog[idx + 1].start; 5825 for (; i < subprog_end; i++) { 5826 int next_insn, sidx; 5827 5828 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 5829 bool err = false; 5830 5831 if (!is_bpf_throw_kfunc(insn + i)) 5832 continue; 5833 if (subprog[idx].is_cb) 5834 err = true; 5835 for (int c = 0; c < frame && !err; c++) { 5836 if (subprog[ret_prog[c]].is_cb) { 5837 err = true; 5838 break; 5839 } 5840 } 5841 if (!err) 5842 continue; 5843 verbose(env, 5844 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 5845 i, idx); 5846 return -EINVAL; 5847 } 5848 5849 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5850 continue; 5851 /* remember insn and function to return to */ 5852 ret_insn[frame] = i + 1; 5853 ret_prog[frame] = idx; 5854 5855 /* find the callee */ 5856 next_insn = i + insn[i].imm + 1; 5857 sidx = find_subprog(env, next_insn); 5858 if (sidx < 0) { 5859 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5860 next_insn); 5861 return -EFAULT; 5862 } 5863 if (subprog[sidx].is_async_cb) { 5864 if (subprog[sidx].has_tail_call) { 5865 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 5866 return -EFAULT; 5867 } 5868 /* async callbacks don't increase bpf prog stack size unless called directly */ 5869 if (!bpf_pseudo_call(insn + i)) 5870 continue; 5871 if (subprog[sidx].is_exception_cb) { 5872 verbose(env, "insn %d cannot call exception cb directly\n", i); 5873 return -EINVAL; 5874 } 5875 } 5876 i = next_insn; 5877 idx = sidx; 5878 5879 if (subprog[idx].has_tail_call) 5880 tail_call_reachable = true; 5881 5882 frame++; 5883 if (frame >= MAX_CALL_FRAMES) { 5884 verbose(env, "the call stack of %d frames is too deep !\n", 5885 frame); 5886 return -E2BIG; 5887 } 5888 goto process_func; 5889 } 5890 /* if tail call got detected across bpf2bpf calls then mark each of the 5891 * currently present subprog frames as tail call reachable subprogs; 5892 * this info will be utilized by JIT so that we will be preserving the 5893 * tail call counter throughout bpf2bpf calls combined with tailcalls 5894 */ 5895 if (tail_call_reachable) 5896 for (j = 0; j < frame; j++) { 5897 if (subprog[ret_prog[j]].is_exception_cb) { 5898 verbose(env, "cannot tail call within exception cb\n"); 5899 return -EINVAL; 5900 } 5901 subprog[ret_prog[j]].tail_call_reachable = true; 5902 } 5903 if (subprog[0].tail_call_reachable) 5904 env->prog->aux->tail_call_reachable = true; 5905 5906 /* end of for() loop means the last insn of the 'subprog' 5907 * was reached. Doesn't matter whether it was JA or EXIT 5908 */ 5909 if (frame == 0) 5910 return 0; 5911 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5912 frame--; 5913 i = ret_insn[frame]; 5914 idx = ret_prog[frame]; 5915 goto continue_func; 5916 } 5917 5918 static int check_max_stack_depth(struct bpf_verifier_env *env) 5919 { 5920 struct bpf_subprog_info *si = env->subprog_info; 5921 int ret; 5922 5923 for (int i = 0; i < env->subprog_cnt; i++) { 5924 if (!i || si[i].is_async_cb) { 5925 ret = check_max_stack_depth_subprog(env, i); 5926 if (ret < 0) 5927 return ret; 5928 } 5929 continue; 5930 } 5931 return 0; 5932 } 5933 5934 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 5935 static int get_callee_stack_depth(struct bpf_verifier_env *env, 5936 const struct bpf_insn *insn, int idx) 5937 { 5938 int start = idx + insn->imm + 1, subprog; 5939 5940 subprog = find_subprog(env, start); 5941 if (subprog < 0) { 5942 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5943 start); 5944 return -EFAULT; 5945 } 5946 return env->subprog_info[subprog].stack_depth; 5947 } 5948 #endif 5949 5950 static int __check_buffer_access(struct bpf_verifier_env *env, 5951 const char *buf_info, 5952 const struct bpf_reg_state *reg, 5953 int regno, int off, int size) 5954 { 5955 if (off < 0) { 5956 verbose(env, 5957 "R%d invalid %s buffer access: off=%d, size=%d\n", 5958 regno, buf_info, off, size); 5959 return -EACCES; 5960 } 5961 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5962 char tn_buf[48]; 5963 5964 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5965 verbose(env, 5966 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 5967 regno, off, tn_buf); 5968 return -EACCES; 5969 } 5970 5971 return 0; 5972 } 5973 5974 static int check_tp_buffer_access(struct bpf_verifier_env *env, 5975 const struct bpf_reg_state *reg, 5976 int regno, int off, int size) 5977 { 5978 int err; 5979 5980 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 5981 if (err) 5982 return err; 5983 5984 if (off + size > env->prog->aux->max_tp_access) 5985 env->prog->aux->max_tp_access = off + size; 5986 5987 return 0; 5988 } 5989 5990 static int check_buffer_access(struct bpf_verifier_env *env, 5991 const struct bpf_reg_state *reg, 5992 int regno, int off, int size, 5993 bool zero_size_allowed, 5994 u32 *max_access) 5995 { 5996 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 5997 int err; 5998 5999 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 6000 if (err) 6001 return err; 6002 6003 if (off + size > *max_access) 6004 *max_access = off + size; 6005 6006 return 0; 6007 } 6008 6009 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 6010 static void zext_32_to_64(struct bpf_reg_state *reg) 6011 { 6012 reg->var_off = tnum_subreg(reg->var_off); 6013 __reg_assign_32_into_64(reg); 6014 } 6015 6016 /* truncate register to smaller size (in bytes) 6017 * must be called with size < BPF_REG_SIZE 6018 */ 6019 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 6020 { 6021 u64 mask; 6022 6023 /* clear high bits in bit representation */ 6024 reg->var_off = tnum_cast(reg->var_off, size); 6025 6026 /* fix arithmetic bounds */ 6027 mask = ((u64)1 << (size * 8)) - 1; 6028 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 6029 reg->umin_value &= mask; 6030 reg->umax_value &= mask; 6031 } else { 6032 reg->umin_value = 0; 6033 reg->umax_value = mask; 6034 } 6035 reg->smin_value = reg->umin_value; 6036 reg->smax_value = reg->umax_value; 6037 6038 /* If size is smaller than 32bit register the 32bit register 6039 * values are also truncated so we push 64-bit bounds into 6040 * 32-bit bounds. Above were truncated < 32-bits already. 6041 */ 6042 if (size < 4) { 6043 __mark_reg32_unbounded(reg); 6044 reg_bounds_sync(reg); 6045 } 6046 } 6047 6048 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 6049 { 6050 if (size == 1) { 6051 reg->smin_value = reg->s32_min_value = S8_MIN; 6052 reg->smax_value = reg->s32_max_value = S8_MAX; 6053 } else if (size == 2) { 6054 reg->smin_value = reg->s32_min_value = S16_MIN; 6055 reg->smax_value = reg->s32_max_value = S16_MAX; 6056 } else { 6057 /* size == 4 */ 6058 reg->smin_value = reg->s32_min_value = S32_MIN; 6059 reg->smax_value = reg->s32_max_value = S32_MAX; 6060 } 6061 reg->umin_value = reg->u32_min_value = 0; 6062 reg->umax_value = U64_MAX; 6063 reg->u32_max_value = U32_MAX; 6064 reg->var_off = tnum_unknown; 6065 } 6066 6067 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6068 { 6069 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6070 u64 top_smax_value, top_smin_value; 6071 u64 num_bits = size * 8; 6072 6073 if (tnum_is_const(reg->var_off)) { 6074 u64_cval = reg->var_off.value; 6075 if (size == 1) 6076 reg->var_off = tnum_const((s8)u64_cval); 6077 else if (size == 2) 6078 reg->var_off = tnum_const((s16)u64_cval); 6079 else 6080 /* size == 4 */ 6081 reg->var_off = tnum_const((s32)u64_cval); 6082 6083 u64_cval = reg->var_off.value; 6084 reg->smax_value = reg->smin_value = u64_cval; 6085 reg->umax_value = reg->umin_value = u64_cval; 6086 reg->s32_max_value = reg->s32_min_value = u64_cval; 6087 reg->u32_max_value = reg->u32_min_value = u64_cval; 6088 return; 6089 } 6090 6091 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6092 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6093 6094 if (top_smax_value != top_smin_value) 6095 goto out; 6096 6097 /* find the s64_min and s64_min after sign extension */ 6098 if (size == 1) { 6099 init_s64_max = (s8)reg->smax_value; 6100 init_s64_min = (s8)reg->smin_value; 6101 } else if (size == 2) { 6102 init_s64_max = (s16)reg->smax_value; 6103 init_s64_min = (s16)reg->smin_value; 6104 } else { 6105 init_s64_max = (s32)reg->smax_value; 6106 init_s64_min = (s32)reg->smin_value; 6107 } 6108 6109 s64_max = max(init_s64_max, init_s64_min); 6110 s64_min = min(init_s64_max, init_s64_min); 6111 6112 /* both of s64_max/s64_min positive or negative */ 6113 if ((s64_max >= 0) == (s64_min >= 0)) { 6114 reg->smin_value = reg->s32_min_value = s64_min; 6115 reg->smax_value = reg->s32_max_value = s64_max; 6116 reg->umin_value = reg->u32_min_value = s64_min; 6117 reg->umax_value = reg->u32_max_value = s64_max; 6118 reg->var_off = tnum_range(s64_min, s64_max); 6119 return; 6120 } 6121 6122 out: 6123 set_sext64_default_val(reg, size); 6124 } 6125 6126 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6127 { 6128 if (size == 1) { 6129 reg->s32_min_value = S8_MIN; 6130 reg->s32_max_value = S8_MAX; 6131 } else { 6132 /* size == 2 */ 6133 reg->s32_min_value = S16_MIN; 6134 reg->s32_max_value = S16_MAX; 6135 } 6136 reg->u32_min_value = 0; 6137 reg->u32_max_value = U32_MAX; 6138 } 6139 6140 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6141 { 6142 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6143 u32 top_smax_value, top_smin_value; 6144 u32 num_bits = size * 8; 6145 6146 if (tnum_is_const(reg->var_off)) { 6147 u32_val = reg->var_off.value; 6148 if (size == 1) 6149 reg->var_off = tnum_const((s8)u32_val); 6150 else 6151 reg->var_off = tnum_const((s16)u32_val); 6152 6153 u32_val = reg->var_off.value; 6154 reg->s32_min_value = reg->s32_max_value = u32_val; 6155 reg->u32_min_value = reg->u32_max_value = u32_val; 6156 return; 6157 } 6158 6159 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 6160 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 6161 6162 if (top_smax_value != top_smin_value) 6163 goto out; 6164 6165 /* find the s32_min and s32_min after sign extension */ 6166 if (size == 1) { 6167 init_s32_max = (s8)reg->s32_max_value; 6168 init_s32_min = (s8)reg->s32_min_value; 6169 } else { 6170 /* size == 2 */ 6171 init_s32_max = (s16)reg->s32_max_value; 6172 init_s32_min = (s16)reg->s32_min_value; 6173 } 6174 s32_max = max(init_s32_max, init_s32_min); 6175 s32_min = min(init_s32_max, init_s32_min); 6176 6177 if ((s32_min >= 0) == (s32_max >= 0)) { 6178 reg->s32_min_value = s32_min; 6179 reg->s32_max_value = s32_max; 6180 reg->u32_min_value = (u32)s32_min; 6181 reg->u32_max_value = (u32)s32_max; 6182 return; 6183 } 6184 6185 out: 6186 set_sext32_default_val(reg, size); 6187 } 6188 6189 static bool bpf_map_is_rdonly(const struct bpf_map *map) 6190 { 6191 /* A map is considered read-only if the following condition are true: 6192 * 6193 * 1) BPF program side cannot change any of the map content. The 6194 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6195 * and was set at map creation time. 6196 * 2) The map value(s) have been initialized from user space by a 6197 * loader and then "frozen", such that no new map update/delete 6198 * operations from syscall side are possible for the rest of 6199 * the map's lifetime from that point onwards. 6200 * 3) Any parallel/pending map update/delete operations from syscall 6201 * side have been completed. Only after that point, it's safe to 6202 * assume that map value(s) are immutable. 6203 */ 6204 return (map->map_flags & BPF_F_RDONLY_PROG) && 6205 READ_ONCE(map->frozen) && 6206 !bpf_map_write_active(map); 6207 } 6208 6209 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6210 bool is_ldsx) 6211 { 6212 void *ptr; 6213 u64 addr; 6214 int err; 6215 6216 err = map->ops->map_direct_value_addr(map, &addr, off); 6217 if (err) 6218 return err; 6219 ptr = (void *)(long)addr + off; 6220 6221 switch (size) { 6222 case sizeof(u8): 6223 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6224 break; 6225 case sizeof(u16): 6226 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6227 break; 6228 case sizeof(u32): 6229 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6230 break; 6231 case sizeof(u64): 6232 *val = *(u64 *)ptr; 6233 break; 6234 default: 6235 return -EINVAL; 6236 } 6237 return 0; 6238 } 6239 6240 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6241 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6242 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6243 6244 /* 6245 * Allow list few fields as RCU trusted or full trusted. 6246 * This logic doesn't allow mix tagging and will be removed once GCC supports 6247 * btf_type_tag. 6248 */ 6249 6250 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6251 BTF_TYPE_SAFE_RCU(struct task_struct) { 6252 const cpumask_t *cpus_ptr; 6253 struct css_set __rcu *cgroups; 6254 struct task_struct __rcu *real_parent; 6255 struct task_struct *group_leader; 6256 }; 6257 6258 BTF_TYPE_SAFE_RCU(struct cgroup) { 6259 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6260 struct kernfs_node *kn; 6261 }; 6262 6263 BTF_TYPE_SAFE_RCU(struct css_set) { 6264 struct cgroup *dfl_cgrp; 6265 }; 6266 6267 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6268 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6269 struct file __rcu *exe_file; 6270 }; 6271 6272 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6273 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6274 */ 6275 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6276 struct sock *sk; 6277 }; 6278 6279 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6280 struct sock *sk; 6281 }; 6282 6283 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6284 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6285 struct seq_file *seq; 6286 }; 6287 6288 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6289 struct bpf_iter_meta *meta; 6290 struct task_struct *task; 6291 }; 6292 6293 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6294 struct file *file; 6295 }; 6296 6297 BTF_TYPE_SAFE_TRUSTED(struct file) { 6298 struct inode *f_inode; 6299 }; 6300 6301 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 6302 /* no negative dentry-s in places where bpf can see it */ 6303 struct inode *d_inode; 6304 }; 6305 6306 BTF_TYPE_SAFE_TRUSTED(struct socket) { 6307 struct sock *sk; 6308 }; 6309 6310 static bool type_is_rcu(struct bpf_verifier_env *env, 6311 struct bpf_reg_state *reg, 6312 const char *field_name, u32 btf_id) 6313 { 6314 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6315 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6316 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6317 6318 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6319 } 6320 6321 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6322 struct bpf_reg_state *reg, 6323 const char *field_name, u32 btf_id) 6324 { 6325 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6326 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6327 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6328 6329 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6330 } 6331 6332 static bool type_is_trusted(struct bpf_verifier_env *env, 6333 struct bpf_reg_state *reg, 6334 const char *field_name, u32 btf_id) 6335 { 6336 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 6337 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6338 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6339 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6340 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 6341 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket)); 6342 6343 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6344 } 6345 6346 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6347 struct bpf_reg_state *regs, 6348 int regno, int off, int size, 6349 enum bpf_access_type atype, 6350 int value_regno) 6351 { 6352 struct bpf_reg_state *reg = regs + regno; 6353 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6354 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6355 const char *field_name = NULL; 6356 enum bpf_type_flag flag = 0; 6357 u32 btf_id = 0; 6358 int ret; 6359 6360 if (!env->allow_ptr_leaks) { 6361 verbose(env, 6362 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6363 tname); 6364 return -EPERM; 6365 } 6366 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6367 verbose(env, 6368 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6369 tname); 6370 return -EINVAL; 6371 } 6372 if (off < 0) { 6373 verbose(env, 6374 "R%d is ptr_%s invalid negative access: off=%d\n", 6375 regno, tname, off); 6376 return -EACCES; 6377 } 6378 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6379 char tn_buf[48]; 6380 6381 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6382 verbose(env, 6383 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6384 regno, tname, off, tn_buf); 6385 return -EACCES; 6386 } 6387 6388 if (reg->type & MEM_USER) { 6389 verbose(env, 6390 "R%d is ptr_%s access user memory: off=%d\n", 6391 regno, tname, off); 6392 return -EACCES; 6393 } 6394 6395 if (reg->type & MEM_PERCPU) { 6396 verbose(env, 6397 "R%d is ptr_%s access percpu memory: off=%d\n", 6398 regno, tname, off); 6399 return -EACCES; 6400 } 6401 6402 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6403 if (!btf_is_kernel(reg->btf)) { 6404 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 6405 return -EFAULT; 6406 } 6407 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6408 } else { 6409 /* Writes are permitted with default btf_struct_access for 6410 * program allocated objects (which always have ref_obj_id > 0), 6411 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6412 */ 6413 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6414 verbose(env, "only read is supported\n"); 6415 return -EACCES; 6416 } 6417 6418 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6419 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 6420 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 6421 return -EFAULT; 6422 } 6423 6424 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6425 } 6426 6427 if (ret < 0) 6428 return ret; 6429 6430 if (ret != PTR_TO_BTF_ID) { 6431 /* just mark; */ 6432 6433 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6434 /* If this is an untrusted pointer, all pointers formed by walking it 6435 * also inherit the untrusted flag. 6436 */ 6437 flag = PTR_UNTRUSTED; 6438 6439 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6440 /* By default any pointer obtained from walking a trusted pointer is no 6441 * longer trusted, unless the field being accessed has explicitly been 6442 * marked as inheriting its parent's state of trust (either full or RCU). 6443 * For example: 6444 * 'cgroups' pointer is untrusted if task->cgroups dereference 6445 * happened in a sleepable program outside of bpf_rcu_read_lock() 6446 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6447 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6448 * 6449 * A regular RCU-protected pointer with __rcu tag can also be deemed 6450 * trusted if we are in an RCU CS. Such pointer can be NULL. 6451 */ 6452 if (type_is_trusted(env, reg, field_name, btf_id)) { 6453 flag |= PTR_TRUSTED; 6454 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6455 if (type_is_rcu(env, reg, field_name, btf_id)) { 6456 /* ignore __rcu tag and mark it MEM_RCU */ 6457 flag |= MEM_RCU; 6458 } else if (flag & MEM_RCU || 6459 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6460 /* __rcu tagged pointers can be NULL */ 6461 flag |= MEM_RCU | PTR_MAYBE_NULL; 6462 6463 /* We always trust them */ 6464 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6465 flag & PTR_UNTRUSTED) 6466 flag &= ~PTR_UNTRUSTED; 6467 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6468 /* keep as-is */ 6469 } else { 6470 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6471 clear_trusted_flags(&flag); 6472 } 6473 } else { 6474 /* 6475 * If not in RCU CS or MEM_RCU pointer can be NULL then 6476 * aggressively mark as untrusted otherwise such 6477 * pointers will be plain PTR_TO_BTF_ID without flags 6478 * and will be allowed to be passed into helpers for 6479 * compat reasons. 6480 */ 6481 flag = PTR_UNTRUSTED; 6482 } 6483 } else { 6484 /* Old compat. Deprecated */ 6485 clear_trusted_flags(&flag); 6486 } 6487 6488 if (atype == BPF_READ && value_regno >= 0) 6489 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6490 6491 return 0; 6492 } 6493 6494 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6495 struct bpf_reg_state *regs, 6496 int regno, int off, int size, 6497 enum bpf_access_type atype, 6498 int value_regno) 6499 { 6500 struct bpf_reg_state *reg = regs + regno; 6501 struct bpf_map *map = reg->map_ptr; 6502 struct bpf_reg_state map_reg; 6503 enum bpf_type_flag flag = 0; 6504 const struct btf_type *t; 6505 const char *tname; 6506 u32 btf_id; 6507 int ret; 6508 6509 if (!btf_vmlinux) { 6510 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6511 return -ENOTSUPP; 6512 } 6513 6514 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6515 verbose(env, "map_ptr access not supported for map type %d\n", 6516 map->map_type); 6517 return -ENOTSUPP; 6518 } 6519 6520 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6521 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6522 6523 if (!env->allow_ptr_leaks) { 6524 verbose(env, 6525 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6526 tname); 6527 return -EPERM; 6528 } 6529 6530 if (off < 0) { 6531 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6532 regno, tname, off); 6533 return -EACCES; 6534 } 6535 6536 if (atype != BPF_READ) { 6537 verbose(env, "only read from %s is supported\n", tname); 6538 return -EACCES; 6539 } 6540 6541 /* Simulate access to a PTR_TO_BTF_ID */ 6542 memset(&map_reg, 0, sizeof(map_reg)); 6543 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6544 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6545 if (ret < 0) 6546 return ret; 6547 6548 if (value_regno >= 0) 6549 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6550 6551 return 0; 6552 } 6553 6554 /* Check that the stack access at the given offset is within bounds. The 6555 * maximum valid offset is -1. 6556 * 6557 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6558 * -state->allocated_stack for reads. 6559 */ 6560 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 6561 s64 off, 6562 struct bpf_func_state *state, 6563 enum bpf_access_type t) 6564 { 6565 int min_valid_off; 6566 6567 if (t == BPF_WRITE || env->allow_uninit_stack) 6568 min_valid_off = -MAX_BPF_STACK; 6569 else 6570 min_valid_off = -state->allocated_stack; 6571 6572 if (off < min_valid_off || off > -1) 6573 return -EACCES; 6574 return 0; 6575 } 6576 6577 /* Check that the stack access at 'regno + off' falls within the maximum stack 6578 * bounds. 6579 * 6580 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6581 */ 6582 static int check_stack_access_within_bounds( 6583 struct bpf_verifier_env *env, 6584 int regno, int off, int access_size, 6585 enum bpf_access_src src, enum bpf_access_type type) 6586 { 6587 struct bpf_reg_state *regs = cur_regs(env); 6588 struct bpf_reg_state *reg = regs + regno; 6589 struct bpf_func_state *state = func(env, reg); 6590 s64 min_off, max_off; 6591 int err; 6592 char *err_extra; 6593 6594 if (src == ACCESS_HELPER) 6595 /* We don't know if helpers are reading or writing (or both). */ 6596 err_extra = " indirect access to"; 6597 else if (type == BPF_READ) 6598 err_extra = " read from"; 6599 else 6600 err_extra = " write to"; 6601 6602 if (tnum_is_const(reg->var_off)) { 6603 min_off = (s64)reg->var_off.value + off; 6604 max_off = min_off + access_size; 6605 } else { 6606 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6607 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6608 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6609 err_extra, regno); 6610 return -EACCES; 6611 } 6612 min_off = reg->smin_value + off; 6613 max_off = reg->smax_value + off + access_size; 6614 } 6615 6616 err = check_stack_slot_within_bounds(env, min_off, state, type); 6617 if (!err && max_off > 0) 6618 err = -EINVAL; /* out of stack access into non-negative offsets */ 6619 6620 if (err) { 6621 if (tnum_is_const(reg->var_off)) { 6622 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 6623 err_extra, regno, off, access_size); 6624 } else { 6625 char tn_buf[48]; 6626 6627 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6628 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n", 6629 err_extra, regno, tn_buf, off, access_size); 6630 } 6631 return err; 6632 } 6633 6634 /* Note that there is no stack access with offset zero, so the needed stack 6635 * size is -min_off, not -min_off+1. 6636 */ 6637 return grow_stack_state(env, state, -min_off /* size */); 6638 } 6639 6640 /* check whether memory at (regno + off) is accessible for t = (read | write) 6641 * if t==write, value_regno is a register which value is stored into memory 6642 * if t==read, value_regno is a register which will receive the value from memory 6643 * if t==write && value_regno==-1, some unknown value is stored into memory 6644 * if t==read && value_regno==-1, don't care what we read from memory 6645 */ 6646 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6647 int off, int bpf_size, enum bpf_access_type t, 6648 int value_regno, bool strict_alignment_once, bool is_ldsx) 6649 { 6650 struct bpf_reg_state *regs = cur_regs(env); 6651 struct bpf_reg_state *reg = regs + regno; 6652 int size, err = 0; 6653 6654 size = bpf_size_to_bytes(bpf_size); 6655 if (size < 0) 6656 return size; 6657 6658 /* alignment checks will add in reg->off themselves */ 6659 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6660 if (err) 6661 return err; 6662 6663 /* for access checks, reg->off is just part of off */ 6664 off += reg->off; 6665 6666 if (reg->type == PTR_TO_MAP_KEY) { 6667 if (t == BPF_WRITE) { 6668 verbose(env, "write to change key R%d not allowed\n", regno); 6669 return -EACCES; 6670 } 6671 6672 err = check_mem_region_access(env, regno, off, size, 6673 reg->map_ptr->key_size, false); 6674 if (err) 6675 return err; 6676 if (value_regno >= 0) 6677 mark_reg_unknown(env, regs, value_regno); 6678 } else if (reg->type == PTR_TO_MAP_VALUE) { 6679 struct btf_field *kptr_field = NULL; 6680 6681 if (t == BPF_WRITE && value_regno >= 0 && 6682 is_pointer_value(env, value_regno)) { 6683 verbose(env, "R%d leaks addr into map\n", value_regno); 6684 return -EACCES; 6685 } 6686 err = check_map_access_type(env, regno, off, size, t); 6687 if (err) 6688 return err; 6689 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6690 if (err) 6691 return err; 6692 if (tnum_is_const(reg->var_off)) 6693 kptr_field = btf_record_find(reg->map_ptr->record, 6694 off + reg->var_off.value, BPF_KPTR); 6695 if (kptr_field) { 6696 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6697 } else if (t == BPF_READ && value_regno >= 0) { 6698 struct bpf_map *map = reg->map_ptr; 6699 6700 /* if map is read-only, track its contents as scalars */ 6701 if (tnum_is_const(reg->var_off) && 6702 bpf_map_is_rdonly(map) && 6703 map->ops->map_direct_value_addr) { 6704 int map_off = off + reg->var_off.value; 6705 u64 val = 0; 6706 6707 err = bpf_map_direct_read(map, map_off, size, 6708 &val, is_ldsx); 6709 if (err) 6710 return err; 6711 6712 regs[value_regno].type = SCALAR_VALUE; 6713 __mark_reg_known(®s[value_regno], val); 6714 } else { 6715 mark_reg_unknown(env, regs, value_regno); 6716 } 6717 } 6718 } else if (base_type(reg->type) == PTR_TO_MEM) { 6719 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6720 6721 if (type_may_be_null(reg->type)) { 6722 verbose(env, "R%d invalid mem access '%s'\n", regno, 6723 reg_type_str(env, reg->type)); 6724 return -EACCES; 6725 } 6726 6727 if (t == BPF_WRITE && rdonly_mem) { 6728 verbose(env, "R%d cannot write into %s\n", 6729 regno, reg_type_str(env, reg->type)); 6730 return -EACCES; 6731 } 6732 6733 if (t == BPF_WRITE && value_regno >= 0 && 6734 is_pointer_value(env, value_regno)) { 6735 verbose(env, "R%d leaks addr into mem\n", value_regno); 6736 return -EACCES; 6737 } 6738 6739 err = check_mem_region_access(env, regno, off, size, 6740 reg->mem_size, false); 6741 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6742 mark_reg_unknown(env, regs, value_regno); 6743 } else if (reg->type == PTR_TO_CTX) { 6744 enum bpf_reg_type reg_type = SCALAR_VALUE; 6745 struct btf *btf = NULL; 6746 u32 btf_id = 0; 6747 6748 if (t == BPF_WRITE && value_regno >= 0 && 6749 is_pointer_value(env, value_regno)) { 6750 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6751 return -EACCES; 6752 } 6753 6754 err = check_ptr_off_reg(env, reg, regno); 6755 if (err < 0) 6756 return err; 6757 6758 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 6759 &btf_id); 6760 if (err) 6761 verbose_linfo(env, insn_idx, "; "); 6762 if (!err && t == BPF_READ && value_regno >= 0) { 6763 /* ctx access returns either a scalar, or a 6764 * PTR_TO_PACKET[_META,_END]. In the latter 6765 * case, we know the offset is zero. 6766 */ 6767 if (reg_type == SCALAR_VALUE) { 6768 mark_reg_unknown(env, regs, value_regno); 6769 } else { 6770 mark_reg_known_zero(env, regs, 6771 value_regno); 6772 if (type_may_be_null(reg_type)) 6773 regs[value_regno].id = ++env->id_gen; 6774 /* A load of ctx field could have different 6775 * actual load size with the one encoded in the 6776 * insn. When the dst is PTR, it is for sure not 6777 * a sub-register. 6778 */ 6779 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6780 if (base_type(reg_type) == PTR_TO_BTF_ID) { 6781 regs[value_regno].btf = btf; 6782 regs[value_regno].btf_id = btf_id; 6783 } 6784 } 6785 regs[value_regno].type = reg_type; 6786 } 6787 6788 } else if (reg->type == PTR_TO_STACK) { 6789 /* Basic bounds checks. */ 6790 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 6791 if (err) 6792 return err; 6793 6794 if (t == BPF_READ) 6795 err = check_stack_read(env, regno, off, size, 6796 value_regno); 6797 else 6798 err = check_stack_write(env, regno, off, size, 6799 value_regno, insn_idx); 6800 } else if (reg_is_pkt_pointer(reg)) { 6801 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6802 verbose(env, "cannot write into packet\n"); 6803 return -EACCES; 6804 } 6805 if (t == BPF_WRITE && value_regno >= 0 && 6806 is_pointer_value(env, value_regno)) { 6807 verbose(env, "R%d leaks addr into packet\n", 6808 value_regno); 6809 return -EACCES; 6810 } 6811 err = check_packet_access(env, regno, off, size, false); 6812 if (!err && t == BPF_READ && value_regno >= 0) 6813 mark_reg_unknown(env, regs, value_regno); 6814 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6815 if (t == BPF_WRITE && value_regno >= 0 && 6816 is_pointer_value(env, value_regno)) { 6817 verbose(env, "R%d leaks addr into flow keys\n", 6818 value_regno); 6819 return -EACCES; 6820 } 6821 6822 err = check_flow_keys_access(env, off, size); 6823 if (!err && t == BPF_READ && value_regno >= 0) 6824 mark_reg_unknown(env, regs, value_regno); 6825 } else if (type_is_sk_pointer(reg->type)) { 6826 if (t == BPF_WRITE) { 6827 verbose(env, "R%d cannot write into %s\n", 6828 regno, reg_type_str(env, reg->type)); 6829 return -EACCES; 6830 } 6831 err = check_sock_access(env, insn_idx, regno, off, size, t); 6832 if (!err && value_regno >= 0) 6833 mark_reg_unknown(env, regs, value_regno); 6834 } else if (reg->type == PTR_TO_TP_BUFFER) { 6835 err = check_tp_buffer_access(env, reg, regno, off, size); 6836 if (!err && t == BPF_READ && value_regno >= 0) 6837 mark_reg_unknown(env, regs, value_regno); 6838 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6839 !type_may_be_null(reg->type)) { 6840 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 6841 value_regno); 6842 } else if (reg->type == CONST_PTR_TO_MAP) { 6843 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 6844 value_regno); 6845 } else if (base_type(reg->type) == PTR_TO_BUF) { 6846 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6847 u32 *max_access; 6848 6849 if (rdonly_mem) { 6850 if (t == BPF_WRITE) { 6851 verbose(env, "R%d cannot write into %s\n", 6852 regno, reg_type_str(env, reg->type)); 6853 return -EACCES; 6854 } 6855 max_access = &env->prog->aux->max_rdonly_access; 6856 } else { 6857 max_access = &env->prog->aux->max_rdwr_access; 6858 } 6859 6860 err = check_buffer_access(env, reg, regno, off, size, false, 6861 max_access); 6862 6863 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6864 mark_reg_unknown(env, regs, value_regno); 6865 } else { 6866 verbose(env, "R%d invalid mem access '%s'\n", regno, 6867 reg_type_str(env, reg->type)); 6868 return -EACCES; 6869 } 6870 6871 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6872 regs[value_regno].type == SCALAR_VALUE) { 6873 if (!is_ldsx) 6874 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6875 coerce_reg_to_size(®s[value_regno], size); 6876 else 6877 coerce_reg_to_size_sx(®s[value_regno], size); 6878 } 6879 return err; 6880 } 6881 6882 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 6883 { 6884 int load_reg; 6885 int err; 6886 6887 switch (insn->imm) { 6888 case BPF_ADD: 6889 case BPF_ADD | BPF_FETCH: 6890 case BPF_AND: 6891 case BPF_AND | BPF_FETCH: 6892 case BPF_OR: 6893 case BPF_OR | BPF_FETCH: 6894 case BPF_XOR: 6895 case BPF_XOR | BPF_FETCH: 6896 case BPF_XCHG: 6897 case BPF_CMPXCHG: 6898 break; 6899 default: 6900 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 6901 return -EINVAL; 6902 } 6903 6904 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6905 verbose(env, "invalid atomic operand size\n"); 6906 return -EINVAL; 6907 } 6908 6909 /* check src1 operand */ 6910 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6911 if (err) 6912 return err; 6913 6914 /* check src2 operand */ 6915 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6916 if (err) 6917 return err; 6918 6919 if (insn->imm == BPF_CMPXCHG) { 6920 /* Check comparison of R0 with memory location */ 6921 const u32 aux_reg = BPF_REG_0; 6922 6923 err = check_reg_arg(env, aux_reg, SRC_OP); 6924 if (err) 6925 return err; 6926 6927 if (is_pointer_value(env, aux_reg)) { 6928 verbose(env, "R%d leaks addr into mem\n", aux_reg); 6929 return -EACCES; 6930 } 6931 } 6932 6933 if (is_pointer_value(env, insn->src_reg)) { 6934 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 6935 return -EACCES; 6936 } 6937 6938 if (is_ctx_reg(env, insn->dst_reg) || 6939 is_pkt_reg(env, insn->dst_reg) || 6940 is_flow_key_reg(env, insn->dst_reg) || 6941 is_sk_reg(env, insn->dst_reg)) { 6942 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6943 insn->dst_reg, 6944 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6945 return -EACCES; 6946 } 6947 6948 if (insn->imm & BPF_FETCH) { 6949 if (insn->imm == BPF_CMPXCHG) 6950 load_reg = BPF_REG_0; 6951 else 6952 load_reg = insn->src_reg; 6953 6954 /* check and record load of old value */ 6955 err = check_reg_arg(env, load_reg, DST_OP); 6956 if (err) 6957 return err; 6958 } else { 6959 /* This instruction accesses a memory location but doesn't 6960 * actually load it into a register. 6961 */ 6962 load_reg = -1; 6963 } 6964 6965 /* Check whether we can read the memory, with second call for fetch 6966 * case to simulate the register fill. 6967 */ 6968 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6969 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 6970 if (!err && load_reg >= 0) 6971 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6972 BPF_SIZE(insn->code), BPF_READ, load_reg, 6973 true, false); 6974 if (err) 6975 return err; 6976 6977 /* Check whether we can write into the same memory. */ 6978 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6979 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 6980 if (err) 6981 return err; 6982 return 0; 6983 } 6984 6985 /* When register 'regno' is used to read the stack (either directly or through 6986 * a helper function) make sure that it's within stack boundary and, depending 6987 * on the access type and privileges, that all elements of the stack are 6988 * initialized. 6989 * 6990 * 'off' includes 'regno->off', but not its dynamic part (if any). 6991 * 6992 * All registers that have been spilled on the stack in the slots within the 6993 * read offsets are marked as read. 6994 */ 6995 static int check_stack_range_initialized( 6996 struct bpf_verifier_env *env, int regno, int off, 6997 int access_size, bool zero_size_allowed, 6998 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 6999 { 7000 struct bpf_reg_state *reg = reg_state(env, regno); 7001 struct bpf_func_state *state = func(env, reg); 7002 int err, min_off, max_off, i, j, slot, spi; 7003 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 7004 enum bpf_access_type bounds_check_type; 7005 /* Some accesses can write anything into the stack, others are 7006 * read-only. 7007 */ 7008 bool clobber = false; 7009 7010 if (access_size == 0 && !zero_size_allowed) { 7011 verbose(env, "invalid zero-sized read\n"); 7012 return -EACCES; 7013 } 7014 7015 if (type == ACCESS_HELPER) { 7016 /* The bounds checks for writes are more permissive than for 7017 * reads. However, if raw_mode is not set, we'll do extra 7018 * checks below. 7019 */ 7020 bounds_check_type = BPF_WRITE; 7021 clobber = true; 7022 } else { 7023 bounds_check_type = BPF_READ; 7024 } 7025 err = check_stack_access_within_bounds(env, regno, off, access_size, 7026 type, bounds_check_type); 7027 if (err) 7028 return err; 7029 7030 7031 if (tnum_is_const(reg->var_off)) { 7032 min_off = max_off = reg->var_off.value + off; 7033 } else { 7034 /* Variable offset is prohibited for unprivileged mode for 7035 * simplicity since it requires corresponding support in 7036 * Spectre masking for stack ALU. 7037 * See also retrieve_ptr_limit(). 7038 */ 7039 if (!env->bypass_spec_v1) { 7040 char tn_buf[48]; 7041 7042 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7043 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 7044 regno, err_extra, tn_buf); 7045 return -EACCES; 7046 } 7047 /* Only initialized buffer on stack is allowed to be accessed 7048 * with variable offset. With uninitialized buffer it's hard to 7049 * guarantee that whole memory is marked as initialized on 7050 * helper return since specific bounds are unknown what may 7051 * cause uninitialized stack leaking. 7052 */ 7053 if (meta && meta->raw_mode) 7054 meta = NULL; 7055 7056 min_off = reg->smin_value + off; 7057 max_off = reg->smax_value + off; 7058 } 7059 7060 if (meta && meta->raw_mode) { 7061 /* Ensure we won't be overwriting dynptrs when simulating byte 7062 * by byte access in check_helper_call using meta.access_size. 7063 * This would be a problem if we have a helper in the future 7064 * which takes: 7065 * 7066 * helper(uninit_mem, len, dynptr) 7067 * 7068 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 7069 * may end up writing to dynptr itself when touching memory from 7070 * arg 1. This can be relaxed on a case by case basis for known 7071 * safe cases, but reject due to the possibilitiy of aliasing by 7072 * default. 7073 */ 7074 for (i = min_off; i < max_off + access_size; i++) { 7075 int stack_off = -i - 1; 7076 7077 spi = __get_spi(i); 7078 /* raw_mode may write past allocated_stack */ 7079 if (state->allocated_stack <= stack_off) 7080 continue; 7081 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 7082 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 7083 return -EACCES; 7084 } 7085 } 7086 meta->access_size = access_size; 7087 meta->regno = regno; 7088 return 0; 7089 } 7090 7091 for (i = min_off; i < max_off + access_size; i++) { 7092 u8 *stype; 7093 7094 slot = -i - 1; 7095 spi = slot / BPF_REG_SIZE; 7096 if (state->allocated_stack <= slot) { 7097 verbose(env, "verifier bug: allocated_stack too small"); 7098 return -EFAULT; 7099 } 7100 7101 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 7102 if (*stype == STACK_MISC) 7103 goto mark; 7104 if ((*stype == STACK_ZERO) || 7105 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 7106 if (clobber) { 7107 /* helper can write anything into the stack */ 7108 *stype = STACK_MISC; 7109 } 7110 goto mark; 7111 } 7112 7113 if (is_spilled_reg(&state->stack[spi]) && 7114 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 7115 env->allow_ptr_leaks)) { 7116 if (clobber) { 7117 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 7118 for (j = 0; j < BPF_REG_SIZE; j++) 7119 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 7120 } 7121 goto mark; 7122 } 7123 7124 if (tnum_is_const(reg->var_off)) { 7125 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 7126 err_extra, regno, min_off, i - min_off, access_size); 7127 } else { 7128 char tn_buf[48]; 7129 7130 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7131 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 7132 err_extra, regno, tn_buf, i - min_off, access_size); 7133 } 7134 return -EACCES; 7135 mark: 7136 /* reading any byte out of 8-byte 'spill_slot' will cause 7137 * the whole slot to be marked as 'read' 7138 */ 7139 mark_reg_read(env, &state->stack[spi].spilled_ptr, 7140 state->stack[spi].spilled_ptr.parent, 7141 REG_LIVE_READ64); 7142 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 7143 * be sure that whether stack slot is written to or not. Hence, 7144 * we must still conservatively propagate reads upwards even if 7145 * helper may write to the entire memory range. 7146 */ 7147 } 7148 return 0; 7149 } 7150 7151 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 7152 int access_size, bool zero_size_allowed, 7153 struct bpf_call_arg_meta *meta) 7154 { 7155 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7156 u32 *max_access; 7157 7158 switch (base_type(reg->type)) { 7159 case PTR_TO_PACKET: 7160 case PTR_TO_PACKET_META: 7161 return check_packet_access(env, regno, reg->off, access_size, 7162 zero_size_allowed); 7163 case PTR_TO_MAP_KEY: 7164 if (meta && meta->raw_mode) { 7165 verbose(env, "R%d cannot write into %s\n", regno, 7166 reg_type_str(env, reg->type)); 7167 return -EACCES; 7168 } 7169 return check_mem_region_access(env, regno, reg->off, access_size, 7170 reg->map_ptr->key_size, false); 7171 case PTR_TO_MAP_VALUE: 7172 if (check_map_access_type(env, regno, reg->off, access_size, 7173 meta && meta->raw_mode ? BPF_WRITE : 7174 BPF_READ)) 7175 return -EACCES; 7176 return check_map_access(env, regno, reg->off, access_size, 7177 zero_size_allowed, ACCESS_HELPER); 7178 case PTR_TO_MEM: 7179 if (type_is_rdonly_mem(reg->type)) { 7180 if (meta && meta->raw_mode) { 7181 verbose(env, "R%d cannot write into %s\n", regno, 7182 reg_type_str(env, reg->type)); 7183 return -EACCES; 7184 } 7185 } 7186 return check_mem_region_access(env, regno, reg->off, 7187 access_size, reg->mem_size, 7188 zero_size_allowed); 7189 case PTR_TO_BUF: 7190 if (type_is_rdonly_mem(reg->type)) { 7191 if (meta && meta->raw_mode) { 7192 verbose(env, "R%d cannot write into %s\n", regno, 7193 reg_type_str(env, reg->type)); 7194 return -EACCES; 7195 } 7196 7197 max_access = &env->prog->aux->max_rdonly_access; 7198 } else { 7199 max_access = &env->prog->aux->max_rdwr_access; 7200 } 7201 return check_buffer_access(env, reg, regno, reg->off, 7202 access_size, zero_size_allowed, 7203 max_access); 7204 case PTR_TO_STACK: 7205 return check_stack_range_initialized( 7206 env, 7207 regno, reg->off, access_size, 7208 zero_size_allowed, ACCESS_HELPER, meta); 7209 case PTR_TO_BTF_ID: 7210 return check_ptr_to_btf_access(env, regs, regno, reg->off, 7211 access_size, BPF_READ, -1); 7212 case PTR_TO_CTX: 7213 /* in case the function doesn't know how to access the context, 7214 * (because we are in a program of type SYSCALL for example), we 7215 * can not statically check its size. 7216 * Dynamically check it now. 7217 */ 7218 if (!env->ops->convert_ctx_access) { 7219 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 7220 int offset = access_size - 1; 7221 7222 /* Allow zero-byte read from PTR_TO_CTX */ 7223 if (access_size == 0) 7224 return zero_size_allowed ? 0 : -EACCES; 7225 7226 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 7227 atype, -1, false, false); 7228 } 7229 7230 fallthrough; 7231 default: /* scalar_value or invalid ptr */ 7232 /* Allow zero-byte read from NULL, regardless of pointer type */ 7233 if (zero_size_allowed && access_size == 0 && 7234 register_is_null(reg)) 7235 return 0; 7236 7237 verbose(env, "R%d type=%s ", regno, 7238 reg_type_str(env, reg->type)); 7239 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7240 return -EACCES; 7241 } 7242 } 7243 7244 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 7245 * size. 7246 * 7247 * @regno is the register containing the access size. regno-1 is the register 7248 * containing the pointer. 7249 */ 7250 static int check_mem_size_reg(struct bpf_verifier_env *env, 7251 struct bpf_reg_state *reg, u32 regno, 7252 bool zero_size_allowed, 7253 struct bpf_call_arg_meta *meta) 7254 { 7255 int err; 7256 7257 /* This is used to refine r0 return value bounds for helpers 7258 * that enforce this value as an upper bound on return values. 7259 * See do_refine_retval_range() for helpers that can refine 7260 * the return value. C type of helper is u32 so we pull register 7261 * bound from umax_value however, if negative verifier errors 7262 * out. Only upper bounds can be learned because retval is an 7263 * int type and negative retvals are allowed. 7264 */ 7265 meta->msize_max_value = reg->umax_value; 7266 7267 /* The register is SCALAR_VALUE; the access check 7268 * happens using its boundaries. 7269 */ 7270 if (!tnum_is_const(reg->var_off)) 7271 /* For unprivileged variable accesses, disable raw 7272 * mode so that the program is required to 7273 * initialize all the memory that the helper could 7274 * just partially fill up. 7275 */ 7276 meta = NULL; 7277 7278 if (reg->smin_value < 0) { 7279 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7280 regno); 7281 return -EACCES; 7282 } 7283 7284 if (reg->umin_value == 0 && !zero_size_allowed) { 7285 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n", 7286 regno, reg->umin_value, reg->umax_value); 7287 return -EACCES; 7288 } 7289 7290 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7291 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7292 regno); 7293 return -EACCES; 7294 } 7295 err = check_helper_mem_access(env, regno - 1, 7296 reg->umax_value, 7297 zero_size_allowed, meta); 7298 if (!err) 7299 err = mark_chain_precision(env, regno); 7300 return err; 7301 } 7302 7303 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7304 u32 regno, u32 mem_size) 7305 { 7306 bool may_be_null = type_may_be_null(reg->type); 7307 struct bpf_reg_state saved_reg; 7308 struct bpf_call_arg_meta meta; 7309 int err; 7310 7311 if (register_is_null(reg)) 7312 return 0; 7313 7314 memset(&meta, 0, sizeof(meta)); 7315 /* Assuming that the register contains a value check if the memory 7316 * access is safe. Temporarily save and restore the register's state as 7317 * the conversion shouldn't be visible to a caller. 7318 */ 7319 if (may_be_null) { 7320 saved_reg = *reg; 7321 mark_ptr_not_null_reg(reg); 7322 } 7323 7324 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 7325 /* Check access for BPF_WRITE */ 7326 meta.raw_mode = true; 7327 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 7328 7329 if (may_be_null) 7330 *reg = saved_reg; 7331 7332 return err; 7333 } 7334 7335 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7336 u32 regno) 7337 { 7338 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7339 bool may_be_null = type_may_be_null(mem_reg->type); 7340 struct bpf_reg_state saved_reg; 7341 struct bpf_call_arg_meta meta; 7342 int err; 7343 7344 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7345 7346 memset(&meta, 0, sizeof(meta)); 7347 7348 if (may_be_null) { 7349 saved_reg = *mem_reg; 7350 mark_ptr_not_null_reg(mem_reg); 7351 } 7352 7353 err = check_mem_size_reg(env, reg, regno, true, &meta); 7354 /* Check access for BPF_WRITE */ 7355 meta.raw_mode = true; 7356 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 7357 7358 if (may_be_null) 7359 *mem_reg = saved_reg; 7360 return err; 7361 } 7362 7363 /* Implementation details: 7364 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7365 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7366 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7367 * Two separate bpf_obj_new will also have different reg->id. 7368 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7369 * clears reg->id after value_or_null->value transition, since the verifier only 7370 * cares about the range of access to valid map value pointer and doesn't care 7371 * about actual address of the map element. 7372 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7373 * reg->id > 0 after value_or_null->value transition. By doing so 7374 * two bpf_map_lookups will be considered two different pointers that 7375 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7376 * returned from bpf_obj_new. 7377 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7378 * dead-locks. 7379 * Since only one bpf_spin_lock is allowed the checks are simpler than 7380 * reg_is_refcounted() logic. The verifier needs to remember only 7381 * one spin_lock instead of array of acquired_refs. 7382 * cur_state->active_lock remembers which map value element or allocated 7383 * object got locked and clears it after bpf_spin_unlock. 7384 */ 7385 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 7386 bool is_lock) 7387 { 7388 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7389 struct bpf_verifier_state *cur = env->cur_state; 7390 bool is_const = tnum_is_const(reg->var_off); 7391 u64 val = reg->var_off.value; 7392 struct bpf_map *map = NULL; 7393 struct btf *btf = NULL; 7394 struct btf_record *rec; 7395 7396 if (!is_const) { 7397 verbose(env, 7398 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 7399 regno); 7400 return -EINVAL; 7401 } 7402 if (reg->type == PTR_TO_MAP_VALUE) { 7403 map = reg->map_ptr; 7404 if (!map->btf) { 7405 verbose(env, 7406 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 7407 map->name); 7408 return -EINVAL; 7409 } 7410 } else { 7411 btf = reg->btf; 7412 } 7413 7414 rec = reg_btf_record(reg); 7415 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 7416 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 7417 map ? map->name : "kptr"); 7418 return -EINVAL; 7419 } 7420 if (rec->spin_lock_off != val + reg->off) { 7421 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 7422 val + reg->off, rec->spin_lock_off); 7423 return -EINVAL; 7424 } 7425 if (is_lock) { 7426 if (cur->active_lock.ptr) { 7427 verbose(env, 7428 "Locking two bpf_spin_locks are not allowed\n"); 7429 return -EINVAL; 7430 } 7431 if (map) 7432 cur->active_lock.ptr = map; 7433 else 7434 cur->active_lock.ptr = btf; 7435 cur->active_lock.id = reg->id; 7436 } else { 7437 void *ptr; 7438 7439 if (map) 7440 ptr = map; 7441 else 7442 ptr = btf; 7443 7444 if (!cur->active_lock.ptr) { 7445 verbose(env, "bpf_spin_unlock without taking a lock\n"); 7446 return -EINVAL; 7447 } 7448 if (cur->active_lock.ptr != ptr || 7449 cur->active_lock.id != reg->id) { 7450 verbose(env, "bpf_spin_unlock of different lock\n"); 7451 return -EINVAL; 7452 } 7453 7454 invalidate_non_owning_refs(env); 7455 7456 cur->active_lock.ptr = NULL; 7457 cur->active_lock.id = 0; 7458 } 7459 return 0; 7460 } 7461 7462 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7463 struct bpf_call_arg_meta *meta) 7464 { 7465 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7466 bool is_const = tnum_is_const(reg->var_off); 7467 struct bpf_map *map = reg->map_ptr; 7468 u64 val = reg->var_off.value; 7469 7470 if (!is_const) { 7471 verbose(env, 7472 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 7473 regno); 7474 return -EINVAL; 7475 } 7476 if (!map->btf) { 7477 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 7478 map->name); 7479 return -EINVAL; 7480 } 7481 if (!btf_record_has_field(map->record, BPF_TIMER)) { 7482 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 7483 return -EINVAL; 7484 } 7485 if (map->record->timer_off != val + reg->off) { 7486 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 7487 val + reg->off, map->record->timer_off); 7488 return -EINVAL; 7489 } 7490 if (meta->map_ptr) { 7491 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 7492 return -EFAULT; 7493 } 7494 meta->map_uid = reg->map_uid; 7495 meta->map_ptr = map; 7496 return 0; 7497 } 7498 7499 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7500 struct bpf_call_arg_meta *meta) 7501 { 7502 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7503 struct bpf_map *map_ptr = reg->map_ptr; 7504 struct btf_field *kptr_field; 7505 u32 kptr_off; 7506 7507 if (!tnum_is_const(reg->var_off)) { 7508 verbose(env, 7509 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7510 regno); 7511 return -EINVAL; 7512 } 7513 if (!map_ptr->btf) { 7514 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7515 map_ptr->name); 7516 return -EINVAL; 7517 } 7518 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 7519 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 7520 return -EINVAL; 7521 } 7522 7523 meta->map_ptr = map_ptr; 7524 kptr_off = reg->off + reg->var_off.value; 7525 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 7526 if (!kptr_field) { 7527 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7528 return -EACCES; 7529 } 7530 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7531 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7532 return -EACCES; 7533 } 7534 meta->kptr_field = kptr_field; 7535 return 0; 7536 } 7537 7538 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7539 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7540 * 7541 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7542 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7543 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7544 * 7545 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7546 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7547 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7548 * mutate the view of the dynptr and also possibly destroy it. In the latter 7549 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7550 * memory that dynptr points to. 7551 * 7552 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7553 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7554 * readonly dynptr view yet, hence only the first case is tracked and checked. 7555 * 7556 * This is consistent with how C applies the const modifier to a struct object, 7557 * where the pointer itself inside bpf_dynptr becomes const but not what it 7558 * points to. 7559 * 7560 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7561 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7562 */ 7563 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7564 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7565 { 7566 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7567 int err; 7568 7569 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7570 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7571 */ 7572 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7573 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 7574 return -EFAULT; 7575 } 7576 7577 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7578 * constructing a mutable bpf_dynptr object. 7579 * 7580 * Currently, this is only possible with PTR_TO_STACK 7581 * pointing to a region of at least 16 bytes which doesn't 7582 * contain an existing bpf_dynptr. 7583 * 7584 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7585 * mutated or destroyed. However, the memory it points to 7586 * may be mutated. 7587 * 7588 * None - Points to a initialized dynptr that can be mutated and 7589 * destroyed, including mutation of the memory it points 7590 * to. 7591 */ 7592 if (arg_type & MEM_UNINIT) { 7593 int i; 7594 7595 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7596 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7597 return -EINVAL; 7598 } 7599 7600 /* we write BPF_DW bits (8 bytes) at a time */ 7601 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7602 err = check_mem_access(env, insn_idx, regno, 7603 i, BPF_DW, BPF_WRITE, -1, false, false); 7604 if (err) 7605 return err; 7606 } 7607 7608 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7609 } else /* MEM_RDONLY and None case from above */ { 7610 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7611 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7612 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7613 return -EINVAL; 7614 } 7615 7616 if (!is_dynptr_reg_valid_init(env, reg)) { 7617 verbose(env, 7618 "Expected an initialized dynptr as arg #%d\n", 7619 regno); 7620 return -EINVAL; 7621 } 7622 7623 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7624 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7625 verbose(env, 7626 "Expected a dynptr of type %s as arg #%d\n", 7627 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 7628 return -EINVAL; 7629 } 7630 7631 err = mark_dynptr_read(env, reg); 7632 } 7633 return err; 7634 } 7635 7636 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7637 { 7638 struct bpf_func_state *state = func(env, reg); 7639 7640 return state->stack[spi].spilled_ptr.ref_obj_id; 7641 } 7642 7643 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7644 { 7645 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7646 } 7647 7648 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7649 { 7650 return meta->kfunc_flags & KF_ITER_NEW; 7651 } 7652 7653 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7654 { 7655 return meta->kfunc_flags & KF_ITER_NEXT; 7656 } 7657 7658 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7659 { 7660 return meta->kfunc_flags & KF_ITER_DESTROY; 7661 } 7662 7663 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg) 7664 { 7665 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7666 * kfunc is iter state pointer 7667 */ 7668 return arg == 0 && is_iter_kfunc(meta); 7669 } 7670 7671 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7672 struct bpf_kfunc_call_arg_meta *meta) 7673 { 7674 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7675 const struct btf_type *t; 7676 const struct btf_param *arg; 7677 int spi, err, i, nr_slots; 7678 u32 btf_id; 7679 7680 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */ 7681 arg = &btf_params(meta->func_proto)[0]; 7682 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */ 7683 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */ 7684 nr_slots = t->size / BPF_REG_SIZE; 7685 7686 if (is_iter_new_kfunc(meta)) { 7687 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7688 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7689 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 7690 iter_type_str(meta->btf, btf_id), regno); 7691 return -EINVAL; 7692 } 7693 7694 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7695 err = check_mem_access(env, insn_idx, regno, 7696 i, BPF_DW, BPF_WRITE, -1, false, false); 7697 if (err) 7698 return err; 7699 } 7700 7701 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 7702 if (err) 7703 return err; 7704 } else { 7705 /* iter_next() or iter_destroy() expect initialized iter state*/ 7706 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 7707 switch (err) { 7708 case 0: 7709 break; 7710 case -EINVAL: 7711 verbose(env, "expected an initialized iter_%s as arg #%d\n", 7712 iter_type_str(meta->btf, btf_id), regno); 7713 return err; 7714 case -EPROTO: 7715 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 7716 return err; 7717 default: 7718 return err; 7719 } 7720 7721 spi = iter_get_spi(env, reg, nr_slots); 7722 if (spi < 0) 7723 return spi; 7724 7725 err = mark_iter_read(env, reg, spi, nr_slots); 7726 if (err) 7727 return err; 7728 7729 /* remember meta->iter info for process_iter_next_call() */ 7730 meta->iter.spi = spi; 7731 meta->iter.frameno = reg->frameno; 7732 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 7733 7734 if (is_iter_destroy_kfunc(meta)) { 7735 err = unmark_stack_slots_iter(env, reg, nr_slots); 7736 if (err) 7737 return err; 7738 } 7739 } 7740 7741 return 0; 7742 } 7743 7744 /* Look for a previous loop entry at insn_idx: nearest parent state 7745 * stopped at insn_idx with callsites matching those in cur->frame. 7746 */ 7747 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 7748 struct bpf_verifier_state *cur, 7749 int insn_idx) 7750 { 7751 struct bpf_verifier_state_list *sl; 7752 struct bpf_verifier_state *st; 7753 7754 /* Explored states are pushed in stack order, most recent states come first */ 7755 sl = *explored_state(env, insn_idx); 7756 for (; sl; sl = sl->next) { 7757 /* If st->branches != 0 state is a part of current DFS verification path, 7758 * hence cur & st for a loop. 7759 */ 7760 st = &sl->state; 7761 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 7762 st->dfs_depth < cur->dfs_depth) 7763 return st; 7764 } 7765 7766 return NULL; 7767 } 7768 7769 static void reset_idmap_scratch(struct bpf_verifier_env *env); 7770 static bool regs_exact(const struct bpf_reg_state *rold, 7771 const struct bpf_reg_state *rcur, 7772 struct bpf_idmap *idmap); 7773 7774 static void maybe_widen_reg(struct bpf_verifier_env *env, 7775 struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 7776 struct bpf_idmap *idmap) 7777 { 7778 if (rold->type != SCALAR_VALUE) 7779 return; 7780 if (rold->type != rcur->type) 7781 return; 7782 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap)) 7783 return; 7784 __mark_reg_unknown(env, rcur); 7785 } 7786 7787 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 7788 struct bpf_verifier_state *old, 7789 struct bpf_verifier_state *cur) 7790 { 7791 struct bpf_func_state *fold, *fcur; 7792 int i, fr; 7793 7794 reset_idmap_scratch(env); 7795 for (fr = old->curframe; fr >= 0; fr--) { 7796 fold = old->frame[fr]; 7797 fcur = cur->frame[fr]; 7798 7799 for (i = 0; i < MAX_BPF_REG; i++) 7800 maybe_widen_reg(env, 7801 &fold->regs[i], 7802 &fcur->regs[i], 7803 &env->idmap_scratch); 7804 7805 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) { 7806 if (!is_spilled_reg(&fold->stack[i]) || 7807 !is_spilled_reg(&fcur->stack[i])) 7808 continue; 7809 7810 maybe_widen_reg(env, 7811 &fold->stack[i].spilled_ptr, 7812 &fcur->stack[i].spilled_ptr, 7813 &env->idmap_scratch); 7814 } 7815 } 7816 return 0; 7817 } 7818 7819 /* process_iter_next_call() is called when verifier gets to iterator's next 7820 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7821 * to it as just "iter_next()" in comments below. 7822 * 7823 * BPF verifier relies on a crucial contract for any iter_next() 7824 * implementation: it should *eventually* return NULL, and once that happens 7825 * it should keep returning NULL. That is, once iterator exhausts elements to 7826 * iterate, it should never reset or spuriously return new elements. 7827 * 7828 * With the assumption of such contract, process_iter_next_call() simulates 7829 * a fork in the verifier state to validate loop logic correctness and safety 7830 * without having to simulate infinite amount of iterations. 7831 * 7832 * In current state, we first assume that iter_next() returned NULL and 7833 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7834 * conditions we should not form an infinite loop and should eventually reach 7835 * exit. 7836 * 7837 * Besides that, we also fork current state and enqueue it for later 7838 * verification. In a forked state we keep iterator state as ACTIVE 7839 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7840 * also bump iteration depth to prevent erroneous infinite loop detection 7841 * later on (see iter_active_depths_differ() comment for details). In this 7842 * state we assume that we'll eventually loop back to another iter_next() 7843 * calls (it could be in exactly same location or in some other instruction, 7844 * it doesn't matter, we don't make any unnecessary assumptions about this, 7845 * everything revolves around iterator state in a stack slot, not which 7846 * instruction is calling iter_next()). When that happens, we either will come 7847 * to iter_next() with equivalent state and can conclude that next iteration 7848 * will proceed in exactly the same way as we just verified, so it's safe to 7849 * assume that loop converges. If not, we'll go on another iteration 7850 * simulation with a different input state, until all possible starting states 7851 * are validated or we reach maximum number of instructions limit. 7852 * 7853 * This way, we will either exhaustively discover all possible input states 7854 * that iterator loop can start with and eventually will converge, or we'll 7855 * effectively regress into bounded loop simulation logic and either reach 7856 * maximum number of instructions if loop is not provably convergent, or there 7857 * is some statically known limit on number of iterations (e.g., if there is 7858 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7859 * 7860 * Iteration convergence logic in is_state_visited() relies on exact 7861 * states comparison, which ignores read and precision marks. 7862 * This is necessary because read and precision marks are not finalized 7863 * while in the loop. Exact comparison might preclude convergence for 7864 * simple programs like below: 7865 * 7866 * i = 0; 7867 * while(iter_next(&it)) 7868 * i++; 7869 * 7870 * At each iteration step i++ would produce a new distinct state and 7871 * eventually instruction processing limit would be reached. 7872 * 7873 * To avoid such behavior speculatively forget (widen) range for 7874 * imprecise scalar registers, if those registers were not precise at the 7875 * end of the previous iteration and do not match exactly. 7876 * 7877 * This is a conservative heuristic that allows to verify wide range of programs, 7878 * however it precludes verification of programs that conjure an 7879 * imprecise value on the first loop iteration and use it as precise on a second. 7880 * For example, the following safe program would fail to verify: 7881 * 7882 * struct bpf_num_iter it; 7883 * int arr[10]; 7884 * int i = 0, a = 0; 7885 * bpf_iter_num_new(&it, 0, 10); 7886 * while (bpf_iter_num_next(&it)) { 7887 * if (a == 0) { 7888 * a = 1; 7889 * i = 7; // Because i changed verifier would forget 7890 * // it's range on second loop entry. 7891 * } else { 7892 * arr[i] = 42; // This would fail to verify. 7893 * } 7894 * } 7895 * bpf_iter_num_destroy(&it); 7896 */ 7897 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7898 struct bpf_kfunc_call_arg_meta *meta) 7899 { 7900 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 7901 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7902 struct bpf_reg_state *cur_iter, *queued_iter; 7903 int iter_frameno = meta->iter.frameno; 7904 int iter_spi = meta->iter.spi; 7905 7906 BTF_TYPE_EMIT(struct bpf_iter); 7907 7908 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7909 7910 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 7911 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 7912 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 7913 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 7914 return -EFAULT; 7915 } 7916 7917 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 7918 /* Because iter_next() call is a checkpoint is_state_visitied() 7919 * should guarantee parent state with same call sites and insn_idx. 7920 */ 7921 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 7922 !same_callsites(cur_st->parent, cur_st)) { 7923 verbose(env, "bug: bad parent state for iter next call"); 7924 return -EFAULT; 7925 } 7926 /* Note cur_st->parent in the call below, it is necessary to skip 7927 * checkpoint created for cur_st by is_state_visited() 7928 * right at this instruction. 7929 */ 7930 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 7931 /* branch out active iter state */ 7932 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 7933 if (!queued_st) 7934 return -ENOMEM; 7935 7936 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7937 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 7938 queued_iter->iter.depth++; 7939 if (prev_st) 7940 widen_imprecise_scalars(env, prev_st, queued_st); 7941 7942 queued_fr = queued_st->frame[queued_st->curframe]; 7943 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 7944 } 7945 7946 /* switch to DRAINED state, but keep the depth unchanged */ 7947 /* mark current iter state as drained and assume returned NULL */ 7948 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 7949 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 7950 7951 return 0; 7952 } 7953 7954 static bool arg_type_is_mem_size(enum bpf_arg_type type) 7955 { 7956 return type == ARG_CONST_SIZE || 7957 type == ARG_CONST_SIZE_OR_ZERO; 7958 } 7959 7960 static bool arg_type_is_release(enum bpf_arg_type type) 7961 { 7962 return type & OBJ_RELEASE; 7963 } 7964 7965 static bool arg_type_is_dynptr(enum bpf_arg_type type) 7966 { 7967 return base_type(type) == ARG_PTR_TO_DYNPTR; 7968 } 7969 7970 static int int_ptr_type_to_size(enum bpf_arg_type type) 7971 { 7972 if (type == ARG_PTR_TO_INT) 7973 return sizeof(u32); 7974 else if (type == ARG_PTR_TO_LONG) 7975 return sizeof(u64); 7976 7977 return -EINVAL; 7978 } 7979 7980 static int resolve_map_arg_type(struct bpf_verifier_env *env, 7981 const struct bpf_call_arg_meta *meta, 7982 enum bpf_arg_type *arg_type) 7983 { 7984 if (!meta->map_ptr) { 7985 /* kernel subsystem misconfigured verifier */ 7986 verbose(env, "invalid map_ptr to access map->type\n"); 7987 return -EACCES; 7988 } 7989 7990 switch (meta->map_ptr->map_type) { 7991 case BPF_MAP_TYPE_SOCKMAP: 7992 case BPF_MAP_TYPE_SOCKHASH: 7993 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 7994 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 7995 } else { 7996 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 7997 return -EINVAL; 7998 } 7999 break; 8000 case BPF_MAP_TYPE_BLOOM_FILTER: 8001 if (meta->func_id == BPF_FUNC_map_peek_elem) 8002 *arg_type = ARG_PTR_TO_MAP_VALUE; 8003 break; 8004 default: 8005 break; 8006 } 8007 return 0; 8008 } 8009 8010 struct bpf_reg_types { 8011 const enum bpf_reg_type types[10]; 8012 u32 *btf_id; 8013 }; 8014 8015 static const struct bpf_reg_types sock_types = { 8016 .types = { 8017 PTR_TO_SOCK_COMMON, 8018 PTR_TO_SOCKET, 8019 PTR_TO_TCP_SOCK, 8020 PTR_TO_XDP_SOCK, 8021 }, 8022 }; 8023 8024 #ifdef CONFIG_NET 8025 static const struct bpf_reg_types btf_id_sock_common_types = { 8026 .types = { 8027 PTR_TO_SOCK_COMMON, 8028 PTR_TO_SOCKET, 8029 PTR_TO_TCP_SOCK, 8030 PTR_TO_XDP_SOCK, 8031 PTR_TO_BTF_ID, 8032 PTR_TO_BTF_ID | PTR_TRUSTED, 8033 }, 8034 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 8035 }; 8036 #endif 8037 8038 static const struct bpf_reg_types mem_types = { 8039 .types = { 8040 PTR_TO_STACK, 8041 PTR_TO_PACKET, 8042 PTR_TO_PACKET_META, 8043 PTR_TO_MAP_KEY, 8044 PTR_TO_MAP_VALUE, 8045 PTR_TO_MEM, 8046 PTR_TO_MEM | MEM_RINGBUF, 8047 PTR_TO_BUF, 8048 PTR_TO_BTF_ID | PTR_TRUSTED, 8049 }, 8050 }; 8051 8052 static const struct bpf_reg_types int_ptr_types = { 8053 .types = { 8054 PTR_TO_STACK, 8055 PTR_TO_PACKET, 8056 PTR_TO_PACKET_META, 8057 PTR_TO_MAP_KEY, 8058 PTR_TO_MAP_VALUE, 8059 }, 8060 }; 8061 8062 static const struct bpf_reg_types spin_lock_types = { 8063 .types = { 8064 PTR_TO_MAP_VALUE, 8065 PTR_TO_BTF_ID | MEM_ALLOC, 8066 } 8067 }; 8068 8069 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 8070 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 8071 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 8072 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 8073 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 8074 static const struct bpf_reg_types btf_ptr_types = { 8075 .types = { 8076 PTR_TO_BTF_ID, 8077 PTR_TO_BTF_ID | PTR_TRUSTED, 8078 PTR_TO_BTF_ID | MEM_RCU, 8079 }, 8080 }; 8081 static const struct bpf_reg_types percpu_btf_ptr_types = { 8082 .types = { 8083 PTR_TO_BTF_ID | MEM_PERCPU, 8084 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 8085 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 8086 } 8087 }; 8088 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 8089 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 8090 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8091 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 8092 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8093 static const struct bpf_reg_types dynptr_types = { 8094 .types = { 8095 PTR_TO_STACK, 8096 CONST_PTR_TO_DYNPTR, 8097 } 8098 }; 8099 8100 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 8101 [ARG_PTR_TO_MAP_KEY] = &mem_types, 8102 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 8103 [ARG_CONST_SIZE] = &scalar_types, 8104 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 8105 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 8106 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 8107 [ARG_PTR_TO_CTX] = &context_types, 8108 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 8109 #ifdef CONFIG_NET 8110 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 8111 #endif 8112 [ARG_PTR_TO_SOCKET] = &fullsock_types, 8113 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 8114 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 8115 [ARG_PTR_TO_MEM] = &mem_types, 8116 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 8117 [ARG_PTR_TO_INT] = &int_ptr_types, 8118 [ARG_PTR_TO_LONG] = &int_ptr_types, 8119 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 8120 [ARG_PTR_TO_FUNC] = &func_ptr_types, 8121 [ARG_PTR_TO_STACK] = &stack_ptr_types, 8122 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 8123 [ARG_PTR_TO_TIMER] = &timer_types, 8124 [ARG_PTR_TO_KPTR] = &kptr_types, 8125 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 8126 }; 8127 8128 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 8129 enum bpf_arg_type arg_type, 8130 const u32 *arg_btf_id, 8131 struct bpf_call_arg_meta *meta) 8132 { 8133 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8134 enum bpf_reg_type expected, type = reg->type; 8135 const struct bpf_reg_types *compatible; 8136 int i, j; 8137 8138 compatible = compatible_reg_types[base_type(arg_type)]; 8139 if (!compatible) { 8140 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 8141 return -EFAULT; 8142 } 8143 8144 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 8145 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 8146 * 8147 * Same for MAYBE_NULL: 8148 * 8149 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 8150 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 8151 * 8152 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 8153 * 8154 * Therefore we fold these flags depending on the arg_type before comparison. 8155 */ 8156 if (arg_type & MEM_RDONLY) 8157 type &= ~MEM_RDONLY; 8158 if (arg_type & PTR_MAYBE_NULL) 8159 type &= ~PTR_MAYBE_NULL; 8160 if (base_type(arg_type) == ARG_PTR_TO_MEM) 8161 type &= ~DYNPTR_TYPE_FLAG_MASK; 8162 8163 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) { 8164 type &= ~MEM_ALLOC; 8165 type &= ~MEM_PERCPU; 8166 } 8167 8168 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 8169 expected = compatible->types[i]; 8170 if (expected == NOT_INIT) 8171 break; 8172 8173 if (type == expected) 8174 goto found; 8175 } 8176 8177 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 8178 for (j = 0; j + 1 < i; j++) 8179 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 8180 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 8181 return -EACCES; 8182 8183 found: 8184 if (base_type(reg->type) != PTR_TO_BTF_ID) 8185 return 0; 8186 8187 if (compatible == &mem_types) { 8188 if (!(arg_type & MEM_RDONLY)) { 8189 verbose(env, 8190 "%s() may write into memory pointed by R%d type=%s\n", 8191 func_id_name(meta->func_id), 8192 regno, reg_type_str(env, reg->type)); 8193 return -EACCES; 8194 } 8195 return 0; 8196 } 8197 8198 switch ((int)reg->type) { 8199 case PTR_TO_BTF_ID: 8200 case PTR_TO_BTF_ID | PTR_TRUSTED: 8201 case PTR_TO_BTF_ID | MEM_RCU: 8202 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 8203 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 8204 { 8205 /* For bpf_sk_release, it needs to match against first member 8206 * 'struct sock_common', hence make an exception for it. This 8207 * allows bpf_sk_release to work for multiple socket types. 8208 */ 8209 bool strict_type_match = arg_type_is_release(arg_type) && 8210 meta->func_id != BPF_FUNC_sk_release; 8211 8212 if (type_may_be_null(reg->type) && 8213 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 8214 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 8215 return -EACCES; 8216 } 8217 8218 if (!arg_btf_id) { 8219 if (!compatible->btf_id) { 8220 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 8221 return -EFAULT; 8222 } 8223 arg_btf_id = compatible->btf_id; 8224 } 8225 8226 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8227 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8228 return -EACCES; 8229 } else { 8230 if (arg_btf_id == BPF_PTR_POISON) { 8231 verbose(env, "verifier internal error:"); 8232 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 8233 regno); 8234 return -EACCES; 8235 } 8236 8237 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 8238 btf_vmlinux, *arg_btf_id, 8239 strict_type_match)) { 8240 verbose(env, "R%d is of type %s but %s is expected\n", 8241 regno, btf_type_name(reg->btf, reg->btf_id), 8242 btf_type_name(btf_vmlinux, *arg_btf_id)); 8243 return -EACCES; 8244 } 8245 } 8246 break; 8247 } 8248 case PTR_TO_BTF_ID | MEM_ALLOC: 8249 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 8250 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8251 meta->func_id != BPF_FUNC_kptr_xchg) { 8252 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 8253 return -EFAULT; 8254 } 8255 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8256 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8257 return -EACCES; 8258 } 8259 break; 8260 case PTR_TO_BTF_ID | MEM_PERCPU: 8261 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 8262 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8263 /* Handled by helper specific checks */ 8264 break; 8265 default: 8266 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 8267 return -EFAULT; 8268 } 8269 return 0; 8270 } 8271 8272 static struct btf_field * 8273 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8274 { 8275 struct btf_field *field; 8276 struct btf_record *rec; 8277 8278 rec = reg_btf_record(reg); 8279 if (!rec) 8280 return NULL; 8281 8282 field = btf_record_find(rec, off, fields); 8283 if (!field) 8284 return NULL; 8285 8286 return field; 8287 } 8288 8289 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 8290 const struct bpf_reg_state *reg, int regno, 8291 enum bpf_arg_type arg_type) 8292 { 8293 u32 type = reg->type; 8294 8295 /* When referenced register is passed to release function, its fixed 8296 * offset must be 0. 8297 * 8298 * We will check arg_type_is_release reg has ref_obj_id when storing 8299 * meta->release_regno. 8300 */ 8301 if (arg_type_is_release(arg_type)) { 8302 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8303 * may not directly point to the object being released, but to 8304 * dynptr pointing to such object, which might be at some offset 8305 * on the stack. In that case, we simply to fallback to the 8306 * default handling. 8307 */ 8308 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8309 return 0; 8310 8311 /* Doing check_ptr_off_reg check for the offset will catch this 8312 * because fixed_off_ok is false, but checking here allows us 8313 * to give the user a better error message. 8314 */ 8315 if (reg->off) { 8316 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 8317 regno); 8318 return -EINVAL; 8319 } 8320 return __check_ptr_off_reg(env, reg, regno, false); 8321 } 8322 8323 switch (type) { 8324 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8325 case PTR_TO_STACK: 8326 case PTR_TO_PACKET: 8327 case PTR_TO_PACKET_META: 8328 case PTR_TO_MAP_KEY: 8329 case PTR_TO_MAP_VALUE: 8330 case PTR_TO_MEM: 8331 case PTR_TO_MEM | MEM_RDONLY: 8332 case PTR_TO_MEM | MEM_RINGBUF: 8333 case PTR_TO_BUF: 8334 case PTR_TO_BUF | MEM_RDONLY: 8335 case SCALAR_VALUE: 8336 return 0; 8337 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8338 * fixed offset. 8339 */ 8340 case PTR_TO_BTF_ID: 8341 case PTR_TO_BTF_ID | MEM_ALLOC: 8342 case PTR_TO_BTF_ID | PTR_TRUSTED: 8343 case PTR_TO_BTF_ID | MEM_RCU: 8344 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8345 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8346 /* When referenced PTR_TO_BTF_ID is passed to release function, 8347 * its fixed offset must be 0. In the other cases, fixed offset 8348 * can be non-zero. This was already checked above. So pass 8349 * fixed_off_ok as true to allow fixed offset for all other 8350 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8351 * still need to do checks instead of returning. 8352 */ 8353 return __check_ptr_off_reg(env, reg, regno, true); 8354 default: 8355 return __check_ptr_off_reg(env, reg, regno, false); 8356 } 8357 } 8358 8359 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8360 const struct bpf_func_proto *fn, 8361 struct bpf_reg_state *regs) 8362 { 8363 struct bpf_reg_state *state = NULL; 8364 int i; 8365 8366 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8367 if (arg_type_is_dynptr(fn->arg_type[i])) { 8368 if (state) { 8369 verbose(env, "verifier internal error: multiple dynptr args\n"); 8370 return NULL; 8371 } 8372 state = ®s[BPF_REG_1 + i]; 8373 } 8374 8375 if (!state) 8376 verbose(env, "verifier internal error: no dynptr arg found\n"); 8377 8378 return state; 8379 } 8380 8381 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8382 { 8383 struct bpf_func_state *state = func(env, reg); 8384 int spi; 8385 8386 if (reg->type == CONST_PTR_TO_DYNPTR) 8387 return reg->id; 8388 spi = dynptr_get_spi(env, reg); 8389 if (spi < 0) 8390 return spi; 8391 return state->stack[spi].spilled_ptr.id; 8392 } 8393 8394 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8395 { 8396 struct bpf_func_state *state = func(env, reg); 8397 int spi; 8398 8399 if (reg->type == CONST_PTR_TO_DYNPTR) 8400 return reg->ref_obj_id; 8401 spi = dynptr_get_spi(env, reg); 8402 if (spi < 0) 8403 return spi; 8404 return state->stack[spi].spilled_ptr.ref_obj_id; 8405 } 8406 8407 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8408 struct bpf_reg_state *reg) 8409 { 8410 struct bpf_func_state *state = func(env, reg); 8411 int spi; 8412 8413 if (reg->type == CONST_PTR_TO_DYNPTR) 8414 return reg->dynptr.type; 8415 8416 spi = __get_spi(reg->off); 8417 if (spi < 0) { 8418 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8419 return BPF_DYNPTR_TYPE_INVALID; 8420 } 8421 8422 return state->stack[spi].spilled_ptr.dynptr.type; 8423 } 8424 8425 static int check_reg_const_str(struct bpf_verifier_env *env, 8426 struct bpf_reg_state *reg, u32 regno) 8427 { 8428 struct bpf_map *map = reg->map_ptr; 8429 int err; 8430 int map_off; 8431 u64 map_addr; 8432 char *str_ptr; 8433 8434 if (reg->type != PTR_TO_MAP_VALUE) 8435 return -EINVAL; 8436 8437 if (!bpf_map_is_rdonly(map)) { 8438 verbose(env, "R%d does not point to a readonly map'\n", regno); 8439 return -EACCES; 8440 } 8441 8442 if (!tnum_is_const(reg->var_off)) { 8443 verbose(env, "R%d is not a constant address'\n", regno); 8444 return -EACCES; 8445 } 8446 8447 if (!map->ops->map_direct_value_addr) { 8448 verbose(env, "no direct value access support for this map type\n"); 8449 return -EACCES; 8450 } 8451 8452 err = check_map_access(env, regno, reg->off, 8453 map->value_size - reg->off, false, 8454 ACCESS_HELPER); 8455 if (err) 8456 return err; 8457 8458 map_off = reg->off + reg->var_off.value; 8459 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8460 if (err) { 8461 verbose(env, "direct value access on string failed\n"); 8462 return err; 8463 } 8464 8465 str_ptr = (char *)(long)(map_addr); 8466 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8467 verbose(env, "string is not zero-terminated\n"); 8468 return -EINVAL; 8469 } 8470 return 0; 8471 } 8472 8473 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8474 struct bpf_call_arg_meta *meta, 8475 const struct bpf_func_proto *fn, 8476 int insn_idx) 8477 { 8478 u32 regno = BPF_REG_1 + arg; 8479 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8480 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8481 enum bpf_reg_type type = reg->type; 8482 u32 *arg_btf_id = NULL; 8483 int err = 0; 8484 8485 if (arg_type == ARG_DONTCARE) 8486 return 0; 8487 8488 err = check_reg_arg(env, regno, SRC_OP); 8489 if (err) 8490 return err; 8491 8492 if (arg_type == ARG_ANYTHING) { 8493 if (is_pointer_value(env, regno)) { 8494 verbose(env, "R%d leaks addr into helper function\n", 8495 regno); 8496 return -EACCES; 8497 } 8498 return 0; 8499 } 8500 8501 if (type_is_pkt_pointer(type) && 8502 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8503 verbose(env, "helper access to the packet is not allowed\n"); 8504 return -EACCES; 8505 } 8506 8507 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8508 err = resolve_map_arg_type(env, meta, &arg_type); 8509 if (err) 8510 return err; 8511 } 8512 8513 if (register_is_null(reg) && type_may_be_null(arg_type)) 8514 /* A NULL register has a SCALAR_VALUE type, so skip 8515 * type checking. 8516 */ 8517 goto skip_type_check; 8518 8519 /* arg_btf_id and arg_size are in a union. */ 8520 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8521 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8522 arg_btf_id = fn->arg_btf_id[arg]; 8523 8524 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 8525 if (err) 8526 return err; 8527 8528 err = check_func_arg_reg_off(env, reg, regno, arg_type); 8529 if (err) 8530 return err; 8531 8532 skip_type_check: 8533 if (arg_type_is_release(arg_type)) { 8534 if (arg_type_is_dynptr(arg_type)) { 8535 struct bpf_func_state *state = func(env, reg); 8536 int spi; 8537 8538 /* Only dynptr created on stack can be released, thus 8539 * the get_spi and stack state checks for spilled_ptr 8540 * should only be done before process_dynptr_func for 8541 * PTR_TO_STACK. 8542 */ 8543 if (reg->type == PTR_TO_STACK) { 8544 spi = dynptr_get_spi(env, reg); 8545 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8546 verbose(env, "arg %d is an unacquired reference\n", regno); 8547 return -EINVAL; 8548 } 8549 } else { 8550 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8551 return -EINVAL; 8552 } 8553 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 8554 verbose(env, "R%d must be referenced when passed to release function\n", 8555 regno); 8556 return -EINVAL; 8557 } 8558 if (meta->release_regno) { 8559 verbose(env, "verifier internal error: more than one release argument\n"); 8560 return -EFAULT; 8561 } 8562 meta->release_regno = regno; 8563 } 8564 8565 if (reg->ref_obj_id) { 8566 if (meta->ref_obj_id) { 8567 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 8568 regno, reg->ref_obj_id, 8569 meta->ref_obj_id); 8570 return -EFAULT; 8571 } 8572 meta->ref_obj_id = reg->ref_obj_id; 8573 } 8574 8575 switch (base_type(arg_type)) { 8576 case ARG_CONST_MAP_PTR: 8577 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8578 if (meta->map_ptr) { 8579 /* Use map_uid (which is unique id of inner map) to reject: 8580 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8581 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8582 * if (inner_map1 && inner_map2) { 8583 * timer = bpf_map_lookup_elem(inner_map1); 8584 * if (timer) 8585 * // mismatch would have been allowed 8586 * bpf_timer_init(timer, inner_map2); 8587 * } 8588 * 8589 * Comparing map_ptr is enough to distinguish normal and outer maps. 8590 */ 8591 if (meta->map_ptr != reg->map_ptr || 8592 meta->map_uid != reg->map_uid) { 8593 verbose(env, 8594 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8595 meta->map_uid, reg->map_uid); 8596 return -EINVAL; 8597 } 8598 } 8599 meta->map_ptr = reg->map_ptr; 8600 meta->map_uid = reg->map_uid; 8601 break; 8602 case ARG_PTR_TO_MAP_KEY: 8603 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8604 * check that [key, key + map->key_size) are within 8605 * stack limits and initialized 8606 */ 8607 if (!meta->map_ptr) { 8608 /* in function declaration map_ptr must come before 8609 * map_key, so that it's verified and known before 8610 * we have to check map_key here. Otherwise it means 8611 * that kernel subsystem misconfigured verifier 8612 */ 8613 verbose(env, "invalid map_ptr to access map->key\n"); 8614 return -EACCES; 8615 } 8616 err = check_helper_mem_access(env, regno, 8617 meta->map_ptr->key_size, false, 8618 NULL); 8619 break; 8620 case ARG_PTR_TO_MAP_VALUE: 8621 if (type_may_be_null(arg_type) && register_is_null(reg)) 8622 return 0; 8623 8624 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8625 * check [value, value + map->value_size) validity 8626 */ 8627 if (!meta->map_ptr) { 8628 /* kernel subsystem misconfigured verifier */ 8629 verbose(env, "invalid map_ptr to access map->value\n"); 8630 return -EACCES; 8631 } 8632 meta->raw_mode = arg_type & MEM_UNINIT; 8633 err = check_helper_mem_access(env, regno, 8634 meta->map_ptr->value_size, false, 8635 meta); 8636 break; 8637 case ARG_PTR_TO_PERCPU_BTF_ID: 8638 if (!reg->btf_id) { 8639 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8640 return -EACCES; 8641 } 8642 meta->ret_btf = reg->btf; 8643 meta->ret_btf_id = reg->btf_id; 8644 break; 8645 case ARG_PTR_TO_SPIN_LOCK: 8646 if (in_rbtree_lock_required_cb(env)) { 8647 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8648 return -EACCES; 8649 } 8650 if (meta->func_id == BPF_FUNC_spin_lock) { 8651 err = process_spin_lock(env, regno, true); 8652 if (err) 8653 return err; 8654 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8655 err = process_spin_lock(env, regno, false); 8656 if (err) 8657 return err; 8658 } else { 8659 verbose(env, "verifier internal error\n"); 8660 return -EFAULT; 8661 } 8662 break; 8663 case ARG_PTR_TO_TIMER: 8664 err = process_timer_func(env, regno, meta); 8665 if (err) 8666 return err; 8667 break; 8668 case ARG_PTR_TO_FUNC: 8669 meta->subprogno = reg->subprogno; 8670 break; 8671 case ARG_PTR_TO_MEM: 8672 /* The access to this pointer is only checked when we hit the 8673 * next is_mem_size argument below. 8674 */ 8675 meta->raw_mode = arg_type & MEM_UNINIT; 8676 if (arg_type & MEM_FIXED_SIZE) { 8677 err = check_helper_mem_access(env, regno, 8678 fn->arg_size[arg], false, 8679 meta); 8680 } 8681 break; 8682 case ARG_CONST_SIZE: 8683 err = check_mem_size_reg(env, reg, regno, false, meta); 8684 break; 8685 case ARG_CONST_SIZE_OR_ZERO: 8686 err = check_mem_size_reg(env, reg, regno, true, meta); 8687 break; 8688 case ARG_PTR_TO_DYNPTR: 8689 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 8690 if (err) 8691 return err; 8692 break; 8693 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8694 if (!tnum_is_const(reg->var_off)) { 8695 verbose(env, "R%d is not a known constant'\n", 8696 regno); 8697 return -EACCES; 8698 } 8699 meta->mem_size = reg->var_off.value; 8700 err = mark_chain_precision(env, regno); 8701 if (err) 8702 return err; 8703 break; 8704 case ARG_PTR_TO_INT: 8705 case ARG_PTR_TO_LONG: 8706 { 8707 int size = int_ptr_type_to_size(arg_type); 8708 8709 err = check_helper_mem_access(env, regno, size, false, meta); 8710 if (err) 8711 return err; 8712 err = check_ptr_alignment(env, reg, 0, size, true); 8713 break; 8714 } 8715 case ARG_PTR_TO_CONST_STR: 8716 { 8717 err = check_reg_const_str(env, reg, regno); 8718 if (err) 8719 return err; 8720 break; 8721 } 8722 case ARG_PTR_TO_KPTR: 8723 err = process_kptr_func(env, regno, meta); 8724 if (err) 8725 return err; 8726 break; 8727 } 8728 8729 return err; 8730 } 8731 8732 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8733 { 8734 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8735 enum bpf_prog_type type = resolve_prog_type(env->prog); 8736 8737 if (func_id != BPF_FUNC_map_update_elem) 8738 return false; 8739 8740 /* It's not possible to get access to a locked struct sock in these 8741 * contexts, so updating is safe. 8742 */ 8743 switch (type) { 8744 case BPF_PROG_TYPE_TRACING: 8745 if (eatype == BPF_TRACE_ITER) 8746 return true; 8747 break; 8748 case BPF_PROG_TYPE_SOCKET_FILTER: 8749 case BPF_PROG_TYPE_SCHED_CLS: 8750 case BPF_PROG_TYPE_SCHED_ACT: 8751 case BPF_PROG_TYPE_XDP: 8752 case BPF_PROG_TYPE_SK_REUSEPORT: 8753 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8754 case BPF_PROG_TYPE_SK_LOOKUP: 8755 return true; 8756 default: 8757 break; 8758 } 8759 8760 verbose(env, "cannot update sockmap in this context\n"); 8761 return false; 8762 } 8763 8764 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8765 { 8766 return env->prog->jit_requested && 8767 bpf_jit_supports_subprog_tailcalls(); 8768 } 8769 8770 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8771 struct bpf_map *map, int func_id) 8772 { 8773 if (!map) 8774 return 0; 8775 8776 /* We need a two way check, first is from map perspective ... */ 8777 switch (map->map_type) { 8778 case BPF_MAP_TYPE_PROG_ARRAY: 8779 if (func_id != BPF_FUNC_tail_call) 8780 goto error; 8781 break; 8782 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8783 if (func_id != BPF_FUNC_perf_event_read && 8784 func_id != BPF_FUNC_perf_event_output && 8785 func_id != BPF_FUNC_skb_output && 8786 func_id != BPF_FUNC_perf_event_read_value && 8787 func_id != BPF_FUNC_xdp_output) 8788 goto error; 8789 break; 8790 case BPF_MAP_TYPE_RINGBUF: 8791 if (func_id != BPF_FUNC_ringbuf_output && 8792 func_id != BPF_FUNC_ringbuf_reserve && 8793 func_id != BPF_FUNC_ringbuf_query && 8794 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8795 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8796 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8797 goto error; 8798 break; 8799 case BPF_MAP_TYPE_USER_RINGBUF: 8800 if (func_id != BPF_FUNC_user_ringbuf_drain) 8801 goto error; 8802 break; 8803 case BPF_MAP_TYPE_STACK_TRACE: 8804 if (func_id != BPF_FUNC_get_stackid) 8805 goto error; 8806 break; 8807 case BPF_MAP_TYPE_CGROUP_ARRAY: 8808 if (func_id != BPF_FUNC_skb_under_cgroup && 8809 func_id != BPF_FUNC_current_task_under_cgroup) 8810 goto error; 8811 break; 8812 case BPF_MAP_TYPE_CGROUP_STORAGE: 8813 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8814 if (func_id != BPF_FUNC_get_local_storage) 8815 goto error; 8816 break; 8817 case BPF_MAP_TYPE_DEVMAP: 8818 case BPF_MAP_TYPE_DEVMAP_HASH: 8819 if (func_id != BPF_FUNC_redirect_map && 8820 func_id != BPF_FUNC_map_lookup_elem) 8821 goto error; 8822 break; 8823 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8824 * appear. 8825 */ 8826 case BPF_MAP_TYPE_CPUMAP: 8827 if (func_id != BPF_FUNC_redirect_map) 8828 goto error; 8829 break; 8830 case BPF_MAP_TYPE_XSKMAP: 8831 if (func_id != BPF_FUNC_redirect_map && 8832 func_id != BPF_FUNC_map_lookup_elem) 8833 goto error; 8834 break; 8835 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8836 case BPF_MAP_TYPE_HASH_OF_MAPS: 8837 if (func_id != BPF_FUNC_map_lookup_elem) 8838 goto error; 8839 break; 8840 case BPF_MAP_TYPE_SOCKMAP: 8841 if (func_id != BPF_FUNC_sk_redirect_map && 8842 func_id != BPF_FUNC_sock_map_update && 8843 func_id != BPF_FUNC_map_delete_elem && 8844 func_id != BPF_FUNC_msg_redirect_map && 8845 func_id != BPF_FUNC_sk_select_reuseport && 8846 func_id != BPF_FUNC_map_lookup_elem && 8847 !may_update_sockmap(env, func_id)) 8848 goto error; 8849 break; 8850 case BPF_MAP_TYPE_SOCKHASH: 8851 if (func_id != BPF_FUNC_sk_redirect_hash && 8852 func_id != BPF_FUNC_sock_hash_update && 8853 func_id != BPF_FUNC_map_delete_elem && 8854 func_id != BPF_FUNC_msg_redirect_hash && 8855 func_id != BPF_FUNC_sk_select_reuseport && 8856 func_id != BPF_FUNC_map_lookup_elem && 8857 !may_update_sockmap(env, func_id)) 8858 goto error; 8859 break; 8860 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8861 if (func_id != BPF_FUNC_sk_select_reuseport) 8862 goto error; 8863 break; 8864 case BPF_MAP_TYPE_QUEUE: 8865 case BPF_MAP_TYPE_STACK: 8866 if (func_id != BPF_FUNC_map_peek_elem && 8867 func_id != BPF_FUNC_map_pop_elem && 8868 func_id != BPF_FUNC_map_push_elem) 8869 goto error; 8870 break; 8871 case BPF_MAP_TYPE_SK_STORAGE: 8872 if (func_id != BPF_FUNC_sk_storage_get && 8873 func_id != BPF_FUNC_sk_storage_delete && 8874 func_id != BPF_FUNC_kptr_xchg) 8875 goto error; 8876 break; 8877 case BPF_MAP_TYPE_INODE_STORAGE: 8878 if (func_id != BPF_FUNC_inode_storage_get && 8879 func_id != BPF_FUNC_inode_storage_delete && 8880 func_id != BPF_FUNC_kptr_xchg) 8881 goto error; 8882 break; 8883 case BPF_MAP_TYPE_TASK_STORAGE: 8884 if (func_id != BPF_FUNC_task_storage_get && 8885 func_id != BPF_FUNC_task_storage_delete && 8886 func_id != BPF_FUNC_kptr_xchg) 8887 goto error; 8888 break; 8889 case BPF_MAP_TYPE_CGRP_STORAGE: 8890 if (func_id != BPF_FUNC_cgrp_storage_get && 8891 func_id != BPF_FUNC_cgrp_storage_delete && 8892 func_id != BPF_FUNC_kptr_xchg) 8893 goto error; 8894 break; 8895 case BPF_MAP_TYPE_BLOOM_FILTER: 8896 if (func_id != BPF_FUNC_map_peek_elem && 8897 func_id != BPF_FUNC_map_push_elem) 8898 goto error; 8899 break; 8900 default: 8901 break; 8902 } 8903 8904 /* ... and second from the function itself. */ 8905 switch (func_id) { 8906 case BPF_FUNC_tail_call: 8907 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8908 goto error; 8909 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 8910 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 8911 return -EINVAL; 8912 } 8913 break; 8914 case BPF_FUNC_perf_event_read: 8915 case BPF_FUNC_perf_event_output: 8916 case BPF_FUNC_perf_event_read_value: 8917 case BPF_FUNC_skb_output: 8918 case BPF_FUNC_xdp_output: 8919 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 8920 goto error; 8921 break; 8922 case BPF_FUNC_ringbuf_output: 8923 case BPF_FUNC_ringbuf_reserve: 8924 case BPF_FUNC_ringbuf_query: 8925 case BPF_FUNC_ringbuf_reserve_dynptr: 8926 case BPF_FUNC_ringbuf_submit_dynptr: 8927 case BPF_FUNC_ringbuf_discard_dynptr: 8928 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 8929 goto error; 8930 break; 8931 case BPF_FUNC_user_ringbuf_drain: 8932 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 8933 goto error; 8934 break; 8935 case BPF_FUNC_get_stackid: 8936 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 8937 goto error; 8938 break; 8939 case BPF_FUNC_current_task_under_cgroup: 8940 case BPF_FUNC_skb_under_cgroup: 8941 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 8942 goto error; 8943 break; 8944 case BPF_FUNC_redirect_map: 8945 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 8946 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 8947 map->map_type != BPF_MAP_TYPE_CPUMAP && 8948 map->map_type != BPF_MAP_TYPE_XSKMAP) 8949 goto error; 8950 break; 8951 case BPF_FUNC_sk_redirect_map: 8952 case BPF_FUNC_msg_redirect_map: 8953 case BPF_FUNC_sock_map_update: 8954 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 8955 goto error; 8956 break; 8957 case BPF_FUNC_sk_redirect_hash: 8958 case BPF_FUNC_msg_redirect_hash: 8959 case BPF_FUNC_sock_hash_update: 8960 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 8961 goto error; 8962 break; 8963 case BPF_FUNC_get_local_storage: 8964 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 8965 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 8966 goto error; 8967 break; 8968 case BPF_FUNC_sk_select_reuseport: 8969 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 8970 map->map_type != BPF_MAP_TYPE_SOCKMAP && 8971 map->map_type != BPF_MAP_TYPE_SOCKHASH) 8972 goto error; 8973 break; 8974 case BPF_FUNC_map_pop_elem: 8975 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8976 map->map_type != BPF_MAP_TYPE_STACK) 8977 goto error; 8978 break; 8979 case BPF_FUNC_map_peek_elem: 8980 case BPF_FUNC_map_push_elem: 8981 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8982 map->map_type != BPF_MAP_TYPE_STACK && 8983 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 8984 goto error; 8985 break; 8986 case BPF_FUNC_map_lookup_percpu_elem: 8987 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 8988 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 8989 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 8990 goto error; 8991 break; 8992 case BPF_FUNC_sk_storage_get: 8993 case BPF_FUNC_sk_storage_delete: 8994 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 8995 goto error; 8996 break; 8997 case BPF_FUNC_inode_storage_get: 8998 case BPF_FUNC_inode_storage_delete: 8999 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 9000 goto error; 9001 break; 9002 case BPF_FUNC_task_storage_get: 9003 case BPF_FUNC_task_storage_delete: 9004 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 9005 goto error; 9006 break; 9007 case BPF_FUNC_cgrp_storage_get: 9008 case BPF_FUNC_cgrp_storage_delete: 9009 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 9010 goto error; 9011 break; 9012 default: 9013 break; 9014 } 9015 9016 return 0; 9017 error: 9018 verbose(env, "cannot pass map_type %d into func %s#%d\n", 9019 map->map_type, func_id_name(func_id), func_id); 9020 return -EINVAL; 9021 } 9022 9023 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 9024 { 9025 int count = 0; 9026 9027 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 9028 count++; 9029 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 9030 count++; 9031 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 9032 count++; 9033 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 9034 count++; 9035 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 9036 count++; 9037 9038 /* We only support one arg being in raw mode at the moment, 9039 * which is sufficient for the helper functions we have 9040 * right now. 9041 */ 9042 return count <= 1; 9043 } 9044 9045 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 9046 { 9047 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 9048 bool has_size = fn->arg_size[arg] != 0; 9049 bool is_next_size = false; 9050 9051 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 9052 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 9053 9054 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 9055 return is_next_size; 9056 9057 return has_size == is_next_size || is_next_size == is_fixed; 9058 } 9059 9060 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 9061 { 9062 /* bpf_xxx(..., buf, len) call will access 'len' 9063 * bytes from memory 'buf'. Both arg types need 9064 * to be paired, so make sure there's no buggy 9065 * helper function specification. 9066 */ 9067 if (arg_type_is_mem_size(fn->arg1_type) || 9068 check_args_pair_invalid(fn, 0) || 9069 check_args_pair_invalid(fn, 1) || 9070 check_args_pair_invalid(fn, 2) || 9071 check_args_pair_invalid(fn, 3) || 9072 check_args_pair_invalid(fn, 4)) 9073 return false; 9074 9075 return true; 9076 } 9077 9078 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 9079 { 9080 int i; 9081 9082 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 9083 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 9084 return !!fn->arg_btf_id[i]; 9085 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 9086 return fn->arg_btf_id[i] == BPF_PTR_POISON; 9087 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 9088 /* arg_btf_id and arg_size are in a union. */ 9089 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 9090 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 9091 return false; 9092 } 9093 9094 return true; 9095 } 9096 9097 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 9098 { 9099 return check_raw_mode_ok(fn) && 9100 check_arg_pair_ok(fn) && 9101 check_btf_id_ok(fn) ? 0 : -EINVAL; 9102 } 9103 9104 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 9105 * are now invalid, so turn them into unknown SCALAR_VALUE. 9106 * 9107 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 9108 * since these slices point to packet data. 9109 */ 9110 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 9111 { 9112 struct bpf_func_state *state; 9113 struct bpf_reg_state *reg; 9114 9115 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9116 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 9117 mark_reg_invalid(env, reg); 9118 })); 9119 } 9120 9121 enum { 9122 AT_PKT_END = -1, 9123 BEYOND_PKT_END = -2, 9124 }; 9125 9126 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 9127 { 9128 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9129 struct bpf_reg_state *reg = &state->regs[regn]; 9130 9131 if (reg->type != PTR_TO_PACKET) 9132 /* PTR_TO_PACKET_META is not supported yet */ 9133 return; 9134 9135 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 9136 * How far beyond pkt_end it goes is unknown. 9137 * if (!range_open) it's the case of pkt >= pkt_end 9138 * if (range_open) it's the case of pkt > pkt_end 9139 * hence this pointer is at least 1 byte bigger than pkt_end 9140 */ 9141 if (range_open) 9142 reg->range = BEYOND_PKT_END; 9143 else 9144 reg->range = AT_PKT_END; 9145 } 9146 9147 /* The pointer with the specified id has released its reference to kernel 9148 * resources. Identify all copies of the same pointer and clear the reference. 9149 */ 9150 static int release_reference(struct bpf_verifier_env *env, 9151 int ref_obj_id) 9152 { 9153 struct bpf_func_state *state; 9154 struct bpf_reg_state *reg; 9155 int err; 9156 9157 err = release_reference_state(cur_func(env), ref_obj_id); 9158 if (err) 9159 return err; 9160 9161 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9162 if (reg->ref_obj_id == ref_obj_id) 9163 mark_reg_invalid(env, reg); 9164 })); 9165 9166 return 0; 9167 } 9168 9169 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9170 { 9171 struct bpf_func_state *unused; 9172 struct bpf_reg_state *reg; 9173 9174 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9175 if (type_is_non_owning_ref(reg->type)) 9176 mark_reg_invalid(env, reg); 9177 })); 9178 } 9179 9180 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9181 struct bpf_reg_state *regs) 9182 { 9183 int i; 9184 9185 /* after the call registers r0 - r5 were scratched */ 9186 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9187 mark_reg_not_init(env, regs, caller_saved[i]); 9188 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9189 } 9190 } 9191 9192 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9193 struct bpf_func_state *caller, 9194 struct bpf_func_state *callee, 9195 int insn_idx); 9196 9197 static int set_callee_state(struct bpf_verifier_env *env, 9198 struct bpf_func_state *caller, 9199 struct bpf_func_state *callee, int insn_idx); 9200 9201 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9202 set_callee_state_fn set_callee_state_cb, 9203 struct bpf_verifier_state *state) 9204 { 9205 struct bpf_func_state *caller, *callee; 9206 int err; 9207 9208 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9209 verbose(env, "the call stack of %d frames is too deep\n", 9210 state->curframe + 2); 9211 return -E2BIG; 9212 } 9213 9214 if (state->frame[state->curframe + 1]) { 9215 verbose(env, "verifier bug. Frame %d already allocated\n", 9216 state->curframe + 1); 9217 return -EFAULT; 9218 } 9219 9220 caller = state->frame[state->curframe]; 9221 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 9222 if (!callee) 9223 return -ENOMEM; 9224 state->frame[state->curframe + 1] = callee; 9225 9226 /* callee cannot access r0, r6 - r9 for reading and has to write 9227 * into its own stack before reading from it. 9228 * callee can read/write into caller's stack 9229 */ 9230 init_func_state(env, callee, 9231 /* remember the callsite, it will be used by bpf_exit */ 9232 callsite, 9233 state->curframe + 1 /* frameno within this callchain */, 9234 subprog /* subprog number within this prog */); 9235 /* Transfer references to the callee */ 9236 err = copy_reference_state(callee, caller); 9237 err = err ?: set_callee_state_cb(env, caller, callee, callsite); 9238 if (err) 9239 goto err_out; 9240 9241 /* only increment it after check_reg_arg() finished */ 9242 state->curframe++; 9243 9244 return 0; 9245 9246 err_out: 9247 free_func_state(callee); 9248 state->frame[state->curframe + 1] = NULL; 9249 return err; 9250 } 9251 9252 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, 9253 const struct btf *btf, 9254 struct bpf_reg_state *regs) 9255 { 9256 struct bpf_subprog_info *sub = subprog_info(env, subprog); 9257 struct bpf_verifier_log *log = &env->log; 9258 u32 i; 9259 int ret; 9260 9261 ret = btf_prepare_func_args(env, subprog); 9262 if (ret) 9263 return ret; 9264 9265 /* check that BTF function arguments match actual types that the 9266 * verifier sees. 9267 */ 9268 for (i = 0; i < sub->arg_cnt; i++) { 9269 u32 regno = i + 1; 9270 struct bpf_reg_state *reg = ®s[regno]; 9271 struct bpf_subprog_arg_info *arg = &sub->args[i]; 9272 9273 if (arg->arg_type == ARG_ANYTHING) { 9274 if (reg->type != SCALAR_VALUE) { 9275 bpf_log(log, "R%d is not a scalar\n", regno); 9276 return -EINVAL; 9277 } 9278 } else if (arg->arg_type == ARG_PTR_TO_CTX) { 9279 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9280 if (ret < 0) 9281 return ret; 9282 /* If function expects ctx type in BTF check that caller 9283 * is passing PTR_TO_CTX. 9284 */ 9285 if (reg->type != PTR_TO_CTX) { 9286 bpf_log(log, "arg#%d expects pointer to ctx\n", i); 9287 return -EINVAL; 9288 } 9289 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 9290 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9291 if (ret < 0) 9292 return ret; 9293 if (check_mem_reg(env, reg, regno, arg->mem_size)) 9294 return -EINVAL; 9295 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) { 9296 bpf_log(log, "arg#%d is expected to be non-NULL\n", i); 9297 return -EINVAL; 9298 } 9299 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 9300 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0); 9301 if (ret) 9302 return ret; 9303 } else { 9304 bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n", 9305 i, arg->arg_type); 9306 return -EFAULT; 9307 } 9308 } 9309 9310 return 0; 9311 } 9312 9313 /* Compare BTF of a function call with given bpf_reg_state. 9314 * Returns: 9315 * EFAULT - there is a verifier bug. Abort verification. 9316 * EINVAL - there is a type mismatch or BTF is not available. 9317 * 0 - BTF matches with what bpf_reg_state expects. 9318 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized. 9319 */ 9320 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog, 9321 struct bpf_reg_state *regs) 9322 { 9323 struct bpf_prog *prog = env->prog; 9324 struct btf *btf = prog->aux->btf; 9325 u32 btf_id; 9326 int err; 9327 9328 if (!prog->aux->func_info) 9329 return -EINVAL; 9330 9331 btf_id = prog->aux->func_info[subprog].type_id; 9332 if (!btf_id) 9333 return -EFAULT; 9334 9335 if (prog->aux->func_info_aux[subprog].unreliable) 9336 return -EINVAL; 9337 9338 err = btf_check_func_arg_match(env, subprog, btf, regs); 9339 /* Compiler optimizations can remove arguments from static functions 9340 * or mismatched type can be passed into a global function. 9341 * In such cases mark the function as unreliable from BTF point of view. 9342 */ 9343 if (err) 9344 prog->aux->func_info_aux[subprog].unreliable = true; 9345 return err; 9346 } 9347 9348 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9349 int insn_idx, int subprog, 9350 set_callee_state_fn set_callee_state_cb) 9351 { 9352 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9353 struct bpf_func_state *caller, *callee; 9354 int err; 9355 9356 caller = state->frame[state->curframe]; 9357 err = btf_check_subprog_call(env, subprog, caller->regs); 9358 if (err == -EFAULT) 9359 return err; 9360 9361 /* set_callee_state is used for direct subprog calls, but we are 9362 * interested in validating only BPF helpers that can call subprogs as 9363 * callbacks 9364 */ 9365 env->subprog_info[subprog].is_cb = true; 9366 if (bpf_pseudo_kfunc_call(insn) && 9367 !is_sync_callback_calling_kfunc(insn->imm)) { 9368 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 9369 func_id_name(insn->imm), insn->imm); 9370 return -EFAULT; 9371 } else if (!bpf_pseudo_kfunc_call(insn) && 9372 !is_callback_calling_function(insn->imm)) { /* helper */ 9373 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 9374 func_id_name(insn->imm), insn->imm); 9375 return -EFAULT; 9376 } 9377 9378 if (insn->code == (BPF_JMP | BPF_CALL) && 9379 insn->src_reg == 0 && 9380 insn->imm == BPF_FUNC_timer_set_callback) { 9381 struct bpf_verifier_state *async_cb; 9382 9383 /* there is no real recursion here. timer callbacks are async */ 9384 env->subprog_info[subprog].is_async_cb = true; 9385 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9386 insn_idx, subprog); 9387 if (!async_cb) 9388 return -EFAULT; 9389 callee = async_cb->frame[0]; 9390 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9391 9392 /* Convert bpf_timer_set_callback() args into timer callback args */ 9393 err = set_callee_state_cb(env, caller, callee, insn_idx); 9394 if (err) 9395 return err; 9396 9397 return 0; 9398 } 9399 9400 /* for callback functions enqueue entry to callback and 9401 * proceed with next instruction within current frame. 9402 */ 9403 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9404 if (!callback_state) 9405 return -ENOMEM; 9406 9407 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9408 callback_state); 9409 if (err) 9410 return err; 9411 9412 callback_state->callback_unroll_depth++; 9413 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9414 caller->callback_depth = 0; 9415 return 0; 9416 } 9417 9418 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9419 int *insn_idx) 9420 { 9421 struct bpf_verifier_state *state = env->cur_state; 9422 struct bpf_func_state *caller; 9423 int err, subprog, target_insn; 9424 9425 target_insn = *insn_idx + insn->imm + 1; 9426 subprog = find_subprog(env, target_insn); 9427 if (subprog < 0) { 9428 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn); 9429 return -EFAULT; 9430 } 9431 9432 caller = state->frame[state->curframe]; 9433 err = btf_check_subprog_call(env, subprog, caller->regs); 9434 if (err == -EFAULT) 9435 return err; 9436 if (subprog_is_global(env, subprog)) { 9437 const char *sub_name = subprog_name(env, subprog); 9438 9439 if (err) { 9440 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 9441 subprog, sub_name); 9442 return err; 9443 } 9444 9445 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 9446 subprog, sub_name); 9447 /* mark global subprog for verifying after main prog */ 9448 subprog_aux(env, subprog)->called = true; 9449 clear_caller_saved_regs(env, caller->regs); 9450 9451 /* All global functions return a 64-bit SCALAR_VALUE */ 9452 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9453 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9454 9455 /* continue with next insn after call */ 9456 return 0; 9457 } 9458 9459 /* for regular function entry setup new frame and continue 9460 * from that frame. 9461 */ 9462 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9463 if (err) 9464 return err; 9465 9466 clear_caller_saved_regs(env, caller->regs); 9467 9468 /* and go analyze first insn of the callee */ 9469 *insn_idx = env->subprog_info[subprog].start - 1; 9470 9471 if (env->log.level & BPF_LOG_LEVEL) { 9472 verbose(env, "caller:\n"); 9473 print_verifier_state(env, caller, true); 9474 verbose(env, "callee:\n"); 9475 print_verifier_state(env, state->frame[state->curframe], true); 9476 } 9477 9478 return 0; 9479 } 9480 9481 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9482 struct bpf_func_state *caller, 9483 struct bpf_func_state *callee) 9484 { 9485 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9486 * void *callback_ctx, u64 flags); 9487 * callback_fn(struct bpf_map *map, void *key, void *value, 9488 * void *callback_ctx); 9489 */ 9490 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9491 9492 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9493 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9494 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9495 9496 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9497 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9498 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9499 9500 /* pointer to stack or null */ 9501 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9502 9503 /* unused */ 9504 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9505 return 0; 9506 } 9507 9508 static int set_callee_state(struct bpf_verifier_env *env, 9509 struct bpf_func_state *caller, 9510 struct bpf_func_state *callee, int insn_idx) 9511 { 9512 int i; 9513 9514 /* copy r1 - r5 args that callee can access. The copy includes parent 9515 * pointers, which connects us up to the liveness chain 9516 */ 9517 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9518 callee->regs[i] = caller->regs[i]; 9519 return 0; 9520 } 9521 9522 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9523 struct bpf_func_state *caller, 9524 struct bpf_func_state *callee, 9525 int insn_idx) 9526 { 9527 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9528 struct bpf_map *map; 9529 int err; 9530 9531 if (bpf_map_ptr_poisoned(insn_aux)) { 9532 verbose(env, "tail_call abusing map_ptr\n"); 9533 return -EINVAL; 9534 } 9535 9536 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 9537 if (!map->ops->map_set_for_each_callback_args || 9538 !map->ops->map_for_each_callback) { 9539 verbose(env, "callback function not allowed for map\n"); 9540 return -ENOTSUPP; 9541 } 9542 9543 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9544 if (err) 9545 return err; 9546 9547 callee->in_callback_fn = true; 9548 callee->callback_ret_range = retval_range(0, 1); 9549 return 0; 9550 } 9551 9552 static int set_loop_callback_state(struct bpf_verifier_env *env, 9553 struct bpf_func_state *caller, 9554 struct bpf_func_state *callee, 9555 int insn_idx) 9556 { 9557 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9558 * u64 flags); 9559 * callback_fn(u32 index, void *callback_ctx); 9560 */ 9561 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9562 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9563 9564 /* unused */ 9565 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9566 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9567 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9568 9569 callee->in_callback_fn = true; 9570 callee->callback_ret_range = retval_range(0, 1); 9571 return 0; 9572 } 9573 9574 static int set_timer_callback_state(struct bpf_verifier_env *env, 9575 struct bpf_func_state *caller, 9576 struct bpf_func_state *callee, 9577 int insn_idx) 9578 { 9579 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9580 9581 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9582 * callback_fn(struct bpf_map *map, void *key, void *value); 9583 */ 9584 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9585 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9586 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9587 9588 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9589 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9590 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9591 9592 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9593 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9594 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9595 9596 /* unused */ 9597 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9598 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9599 callee->in_async_callback_fn = true; 9600 callee->callback_ret_range = retval_range(0, 1); 9601 return 0; 9602 } 9603 9604 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9605 struct bpf_func_state *caller, 9606 struct bpf_func_state *callee, 9607 int insn_idx) 9608 { 9609 /* bpf_find_vma(struct task_struct *task, u64 addr, 9610 * void *callback_fn, void *callback_ctx, u64 flags) 9611 * (callback_fn)(struct task_struct *task, 9612 * struct vm_area_struct *vma, void *callback_ctx); 9613 */ 9614 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9615 9616 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9617 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9618 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9619 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 9620 9621 /* pointer to stack or null */ 9622 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9623 9624 /* unused */ 9625 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9626 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9627 callee->in_callback_fn = true; 9628 callee->callback_ret_range = retval_range(0, 1); 9629 return 0; 9630 } 9631 9632 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9633 struct bpf_func_state *caller, 9634 struct bpf_func_state *callee, 9635 int insn_idx) 9636 { 9637 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9638 * callback_ctx, u64 flags); 9639 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9640 */ 9641 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9642 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9643 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9644 9645 /* unused */ 9646 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9647 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9648 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9649 9650 callee->in_callback_fn = true; 9651 callee->callback_ret_range = retval_range(0, 1); 9652 return 0; 9653 } 9654 9655 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9656 struct bpf_func_state *caller, 9657 struct bpf_func_state *callee, 9658 int insn_idx) 9659 { 9660 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9661 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9662 * 9663 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9664 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9665 * by this point, so look at 'root' 9666 */ 9667 struct btf_field *field; 9668 9669 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 9670 BPF_RB_ROOT); 9671 if (!field || !field->graph_root.value_btf_id) 9672 return -EFAULT; 9673 9674 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9675 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9676 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9677 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9678 9679 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9680 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9681 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9682 callee->in_callback_fn = true; 9683 callee->callback_ret_range = retval_range(0, 1); 9684 return 0; 9685 } 9686 9687 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9688 9689 /* Are we currently verifying the callback for a rbtree helper that must 9690 * be called with lock held? If so, no need to complain about unreleased 9691 * lock 9692 */ 9693 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9694 { 9695 struct bpf_verifier_state *state = env->cur_state; 9696 struct bpf_insn *insn = env->prog->insnsi; 9697 struct bpf_func_state *callee; 9698 int kfunc_btf_id; 9699 9700 if (!state->curframe) 9701 return false; 9702 9703 callee = state->frame[state->curframe]; 9704 9705 if (!callee->in_callback_fn) 9706 return false; 9707 9708 kfunc_btf_id = insn[callee->callsite].imm; 9709 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9710 } 9711 9712 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg) 9713 { 9714 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval; 9715 } 9716 9717 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9718 { 9719 struct bpf_verifier_state *state = env->cur_state, *prev_st; 9720 struct bpf_func_state *caller, *callee; 9721 struct bpf_reg_state *r0; 9722 bool in_callback_fn; 9723 int err; 9724 9725 callee = state->frame[state->curframe]; 9726 r0 = &callee->regs[BPF_REG_0]; 9727 if (r0->type == PTR_TO_STACK) { 9728 /* technically it's ok to return caller's stack pointer 9729 * (or caller's caller's pointer) back to the caller, 9730 * since these pointers are valid. Only current stack 9731 * pointer will be invalid as soon as function exits, 9732 * but let's be conservative 9733 */ 9734 verbose(env, "cannot return stack pointer to the caller\n"); 9735 return -EINVAL; 9736 } 9737 9738 caller = state->frame[state->curframe - 1]; 9739 if (callee->in_callback_fn) { 9740 if (r0->type != SCALAR_VALUE) { 9741 verbose(env, "R0 not a scalar value\n"); 9742 return -EACCES; 9743 } 9744 9745 /* we are going to rely on register's precise value */ 9746 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64); 9747 err = err ?: mark_chain_precision(env, BPF_REG_0); 9748 if (err) 9749 return err; 9750 9751 /* enforce R0 return value range */ 9752 if (!retval_range_within(callee->callback_ret_range, r0)) { 9753 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 9754 "At callback return", "R0"); 9755 return -EINVAL; 9756 } 9757 if (!calls_callback(env, callee->callsite)) { 9758 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n", 9759 *insn_idx, callee->callsite); 9760 return -EFAULT; 9761 } 9762 } else { 9763 /* return to the caller whatever r0 had in the callee */ 9764 caller->regs[BPF_REG_0] = *r0; 9765 } 9766 9767 /* callback_fn frame should have released its own additions to parent's 9768 * reference state at this point, or check_reference_leak would 9769 * complain, hence it must be the same as the caller. There is no need 9770 * to copy it back. 9771 */ 9772 if (!callee->in_callback_fn) { 9773 /* Transfer references to the caller */ 9774 err = copy_reference_state(caller, callee); 9775 if (err) 9776 return err; 9777 } 9778 9779 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 9780 * there function call logic would reschedule callback visit. If iteration 9781 * converges is_state_visited() would prune that visit eventually. 9782 */ 9783 in_callback_fn = callee->in_callback_fn; 9784 if (in_callback_fn) 9785 *insn_idx = callee->callsite; 9786 else 9787 *insn_idx = callee->callsite + 1; 9788 9789 if (env->log.level & BPF_LOG_LEVEL) { 9790 verbose(env, "returning from callee:\n"); 9791 print_verifier_state(env, callee, true); 9792 verbose(env, "to caller at %d:\n", *insn_idx); 9793 print_verifier_state(env, caller, true); 9794 } 9795 /* clear everything in the callee. In case of exceptional exits using 9796 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 9797 free_func_state(callee); 9798 state->frame[state->curframe--] = NULL; 9799 9800 /* for callbacks widen imprecise scalars to make programs like below verify: 9801 * 9802 * struct ctx { int i; } 9803 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 9804 * ... 9805 * struct ctx = { .i = 0; } 9806 * bpf_loop(100, cb, &ctx, 0); 9807 * 9808 * This is similar to what is done in process_iter_next_call() for open 9809 * coded iterators. 9810 */ 9811 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 9812 if (prev_st) { 9813 err = widen_imprecise_scalars(env, prev_st, state); 9814 if (err) 9815 return err; 9816 } 9817 return 0; 9818 } 9819 9820 static int do_refine_retval_range(struct bpf_verifier_env *env, 9821 struct bpf_reg_state *regs, int ret_type, 9822 int func_id, 9823 struct bpf_call_arg_meta *meta) 9824 { 9825 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 9826 9827 if (ret_type != RET_INTEGER) 9828 return 0; 9829 9830 switch (func_id) { 9831 case BPF_FUNC_get_stack: 9832 case BPF_FUNC_get_task_stack: 9833 case BPF_FUNC_probe_read_str: 9834 case BPF_FUNC_probe_read_kernel_str: 9835 case BPF_FUNC_probe_read_user_str: 9836 ret_reg->smax_value = meta->msize_max_value; 9837 ret_reg->s32_max_value = meta->msize_max_value; 9838 ret_reg->smin_value = -MAX_ERRNO; 9839 ret_reg->s32_min_value = -MAX_ERRNO; 9840 reg_bounds_sync(ret_reg); 9841 break; 9842 case BPF_FUNC_get_smp_processor_id: 9843 ret_reg->umax_value = nr_cpu_ids - 1; 9844 ret_reg->u32_max_value = nr_cpu_ids - 1; 9845 ret_reg->smax_value = nr_cpu_ids - 1; 9846 ret_reg->s32_max_value = nr_cpu_ids - 1; 9847 ret_reg->umin_value = 0; 9848 ret_reg->u32_min_value = 0; 9849 ret_reg->smin_value = 0; 9850 ret_reg->s32_min_value = 0; 9851 reg_bounds_sync(ret_reg); 9852 break; 9853 } 9854 9855 return reg_bounds_sanity_check(env, ret_reg, "retval"); 9856 } 9857 9858 static int 9859 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9860 int func_id, int insn_idx) 9861 { 9862 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9863 struct bpf_map *map = meta->map_ptr; 9864 9865 if (func_id != BPF_FUNC_tail_call && 9866 func_id != BPF_FUNC_map_lookup_elem && 9867 func_id != BPF_FUNC_map_update_elem && 9868 func_id != BPF_FUNC_map_delete_elem && 9869 func_id != BPF_FUNC_map_push_elem && 9870 func_id != BPF_FUNC_map_pop_elem && 9871 func_id != BPF_FUNC_map_peek_elem && 9872 func_id != BPF_FUNC_for_each_map_elem && 9873 func_id != BPF_FUNC_redirect_map && 9874 func_id != BPF_FUNC_map_lookup_percpu_elem) 9875 return 0; 9876 9877 if (map == NULL) { 9878 verbose(env, "kernel subsystem misconfigured verifier\n"); 9879 return -EINVAL; 9880 } 9881 9882 /* In case of read-only, some additional restrictions 9883 * need to be applied in order to prevent altering the 9884 * state of the map from program side. 9885 */ 9886 if ((map->map_flags & BPF_F_RDONLY_PROG) && 9887 (func_id == BPF_FUNC_map_delete_elem || 9888 func_id == BPF_FUNC_map_update_elem || 9889 func_id == BPF_FUNC_map_push_elem || 9890 func_id == BPF_FUNC_map_pop_elem)) { 9891 verbose(env, "write into map forbidden\n"); 9892 return -EACCES; 9893 } 9894 9895 if (!BPF_MAP_PTR(aux->map_ptr_state)) 9896 bpf_map_ptr_store(aux, meta->map_ptr, 9897 !meta->map_ptr->bypass_spec_v1); 9898 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 9899 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 9900 !meta->map_ptr->bypass_spec_v1); 9901 return 0; 9902 } 9903 9904 static int 9905 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9906 int func_id, int insn_idx) 9907 { 9908 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9909 struct bpf_reg_state *regs = cur_regs(env), *reg; 9910 struct bpf_map *map = meta->map_ptr; 9911 u64 val, max; 9912 int err; 9913 9914 if (func_id != BPF_FUNC_tail_call) 9915 return 0; 9916 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 9917 verbose(env, "kernel subsystem misconfigured verifier\n"); 9918 return -EINVAL; 9919 } 9920 9921 reg = ®s[BPF_REG_3]; 9922 val = reg->var_off.value; 9923 max = map->max_entries; 9924 9925 if (!(is_reg_const(reg, false) && val < max)) { 9926 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9927 return 0; 9928 } 9929 9930 err = mark_chain_precision(env, BPF_REG_3); 9931 if (err) 9932 return err; 9933 if (bpf_map_key_unseen(aux)) 9934 bpf_map_key_store(aux, val); 9935 else if (!bpf_map_key_poisoned(aux) && 9936 bpf_map_key_immediate(aux) != val) 9937 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9938 return 0; 9939 } 9940 9941 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 9942 { 9943 struct bpf_func_state *state = cur_func(env); 9944 bool refs_lingering = false; 9945 int i; 9946 9947 if (!exception_exit && state->frameno && !state->in_callback_fn) 9948 return 0; 9949 9950 for (i = 0; i < state->acquired_refs; i++) { 9951 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 9952 continue; 9953 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 9954 state->refs[i].id, state->refs[i].insn_idx); 9955 refs_lingering = true; 9956 } 9957 return refs_lingering ? -EINVAL : 0; 9958 } 9959 9960 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 9961 struct bpf_reg_state *regs) 9962 { 9963 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 9964 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 9965 struct bpf_map *fmt_map = fmt_reg->map_ptr; 9966 struct bpf_bprintf_data data = {}; 9967 int err, fmt_map_off, num_args; 9968 u64 fmt_addr; 9969 char *fmt; 9970 9971 /* data must be an array of u64 */ 9972 if (data_len_reg->var_off.value % 8) 9973 return -EINVAL; 9974 num_args = data_len_reg->var_off.value / 8; 9975 9976 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 9977 * and map_direct_value_addr is set. 9978 */ 9979 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 9980 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 9981 fmt_map_off); 9982 if (err) { 9983 verbose(env, "verifier bug\n"); 9984 return -EFAULT; 9985 } 9986 fmt = (char *)(long)fmt_addr + fmt_map_off; 9987 9988 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 9989 * can focus on validating the format specifiers. 9990 */ 9991 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 9992 if (err < 0) 9993 verbose(env, "Invalid format string\n"); 9994 9995 return err; 9996 } 9997 9998 static int check_get_func_ip(struct bpf_verifier_env *env) 9999 { 10000 enum bpf_prog_type type = resolve_prog_type(env->prog); 10001 int func_id = BPF_FUNC_get_func_ip; 10002 10003 if (type == BPF_PROG_TYPE_TRACING) { 10004 if (!bpf_prog_has_trampoline(env->prog)) { 10005 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 10006 func_id_name(func_id), func_id); 10007 return -ENOTSUPP; 10008 } 10009 return 0; 10010 } else if (type == BPF_PROG_TYPE_KPROBE) { 10011 return 0; 10012 } 10013 10014 verbose(env, "func %s#%d not supported for program type %d\n", 10015 func_id_name(func_id), func_id, type); 10016 return -ENOTSUPP; 10017 } 10018 10019 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 10020 { 10021 return &env->insn_aux_data[env->insn_idx]; 10022 } 10023 10024 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 10025 { 10026 struct bpf_reg_state *regs = cur_regs(env); 10027 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 10028 bool reg_is_null = register_is_null(reg); 10029 10030 if (reg_is_null) 10031 mark_chain_precision(env, BPF_REG_4); 10032 10033 return reg_is_null; 10034 } 10035 10036 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 10037 { 10038 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 10039 10040 if (!state->initialized) { 10041 state->initialized = 1; 10042 state->fit_for_inline = loop_flag_is_zero(env); 10043 state->callback_subprogno = subprogno; 10044 return; 10045 } 10046 10047 if (!state->fit_for_inline) 10048 return; 10049 10050 state->fit_for_inline = (loop_flag_is_zero(env) && 10051 state->callback_subprogno == subprogno); 10052 } 10053 10054 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10055 int *insn_idx_p) 10056 { 10057 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 10058 bool returns_cpu_specific_alloc_ptr = false; 10059 const struct bpf_func_proto *fn = NULL; 10060 enum bpf_return_type ret_type; 10061 enum bpf_type_flag ret_flag; 10062 struct bpf_reg_state *regs; 10063 struct bpf_call_arg_meta meta; 10064 int insn_idx = *insn_idx_p; 10065 bool changes_data; 10066 int i, err, func_id; 10067 10068 /* find function prototype */ 10069 func_id = insn->imm; 10070 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 10071 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 10072 func_id); 10073 return -EINVAL; 10074 } 10075 10076 if (env->ops->get_func_proto) 10077 fn = env->ops->get_func_proto(func_id, env->prog); 10078 if (!fn) { 10079 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 10080 func_id); 10081 return -EINVAL; 10082 } 10083 10084 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 10085 if (!env->prog->gpl_compatible && fn->gpl_only) { 10086 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10087 return -EINVAL; 10088 } 10089 10090 if (fn->allowed && !fn->allowed(env->prog)) { 10091 verbose(env, "helper call is not allowed in probe\n"); 10092 return -EINVAL; 10093 } 10094 10095 if (!env->prog->aux->sleepable && fn->might_sleep) { 10096 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 10097 return -EINVAL; 10098 } 10099 10100 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10101 changes_data = bpf_helper_changes_pkt_data(fn->func); 10102 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10103 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 10104 func_id_name(func_id), func_id); 10105 return -EINVAL; 10106 } 10107 10108 memset(&meta, 0, sizeof(meta)); 10109 meta.pkt_access = fn->pkt_access; 10110 10111 err = check_func_proto(fn, func_id); 10112 if (err) { 10113 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 10114 func_id_name(func_id), func_id); 10115 return err; 10116 } 10117 10118 if (env->cur_state->active_rcu_lock) { 10119 if (fn->might_sleep) { 10120 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 10121 func_id_name(func_id), func_id); 10122 return -EINVAL; 10123 } 10124 10125 if (env->prog->aux->sleepable && is_storage_get_function(func_id)) 10126 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10127 } 10128 10129 meta.func_id = func_id; 10130 /* check args */ 10131 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10132 err = check_func_arg(env, i, &meta, fn, insn_idx); 10133 if (err) 10134 return err; 10135 } 10136 10137 err = record_func_map(env, &meta, func_id, insn_idx); 10138 if (err) 10139 return err; 10140 10141 err = record_func_key(env, &meta, func_id, insn_idx); 10142 if (err) 10143 return err; 10144 10145 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10146 * is inferred from register state. 10147 */ 10148 for (i = 0; i < meta.access_size; i++) { 10149 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 10150 BPF_WRITE, -1, false, false); 10151 if (err) 10152 return err; 10153 } 10154 10155 regs = cur_regs(env); 10156 10157 if (meta.release_regno) { 10158 err = -EINVAL; 10159 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 10160 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 10161 * is safe to do directly. 10162 */ 10163 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 10164 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 10165 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 10166 return -EFAULT; 10167 } 10168 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 10169 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 10170 u32 ref_obj_id = meta.ref_obj_id; 10171 bool in_rcu = in_rcu_cs(env); 10172 struct bpf_func_state *state; 10173 struct bpf_reg_state *reg; 10174 10175 err = release_reference_state(cur_func(env), ref_obj_id); 10176 if (!err) { 10177 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10178 if (reg->ref_obj_id == ref_obj_id) { 10179 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 10180 reg->ref_obj_id = 0; 10181 reg->type &= ~MEM_ALLOC; 10182 reg->type |= MEM_RCU; 10183 } else { 10184 mark_reg_invalid(env, reg); 10185 } 10186 } 10187 })); 10188 } 10189 } else if (meta.ref_obj_id) { 10190 err = release_reference(env, meta.ref_obj_id); 10191 } else if (register_is_null(®s[meta.release_regno])) { 10192 /* meta.ref_obj_id can only be 0 if register that is meant to be 10193 * released is NULL, which must be > R0. 10194 */ 10195 err = 0; 10196 } 10197 if (err) { 10198 verbose(env, "func %s#%d reference has not been acquired before\n", 10199 func_id_name(func_id), func_id); 10200 return err; 10201 } 10202 } 10203 10204 switch (func_id) { 10205 case BPF_FUNC_tail_call: 10206 err = check_reference_leak(env, false); 10207 if (err) { 10208 verbose(env, "tail_call would lead to reference leak\n"); 10209 return err; 10210 } 10211 break; 10212 case BPF_FUNC_get_local_storage: 10213 /* check that flags argument in get_local_storage(map, flags) is 0, 10214 * this is required because get_local_storage() can't return an error. 10215 */ 10216 if (!register_is_null(®s[BPF_REG_2])) { 10217 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10218 return -EINVAL; 10219 } 10220 break; 10221 case BPF_FUNC_for_each_map_elem: 10222 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10223 set_map_elem_callback_state); 10224 break; 10225 case BPF_FUNC_timer_set_callback: 10226 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10227 set_timer_callback_state); 10228 break; 10229 case BPF_FUNC_find_vma: 10230 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10231 set_find_vma_callback_state); 10232 break; 10233 case BPF_FUNC_snprintf: 10234 err = check_bpf_snprintf_call(env, regs); 10235 break; 10236 case BPF_FUNC_loop: 10237 update_loop_inline_state(env, meta.subprogno); 10238 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10239 * is finished, thus mark it precise. 10240 */ 10241 err = mark_chain_precision(env, BPF_REG_1); 10242 if (err) 10243 return err; 10244 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) { 10245 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10246 set_loop_callback_state); 10247 } else { 10248 cur_func(env)->callback_depth = 0; 10249 if (env->log.level & BPF_LOG_LEVEL2) 10250 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10251 env->cur_state->curframe); 10252 } 10253 break; 10254 case BPF_FUNC_dynptr_from_mem: 10255 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10256 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10257 reg_type_str(env, regs[BPF_REG_1].type)); 10258 return -EACCES; 10259 } 10260 break; 10261 case BPF_FUNC_set_retval: 10262 if (prog_type == BPF_PROG_TYPE_LSM && 10263 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10264 if (!env->prog->aux->attach_func_proto->type) { 10265 /* Make sure programs that attach to void 10266 * hooks don't try to modify return value. 10267 */ 10268 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10269 return -EINVAL; 10270 } 10271 } 10272 break; 10273 case BPF_FUNC_dynptr_data: 10274 { 10275 struct bpf_reg_state *reg; 10276 int id, ref_obj_id; 10277 10278 reg = get_dynptr_arg_reg(env, fn, regs); 10279 if (!reg) 10280 return -EFAULT; 10281 10282 10283 if (meta.dynptr_id) { 10284 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 10285 return -EFAULT; 10286 } 10287 if (meta.ref_obj_id) { 10288 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 10289 return -EFAULT; 10290 } 10291 10292 id = dynptr_id(env, reg); 10293 if (id < 0) { 10294 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 10295 return id; 10296 } 10297 10298 ref_obj_id = dynptr_ref_obj_id(env, reg); 10299 if (ref_obj_id < 0) { 10300 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 10301 return ref_obj_id; 10302 } 10303 10304 meta.dynptr_id = id; 10305 meta.ref_obj_id = ref_obj_id; 10306 10307 break; 10308 } 10309 case BPF_FUNC_dynptr_write: 10310 { 10311 enum bpf_dynptr_type dynptr_type; 10312 struct bpf_reg_state *reg; 10313 10314 reg = get_dynptr_arg_reg(env, fn, regs); 10315 if (!reg) 10316 return -EFAULT; 10317 10318 dynptr_type = dynptr_get_type(env, reg); 10319 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10320 return -EFAULT; 10321 10322 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 10323 /* this will trigger clear_all_pkt_pointers(), which will 10324 * invalidate all dynptr slices associated with the skb 10325 */ 10326 changes_data = true; 10327 10328 break; 10329 } 10330 case BPF_FUNC_per_cpu_ptr: 10331 case BPF_FUNC_this_cpu_ptr: 10332 { 10333 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 10334 const struct btf_type *type; 10335 10336 if (reg->type & MEM_RCU) { 10337 type = btf_type_by_id(reg->btf, reg->btf_id); 10338 if (!type || !btf_type_is_struct(type)) { 10339 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 10340 return -EFAULT; 10341 } 10342 returns_cpu_specific_alloc_ptr = true; 10343 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 10344 } 10345 break; 10346 } 10347 case BPF_FUNC_user_ringbuf_drain: 10348 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10349 set_user_ringbuf_callback_state); 10350 break; 10351 } 10352 10353 if (err) 10354 return err; 10355 10356 /* reset caller saved regs */ 10357 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10358 mark_reg_not_init(env, regs, caller_saved[i]); 10359 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10360 } 10361 10362 /* helper call returns 64-bit value. */ 10363 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10364 10365 /* update return register (already marked as written above) */ 10366 ret_type = fn->ret_type; 10367 ret_flag = type_flag(ret_type); 10368 10369 switch (base_type(ret_type)) { 10370 case RET_INTEGER: 10371 /* sets type to SCALAR_VALUE */ 10372 mark_reg_unknown(env, regs, BPF_REG_0); 10373 break; 10374 case RET_VOID: 10375 regs[BPF_REG_0].type = NOT_INIT; 10376 break; 10377 case RET_PTR_TO_MAP_VALUE: 10378 /* There is no offset yet applied, variable or fixed */ 10379 mark_reg_known_zero(env, regs, BPF_REG_0); 10380 /* remember map_ptr, so that check_map_access() 10381 * can check 'value_size' boundary of memory access 10382 * to map element returned from bpf_map_lookup_elem() 10383 */ 10384 if (meta.map_ptr == NULL) { 10385 verbose(env, 10386 "kernel subsystem misconfigured verifier\n"); 10387 return -EINVAL; 10388 } 10389 regs[BPF_REG_0].map_ptr = meta.map_ptr; 10390 regs[BPF_REG_0].map_uid = meta.map_uid; 10391 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10392 if (!type_may_be_null(ret_type) && 10393 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 10394 regs[BPF_REG_0].id = ++env->id_gen; 10395 } 10396 break; 10397 case RET_PTR_TO_SOCKET: 10398 mark_reg_known_zero(env, regs, BPF_REG_0); 10399 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10400 break; 10401 case RET_PTR_TO_SOCK_COMMON: 10402 mark_reg_known_zero(env, regs, BPF_REG_0); 10403 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10404 break; 10405 case RET_PTR_TO_TCP_SOCK: 10406 mark_reg_known_zero(env, regs, BPF_REG_0); 10407 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10408 break; 10409 case RET_PTR_TO_MEM: 10410 mark_reg_known_zero(env, regs, BPF_REG_0); 10411 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10412 regs[BPF_REG_0].mem_size = meta.mem_size; 10413 break; 10414 case RET_PTR_TO_MEM_OR_BTF_ID: 10415 { 10416 const struct btf_type *t; 10417 10418 mark_reg_known_zero(env, regs, BPF_REG_0); 10419 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10420 if (!btf_type_is_struct(t)) { 10421 u32 tsize; 10422 const struct btf_type *ret; 10423 const char *tname; 10424 10425 /* resolve the type size of ksym. */ 10426 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10427 if (IS_ERR(ret)) { 10428 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10429 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10430 tname, PTR_ERR(ret)); 10431 return -EINVAL; 10432 } 10433 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10434 regs[BPF_REG_0].mem_size = tsize; 10435 } else { 10436 if (returns_cpu_specific_alloc_ptr) { 10437 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10438 } else { 10439 /* MEM_RDONLY may be carried from ret_flag, but it 10440 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10441 * it will confuse the check of PTR_TO_BTF_ID in 10442 * check_mem_access(). 10443 */ 10444 ret_flag &= ~MEM_RDONLY; 10445 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10446 } 10447 10448 regs[BPF_REG_0].btf = meta.ret_btf; 10449 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10450 } 10451 break; 10452 } 10453 case RET_PTR_TO_BTF_ID: 10454 { 10455 struct btf *ret_btf; 10456 int ret_btf_id; 10457 10458 mark_reg_known_zero(env, regs, BPF_REG_0); 10459 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10460 if (func_id == BPF_FUNC_kptr_xchg) { 10461 ret_btf = meta.kptr_field->kptr.btf; 10462 ret_btf_id = meta.kptr_field->kptr.btf_id; 10463 if (!btf_is_kernel(ret_btf)) { 10464 regs[BPF_REG_0].type |= MEM_ALLOC; 10465 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10466 regs[BPF_REG_0].type |= MEM_PERCPU; 10467 } 10468 } else { 10469 if (fn->ret_btf_id == BPF_PTR_POISON) { 10470 verbose(env, "verifier internal error:"); 10471 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 10472 func_id_name(func_id)); 10473 return -EINVAL; 10474 } 10475 ret_btf = btf_vmlinux; 10476 ret_btf_id = *fn->ret_btf_id; 10477 } 10478 if (ret_btf_id == 0) { 10479 verbose(env, "invalid return type %u of func %s#%d\n", 10480 base_type(ret_type), func_id_name(func_id), 10481 func_id); 10482 return -EINVAL; 10483 } 10484 regs[BPF_REG_0].btf = ret_btf; 10485 regs[BPF_REG_0].btf_id = ret_btf_id; 10486 break; 10487 } 10488 default: 10489 verbose(env, "unknown return type %u of func %s#%d\n", 10490 base_type(ret_type), func_id_name(func_id), func_id); 10491 return -EINVAL; 10492 } 10493 10494 if (type_may_be_null(regs[BPF_REG_0].type)) 10495 regs[BPF_REG_0].id = ++env->id_gen; 10496 10497 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 10498 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 10499 func_id_name(func_id), func_id); 10500 return -EFAULT; 10501 } 10502 10503 if (is_dynptr_ref_function(func_id)) 10504 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 10505 10506 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 10507 /* For release_reference() */ 10508 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10509 } else if (is_acquire_function(func_id, meta.map_ptr)) { 10510 int id = acquire_reference_state(env, insn_idx); 10511 10512 if (id < 0) 10513 return id; 10514 /* For mark_ptr_or_null_reg() */ 10515 regs[BPF_REG_0].id = id; 10516 /* For release_reference() */ 10517 regs[BPF_REG_0].ref_obj_id = id; 10518 } 10519 10520 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 10521 if (err) 10522 return err; 10523 10524 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 10525 if (err) 10526 return err; 10527 10528 if ((func_id == BPF_FUNC_get_stack || 10529 func_id == BPF_FUNC_get_task_stack) && 10530 !env->prog->has_callchain_buf) { 10531 const char *err_str; 10532 10533 #ifdef CONFIG_PERF_EVENTS 10534 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10535 err_str = "cannot get callchain buffer for func %s#%d\n"; 10536 #else 10537 err = -ENOTSUPP; 10538 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10539 #endif 10540 if (err) { 10541 verbose(env, err_str, func_id_name(func_id), func_id); 10542 return err; 10543 } 10544 10545 env->prog->has_callchain_buf = true; 10546 } 10547 10548 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10549 env->prog->call_get_stack = true; 10550 10551 if (func_id == BPF_FUNC_get_func_ip) { 10552 if (check_get_func_ip(env)) 10553 return -ENOTSUPP; 10554 env->prog->call_get_func_ip = true; 10555 } 10556 10557 if (changes_data) 10558 clear_all_pkt_pointers(env); 10559 return 0; 10560 } 10561 10562 /* mark_btf_func_reg_size() is used when the reg size is determined by 10563 * the BTF func_proto's return value size and argument. 10564 */ 10565 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10566 size_t reg_size) 10567 { 10568 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 10569 10570 if (regno == BPF_REG_0) { 10571 /* Function return value */ 10572 reg->live |= REG_LIVE_WRITTEN; 10573 reg->subreg_def = reg_size == sizeof(u64) ? 10574 DEF_NOT_SUBREG : env->insn_idx + 1; 10575 } else { 10576 /* Function argument */ 10577 if (reg_size == sizeof(u64)) { 10578 mark_insn_zext(env, reg); 10579 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 10580 } else { 10581 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 10582 } 10583 } 10584 } 10585 10586 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10587 { 10588 return meta->kfunc_flags & KF_ACQUIRE; 10589 } 10590 10591 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10592 { 10593 return meta->kfunc_flags & KF_RELEASE; 10594 } 10595 10596 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 10597 { 10598 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 10599 } 10600 10601 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 10602 { 10603 return meta->kfunc_flags & KF_SLEEPABLE; 10604 } 10605 10606 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10607 { 10608 return meta->kfunc_flags & KF_DESTRUCTIVE; 10609 } 10610 10611 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10612 { 10613 return meta->kfunc_flags & KF_RCU; 10614 } 10615 10616 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 10617 { 10618 return meta->kfunc_flags & KF_RCU_PROTECTED; 10619 } 10620 10621 static bool __kfunc_param_match_suffix(const struct btf *btf, 10622 const struct btf_param *arg, 10623 const char *suffix) 10624 { 10625 int suffix_len = strlen(suffix), len; 10626 const char *param_name; 10627 10628 /* In the future, this can be ported to use BTF tagging */ 10629 param_name = btf_name_by_offset(btf, arg->name_off); 10630 if (str_is_empty(param_name)) 10631 return false; 10632 len = strlen(param_name); 10633 if (len < suffix_len) 10634 return false; 10635 param_name += len - suffix_len; 10636 return !strncmp(param_name, suffix, suffix_len); 10637 } 10638 10639 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10640 const struct btf_param *arg, 10641 const struct bpf_reg_state *reg) 10642 { 10643 const struct btf_type *t; 10644 10645 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10646 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10647 return false; 10648 10649 return __kfunc_param_match_suffix(btf, arg, "__sz"); 10650 } 10651 10652 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10653 const struct btf_param *arg, 10654 const struct bpf_reg_state *reg) 10655 { 10656 const struct btf_type *t; 10657 10658 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10659 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10660 return false; 10661 10662 return __kfunc_param_match_suffix(btf, arg, "__szk"); 10663 } 10664 10665 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 10666 { 10667 return __kfunc_param_match_suffix(btf, arg, "__opt"); 10668 } 10669 10670 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10671 { 10672 return __kfunc_param_match_suffix(btf, arg, "__k"); 10673 } 10674 10675 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10676 { 10677 return __kfunc_param_match_suffix(btf, arg, "__ign"); 10678 } 10679 10680 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10681 { 10682 return __kfunc_param_match_suffix(btf, arg, "__alloc"); 10683 } 10684 10685 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10686 { 10687 return __kfunc_param_match_suffix(btf, arg, "__uninit"); 10688 } 10689 10690 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10691 { 10692 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr"); 10693 } 10694 10695 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 10696 { 10697 return __kfunc_param_match_suffix(btf, arg, "__nullable"); 10698 } 10699 10700 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 10701 { 10702 return __kfunc_param_match_suffix(btf, arg, "__str"); 10703 } 10704 10705 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10706 const struct btf_param *arg, 10707 const char *name) 10708 { 10709 int len, target_len = strlen(name); 10710 const char *param_name; 10711 10712 param_name = btf_name_by_offset(btf, arg->name_off); 10713 if (str_is_empty(param_name)) 10714 return false; 10715 len = strlen(param_name); 10716 if (len != target_len) 10717 return false; 10718 if (strcmp(param_name, name)) 10719 return false; 10720 10721 return true; 10722 } 10723 10724 enum { 10725 KF_ARG_DYNPTR_ID, 10726 KF_ARG_LIST_HEAD_ID, 10727 KF_ARG_LIST_NODE_ID, 10728 KF_ARG_RB_ROOT_ID, 10729 KF_ARG_RB_NODE_ID, 10730 }; 10731 10732 BTF_ID_LIST(kf_arg_btf_ids) 10733 BTF_ID(struct, bpf_dynptr_kern) 10734 BTF_ID(struct, bpf_list_head) 10735 BTF_ID(struct, bpf_list_node) 10736 BTF_ID(struct, bpf_rb_root) 10737 BTF_ID(struct, bpf_rb_node) 10738 10739 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10740 const struct btf_param *arg, int type) 10741 { 10742 const struct btf_type *t; 10743 u32 res_id; 10744 10745 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10746 if (!t) 10747 return false; 10748 if (!btf_type_is_ptr(t)) 10749 return false; 10750 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10751 if (!t) 10752 return false; 10753 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10754 } 10755 10756 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10757 { 10758 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10759 } 10760 10761 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10762 { 10763 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10764 } 10765 10766 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10767 { 10768 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10769 } 10770 10771 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10772 { 10773 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10774 } 10775 10776 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10777 { 10778 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10779 } 10780 10781 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10782 const struct btf_param *arg) 10783 { 10784 const struct btf_type *t; 10785 10786 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10787 if (!t) 10788 return false; 10789 10790 return true; 10791 } 10792 10793 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10794 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10795 const struct btf *btf, 10796 const struct btf_type *t, int rec) 10797 { 10798 const struct btf_type *member_type; 10799 const struct btf_member *member; 10800 u32 i; 10801 10802 if (!btf_type_is_struct(t)) 10803 return false; 10804 10805 for_each_member(i, t, member) { 10806 const struct btf_array *array; 10807 10808 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 10809 if (btf_type_is_struct(member_type)) { 10810 if (rec >= 3) { 10811 verbose(env, "max struct nesting depth exceeded\n"); 10812 return false; 10813 } 10814 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 10815 return false; 10816 continue; 10817 } 10818 if (btf_type_is_array(member_type)) { 10819 array = btf_array(member_type); 10820 if (!array->nelems) 10821 return false; 10822 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 10823 if (!btf_type_is_scalar(member_type)) 10824 return false; 10825 continue; 10826 } 10827 if (!btf_type_is_scalar(member_type)) 10828 return false; 10829 } 10830 return true; 10831 } 10832 10833 enum kfunc_ptr_arg_type { 10834 KF_ARG_PTR_TO_CTX, 10835 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 10836 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 10837 KF_ARG_PTR_TO_DYNPTR, 10838 KF_ARG_PTR_TO_ITER, 10839 KF_ARG_PTR_TO_LIST_HEAD, 10840 KF_ARG_PTR_TO_LIST_NODE, 10841 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 10842 KF_ARG_PTR_TO_MEM, 10843 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 10844 KF_ARG_PTR_TO_CALLBACK, 10845 KF_ARG_PTR_TO_RB_ROOT, 10846 KF_ARG_PTR_TO_RB_NODE, 10847 KF_ARG_PTR_TO_NULL, 10848 KF_ARG_PTR_TO_CONST_STR, 10849 }; 10850 10851 enum special_kfunc_type { 10852 KF_bpf_obj_new_impl, 10853 KF_bpf_obj_drop_impl, 10854 KF_bpf_refcount_acquire_impl, 10855 KF_bpf_list_push_front_impl, 10856 KF_bpf_list_push_back_impl, 10857 KF_bpf_list_pop_front, 10858 KF_bpf_list_pop_back, 10859 KF_bpf_cast_to_kern_ctx, 10860 KF_bpf_rdonly_cast, 10861 KF_bpf_rcu_read_lock, 10862 KF_bpf_rcu_read_unlock, 10863 KF_bpf_rbtree_remove, 10864 KF_bpf_rbtree_add_impl, 10865 KF_bpf_rbtree_first, 10866 KF_bpf_dynptr_from_skb, 10867 KF_bpf_dynptr_from_xdp, 10868 KF_bpf_dynptr_slice, 10869 KF_bpf_dynptr_slice_rdwr, 10870 KF_bpf_dynptr_clone, 10871 KF_bpf_percpu_obj_new_impl, 10872 KF_bpf_percpu_obj_drop_impl, 10873 KF_bpf_throw, 10874 KF_bpf_iter_css_task_new, 10875 }; 10876 10877 BTF_SET_START(special_kfunc_set) 10878 BTF_ID(func, bpf_obj_new_impl) 10879 BTF_ID(func, bpf_obj_drop_impl) 10880 BTF_ID(func, bpf_refcount_acquire_impl) 10881 BTF_ID(func, bpf_list_push_front_impl) 10882 BTF_ID(func, bpf_list_push_back_impl) 10883 BTF_ID(func, bpf_list_pop_front) 10884 BTF_ID(func, bpf_list_pop_back) 10885 BTF_ID(func, bpf_cast_to_kern_ctx) 10886 BTF_ID(func, bpf_rdonly_cast) 10887 BTF_ID(func, bpf_rbtree_remove) 10888 BTF_ID(func, bpf_rbtree_add_impl) 10889 BTF_ID(func, bpf_rbtree_first) 10890 BTF_ID(func, bpf_dynptr_from_skb) 10891 BTF_ID(func, bpf_dynptr_from_xdp) 10892 BTF_ID(func, bpf_dynptr_slice) 10893 BTF_ID(func, bpf_dynptr_slice_rdwr) 10894 BTF_ID(func, bpf_dynptr_clone) 10895 BTF_ID(func, bpf_percpu_obj_new_impl) 10896 BTF_ID(func, bpf_percpu_obj_drop_impl) 10897 BTF_ID(func, bpf_throw) 10898 #ifdef CONFIG_CGROUPS 10899 BTF_ID(func, bpf_iter_css_task_new) 10900 #endif 10901 BTF_SET_END(special_kfunc_set) 10902 10903 BTF_ID_LIST(special_kfunc_list) 10904 BTF_ID(func, bpf_obj_new_impl) 10905 BTF_ID(func, bpf_obj_drop_impl) 10906 BTF_ID(func, bpf_refcount_acquire_impl) 10907 BTF_ID(func, bpf_list_push_front_impl) 10908 BTF_ID(func, bpf_list_push_back_impl) 10909 BTF_ID(func, bpf_list_pop_front) 10910 BTF_ID(func, bpf_list_pop_back) 10911 BTF_ID(func, bpf_cast_to_kern_ctx) 10912 BTF_ID(func, bpf_rdonly_cast) 10913 BTF_ID(func, bpf_rcu_read_lock) 10914 BTF_ID(func, bpf_rcu_read_unlock) 10915 BTF_ID(func, bpf_rbtree_remove) 10916 BTF_ID(func, bpf_rbtree_add_impl) 10917 BTF_ID(func, bpf_rbtree_first) 10918 BTF_ID(func, bpf_dynptr_from_skb) 10919 BTF_ID(func, bpf_dynptr_from_xdp) 10920 BTF_ID(func, bpf_dynptr_slice) 10921 BTF_ID(func, bpf_dynptr_slice_rdwr) 10922 BTF_ID(func, bpf_dynptr_clone) 10923 BTF_ID(func, bpf_percpu_obj_new_impl) 10924 BTF_ID(func, bpf_percpu_obj_drop_impl) 10925 BTF_ID(func, bpf_throw) 10926 #ifdef CONFIG_CGROUPS 10927 BTF_ID(func, bpf_iter_css_task_new) 10928 #else 10929 BTF_ID_UNUSED 10930 #endif 10931 10932 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 10933 { 10934 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 10935 meta->arg_owning_ref) { 10936 return false; 10937 } 10938 10939 return meta->kfunc_flags & KF_RET_NULL; 10940 } 10941 10942 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 10943 { 10944 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 10945 } 10946 10947 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 10948 { 10949 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 10950 } 10951 10952 static enum kfunc_ptr_arg_type 10953 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 10954 struct bpf_kfunc_call_arg_meta *meta, 10955 const struct btf_type *t, const struct btf_type *ref_t, 10956 const char *ref_tname, const struct btf_param *args, 10957 int argno, int nargs) 10958 { 10959 u32 regno = argno + 1; 10960 struct bpf_reg_state *regs = cur_regs(env); 10961 struct bpf_reg_state *reg = ®s[regno]; 10962 bool arg_mem_size = false; 10963 10964 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 10965 return KF_ARG_PTR_TO_CTX; 10966 10967 /* In this function, we verify the kfunc's BTF as per the argument type, 10968 * leaving the rest of the verification with respect to the register 10969 * type to our caller. When a set of conditions hold in the BTF type of 10970 * arguments, we resolve it to a known kfunc_ptr_arg_type. 10971 */ 10972 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 10973 return KF_ARG_PTR_TO_CTX; 10974 10975 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 10976 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 10977 10978 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 10979 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 10980 10981 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 10982 return KF_ARG_PTR_TO_DYNPTR; 10983 10984 if (is_kfunc_arg_iter(meta, argno)) 10985 return KF_ARG_PTR_TO_ITER; 10986 10987 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 10988 return KF_ARG_PTR_TO_LIST_HEAD; 10989 10990 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 10991 return KF_ARG_PTR_TO_LIST_NODE; 10992 10993 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 10994 return KF_ARG_PTR_TO_RB_ROOT; 10995 10996 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 10997 return KF_ARG_PTR_TO_RB_NODE; 10998 10999 if (is_kfunc_arg_const_str(meta->btf, &args[argno])) 11000 return KF_ARG_PTR_TO_CONST_STR; 11001 11002 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 11003 if (!btf_type_is_struct(ref_t)) { 11004 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 11005 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 11006 return -EINVAL; 11007 } 11008 return KF_ARG_PTR_TO_BTF_ID; 11009 } 11010 11011 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 11012 return KF_ARG_PTR_TO_CALLBACK; 11013 11014 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg)) 11015 return KF_ARG_PTR_TO_NULL; 11016 11017 if (argno + 1 < nargs && 11018 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 11019 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 11020 arg_mem_size = true; 11021 11022 /* This is the catch all argument type of register types supported by 11023 * check_helper_mem_access. However, we only allow when argument type is 11024 * pointer to scalar, or struct composed (recursively) of scalars. When 11025 * arg_mem_size is true, the pointer can be void *. 11026 */ 11027 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 11028 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 11029 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 11030 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 11031 return -EINVAL; 11032 } 11033 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 11034 } 11035 11036 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 11037 struct bpf_reg_state *reg, 11038 const struct btf_type *ref_t, 11039 const char *ref_tname, u32 ref_id, 11040 struct bpf_kfunc_call_arg_meta *meta, 11041 int argno) 11042 { 11043 const struct btf_type *reg_ref_t; 11044 bool strict_type_match = false; 11045 const struct btf *reg_btf; 11046 const char *reg_ref_tname; 11047 u32 reg_ref_id; 11048 11049 if (base_type(reg->type) == PTR_TO_BTF_ID) { 11050 reg_btf = reg->btf; 11051 reg_ref_id = reg->btf_id; 11052 } else { 11053 reg_btf = btf_vmlinux; 11054 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 11055 } 11056 11057 /* Enforce strict type matching for calls to kfuncs that are acquiring 11058 * or releasing a reference, or are no-cast aliases. We do _not_ 11059 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 11060 * as we want to enable BPF programs to pass types that are bitwise 11061 * equivalent without forcing them to explicitly cast with something 11062 * like bpf_cast_to_kern_ctx(). 11063 * 11064 * For example, say we had a type like the following: 11065 * 11066 * struct bpf_cpumask { 11067 * cpumask_t cpumask; 11068 * refcount_t usage; 11069 * }; 11070 * 11071 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 11072 * to a struct cpumask, so it would be safe to pass a struct 11073 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 11074 * 11075 * The philosophy here is similar to how we allow scalars of different 11076 * types to be passed to kfuncs as long as the size is the same. The 11077 * only difference here is that we're simply allowing 11078 * btf_struct_ids_match() to walk the struct at the 0th offset, and 11079 * resolve types. 11080 */ 11081 if (is_kfunc_acquire(meta) || 11082 (is_kfunc_release(meta) && reg->ref_obj_id) || 11083 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 11084 strict_type_match = true; 11085 11086 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 11087 11088 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 11089 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 11090 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 11091 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 11092 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 11093 btf_type_str(reg_ref_t), reg_ref_tname); 11094 return -EINVAL; 11095 } 11096 return 0; 11097 } 11098 11099 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11100 { 11101 struct bpf_verifier_state *state = env->cur_state; 11102 struct btf_record *rec = reg_btf_record(reg); 11103 11104 if (!state->active_lock.ptr) { 11105 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 11106 return -EFAULT; 11107 } 11108 11109 if (type_flag(reg->type) & NON_OWN_REF) { 11110 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 11111 return -EFAULT; 11112 } 11113 11114 reg->type |= NON_OWN_REF; 11115 if (rec->refcount_off >= 0) 11116 reg->type |= MEM_RCU; 11117 11118 return 0; 11119 } 11120 11121 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 11122 { 11123 struct bpf_func_state *state, *unused; 11124 struct bpf_reg_state *reg; 11125 int i; 11126 11127 state = cur_func(env); 11128 11129 if (!ref_obj_id) { 11130 verbose(env, "verifier internal error: ref_obj_id is zero for " 11131 "owning -> non-owning conversion\n"); 11132 return -EFAULT; 11133 } 11134 11135 for (i = 0; i < state->acquired_refs; i++) { 11136 if (state->refs[i].id != ref_obj_id) 11137 continue; 11138 11139 /* Clear ref_obj_id here so release_reference doesn't clobber 11140 * the whole reg 11141 */ 11142 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11143 if (reg->ref_obj_id == ref_obj_id) { 11144 reg->ref_obj_id = 0; 11145 ref_set_non_owning(env, reg); 11146 } 11147 })); 11148 return 0; 11149 } 11150 11151 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 11152 return -EFAULT; 11153 } 11154 11155 /* Implementation details: 11156 * 11157 * Each register points to some region of memory, which we define as an 11158 * allocation. Each allocation may embed a bpf_spin_lock which protects any 11159 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 11160 * allocation. The lock and the data it protects are colocated in the same 11161 * memory region. 11162 * 11163 * Hence, everytime a register holds a pointer value pointing to such 11164 * allocation, the verifier preserves a unique reg->id for it. 11165 * 11166 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 11167 * bpf_spin_lock is called. 11168 * 11169 * To enable this, lock state in the verifier captures two values: 11170 * active_lock.ptr = Register's type specific pointer 11171 * active_lock.id = A unique ID for each register pointer value 11172 * 11173 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11174 * supported register types. 11175 * 11176 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11177 * allocated objects is the reg->btf pointer. 11178 * 11179 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11180 * can establish the provenance of the map value statically for each distinct 11181 * lookup into such maps. They always contain a single map value hence unique 11182 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11183 * 11184 * So, in case of global variables, they use array maps with max_entries = 1, 11185 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11186 * into the same map value as max_entries is 1, as described above). 11187 * 11188 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11189 * outer map pointer (in verifier context), but each lookup into an inner map 11190 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11191 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11192 * will get different reg->id assigned to each lookup, hence different 11193 * active_lock.id. 11194 * 11195 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11196 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11197 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11198 */ 11199 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11200 { 11201 void *ptr; 11202 u32 id; 11203 11204 switch ((int)reg->type) { 11205 case PTR_TO_MAP_VALUE: 11206 ptr = reg->map_ptr; 11207 break; 11208 case PTR_TO_BTF_ID | MEM_ALLOC: 11209 ptr = reg->btf; 11210 break; 11211 default: 11212 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 11213 return -EFAULT; 11214 } 11215 id = reg->id; 11216 11217 if (!env->cur_state->active_lock.ptr) 11218 return -EINVAL; 11219 if (env->cur_state->active_lock.ptr != ptr || 11220 env->cur_state->active_lock.id != id) { 11221 verbose(env, "held lock and object are not in the same allocation\n"); 11222 return -EINVAL; 11223 } 11224 return 0; 11225 } 11226 11227 static bool is_bpf_list_api_kfunc(u32 btf_id) 11228 { 11229 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11230 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11231 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11232 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 11233 } 11234 11235 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11236 { 11237 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 11238 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11239 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 11240 } 11241 11242 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11243 { 11244 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 11245 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11246 } 11247 11248 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11249 { 11250 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11251 } 11252 11253 static bool is_bpf_throw_kfunc(struct bpf_insn *insn) 11254 { 11255 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 11256 insn->imm == special_kfunc_list[KF_bpf_throw]; 11257 } 11258 11259 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11260 { 11261 return is_bpf_rbtree_api_kfunc(btf_id); 11262 } 11263 11264 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11265 enum btf_field_type head_field_type, 11266 u32 kfunc_btf_id) 11267 { 11268 bool ret; 11269 11270 switch (head_field_type) { 11271 case BPF_LIST_HEAD: 11272 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11273 break; 11274 case BPF_RB_ROOT: 11275 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11276 break; 11277 default: 11278 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11279 btf_field_type_name(head_field_type)); 11280 return false; 11281 } 11282 11283 if (!ret) 11284 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11285 btf_field_type_name(head_field_type)); 11286 return ret; 11287 } 11288 11289 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11290 enum btf_field_type node_field_type, 11291 u32 kfunc_btf_id) 11292 { 11293 bool ret; 11294 11295 switch (node_field_type) { 11296 case BPF_LIST_NODE: 11297 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11298 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 11299 break; 11300 case BPF_RB_NODE: 11301 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11302 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 11303 break; 11304 default: 11305 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11306 btf_field_type_name(node_field_type)); 11307 return false; 11308 } 11309 11310 if (!ret) 11311 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11312 btf_field_type_name(node_field_type)); 11313 return ret; 11314 } 11315 11316 static int 11317 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11318 struct bpf_reg_state *reg, u32 regno, 11319 struct bpf_kfunc_call_arg_meta *meta, 11320 enum btf_field_type head_field_type, 11321 struct btf_field **head_field) 11322 { 11323 const char *head_type_name; 11324 struct btf_field *field; 11325 struct btf_record *rec; 11326 u32 head_off; 11327 11328 if (meta->btf != btf_vmlinux) { 11329 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11330 return -EFAULT; 11331 } 11332 11333 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11334 return -EFAULT; 11335 11336 head_type_name = btf_field_type_name(head_field_type); 11337 if (!tnum_is_const(reg->var_off)) { 11338 verbose(env, 11339 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11340 regno, head_type_name); 11341 return -EINVAL; 11342 } 11343 11344 rec = reg_btf_record(reg); 11345 head_off = reg->off + reg->var_off.value; 11346 field = btf_record_find(rec, head_off, head_field_type); 11347 if (!field) { 11348 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11349 return -EINVAL; 11350 } 11351 11352 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11353 if (check_reg_allocation_locked(env, reg)) { 11354 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11355 rec->spin_lock_off, head_type_name); 11356 return -EINVAL; 11357 } 11358 11359 if (*head_field) { 11360 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 11361 return -EFAULT; 11362 } 11363 *head_field = field; 11364 return 0; 11365 } 11366 11367 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11368 struct bpf_reg_state *reg, u32 regno, 11369 struct bpf_kfunc_call_arg_meta *meta) 11370 { 11371 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 11372 &meta->arg_list_head.field); 11373 } 11374 11375 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11376 struct bpf_reg_state *reg, u32 regno, 11377 struct bpf_kfunc_call_arg_meta *meta) 11378 { 11379 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 11380 &meta->arg_rbtree_root.field); 11381 } 11382 11383 static int 11384 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11385 struct bpf_reg_state *reg, u32 regno, 11386 struct bpf_kfunc_call_arg_meta *meta, 11387 enum btf_field_type head_field_type, 11388 enum btf_field_type node_field_type, 11389 struct btf_field **node_field) 11390 { 11391 const char *node_type_name; 11392 const struct btf_type *et, *t; 11393 struct btf_field *field; 11394 u32 node_off; 11395 11396 if (meta->btf != btf_vmlinux) { 11397 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11398 return -EFAULT; 11399 } 11400 11401 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11402 return -EFAULT; 11403 11404 node_type_name = btf_field_type_name(node_field_type); 11405 if (!tnum_is_const(reg->var_off)) { 11406 verbose(env, 11407 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11408 regno, node_type_name); 11409 return -EINVAL; 11410 } 11411 11412 node_off = reg->off + reg->var_off.value; 11413 field = reg_find_field_offset(reg, node_off, node_field_type); 11414 if (!field || field->offset != node_off) { 11415 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11416 return -EINVAL; 11417 } 11418 11419 field = *node_field; 11420 11421 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11422 t = btf_type_by_id(reg->btf, reg->btf_id); 11423 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11424 field->graph_root.value_btf_id, true)) { 11425 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11426 "in struct %s, but arg is at offset=%d in struct %s\n", 11427 btf_field_type_name(head_field_type), 11428 btf_field_type_name(node_field_type), 11429 field->graph_root.node_offset, 11430 btf_name_by_offset(field->graph_root.btf, et->name_off), 11431 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11432 return -EINVAL; 11433 } 11434 meta->arg_btf = reg->btf; 11435 meta->arg_btf_id = reg->btf_id; 11436 11437 if (node_off != field->graph_root.node_offset) { 11438 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11439 node_off, btf_field_type_name(node_field_type), 11440 field->graph_root.node_offset, 11441 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11442 return -EINVAL; 11443 } 11444 11445 return 0; 11446 } 11447 11448 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11449 struct bpf_reg_state *reg, u32 regno, 11450 struct bpf_kfunc_call_arg_meta *meta) 11451 { 11452 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11453 BPF_LIST_HEAD, BPF_LIST_NODE, 11454 &meta->arg_list_head.field); 11455 } 11456 11457 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11458 struct bpf_reg_state *reg, u32 regno, 11459 struct bpf_kfunc_call_arg_meta *meta) 11460 { 11461 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11462 BPF_RB_ROOT, BPF_RB_NODE, 11463 &meta->arg_rbtree_root.field); 11464 } 11465 11466 /* 11467 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 11468 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 11469 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 11470 * them can only be attached to some specific hook points. 11471 */ 11472 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 11473 { 11474 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11475 11476 switch (prog_type) { 11477 case BPF_PROG_TYPE_LSM: 11478 return true; 11479 case BPF_PROG_TYPE_TRACING: 11480 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 11481 return true; 11482 fallthrough; 11483 default: 11484 return env->prog->aux->sleepable; 11485 } 11486 } 11487 11488 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11489 int insn_idx) 11490 { 11491 const char *func_name = meta->func_name, *ref_tname; 11492 const struct btf *btf = meta->btf; 11493 const struct btf_param *args; 11494 struct btf_record *rec; 11495 u32 i, nargs; 11496 int ret; 11497 11498 args = (const struct btf_param *)(meta->func_proto + 1); 11499 nargs = btf_type_vlen(meta->func_proto); 11500 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 11501 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11502 MAX_BPF_FUNC_REG_ARGS); 11503 return -EINVAL; 11504 } 11505 11506 /* Check that BTF function arguments match actual types that the 11507 * verifier sees. 11508 */ 11509 for (i = 0; i < nargs; i++) { 11510 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 11511 const struct btf_type *t, *ref_t, *resolve_ret; 11512 enum bpf_arg_type arg_type = ARG_DONTCARE; 11513 u32 regno = i + 1, ref_id, type_size; 11514 bool is_ret_buf_sz = false; 11515 int kf_arg_type; 11516 11517 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11518 11519 if (is_kfunc_arg_ignore(btf, &args[i])) 11520 continue; 11521 11522 if (btf_type_is_scalar(t)) { 11523 if (reg->type != SCALAR_VALUE) { 11524 verbose(env, "R%d is not a scalar\n", regno); 11525 return -EINVAL; 11526 } 11527 11528 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11529 if (meta->arg_constant.found) { 11530 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11531 return -EFAULT; 11532 } 11533 if (!tnum_is_const(reg->var_off)) { 11534 verbose(env, "R%d must be a known constant\n", regno); 11535 return -EINVAL; 11536 } 11537 ret = mark_chain_precision(env, regno); 11538 if (ret < 0) 11539 return ret; 11540 meta->arg_constant.found = true; 11541 meta->arg_constant.value = reg->var_off.value; 11542 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 11543 meta->r0_rdonly = true; 11544 is_ret_buf_sz = true; 11545 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 11546 is_ret_buf_sz = true; 11547 } 11548 11549 if (is_ret_buf_sz) { 11550 if (meta->r0_size) { 11551 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 11552 return -EINVAL; 11553 } 11554 11555 if (!tnum_is_const(reg->var_off)) { 11556 verbose(env, "R%d is not a const\n", regno); 11557 return -EINVAL; 11558 } 11559 11560 meta->r0_size = reg->var_off.value; 11561 ret = mark_chain_precision(env, regno); 11562 if (ret) 11563 return ret; 11564 } 11565 continue; 11566 } 11567 11568 if (!btf_type_is_ptr(t)) { 11569 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 11570 return -EINVAL; 11571 } 11572 11573 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 11574 (register_is_null(reg) || type_may_be_null(reg->type)) && 11575 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 11576 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 11577 return -EACCES; 11578 } 11579 11580 if (reg->ref_obj_id) { 11581 if (is_kfunc_release(meta) && meta->ref_obj_id) { 11582 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 11583 regno, reg->ref_obj_id, 11584 meta->ref_obj_id); 11585 return -EFAULT; 11586 } 11587 meta->ref_obj_id = reg->ref_obj_id; 11588 if (is_kfunc_release(meta)) 11589 meta->release_regno = regno; 11590 } 11591 11592 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 11593 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 11594 11595 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 11596 if (kf_arg_type < 0) 11597 return kf_arg_type; 11598 11599 switch (kf_arg_type) { 11600 case KF_ARG_PTR_TO_NULL: 11601 continue; 11602 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11603 case KF_ARG_PTR_TO_BTF_ID: 11604 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 11605 break; 11606 11607 if (!is_trusted_reg(reg)) { 11608 if (!is_kfunc_rcu(meta)) { 11609 verbose(env, "R%d must be referenced or trusted\n", regno); 11610 return -EINVAL; 11611 } 11612 if (!is_rcu_reg(reg)) { 11613 verbose(env, "R%d must be a rcu pointer\n", regno); 11614 return -EINVAL; 11615 } 11616 } 11617 11618 fallthrough; 11619 case KF_ARG_PTR_TO_CTX: 11620 /* Trusted arguments have the same offset checks as release arguments */ 11621 arg_type |= OBJ_RELEASE; 11622 break; 11623 case KF_ARG_PTR_TO_DYNPTR: 11624 case KF_ARG_PTR_TO_ITER: 11625 case KF_ARG_PTR_TO_LIST_HEAD: 11626 case KF_ARG_PTR_TO_LIST_NODE: 11627 case KF_ARG_PTR_TO_RB_ROOT: 11628 case KF_ARG_PTR_TO_RB_NODE: 11629 case KF_ARG_PTR_TO_MEM: 11630 case KF_ARG_PTR_TO_MEM_SIZE: 11631 case KF_ARG_PTR_TO_CALLBACK: 11632 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11633 case KF_ARG_PTR_TO_CONST_STR: 11634 /* Trusted by default */ 11635 break; 11636 default: 11637 WARN_ON_ONCE(1); 11638 return -EFAULT; 11639 } 11640 11641 if (is_kfunc_release(meta) && reg->ref_obj_id) 11642 arg_type |= OBJ_RELEASE; 11643 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 11644 if (ret < 0) 11645 return ret; 11646 11647 switch (kf_arg_type) { 11648 case KF_ARG_PTR_TO_CTX: 11649 if (reg->type != PTR_TO_CTX) { 11650 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 11651 return -EINVAL; 11652 } 11653 11654 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11655 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 11656 if (ret < 0) 11657 return -EINVAL; 11658 meta->ret_btf_id = ret; 11659 } 11660 break; 11661 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11662 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 11663 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) { 11664 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i); 11665 return -EINVAL; 11666 } 11667 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 11668 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 11669 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i); 11670 return -EINVAL; 11671 } 11672 } else { 11673 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11674 return -EINVAL; 11675 } 11676 if (!reg->ref_obj_id) { 11677 verbose(env, "allocated object must be referenced\n"); 11678 return -EINVAL; 11679 } 11680 if (meta->btf == btf_vmlinux) { 11681 meta->arg_btf = reg->btf; 11682 meta->arg_btf_id = reg->btf_id; 11683 } 11684 break; 11685 case KF_ARG_PTR_TO_DYNPTR: 11686 { 11687 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 11688 int clone_ref_obj_id = 0; 11689 11690 if (reg->type != PTR_TO_STACK && 11691 reg->type != CONST_PTR_TO_DYNPTR) { 11692 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 11693 return -EINVAL; 11694 } 11695 11696 if (reg->type == CONST_PTR_TO_DYNPTR) 11697 dynptr_arg_type |= MEM_RDONLY; 11698 11699 if (is_kfunc_arg_uninit(btf, &args[i])) 11700 dynptr_arg_type |= MEM_UNINIT; 11701 11702 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 11703 dynptr_arg_type |= DYNPTR_TYPE_SKB; 11704 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 11705 dynptr_arg_type |= DYNPTR_TYPE_XDP; 11706 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 11707 (dynptr_arg_type & MEM_UNINIT)) { 11708 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 11709 11710 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 11711 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 11712 return -EFAULT; 11713 } 11714 11715 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 11716 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 11717 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 11718 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 11719 return -EFAULT; 11720 } 11721 } 11722 11723 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 11724 if (ret < 0) 11725 return ret; 11726 11727 if (!(dynptr_arg_type & MEM_UNINIT)) { 11728 int id = dynptr_id(env, reg); 11729 11730 if (id < 0) { 11731 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 11732 return id; 11733 } 11734 meta->initialized_dynptr.id = id; 11735 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 11736 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 11737 } 11738 11739 break; 11740 } 11741 case KF_ARG_PTR_TO_ITER: 11742 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 11743 if (!check_css_task_iter_allowlist(env)) { 11744 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 11745 return -EINVAL; 11746 } 11747 } 11748 ret = process_iter_arg(env, regno, insn_idx, meta); 11749 if (ret < 0) 11750 return ret; 11751 break; 11752 case KF_ARG_PTR_TO_LIST_HEAD: 11753 if (reg->type != PTR_TO_MAP_VALUE && 11754 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11755 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11756 return -EINVAL; 11757 } 11758 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11759 verbose(env, "allocated object must be referenced\n"); 11760 return -EINVAL; 11761 } 11762 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 11763 if (ret < 0) 11764 return ret; 11765 break; 11766 case KF_ARG_PTR_TO_RB_ROOT: 11767 if (reg->type != PTR_TO_MAP_VALUE && 11768 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11769 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11770 return -EINVAL; 11771 } 11772 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11773 verbose(env, "allocated object must be referenced\n"); 11774 return -EINVAL; 11775 } 11776 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 11777 if (ret < 0) 11778 return ret; 11779 break; 11780 case KF_ARG_PTR_TO_LIST_NODE: 11781 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11782 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11783 return -EINVAL; 11784 } 11785 if (!reg->ref_obj_id) { 11786 verbose(env, "allocated object must be referenced\n"); 11787 return -EINVAL; 11788 } 11789 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 11790 if (ret < 0) 11791 return ret; 11792 break; 11793 case KF_ARG_PTR_TO_RB_NODE: 11794 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 11795 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 11796 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 11797 return -EINVAL; 11798 } 11799 if (in_rbtree_lock_required_cb(env)) { 11800 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 11801 return -EINVAL; 11802 } 11803 } else { 11804 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11805 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11806 return -EINVAL; 11807 } 11808 if (!reg->ref_obj_id) { 11809 verbose(env, "allocated object must be referenced\n"); 11810 return -EINVAL; 11811 } 11812 } 11813 11814 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 11815 if (ret < 0) 11816 return ret; 11817 break; 11818 case KF_ARG_PTR_TO_BTF_ID: 11819 /* Only base_type is checked, further checks are done here */ 11820 if ((base_type(reg->type) != PTR_TO_BTF_ID || 11821 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 11822 !reg2btf_ids[base_type(reg->type)]) { 11823 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 11824 verbose(env, "expected %s or socket\n", 11825 reg_type_str(env, base_type(reg->type) | 11826 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 11827 return -EINVAL; 11828 } 11829 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 11830 if (ret < 0) 11831 return ret; 11832 break; 11833 case KF_ARG_PTR_TO_MEM: 11834 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 11835 if (IS_ERR(resolve_ret)) { 11836 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 11837 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 11838 return -EINVAL; 11839 } 11840 ret = check_mem_reg(env, reg, regno, type_size); 11841 if (ret < 0) 11842 return ret; 11843 break; 11844 case KF_ARG_PTR_TO_MEM_SIZE: 11845 { 11846 struct bpf_reg_state *buff_reg = ®s[regno]; 11847 const struct btf_param *buff_arg = &args[i]; 11848 struct bpf_reg_state *size_reg = ®s[regno + 1]; 11849 const struct btf_param *size_arg = &args[i + 1]; 11850 11851 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 11852 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 11853 if (ret < 0) { 11854 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 11855 return ret; 11856 } 11857 } 11858 11859 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 11860 if (meta->arg_constant.found) { 11861 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11862 return -EFAULT; 11863 } 11864 if (!tnum_is_const(size_reg->var_off)) { 11865 verbose(env, "R%d must be a known constant\n", regno + 1); 11866 return -EINVAL; 11867 } 11868 meta->arg_constant.found = true; 11869 meta->arg_constant.value = size_reg->var_off.value; 11870 } 11871 11872 /* Skip next '__sz' or '__szk' argument */ 11873 i++; 11874 break; 11875 } 11876 case KF_ARG_PTR_TO_CALLBACK: 11877 if (reg->type != PTR_TO_FUNC) { 11878 verbose(env, "arg%d expected pointer to func\n", i); 11879 return -EINVAL; 11880 } 11881 meta->subprogno = reg->subprogno; 11882 break; 11883 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11884 if (!type_is_ptr_alloc_obj(reg->type)) { 11885 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 11886 return -EINVAL; 11887 } 11888 if (!type_is_non_owning_ref(reg->type)) 11889 meta->arg_owning_ref = true; 11890 11891 rec = reg_btf_record(reg); 11892 if (!rec) { 11893 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 11894 return -EFAULT; 11895 } 11896 11897 if (rec->refcount_off < 0) { 11898 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 11899 return -EINVAL; 11900 } 11901 11902 meta->arg_btf = reg->btf; 11903 meta->arg_btf_id = reg->btf_id; 11904 break; 11905 case KF_ARG_PTR_TO_CONST_STR: 11906 if (reg->type != PTR_TO_MAP_VALUE) { 11907 verbose(env, "arg#%d doesn't point to a const string\n", i); 11908 return -EINVAL; 11909 } 11910 ret = check_reg_const_str(env, reg, regno); 11911 if (ret) 11912 return ret; 11913 break; 11914 } 11915 } 11916 11917 if (is_kfunc_release(meta) && !meta->release_regno) { 11918 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 11919 func_name); 11920 return -EINVAL; 11921 } 11922 11923 return 0; 11924 } 11925 11926 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 11927 struct bpf_insn *insn, 11928 struct bpf_kfunc_call_arg_meta *meta, 11929 const char **kfunc_name) 11930 { 11931 const struct btf_type *func, *func_proto; 11932 u32 func_id, *kfunc_flags; 11933 const char *func_name; 11934 struct btf *desc_btf; 11935 11936 if (kfunc_name) 11937 *kfunc_name = NULL; 11938 11939 if (!insn->imm) 11940 return -EINVAL; 11941 11942 desc_btf = find_kfunc_desc_btf(env, insn->off); 11943 if (IS_ERR(desc_btf)) 11944 return PTR_ERR(desc_btf); 11945 11946 func_id = insn->imm; 11947 func = btf_type_by_id(desc_btf, func_id); 11948 func_name = btf_name_by_offset(desc_btf, func->name_off); 11949 if (kfunc_name) 11950 *kfunc_name = func_name; 11951 func_proto = btf_type_by_id(desc_btf, func->type); 11952 11953 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 11954 if (!kfunc_flags) { 11955 return -EACCES; 11956 } 11957 11958 memset(meta, 0, sizeof(*meta)); 11959 meta->btf = desc_btf; 11960 meta->func_id = func_id; 11961 meta->kfunc_flags = *kfunc_flags; 11962 meta->func_proto = func_proto; 11963 meta->func_name = func_name; 11964 11965 return 0; 11966 } 11967 11968 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 11969 11970 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 11971 int *insn_idx_p) 11972 { 11973 const struct btf_type *t, *ptr_type; 11974 u32 i, nargs, ptr_type_id, release_ref_obj_id; 11975 struct bpf_reg_state *regs = cur_regs(env); 11976 const char *func_name, *ptr_type_name; 11977 bool sleepable, rcu_lock, rcu_unlock; 11978 struct bpf_kfunc_call_arg_meta meta; 11979 struct bpf_insn_aux_data *insn_aux; 11980 int err, insn_idx = *insn_idx_p; 11981 const struct btf_param *args; 11982 const struct btf_type *ret_t; 11983 struct btf *desc_btf; 11984 11985 /* skip for now, but return error when we find this in fixup_kfunc_call */ 11986 if (!insn->imm) 11987 return 0; 11988 11989 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 11990 if (err == -EACCES && func_name) 11991 verbose(env, "calling kernel function %s is not allowed\n", func_name); 11992 if (err) 11993 return err; 11994 desc_btf = meta.btf; 11995 insn_aux = &env->insn_aux_data[insn_idx]; 11996 11997 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 11998 11999 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 12000 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 12001 return -EACCES; 12002 } 12003 12004 sleepable = is_kfunc_sleepable(&meta); 12005 if (sleepable && !env->prog->aux->sleepable) { 12006 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 12007 return -EACCES; 12008 } 12009 12010 /* Check the arguments */ 12011 err = check_kfunc_args(env, &meta, insn_idx); 12012 if (err < 0) 12013 return err; 12014 12015 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12016 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12017 set_rbtree_add_callback_state); 12018 if (err) { 12019 verbose(env, "kfunc %s#%d failed callback verification\n", 12020 func_name, meta.func_id); 12021 return err; 12022 } 12023 } 12024 12025 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 12026 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 12027 12028 if (env->cur_state->active_rcu_lock) { 12029 struct bpf_func_state *state; 12030 struct bpf_reg_state *reg; 12031 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 12032 12033 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 12034 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 12035 return -EACCES; 12036 } 12037 12038 if (rcu_lock) { 12039 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 12040 return -EINVAL; 12041 } else if (rcu_unlock) { 12042 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({ 12043 if (reg->type & MEM_RCU) { 12044 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 12045 reg->type |= PTR_UNTRUSTED; 12046 } 12047 })); 12048 env->cur_state->active_rcu_lock = false; 12049 } else if (sleepable) { 12050 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 12051 return -EACCES; 12052 } 12053 } else if (rcu_lock) { 12054 env->cur_state->active_rcu_lock = true; 12055 } else if (rcu_unlock) { 12056 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 12057 return -EINVAL; 12058 } 12059 12060 /* In case of release function, we get register number of refcounted 12061 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 12062 */ 12063 if (meta.release_regno) { 12064 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 12065 if (err) { 12066 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12067 func_name, meta.func_id); 12068 return err; 12069 } 12070 } 12071 12072 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 12073 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 12074 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12075 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 12076 insn_aux->insert_off = regs[BPF_REG_2].off; 12077 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 12078 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 12079 if (err) { 12080 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 12081 func_name, meta.func_id); 12082 return err; 12083 } 12084 12085 err = release_reference(env, release_ref_obj_id); 12086 if (err) { 12087 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12088 func_name, meta.func_id); 12089 return err; 12090 } 12091 } 12092 12093 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 12094 if (!bpf_jit_supports_exceptions()) { 12095 verbose(env, "JIT does not support calling kfunc %s#%d\n", 12096 func_name, meta.func_id); 12097 return -ENOTSUPP; 12098 } 12099 env->seen_exception = true; 12100 12101 /* In the case of the default callback, the cookie value passed 12102 * to bpf_throw becomes the return value of the program. 12103 */ 12104 if (!env->exception_callback_subprog) { 12105 err = check_return_code(env, BPF_REG_1, "R1"); 12106 if (err < 0) 12107 return err; 12108 } 12109 } 12110 12111 for (i = 0; i < CALLER_SAVED_REGS; i++) 12112 mark_reg_not_init(env, regs, caller_saved[i]); 12113 12114 /* Check return type */ 12115 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 12116 12117 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 12118 /* Only exception is bpf_obj_new_impl */ 12119 if (meta.btf != btf_vmlinux || 12120 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 12121 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] && 12122 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 12123 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 12124 return -EINVAL; 12125 } 12126 } 12127 12128 if (btf_type_is_scalar(t)) { 12129 mark_reg_unknown(env, regs, BPF_REG_0); 12130 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 12131 } else if (btf_type_is_ptr(t)) { 12132 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 12133 12134 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12135 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 12136 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12137 struct btf_struct_meta *struct_meta; 12138 struct btf *ret_btf; 12139 u32 ret_btf_id; 12140 12141 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set) 12142 return -ENOMEM; 12143 12144 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 12145 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 12146 return -EINVAL; 12147 } 12148 12149 ret_btf = env->prog->aux->btf; 12150 ret_btf_id = meta.arg_constant.value; 12151 12152 /* This may be NULL due to user not supplying a BTF */ 12153 if (!ret_btf) { 12154 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 12155 return -EINVAL; 12156 } 12157 12158 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 12159 if (!ret_t || !__btf_type_is_struct(ret_t)) { 12160 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 12161 return -EINVAL; 12162 } 12163 12164 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12165 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 12166 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 12167 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 12168 return -EINVAL; 12169 } 12170 12171 if (!bpf_global_percpu_ma_set) { 12172 mutex_lock(&bpf_percpu_ma_lock); 12173 if (!bpf_global_percpu_ma_set) { 12174 /* Charge memory allocated with bpf_global_percpu_ma to 12175 * root memcg. The obj_cgroup for root memcg is NULL. 12176 */ 12177 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 12178 if (!err) 12179 bpf_global_percpu_ma_set = true; 12180 } 12181 mutex_unlock(&bpf_percpu_ma_lock); 12182 if (err) 12183 return err; 12184 } 12185 12186 mutex_lock(&bpf_percpu_ma_lock); 12187 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 12188 mutex_unlock(&bpf_percpu_ma_lock); 12189 if (err) 12190 return err; 12191 } 12192 12193 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 12194 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12195 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 12196 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 12197 return -EINVAL; 12198 } 12199 12200 if (struct_meta) { 12201 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 12202 return -EINVAL; 12203 } 12204 } 12205 12206 mark_reg_known_zero(env, regs, BPF_REG_0); 12207 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12208 regs[BPF_REG_0].btf = ret_btf; 12209 regs[BPF_REG_0].btf_id = ret_btf_id; 12210 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) 12211 regs[BPF_REG_0].type |= MEM_PERCPU; 12212 12213 insn_aux->obj_new_size = ret_t->size; 12214 insn_aux->kptr_struct_meta = struct_meta; 12215 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 12216 mark_reg_known_zero(env, regs, BPF_REG_0); 12217 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12218 regs[BPF_REG_0].btf = meta.arg_btf; 12219 regs[BPF_REG_0].btf_id = meta.arg_btf_id; 12220 12221 insn_aux->kptr_struct_meta = 12222 btf_find_struct_meta(meta.arg_btf, 12223 meta.arg_btf_id); 12224 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 12225 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 12226 struct btf_field *field = meta.arg_list_head.field; 12227 12228 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12229 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12230 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12231 struct btf_field *field = meta.arg_rbtree_root.field; 12232 12233 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12234 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12235 mark_reg_known_zero(env, regs, BPF_REG_0); 12236 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 12237 regs[BPF_REG_0].btf = desc_btf; 12238 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 12239 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 12240 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 12241 if (!ret_t || !btf_type_is_struct(ret_t)) { 12242 verbose(env, 12243 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 12244 return -EINVAL; 12245 } 12246 12247 mark_reg_known_zero(env, regs, BPF_REG_0); 12248 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 12249 regs[BPF_REG_0].btf = desc_btf; 12250 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 12251 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 12252 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 12253 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 12254 12255 mark_reg_known_zero(env, regs, BPF_REG_0); 12256 12257 if (!meta.arg_constant.found) { 12258 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 12259 return -EFAULT; 12260 } 12261 12262 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 12263 12264 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 12265 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 12266 12267 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 12268 regs[BPF_REG_0].type |= MEM_RDONLY; 12269 } else { 12270 /* this will set env->seen_direct_write to true */ 12271 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 12272 verbose(env, "the prog does not allow writes to packet data\n"); 12273 return -EINVAL; 12274 } 12275 } 12276 12277 if (!meta.initialized_dynptr.id) { 12278 verbose(env, "verifier internal error: no dynptr id\n"); 12279 return -EFAULT; 12280 } 12281 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 12282 12283 /* we don't need to set BPF_REG_0's ref obj id 12284 * because packet slices are not refcounted (see 12285 * dynptr_type_refcounted) 12286 */ 12287 } else { 12288 verbose(env, "kernel function %s unhandled dynamic return type\n", 12289 meta.func_name); 12290 return -EFAULT; 12291 } 12292 } else if (!__btf_type_is_struct(ptr_type)) { 12293 if (!meta.r0_size) { 12294 __u32 sz; 12295 12296 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 12297 meta.r0_size = sz; 12298 meta.r0_rdonly = true; 12299 } 12300 } 12301 if (!meta.r0_size) { 12302 ptr_type_name = btf_name_by_offset(desc_btf, 12303 ptr_type->name_off); 12304 verbose(env, 12305 "kernel function %s returns pointer type %s %s is not supported\n", 12306 func_name, 12307 btf_type_str(ptr_type), 12308 ptr_type_name); 12309 return -EINVAL; 12310 } 12311 12312 mark_reg_known_zero(env, regs, BPF_REG_0); 12313 regs[BPF_REG_0].type = PTR_TO_MEM; 12314 regs[BPF_REG_0].mem_size = meta.r0_size; 12315 12316 if (meta.r0_rdonly) 12317 regs[BPF_REG_0].type |= MEM_RDONLY; 12318 12319 /* Ensures we don't access the memory after a release_reference() */ 12320 if (meta.ref_obj_id) 12321 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 12322 } else { 12323 mark_reg_known_zero(env, regs, BPF_REG_0); 12324 regs[BPF_REG_0].btf = desc_btf; 12325 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 12326 regs[BPF_REG_0].btf_id = ptr_type_id; 12327 } 12328 12329 if (is_kfunc_ret_null(&meta)) { 12330 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 12331 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 12332 regs[BPF_REG_0].id = ++env->id_gen; 12333 } 12334 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 12335 if (is_kfunc_acquire(&meta)) { 12336 int id = acquire_reference_state(env, insn_idx); 12337 12338 if (id < 0) 12339 return id; 12340 if (is_kfunc_ret_null(&meta)) 12341 regs[BPF_REG_0].id = id; 12342 regs[BPF_REG_0].ref_obj_id = id; 12343 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12344 ref_set_non_owning(env, ®s[BPF_REG_0]); 12345 } 12346 12347 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 12348 regs[BPF_REG_0].id = ++env->id_gen; 12349 } else if (btf_type_is_void(t)) { 12350 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12351 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 12352 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 12353 insn_aux->kptr_struct_meta = 12354 btf_find_struct_meta(meta.arg_btf, 12355 meta.arg_btf_id); 12356 } 12357 } 12358 } 12359 12360 nargs = btf_type_vlen(meta.func_proto); 12361 args = (const struct btf_param *)(meta.func_proto + 1); 12362 for (i = 0; i < nargs; i++) { 12363 u32 regno = i + 1; 12364 12365 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 12366 if (btf_type_is_ptr(t)) 12367 mark_btf_func_reg_size(env, regno, sizeof(void *)); 12368 else 12369 /* scalar. ensured by btf_check_kfunc_arg_match() */ 12370 mark_btf_func_reg_size(env, regno, t->size); 12371 } 12372 12373 if (is_iter_next_kfunc(&meta)) { 12374 err = process_iter_next_call(env, insn_idx, &meta); 12375 if (err) 12376 return err; 12377 } 12378 12379 return 0; 12380 } 12381 12382 static bool signed_add_overflows(s64 a, s64 b) 12383 { 12384 /* Do the add in u64, where overflow is well-defined */ 12385 s64 res = (s64)((u64)a + (u64)b); 12386 12387 if (b < 0) 12388 return res > a; 12389 return res < a; 12390 } 12391 12392 static bool signed_add32_overflows(s32 a, s32 b) 12393 { 12394 /* Do the add in u32, where overflow is well-defined */ 12395 s32 res = (s32)((u32)a + (u32)b); 12396 12397 if (b < 0) 12398 return res > a; 12399 return res < a; 12400 } 12401 12402 static bool signed_sub_overflows(s64 a, s64 b) 12403 { 12404 /* Do the sub in u64, where overflow is well-defined */ 12405 s64 res = (s64)((u64)a - (u64)b); 12406 12407 if (b < 0) 12408 return res < a; 12409 return res > a; 12410 } 12411 12412 static bool signed_sub32_overflows(s32 a, s32 b) 12413 { 12414 /* Do the sub in u32, where overflow is well-defined */ 12415 s32 res = (s32)((u32)a - (u32)b); 12416 12417 if (b < 0) 12418 return res < a; 12419 return res > a; 12420 } 12421 12422 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 12423 const struct bpf_reg_state *reg, 12424 enum bpf_reg_type type) 12425 { 12426 bool known = tnum_is_const(reg->var_off); 12427 s64 val = reg->var_off.value; 12428 s64 smin = reg->smin_value; 12429 12430 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 12431 verbose(env, "math between %s pointer and %lld is not allowed\n", 12432 reg_type_str(env, type), val); 12433 return false; 12434 } 12435 12436 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 12437 verbose(env, "%s pointer offset %d is not allowed\n", 12438 reg_type_str(env, type), reg->off); 12439 return false; 12440 } 12441 12442 if (smin == S64_MIN) { 12443 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 12444 reg_type_str(env, type)); 12445 return false; 12446 } 12447 12448 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 12449 verbose(env, "value %lld makes %s pointer be out of bounds\n", 12450 smin, reg_type_str(env, type)); 12451 return false; 12452 } 12453 12454 return true; 12455 } 12456 12457 enum { 12458 REASON_BOUNDS = -1, 12459 REASON_TYPE = -2, 12460 REASON_PATHS = -3, 12461 REASON_LIMIT = -4, 12462 REASON_STACK = -5, 12463 }; 12464 12465 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 12466 u32 *alu_limit, bool mask_to_left) 12467 { 12468 u32 max = 0, ptr_limit = 0; 12469 12470 switch (ptr_reg->type) { 12471 case PTR_TO_STACK: 12472 /* Offset 0 is out-of-bounds, but acceptable start for the 12473 * left direction, see BPF_REG_FP. Also, unknown scalar 12474 * offset where we would need to deal with min/max bounds is 12475 * currently prohibited for unprivileged. 12476 */ 12477 max = MAX_BPF_STACK + mask_to_left; 12478 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 12479 break; 12480 case PTR_TO_MAP_VALUE: 12481 max = ptr_reg->map_ptr->value_size; 12482 ptr_limit = (mask_to_left ? 12483 ptr_reg->smin_value : 12484 ptr_reg->umax_value) + ptr_reg->off; 12485 break; 12486 default: 12487 return REASON_TYPE; 12488 } 12489 12490 if (ptr_limit >= max) 12491 return REASON_LIMIT; 12492 *alu_limit = ptr_limit; 12493 return 0; 12494 } 12495 12496 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 12497 const struct bpf_insn *insn) 12498 { 12499 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 12500 } 12501 12502 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 12503 u32 alu_state, u32 alu_limit) 12504 { 12505 /* If we arrived here from different branches with different 12506 * state or limits to sanitize, then this won't work. 12507 */ 12508 if (aux->alu_state && 12509 (aux->alu_state != alu_state || 12510 aux->alu_limit != alu_limit)) 12511 return REASON_PATHS; 12512 12513 /* Corresponding fixup done in do_misc_fixups(). */ 12514 aux->alu_state = alu_state; 12515 aux->alu_limit = alu_limit; 12516 return 0; 12517 } 12518 12519 static int sanitize_val_alu(struct bpf_verifier_env *env, 12520 struct bpf_insn *insn) 12521 { 12522 struct bpf_insn_aux_data *aux = cur_aux(env); 12523 12524 if (can_skip_alu_sanitation(env, insn)) 12525 return 0; 12526 12527 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 12528 } 12529 12530 static bool sanitize_needed(u8 opcode) 12531 { 12532 return opcode == BPF_ADD || opcode == BPF_SUB; 12533 } 12534 12535 struct bpf_sanitize_info { 12536 struct bpf_insn_aux_data aux; 12537 bool mask_to_left; 12538 }; 12539 12540 static struct bpf_verifier_state * 12541 sanitize_speculative_path(struct bpf_verifier_env *env, 12542 const struct bpf_insn *insn, 12543 u32 next_idx, u32 curr_idx) 12544 { 12545 struct bpf_verifier_state *branch; 12546 struct bpf_reg_state *regs; 12547 12548 branch = push_stack(env, next_idx, curr_idx, true); 12549 if (branch && insn) { 12550 regs = branch->frame[branch->curframe]->regs; 12551 if (BPF_SRC(insn->code) == BPF_K) { 12552 mark_reg_unknown(env, regs, insn->dst_reg); 12553 } else if (BPF_SRC(insn->code) == BPF_X) { 12554 mark_reg_unknown(env, regs, insn->dst_reg); 12555 mark_reg_unknown(env, regs, insn->src_reg); 12556 } 12557 } 12558 return branch; 12559 } 12560 12561 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 12562 struct bpf_insn *insn, 12563 const struct bpf_reg_state *ptr_reg, 12564 const struct bpf_reg_state *off_reg, 12565 struct bpf_reg_state *dst_reg, 12566 struct bpf_sanitize_info *info, 12567 const bool commit_window) 12568 { 12569 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 12570 struct bpf_verifier_state *vstate = env->cur_state; 12571 bool off_is_imm = tnum_is_const(off_reg->var_off); 12572 bool off_is_neg = off_reg->smin_value < 0; 12573 bool ptr_is_dst_reg = ptr_reg == dst_reg; 12574 u8 opcode = BPF_OP(insn->code); 12575 u32 alu_state, alu_limit; 12576 struct bpf_reg_state tmp; 12577 bool ret; 12578 int err; 12579 12580 if (can_skip_alu_sanitation(env, insn)) 12581 return 0; 12582 12583 /* We already marked aux for masking from non-speculative 12584 * paths, thus we got here in the first place. We only care 12585 * to explore bad access from here. 12586 */ 12587 if (vstate->speculative) 12588 goto do_sim; 12589 12590 if (!commit_window) { 12591 if (!tnum_is_const(off_reg->var_off) && 12592 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 12593 return REASON_BOUNDS; 12594 12595 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 12596 (opcode == BPF_SUB && !off_is_neg); 12597 } 12598 12599 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 12600 if (err < 0) 12601 return err; 12602 12603 if (commit_window) { 12604 /* In commit phase we narrow the masking window based on 12605 * the observed pointer move after the simulated operation. 12606 */ 12607 alu_state = info->aux.alu_state; 12608 alu_limit = abs(info->aux.alu_limit - alu_limit); 12609 } else { 12610 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 12611 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 12612 alu_state |= ptr_is_dst_reg ? 12613 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 12614 12615 /* Limit pruning on unknown scalars to enable deep search for 12616 * potential masking differences from other program paths. 12617 */ 12618 if (!off_is_imm) 12619 env->explore_alu_limits = true; 12620 } 12621 12622 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 12623 if (err < 0) 12624 return err; 12625 do_sim: 12626 /* If we're in commit phase, we're done here given we already 12627 * pushed the truncated dst_reg into the speculative verification 12628 * stack. 12629 * 12630 * Also, when register is a known constant, we rewrite register-based 12631 * operation to immediate-based, and thus do not need masking (and as 12632 * a consequence, do not need to simulate the zero-truncation either). 12633 */ 12634 if (commit_window || off_is_imm) 12635 return 0; 12636 12637 /* Simulate and find potential out-of-bounds access under 12638 * speculative execution from truncation as a result of 12639 * masking when off was not within expected range. If off 12640 * sits in dst, then we temporarily need to move ptr there 12641 * to simulate dst (== 0) +/-= ptr. Needed, for example, 12642 * for cases where we use K-based arithmetic in one direction 12643 * and truncated reg-based in the other in order to explore 12644 * bad access. 12645 */ 12646 if (!ptr_is_dst_reg) { 12647 tmp = *dst_reg; 12648 copy_register_state(dst_reg, ptr_reg); 12649 } 12650 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 12651 env->insn_idx); 12652 if (!ptr_is_dst_reg && ret) 12653 *dst_reg = tmp; 12654 return !ret ? REASON_STACK : 0; 12655 } 12656 12657 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 12658 { 12659 struct bpf_verifier_state *vstate = env->cur_state; 12660 12661 /* If we simulate paths under speculation, we don't update the 12662 * insn as 'seen' such that when we verify unreachable paths in 12663 * the non-speculative domain, sanitize_dead_code() can still 12664 * rewrite/sanitize them. 12665 */ 12666 if (!vstate->speculative) 12667 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 12668 } 12669 12670 static int sanitize_err(struct bpf_verifier_env *env, 12671 const struct bpf_insn *insn, int reason, 12672 const struct bpf_reg_state *off_reg, 12673 const struct bpf_reg_state *dst_reg) 12674 { 12675 static const char *err = "pointer arithmetic with it prohibited for !root"; 12676 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 12677 u32 dst = insn->dst_reg, src = insn->src_reg; 12678 12679 switch (reason) { 12680 case REASON_BOUNDS: 12681 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 12682 off_reg == dst_reg ? dst : src, err); 12683 break; 12684 case REASON_TYPE: 12685 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 12686 off_reg == dst_reg ? src : dst, err); 12687 break; 12688 case REASON_PATHS: 12689 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 12690 dst, op, err); 12691 break; 12692 case REASON_LIMIT: 12693 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 12694 dst, op, err); 12695 break; 12696 case REASON_STACK: 12697 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 12698 dst, err); 12699 break; 12700 default: 12701 verbose(env, "verifier internal error: unknown reason (%d)\n", 12702 reason); 12703 break; 12704 } 12705 12706 return -EACCES; 12707 } 12708 12709 /* check that stack access falls within stack limits and that 'reg' doesn't 12710 * have a variable offset. 12711 * 12712 * Variable offset is prohibited for unprivileged mode for simplicity since it 12713 * requires corresponding support in Spectre masking for stack ALU. See also 12714 * retrieve_ptr_limit(). 12715 * 12716 * 12717 * 'off' includes 'reg->off'. 12718 */ 12719 static int check_stack_access_for_ptr_arithmetic( 12720 struct bpf_verifier_env *env, 12721 int regno, 12722 const struct bpf_reg_state *reg, 12723 int off) 12724 { 12725 if (!tnum_is_const(reg->var_off)) { 12726 char tn_buf[48]; 12727 12728 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 12729 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 12730 regno, tn_buf, off); 12731 return -EACCES; 12732 } 12733 12734 if (off >= 0 || off < -MAX_BPF_STACK) { 12735 verbose(env, "R%d stack pointer arithmetic goes out of range, " 12736 "prohibited for !root; off=%d\n", regno, off); 12737 return -EACCES; 12738 } 12739 12740 return 0; 12741 } 12742 12743 static int sanitize_check_bounds(struct bpf_verifier_env *env, 12744 const struct bpf_insn *insn, 12745 const struct bpf_reg_state *dst_reg) 12746 { 12747 u32 dst = insn->dst_reg; 12748 12749 /* For unprivileged we require that resulting offset must be in bounds 12750 * in order to be able to sanitize access later on. 12751 */ 12752 if (env->bypass_spec_v1) 12753 return 0; 12754 12755 switch (dst_reg->type) { 12756 case PTR_TO_STACK: 12757 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 12758 dst_reg->off + dst_reg->var_off.value)) 12759 return -EACCES; 12760 break; 12761 case PTR_TO_MAP_VALUE: 12762 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 12763 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 12764 "prohibited for !root\n", dst); 12765 return -EACCES; 12766 } 12767 break; 12768 default: 12769 break; 12770 } 12771 12772 return 0; 12773 } 12774 12775 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 12776 * Caller should also handle BPF_MOV case separately. 12777 * If we return -EACCES, caller may want to try again treating pointer as a 12778 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 12779 */ 12780 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 12781 struct bpf_insn *insn, 12782 const struct bpf_reg_state *ptr_reg, 12783 const struct bpf_reg_state *off_reg) 12784 { 12785 struct bpf_verifier_state *vstate = env->cur_state; 12786 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 12787 struct bpf_reg_state *regs = state->regs, *dst_reg; 12788 bool known = tnum_is_const(off_reg->var_off); 12789 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 12790 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 12791 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 12792 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 12793 struct bpf_sanitize_info info = {}; 12794 u8 opcode = BPF_OP(insn->code); 12795 u32 dst = insn->dst_reg; 12796 int ret; 12797 12798 dst_reg = ®s[dst]; 12799 12800 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 12801 smin_val > smax_val || umin_val > umax_val) { 12802 /* Taint dst register if offset had invalid bounds derived from 12803 * e.g. dead branches. 12804 */ 12805 __mark_reg_unknown(env, dst_reg); 12806 return 0; 12807 } 12808 12809 if (BPF_CLASS(insn->code) != BPF_ALU64) { 12810 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 12811 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 12812 __mark_reg_unknown(env, dst_reg); 12813 return 0; 12814 } 12815 12816 verbose(env, 12817 "R%d 32-bit pointer arithmetic prohibited\n", 12818 dst); 12819 return -EACCES; 12820 } 12821 12822 if (ptr_reg->type & PTR_MAYBE_NULL) { 12823 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 12824 dst, reg_type_str(env, ptr_reg->type)); 12825 return -EACCES; 12826 } 12827 12828 switch (base_type(ptr_reg->type)) { 12829 case CONST_PTR_TO_MAP: 12830 /* smin_val represents the known value */ 12831 if (known && smin_val == 0 && opcode == BPF_ADD) 12832 break; 12833 fallthrough; 12834 case PTR_TO_PACKET_END: 12835 case PTR_TO_SOCKET: 12836 case PTR_TO_SOCK_COMMON: 12837 case PTR_TO_TCP_SOCK: 12838 case PTR_TO_XDP_SOCK: 12839 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 12840 dst, reg_type_str(env, ptr_reg->type)); 12841 return -EACCES; 12842 default: 12843 break; 12844 } 12845 12846 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 12847 * The id may be overwritten later if we create a new variable offset. 12848 */ 12849 dst_reg->type = ptr_reg->type; 12850 dst_reg->id = ptr_reg->id; 12851 12852 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 12853 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 12854 return -EINVAL; 12855 12856 /* pointer types do not carry 32-bit bounds at the moment. */ 12857 __mark_reg32_unbounded(dst_reg); 12858 12859 if (sanitize_needed(opcode)) { 12860 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 12861 &info, false); 12862 if (ret < 0) 12863 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12864 } 12865 12866 switch (opcode) { 12867 case BPF_ADD: 12868 /* We can take a fixed offset as long as it doesn't overflow 12869 * the s32 'off' field 12870 */ 12871 if (known && (ptr_reg->off + smin_val == 12872 (s64)(s32)(ptr_reg->off + smin_val))) { 12873 /* pointer += K. Accumulate it into fixed offset */ 12874 dst_reg->smin_value = smin_ptr; 12875 dst_reg->smax_value = smax_ptr; 12876 dst_reg->umin_value = umin_ptr; 12877 dst_reg->umax_value = umax_ptr; 12878 dst_reg->var_off = ptr_reg->var_off; 12879 dst_reg->off = ptr_reg->off + smin_val; 12880 dst_reg->raw = ptr_reg->raw; 12881 break; 12882 } 12883 /* A new variable offset is created. Note that off_reg->off 12884 * == 0, since it's a scalar. 12885 * dst_reg gets the pointer type and since some positive 12886 * integer value was added to the pointer, give it a new 'id' 12887 * if it's a PTR_TO_PACKET. 12888 * this creates a new 'base' pointer, off_reg (variable) gets 12889 * added into the variable offset, and we copy the fixed offset 12890 * from ptr_reg. 12891 */ 12892 if (signed_add_overflows(smin_ptr, smin_val) || 12893 signed_add_overflows(smax_ptr, smax_val)) { 12894 dst_reg->smin_value = S64_MIN; 12895 dst_reg->smax_value = S64_MAX; 12896 } else { 12897 dst_reg->smin_value = smin_ptr + smin_val; 12898 dst_reg->smax_value = smax_ptr + smax_val; 12899 } 12900 if (umin_ptr + umin_val < umin_ptr || 12901 umax_ptr + umax_val < umax_ptr) { 12902 dst_reg->umin_value = 0; 12903 dst_reg->umax_value = U64_MAX; 12904 } else { 12905 dst_reg->umin_value = umin_ptr + umin_val; 12906 dst_reg->umax_value = umax_ptr + umax_val; 12907 } 12908 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 12909 dst_reg->off = ptr_reg->off; 12910 dst_reg->raw = ptr_reg->raw; 12911 if (reg_is_pkt_pointer(ptr_reg)) { 12912 dst_reg->id = ++env->id_gen; 12913 /* something was added to pkt_ptr, set range to zero */ 12914 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12915 } 12916 break; 12917 case BPF_SUB: 12918 if (dst_reg == off_reg) { 12919 /* scalar -= pointer. Creates an unknown scalar */ 12920 verbose(env, "R%d tried to subtract pointer from scalar\n", 12921 dst); 12922 return -EACCES; 12923 } 12924 /* We don't allow subtraction from FP, because (according to 12925 * test_verifier.c test "invalid fp arithmetic", JITs might not 12926 * be able to deal with it. 12927 */ 12928 if (ptr_reg->type == PTR_TO_STACK) { 12929 verbose(env, "R%d subtraction from stack pointer prohibited\n", 12930 dst); 12931 return -EACCES; 12932 } 12933 if (known && (ptr_reg->off - smin_val == 12934 (s64)(s32)(ptr_reg->off - smin_val))) { 12935 /* pointer -= K. Subtract it from fixed offset */ 12936 dst_reg->smin_value = smin_ptr; 12937 dst_reg->smax_value = smax_ptr; 12938 dst_reg->umin_value = umin_ptr; 12939 dst_reg->umax_value = umax_ptr; 12940 dst_reg->var_off = ptr_reg->var_off; 12941 dst_reg->id = ptr_reg->id; 12942 dst_reg->off = ptr_reg->off - smin_val; 12943 dst_reg->raw = ptr_reg->raw; 12944 break; 12945 } 12946 /* A new variable offset is created. If the subtrahend is known 12947 * nonnegative, then any reg->range we had before is still good. 12948 */ 12949 if (signed_sub_overflows(smin_ptr, smax_val) || 12950 signed_sub_overflows(smax_ptr, smin_val)) { 12951 /* Overflow possible, we know nothing */ 12952 dst_reg->smin_value = S64_MIN; 12953 dst_reg->smax_value = S64_MAX; 12954 } else { 12955 dst_reg->smin_value = smin_ptr - smax_val; 12956 dst_reg->smax_value = smax_ptr - smin_val; 12957 } 12958 if (umin_ptr < umax_val) { 12959 /* Overflow possible, we know nothing */ 12960 dst_reg->umin_value = 0; 12961 dst_reg->umax_value = U64_MAX; 12962 } else { 12963 /* Cannot overflow (as long as bounds are consistent) */ 12964 dst_reg->umin_value = umin_ptr - umax_val; 12965 dst_reg->umax_value = umax_ptr - umin_val; 12966 } 12967 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 12968 dst_reg->off = ptr_reg->off; 12969 dst_reg->raw = ptr_reg->raw; 12970 if (reg_is_pkt_pointer(ptr_reg)) { 12971 dst_reg->id = ++env->id_gen; 12972 /* something was added to pkt_ptr, set range to zero */ 12973 if (smin_val < 0) 12974 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12975 } 12976 break; 12977 case BPF_AND: 12978 case BPF_OR: 12979 case BPF_XOR: 12980 /* bitwise ops on pointers are troublesome, prohibit. */ 12981 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 12982 dst, bpf_alu_string[opcode >> 4]); 12983 return -EACCES; 12984 default: 12985 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 12986 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 12987 dst, bpf_alu_string[opcode >> 4]); 12988 return -EACCES; 12989 } 12990 12991 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 12992 return -EINVAL; 12993 reg_bounds_sync(dst_reg); 12994 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 12995 return -EACCES; 12996 if (sanitize_needed(opcode)) { 12997 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 12998 &info, true); 12999 if (ret < 0) 13000 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13001 } 13002 13003 return 0; 13004 } 13005 13006 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 13007 struct bpf_reg_state *src_reg) 13008 { 13009 s32 smin_val = src_reg->s32_min_value; 13010 s32 smax_val = src_reg->s32_max_value; 13011 u32 umin_val = src_reg->u32_min_value; 13012 u32 umax_val = src_reg->u32_max_value; 13013 13014 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 13015 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 13016 dst_reg->s32_min_value = S32_MIN; 13017 dst_reg->s32_max_value = S32_MAX; 13018 } else { 13019 dst_reg->s32_min_value += smin_val; 13020 dst_reg->s32_max_value += smax_val; 13021 } 13022 if (dst_reg->u32_min_value + umin_val < umin_val || 13023 dst_reg->u32_max_value + umax_val < umax_val) { 13024 dst_reg->u32_min_value = 0; 13025 dst_reg->u32_max_value = U32_MAX; 13026 } else { 13027 dst_reg->u32_min_value += umin_val; 13028 dst_reg->u32_max_value += umax_val; 13029 } 13030 } 13031 13032 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 13033 struct bpf_reg_state *src_reg) 13034 { 13035 s64 smin_val = src_reg->smin_value; 13036 s64 smax_val = src_reg->smax_value; 13037 u64 umin_val = src_reg->umin_value; 13038 u64 umax_val = src_reg->umax_value; 13039 13040 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 13041 signed_add_overflows(dst_reg->smax_value, smax_val)) { 13042 dst_reg->smin_value = S64_MIN; 13043 dst_reg->smax_value = S64_MAX; 13044 } else { 13045 dst_reg->smin_value += smin_val; 13046 dst_reg->smax_value += smax_val; 13047 } 13048 if (dst_reg->umin_value + umin_val < umin_val || 13049 dst_reg->umax_value + umax_val < umax_val) { 13050 dst_reg->umin_value = 0; 13051 dst_reg->umax_value = U64_MAX; 13052 } else { 13053 dst_reg->umin_value += umin_val; 13054 dst_reg->umax_value += umax_val; 13055 } 13056 } 13057 13058 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 13059 struct bpf_reg_state *src_reg) 13060 { 13061 s32 smin_val = src_reg->s32_min_value; 13062 s32 smax_val = src_reg->s32_max_value; 13063 u32 umin_val = src_reg->u32_min_value; 13064 u32 umax_val = src_reg->u32_max_value; 13065 13066 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 13067 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 13068 /* Overflow possible, we know nothing */ 13069 dst_reg->s32_min_value = S32_MIN; 13070 dst_reg->s32_max_value = S32_MAX; 13071 } else { 13072 dst_reg->s32_min_value -= smax_val; 13073 dst_reg->s32_max_value -= smin_val; 13074 } 13075 if (dst_reg->u32_min_value < umax_val) { 13076 /* Overflow possible, we know nothing */ 13077 dst_reg->u32_min_value = 0; 13078 dst_reg->u32_max_value = U32_MAX; 13079 } else { 13080 /* Cannot overflow (as long as bounds are consistent) */ 13081 dst_reg->u32_min_value -= umax_val; 13082 dst_reg->u32_max_value -= umin_val; 13083 } 13084 } 13085 13086 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 13087 struct bpf_reg_state *src_reg) 13088 { 13089 s64 smin_val = src_reg->smin_value; 13090 s64 smax_val = src_reg->smax_value; 13091 u64 umin_val = src_reg->umin_value; 13092 u64 umax_val = src_reg->umax_value; 13093 13094 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 13095 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 13096 /* Overflow possible, we know nothing */ 13097 dst_reg->smin_value = S64_MIN; 13098 dst_reg->smax_value = S64_MAX; 13099 } else { 13100 dst_reg->smin_value -= smax_val; 13101 dst_reg->smax_value -= smin_val; 13102 } 13103 if (dst_reg->umin_value < umax_val) { 13104 /* Overflow possible, we know nothing */ 13105 dst_reg->umin_value = 0; 13106 dst_reg->umax_value = U64_MAX; 13107 } else { 13108 /* Cannot overflow (as long as bounds are consistent) */ 13109 dst_reg->umin_value -= umax_val; 13110 dst_reg->umax_value -= umin_val; 13111 } 13112 } 13113 13114 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 13115 struct bpf_reg_state *src_reg) 13116 { 13117 s32 smin_val = src_reg->s32_min_value; 13118 u32 umin_val = src_reg->u32_min_value; 13119 u32 umax_val = src_reg->u32_max_value; 13120 13121 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 13122 /* Ain't nobody got time to multiply that sign */ 13123 __mark_reg32_unbounded(dst_reg); 13124 return; 13125 } 13126 /* Both values are positive, so we can work with unsigned and 13127 * copy the result to signed (unless it exceeds S32_MAX). 13128 */ 13129 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 13130 /* Potential overflow, we know nothing */ 13131 __mark_reg32_unbounded(dst_reg); 13132 return; 13133 } 13134 dst_reg->u32_min_value *= umin_val; 13135 dst_reg->u32_max_value *= umax_val; 13136 if (dst_reg->u32_max_value > S32_MAX) { 13137 /* Overflow possible, we know nothing */ 13138 dst_reg->s32_min_value = S32_MIN; 13139 dst_reg->s32_max_value = S32_MAX; 13140 } else { 13141 dst_reg->s32_min_value = dst_reg->u32_min_value; 13142 dst_reg->s32_max_value = dst_reg->u32_max_value; 13143 } 13144 } 13145 13146 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 13147 struct bpf_reg_state *src_reg) 13148 { 13149 s64 smin_val = src_reg->smin_value; 13150 u64 umin_val = src_reg->umin_value; 13151 u64 umax_val = src_reg->umax_value; 13152 13153 if (smin_val < 0 || dst_reg->smin_value < 0) { 13154 /* Ain't nobody got time to multiply that sign */ 13155 __mark_reg64_unbounded(dst_reg); 13156 return; 13157 } 13158 /* Both values are positive, so we can work with unsigned and 13159 * copy the result to signed (unless it exceeds S64_MAX). 13160 */ 13161 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 13162 /* Potential overflow, we know nothing */ 13163 __mark_reg64_unbounded(dst_reg); 13164 return; 13165 } 13166 dst_reg->umin_value *= umin_val; 13167 dst_reg->umax_value *= umax_val; 13168 if (dst_reg->umax_value > S64_MAX) { 13169 /* Overflow possible, we know nothing */ 13170 dst_reg->smin_value = S64_MIN; 13171 dst_reg->smax_value = S64_MAX; 13172 } else { 13173 dst_reg->smin_value = dst_reg->umin_value; 13174 dst_reg->smax_value = dst_reg->umax_value; 13175 } 13176 } 13177 13178 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 13179 struct bpf_reg_state *src_reg) 13180 { 13181 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13182 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13183 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13184 s32 smin_val = src_reg->s32_min_value; 13185 u32 umax_val = src_reg->u32_max_value; 13186 13187 if (src_known && dst_known) { 13188 __mark_reg32_known(dst_reg, var32_off.value); 13189 return; 13190 } 13191 13192 /* We get our minimum from the var_off, since that's inherently 13193 * bitwise. Our maximum is the minimum of the operands' maxima. 13194 */ 13195 dst_reg->u32_min_value = var32_off.value; 13196 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 13197 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 13198 /* Lose signed bounds when ANDing negative numbers, 13199 * ain't nobody got time for that. 13200 */ 13201 dst_reg->s32_min_value = S32_MIN; 13202 dst_reg->s32_max_value = S32_MAX; 13203 } else { 13204 /* ANDing two positives gives a positive, so safe to 13205 * cast result into s64. 13206 */ 13207 dst_reg->s32_min_value = dst_reg->u32_min_value; 13208 dst_reg->s32_max_value = dst_reg->u32_max_value; 13209 } 13210 } 13211 13212 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 13213 struct bpf_reg_state *src_reg) 13214 { 13215 bool src_known = tnum_is_const(src_reg->var_off); 13216 bool dst_known = tnum_is_const(dst_reg->var_off); 13217 s64 smin_val = src_reg->smin_value; 13218 u64 umax_val = src_reg->umax_value; 13219 13220 if (src_known && dst_known) { 13221 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13222 return; 13223 } 13224 13225 /* We get our minimum from the var_off, since that's inherently 13226 * bitwise. Our maximum is the minimum of the operands' maxima. 13227 */ 13228 dst_reg->umin_value = dst_reg->var_off.value; 13229 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 13230 if (dst_reg->smin_value < 0 || smin_val < 0) { 13231 /* Lose signed bounds when ANDing negative numbers, 13232 * ain't nobody got time for that. 13233 */ 13234 dst_reg->smin_value = S64_MIN; 13235 dst_reg->smax_value = S64_MAX; 13236 } else { 13237 /* ANDing two positives gives a positive, so safe to 13238 * cast result into s64. 13239 */ 13240 dst_reg->smin_value = dst_reg->umin_value; 13241 dst_reg->smax_value = dst_reg->umax_value; 13242 } 13243 /* We may learn something more from the var_off */ 13244 __update_reg_bounds(dst_reg); 13245 } 13246 13247 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 13248 struct bpf_reg_state *src_reg) 13249 { 13250 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13251 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13252 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13253 s32 smin_val = src_reg->s32_min_value; 13254 u32 umin_val = src_reg->u32_min_value; 13255 13256 if (src_known && dst_known) { 13257 __mark_reg32_known(dst_reg, var32_off.value); 13258 return; 13259 } 13260 13261 /* We get our maximum from the var_off, and our minimum is the 13262 * maximum of the operands' minima 13263 */ 13264 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 13265 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13266 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 13267 /* Lose signed bounds when ORing negative numbers, 13268 * ain't nobody got time for that. 13269 */ 13270 dst_reg->s32_min_value = S32_MIN; 13271 dst_reg->s32_max_value = S32_MAX; 13272 } else { 13273 /* ORing two positives gives a positive, so safe to 13274 * cast result into s64. 13275 */ 13276 dst_reg->s32_min_value = dst_reg->u32_min_value; 13277 dst_reg->s32_max_value = dst_reg->u32_max_value; 13278 } 13279 } 13280 13281 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 13282 struct bpf_reg_state *src_reg) 13283 { 13284 bool src_known = tnum_is_const(src_reg->var_off); 13285 bool dst_known = tnum_is_const(dst_reg->var_off); 13286 s64 smin_val = src_reg->smin_value; 13287 u64 umin_val = src_reg->umin_value; 13288 13289 if (src_known && dst_known) { 13290 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13291 return; 13292 } 13293 13294 /* We get our maximum from the var_off, and our minimum is the 13295 * maximum of the operands' minima 13296 */ 13297 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 13298 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13299 if (dst_reg->smin_value < 0 || smin_val < 0) { 13300 /* Lose signed bounds when ORing negative numbers, 13301 * ain't nobody got time for that. 13302 */ 13303 dst_reg->smin_value = S64_MIN; 13304 dst_reg->smax_value = S64_MAX; 13305 } else { 13306 /* ORing two positives gives a positive, so safe to 13307 * cast result into s64. 13308 */ 13309 dst_reg->smin_value = dst_reg->umin_value; 13310 dst_reg->smax_value = dst_reg->umax_value; 13311 } 13312 /* We may learn something more from the var_off */ 13313 __update_reg_bounds(dst_reg); 13314 } 13315 13316 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 13317 struct bpf_reg_state *src_reg) 13318 { 13319 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13320 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13321 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13322 s32 smin_val = src_reg->s32_min_value; 13323 13324 if (src_known && dst_known) { 13325 __mark_reg32_known(dst_reg, var32_off.value); 13326 return; 13327 } 13328 13329 /* We get both minimum and maximum from the var32_off. */ 13330 dst_reg->u32_min_value = var32_off.value; 13331 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13332 13333 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 13334 /* XORing two positive sign numbers gives a positive, 13335 * so safe to cast u32 result into s32. 13336 */ 13337 dst_reg->s32_min_value = dst_reg->u32_min_value; 13338 dst_reg->s32_max_value = dst_reg->u32_max_value; 13339 } else { 13340 dst_reg->s32_min_value = S32_MIN; 13341 dst_reg->s32_max_value = S32_MAX; 13342 } 13343 } 13344 13345 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 13346 struct bpf_reg_state *src_reg) 13347 { 13348 bool src_known = tnum_is_const(src_reg->var_off); 13349 bool dst_known = tnum_is_const(dst_reg->var_off); 13350 s64 smin_val = src_reg->smin_value; 13351 13352 if (src_known && dst_known) { 13353 /* dst_reg->var_off.value has been updated earlier */ 13354 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13355 return; 13356 } 13357 13358 /* We get both minimum and maximum from the var_off. */ 13359 dst_reg->umin_value = dst_reg->var_off.value; 13360 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13361 13362 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 13363 /* XORing two positive sign numbers gives a positive, 13364 * so safe to cast u64 result into s64. 13365 */ 13366 dst_reg->smin_value = dst_reg->umin_value; 13367 dst_reg->smax_value = dst_reg->umax_value; 13368 } else { 13369 dst_reg->smin_value = S64_MIN; 13370 dst_reg->smax_value = S64_MAX; 13371 } 13372 13373 __update_reg_bounds(dst_reg); 13374 } 13375 13376 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13377 u64 umin_val, u64 umax_val) 13378 { 13379 /* We lose all sign bit information (except what we can pick 13380 * up from var_off) 13381 */ 13382 dst_reg->s32_min_value = S32_MIN; 13383 dst_reg->s32_max_value = S32_MAX; 13384 /* If we might shift our top bit out, then we know nothing */ 13385 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 13386 dst_reg->u32_min_value = 0; 13387 dst_reg->u32_max_value = U32_MAX; 13388 } else { 13389 dst_reg->u32_min_value <<= umin_val; 13390 dst_reg->u32_max_value <<= umax_val; 13391 } 13392 } 13393 13394 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13395 struct bpf_reg_state *src_reg) 13396 { 13397 u32 umax_val = src_reg->u32_max_value; 13398 u32 umin_val = src_reg->u32_min_value; 13399 /* u32 alu operation will zext upper bits */ 13400 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13401 13402 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13403 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 13404 /* Not required but being careful mark reg64 bounds as unknown so 13405 * that we are forced to pick them up from tnum and zext later and 13406 * if some path skips this step we are still safe. 13407 */ 13408 __mark_reg64_unbounded(dst_reg); 13409 __update_reg32_bounds(dst_reg); 13410 } 13411 13412 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 13413 u64 umin_val, u64 umax_val) 13414 { 13415 /* Special case <<32 because it is a common compiler pattern to sign 13416 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 13417 * positive we know this shift will also be positive so we can track 13418 * bounds correctly. Otherwise we lose all sign bit information except 13419 * what we can pick up from var_off. Perhaps we can generalize this 13420 * later to shifts of any length. 13421 */ 13422 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 13423 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 13424 else 13425 dst_reg->smax_value = S64_MAX; 13426 13427 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 13428 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 13429 else 13430 dst_reg->smin_value = S64_MIN; 13431 13432 /* If we might shift our top bit out, then we know nothing */ 13433 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 13434 dst_reg->umin_value = 0; 13435 dst_reg->umax_value = U64_MAX; 13436 } else { 13437 dst_reg->umin_value <<= umin_val; 13438 dst_reg->umax_value <<= umax_val; 13439 } 13440 } 13441 13442 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 13443 struct bpf_reg_state *src_reg) 13444 { 13445 u64 umax_val = src_reg->umax_value; 13446 u64 umin_val = src_reg->umin_value; 13447 13448 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 13449 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 13450 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13451 13452 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 13453 /* We may learn something more from the var_off */ 13454 __update_reg_bounds(dst_reg); 13455 } 13456 13457 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 13458 struct bpf_reg_state *src_reg) 13459 { 13460 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13461 u32 umax_val = src_reg->u32_max_value; 13462 u32 umin_val = src_reg->u32_min_value; 13463 13464 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13465 * be negative, then either: 13466 * 1) src_reg might be zero, so the sign bit of the result is 13467 * unknown, so we lose our signed bounds 13468 * 2) it's known negative, thus the unsigned bounds capture the 13469 * signed bounds 13470 * 3) the signed bounds cross zero, so they tell us nothing 13471 * about the result 13472 * If the value in dst_reg is known nonnegative, then again the 13473 * unsigned bounds capture the signed bounds. 13474 * Thus, in all cases it suffices to blow away our signed bounds 13475 * and rely on inferring new ones from the unsigned bounds and 13476 * var_off of the result. 13477 */ 13478 dst_reg->s32_min_value = S32_MIN; 13479 dst_reg->s32_max_value = S32_MAX; 13480 13481 dst_reg->var_off = tnum_rshift(subreg, umin_val); 13482 dst_reg->u32_min_value >>= umax_val; 13483 dst_reg->u32_max_value >>= umin_val; 13484 13485 __mark_reg64_unbounded(dst_reg); 13486 __update_reg32_bounds(dst_reg); 13487 } 13488 13489 static void scalar_min_max_rsh(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 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13496 * be negative, then either: 13497 * 1) src_reg might be zero, so the sign bit of the result is 13498 * unknown, so we lose our signed bounds 13499 * 2) it's known negative, thus the unsigned bounds capture the 13500 * signed bounds 13501 * 3) the signed bounds cross zero, so they tell us nothing 13502 * about the result 13503 * If the value in dst_reg is known nonnegative, then again the 13504 * unsigned bounds capture the signed bounds. 13505 * Thus, in all cases it suffices to blow away our signed bounds 13506 * and rely on inferring new ones from the unsigned bounds and 13507 * var_off of the result. 13508 */ 13509 dst_reg->smin_value = S64_MIN; 13510 dst_reg->smax_value = S64_MAX; 13511 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 13512 dst_reg->umin_value >>= umax_val; 13513 dst_reg->umax_value >>= umin_val; 13514 13515 /* Its not easy to operate on alu32 bounds here because it depends 13516 * on bits being shifted in. Take easy way out and mark unbounded 13517 * so we can recalculate later from tnum. 13518 */ 13519 __mark_reg32_unbounded(dst_reg); 13520 __update_reg_bounds(dst_reg); 13521 } 13522 13523 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 13524 struct bpf_reg_state *src_reg) 13525 { 13526 u64 umin_val = src_reg->u32_min_value; 13527 13528 /* Upon reaching here, src_known is true and 13529 * umax_val is equal to umin_val. 13530 */ 13531 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 13532 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 13533 13534 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 13535 13536 /* blow away the dst_reg umin_value/umax_value and rely on 13537 * dst_reg var_off to refine the result. 13538 */ 13539 dst_reg->u32_min_value = 0; 13540 dst_reg->u32_max_value = U32_MAX; 13541 13542 __mark_reg64_unbounded(dst_reg); 13543 __update_reg32_bounds(dst_reg); 13544 } 13545 13546 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 13547 struct bpf_reg_state *src_reg) 13548 { 13549 u64 umin_val = src_reg->umin_value; 13550 13551 /* Upon reaching here, src_known is true and umax_val is equal 13552 * to umin_val. 13553 */ 13554 dst_reg->smin_value >>= umin_val; 13555 dst_reg->smax_value >>= umin_val; 13556 13557 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 13558 13559 /* blow away the dst_reg umin_value/umax_value and rely on 13560 * dst_reg var_off to refine the result. 13561 */ 13562 dst_reg->umin_value = 0; 13563 dst_reg->umax_value = U64_MAX; 13564 13565 /* Its not easy to operate on alu32 bounds here because it depends 13566 * on bits being shifted in from upper 32-bits. Take easy way out 13567 * and mark unbounded so we can recalculate later from tnum. 13568 */ 13569 __mark_reg32_unbounded(dst_reg); 13570 __update_reg_bounds(dst_reg); 13571 } 13572 13573 /* WARNING: This function does calculations on 64-bit values, but the actual 13574 * execution may occur on 32-bit values. Therefore, things like bitshifts 13575 * need extra checks in the 32-bit case. 13576 */ 13577 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 13578 struct bpf_insn *insn, 13579 struct bpf_reg_state *dst_reg, 13580 struct bpf_reg_state src_reg) 13581 { 13582 struct bpf_reg_state *regs = cur_regs(env); 13583 u8 opcode = BPF_OP(insn->code); 13584 bool src_known; 13585 s64 smin_val, smax_val; 13586 u64 umin_val, umax_val; 13587 s32 s32_min_val, s32_max_val; 13588 u32 u32_min_val, u32_max_val; 13589 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 13590 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 13591 int ret; 13592 13593 smin_val = src_reg.smin_value; 13594 smax_val = src_reg.smax_value; 13595 umin_val = src_reg.umin_value; 13596 umax_val = src_reg.umax_value; 13597 13598 s32_min_val = src_reg.s32_min_value; 13599 s32_max_val = src_reg.s32_max_value; 13600 u32_min_val = src_reg.u32_min_value; 13601 u32_max_val = src_reg.u32_max_value; 13602 13603 if (alu32) { 13604 src_known = tnum_subreg_is_const(src_reg.var_off); 13605 if ((src_known && 13606 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 13607 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 13608 /* Taint dst register if offset had invalid bounds 13609 * derived from e.g. dead branches. 13610 */ 13611 __mark_reg_unknown(env, dst_reg); 13612 return 0; 13613 } 13614 } else { 13615 src_known = tnum_is_const(src_reg.var_off); 13616 if ((src_known && 13617 (smin_val != smax_val || umin_val != umax_val)) || 13618 smin_val > smax_val || umin_val > umax_val) { 13619 /* Taint dst register if offset had invalid bounds 13620 * derived from e.g. dead branches. 13621 */ 13622 __mark_reg_unknown(env, dst_reg); 13623 return 0; 13624 } 13625 } 13626 13627 if (!src_known && 13628 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 13629 __mark_reg_unknown(env, dst_reg); 13630 return 0; 13631 } 13632 13633 if (sanitize_needed(opcode)) { 13634 ret = sanitize_val_alu(env, insn); 13635 if (ret < 0) 13636 return sanitize_err(env, insn, ret, NULL, NULL); 13637 } 13638 13639 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 13640 * There are two classes of instructions: The first class we track both 13641 * alu32 and alu64 sign/unsigned bounds independently this provides the 13642 * greatest amount of precision when alu operations are mixed with jmp32 13643 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 13644 * and BPF_OR. This is possible because these ops have fairly easy to 13645 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 13646 * See alu32 verifier tests for examples. The second class of 13647 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 13648 * with regards to tracking sign/unsigned bounds because the bits may 13649 * cross subreg boundaries in the alu64 case. When this happens we mark 13650 * the reg unbounded in the subreg bound space and use the resulting 13651 * tnum to calculate an approximation of the sign/unsigned bounds. 13652 */ 13653 switch (opcode) { 13654 case BPF_ADD: 13655 scalar32_min_max_add(dst_reg, &src_reg); 13656 scalar_min_max_add(dst_reg, &src_reg); 13657 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 13658 break; 13659 case BPF_SUB: 13660 scalar32_min_max_sub(dst_reg, &src_reg); 13661 scalar_min_max_sub(dst_reg, &src_reg); 13662 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 13663 break; 13664 case BPF_MUL: 13665 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 13666 scalar32_min_max_mul(dst_reg, &src_reg); 13667 scalar_min_max_mul(dst_reg, &src_reg); 13668 break; 13669 case BPF_AND: 13670 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 13671 scalar32_min_max_and(dst_reg, &src_reg); 13672 scalar_min_max_and(dst_reg, &src_reg); 13673 break; 13674 case BPF_OR: 13675 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 13676 scalar32_min_max_or(dst_reg, &src_reg); 13677 scalar_min_max_or(dst_reg, &src_reg); 13678 break; 13679 case BPF_XOR: 13680 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 13681 scalar32_min_max_xor(dst_reg, &src_reg); 13682 scalar_min_max_xor(dst_reg, &src_reg); 13683 break; 13684 case BPF_LSH: 13685 if (umax_val >= insn_bitness) { 13686 /* Shifts greater than 31 or 63 are undefined. 13687 * This includes shifts by a negative number. 13688 */ 13689 mark_reg_unknown(env, regs, insn->dst_reg); 13690 break; 13691 } 13692 if (alu32) 13693 scalar32_min_max_lsh(dst_reg, &src_reg); 13694 else 13695 scalar_min_max_lsh(dst_reg, &src_reg); 13696 break; 13697 case BPF_RSH: 13698 if (umax_val >= insn_bitness) { 13699 /* Shifts greater than 31 or 63 are undefined. 13700 * This includes shifts by a negative number. 13701 */ 13702 mark_reg_unknown(env, regs, insn->dst_reg); 13703 break; 13704 } 13705 if (alu32) 13706 scalar32_min_max_rsh(dst_reg, &src_reg); 13707 else 13708 scalar_min_max_rsh(dst_reg, &src_reg); 13709 break; 13710 case BPF_ARSH: 13711 if (umax_val >= insn_bitness) { 13712 /* Shifts greater than 31 or 63 are undefined. 13713 * This includes shifts by a negative number. 13714 */ 13715 mark_reg_unknown(env, regs, insn->dst_reg); 13716 break; 13717 } 13718 if (alu32) 13719 scalar32_min_max_arsh(dst_reg, &src_reg); 13720 else 13721 scalar_min_max_arsh(dst_reg, &src_reg); 13722 break; 13723 default: 13724 mark_reg_unknown(env, regs, insn->dst_reg); 13725 break; 13726 } 13727 13728 /* ALU32 ops are zero extended into 64bit register */ 13729 if (alu32) 13730 zext_32_to_64(dst_reg); 13731 reg_bounds_sync(dst_reg); 13732 return 0; 13733 } 13734 13735 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 13736 * and var_off. 13737 */ 13738 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 13739 struct bpf_insn *insn) 13740 { 13741 struct bpf_verifier_state *vstate = env->cur_state; 13742 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13743 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 13744 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 13745 u8 opcode = BPF_OP(insn->code); 13746 int err; 13747 13748 dst_reg = ®s[insn->dst_reg]; 13749 src_reg = NULL; 13750 if (dst_reg->type != SCALAR_VALUE) 13751 ptr_reg = dst_reg; 13752 else 13753 /* Make sure ID is cleared otherwise dst_reg min/max could be 13754 * incorrectly propagated into other registers by find_equal_scalars() 13755 */ 13756 dst_reg->id = 0; 13757 if (BPF_SRC(insn->code) == BPF_X) { 13758 src_reg = ®s[insn->src_reg]; 13759 if (src_reg->type != SCALAR_VALUE) { 13760 if (dst_reg->type != SCALAR_VALUE) { 13761 /* Combining two pointers by any ALU op yields 13762 * an arbitrary scalar. Disallow all math except 13763 * pointer subtraction 13764 */ 13765 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13766 mark_reg_unknown(env, regs, insn->dst_reg); 13767 return 0; 13768 } 13769 verbose(env, "R%d pointer %s pointer prohibited\n", 13770 insn->dst_reg, 13771 bpf_alu_string[opcode >> 4]); 13772 return -EACCES; 13773 } else { 13774 /* scalar += pointer 13775 * This is legal, but we have to reverse our 13776 * src/dest handling in computing the range 13777 */ 13778 err = mark_chain_precision(env, insn->dst_reg); 13779 if (err) 13780 return err; 13781 return adjust_ptr_min_max_vals(env, insn, 13782 src_reg, dst_reg); 13783 } 13784 } else if (ptr_reg) { 13785 /* pointer += scalar */ 13786 err = mark_chain_precision(env, insn->src_reg); 13787 if (err) 13788 return err; 13789 return adjust_ptr_min_max_vals(env, insn, 13790 dst_reg, src_reg); 13791 } else if (dst_reg->precise) { 13792 /* if dst_reg is precise, src_reg should be precise as well */ 13793 err = mark_chain_precision(env, insn->src_reg); 13794 if (err) 13795 return err; 13796 } 13797 } else { 13798 /* Pretend the src is a reg with a known value, since we only 13799 * need to be able to read from this state. 13800 */ 13801 off_reg.type = SCALAR_VALUE; 13802 __mark_reg_known(&off_reg, insn->imm); 13803 src_reg = &off_reg; 13804 if (ptr_reg) /* pointer += K */ 13805 return adjust_ptr_min_max_vals(env, insn, 13806 ptr_reg, src_reg); 13807 } 13808 13809 /* Got here implies adding two SCALAR_VALUEs */ 13810 if (WARN_ON_ONCE(ptr_reg)) { 13811 print_verifier_state(env, state, true); 13812 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 13813 return -EINVAL; 13814 } 13815 if (WARN_ON(!src_reg)) { 13816 print_verifier_state(env, state, true); 13817 verbose(env, "verifier internal error: no src_reg\n"); 13818 return -EINVAL; 13819 } 13820 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 13821 } 13822 13823 /* check validity of 32-bit and 64-bit arithmetic operations */ 13824 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 13825 { 13826 struct bpf_reg_state *regs = cur_regs(env); 13827 u8 opcode = BPF_OP(insn->code); 13828 int err; 13829 13830 if (opcode == BPF_END || opcode == BPF_NEG) { 13831 if (opcode == BPF_NEG) { 13832 if (BPF_SRC(insn->code) != BPF_K || 13833 insn->src_reg != BPF_REG_0 || 13834 insn->off != 0 || insn->imm != 0) { 13835 verbose(env, "BPF_NEG uses reserved fields\n"); 13836 return -EINVAL; 13837 } 13838 } else { 13839 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 13840 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 13841 (BPF_CLASS(insn->code) == BPF_ALU64 && 13842 BPF_SRC(insn->code) != BPF_TO_LE)) { 13843 verbose(env, "BPF_END uses reserved fields\n"); 13844 return -EINVAL; 13845 } 13846 } 13847 13848 /* check src operand */ 13849 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13850 if (err) 13851 return err; 13852 13853 if (is_pointer_value(env, insn->dst_reg)) { 13854 verbose(env, "R%d pointer arithmetic prohibited\n", 13855 insn->dst_reg); 13856 return -EACCES; 13857 } 13858 13859 /* check dest operand */ 13860 err = check_reg_arg(env, insn->dst_reg, DST_OP); 13861 if (err) 13862 return err; 13863 13864 } else if (opcode == BPF_MOV) { 13865 13866 if (BPF_SRC(insn->code) == BPF_X) { 13867 if (insn->imm != 0) { 13868 verbose(env, "BPF_MOV uses reserved fields\n"); 13869 return -EINVAL; 13870 } 13871 13872 if (BPF_CLASS(insn->code) == BPF_ALU) { 13873 if (insn->off != 0 && insn->off != 8 && insn->off != 16) { 13874 verbose(env, "BPF_MOV uses reserved fields\n"); 13875 return -EINVAL; 13876 } 13877 } else { 13878 if (insn->off != 0 && insn->off != 8 && insn->off != 16 && 13879 insn->off != 32) { 13880 verbose(env, "BPF_MOV uses reserved fields\n"); 13881 return -EINVAL; 13882 } 13883 } 13884 13885 /* check src operand */ 13886 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13887 if (err) 13888 return err; 13889 } else { 13890 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 13891 verbose(env, "BPF_MOV uses reserved fields\n"); 13892 return -EINVAL; 13893 } 13894 } 13895 13896 /* check dest operand, mark as required later */ 13897 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13898 if (err) 13899 return err; 13900 13901 if (BPF_SRC(insn->code) == BPF_X) { 13902 struct bpf_reg_state *src_reg = regs + insn->src_reg; 13903 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 13904 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id && 13905 !tnum_is_const(src_reg->var_off); 13906 13907 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13908 if (insn->off == 0) { 13909 /* case: R1 = R2 13910 * copy register state to dest reg 13911 */ 13912 if (need_id) 13913 /* Assign src and dst registers the same ID 13914 * that will be used by find_equal_scalars() 13915 * to propagate min/max range. 13916 */ 13917 src_reg->id = ++env->id_gen; 13918 copy_register_state(dst_reg, src_reg); 13919 dst_reg->live |= REG_LIVE_WRITTEN; 13920 dst_reg->subreg_def = DEF_NOT_SUBREG; 13921 } else { 13922 /* case: R1 = (s8, s16 s32)R2 */ 13923 if (is_pointer_value(env, insn->src_reg)) { 13924 verbose(env, 13925 "R%d sign-extension part of pointer\n", 13926 insn->src_reg); 13927 return -EACCES; 13928 } else if (src_reg->type == SCALAR_VALUE) { 13929 bool no_sext; 13930 13931 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13932 if (no_sext && need_id) 13933 src_reg->id = ++env->id_gen; 13934 copy_register_state(dst_reg, src_reg); 13935 if (!no_sext) 13936 dst_reg->id = 0; 13937 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 13938 dst_reg->live |= REG_LIVE_WRITTEN; 13939 dst_reg->subreg_def = DEF_NOT_SUBREG; 13940 } else { 13941 mark_reg_unknown(env, regs, insn->dst_reg); 13942 } 13943 } 13944 } else { 13945 /* R1 = (u32) R2 */ 13946 if (is_pointer_value(env, insn->src_reg)) { 13947 verbose(env, 13948 "R%d partial copy of pointer\n", 13949 insn->src_reg); 13950 return -EACCES; 13951 } else if (src_reg->type == SCALAR_VALUE) { 13952 if (insn->off == 0) { 13953 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX; 13954 13955 if (is_src_reg_u32 && need_id) 13956 src_reg->id = ++env->id_gen; 13957 copy_register_state(dst_reg, src_reg); 13958 /* Make sure ID is cleared if src_reg is not in u32 13959 * range otherwise dst_reg min/max could be incorrectly 13960 * propagated into src_reg by find_equal_scalars() 13961 */ 13962 if (!is_src_reg_u32) 13963 dst_reg->id = 0; 13964 dst_reg->live |= REG_LIVE_WRITTEN; 13965 dst_reg->subreg_def = env->insn_idx + 1; 13966 } else { 13967 /* case: W1 = (s8, s16)W2 */ 13968 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13969 13970 if (no_sext && need_id) 13971 src_reg->id = ++env->id_gen; 13972 copy_register_state(dst_reg, src_reg); 13973 if (!no_sext) 13974 dst_reg->id = 0; 13975 dst_reg->live |= REG_LIVE_WRITTEN; 13976 dst_reg->subreg_def = env->insn_idx + 1; 13977 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 13978 } 13979 } else { 13980 mark_reg_unknown(env, regs, 13981 insn->dst_reg); 13982 } 13983 zext_32_to_64(dst_reg); 13984 reg_bounds_sync(dst_reg); 13985 } 13986 } else { 13987 /* case: R = imm 13988 * remember the value we stored into this reg 13989 */ 13990 /* clear any state __mark_reg_known doesn't set */ 13991 mark_reg_unknown(env, regs, insn->dst_reg); 13992 regs[insn->dst_reg].type = SCALAR_VALUE; 13993 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13994 __mark_reg_known(regs + insn->dst_reg, 13995 insn->imm); 13996 } else { 13997 __mark_reg_known(regs + insn->dst_reg, 13998 (u32)insn->imm); 13999 } 14000 } 14001 14002 } else if (opcode > BPF_END) { 14003 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 14004 return -EINVAL; 14005 14006 } else { /* all other ALU ops: and, sub, xor, add, ... */ 14007 14008 if (BPF_SRC(insn->code) == BPF_X) { 14009 if (insn->imm != 0 || insn->off > 1 || 14010 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14011 verbose(env, "BPF_ALU uses reserved fields\n"); 14012 return -EINVAL; 14013 } 14014 /* check src1 operand */ 14015 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14016 if (err) 14017 return err; 14018 } else { 14019 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 14020 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14021 verbose(env, "BPF_ALU uses reserved fields\n"); 14022 return -EINVAL; 14023 } 14024 } 14025 14026 /* check src2 operand */ 14027 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14028 if (err) 14029 return err; 14030 14031 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 14032 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 14033 verbose(env, "div by zero\n"); 14034 return -EINVAL; 14035 } 14036 14037 if ((opcode == BPF_LSH || opcode == BPF_RSH || 14038 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 14039 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 14040 14041 if (insn->imm < 0 || insn->imm >= size) { 14042 verbose(env, "invalid shift %d\n", insn->imm); 14043 return -EINVAL; 14044 } 14045 } 14046 14047 /* check dest operand */ 14048 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14049 err = err ?: adjust_reg_min_max_vals(env, insn); 14050 if (err) 14051 return err; 14052 } 14053 14054 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 14055 } 14056 14057 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 14058 struct bpf_reg_state *dst_reg, 14059 enum bpf_reg_type type, 14060 bool range_right_open) 14061 { 14062 struct bpf_func_state *state; 14063 struct bpf_reg_state *reg; 14064 int new_range; 14065 14066 if (dst_reg->off < 0 || 14067 (dst_reg->off == 0 && range_right_open)) 14068 /* This doesn't give us any range */ 14069 return; 14070 14071 if (dst_reg->umax_value > MAX_PACKET_OFF || 14072 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 14073 /* Risk of overflow. For instance, ptr + (1<<63) may be less 14074 * than pkt_end, but that's because it's also less than pkt. 14075 */ 14076 return; 14077 14078 new_range = dst_reg->off; 14079 if (range_right_open) 14080 new_range++; 14081 14082 /* Examples for register markings: 14083 * 14084 * pkt_data in dst register: 14085 * 14086 * r2 = r3; 14087 * r2 += 8; 14088 * if (r2 > pkt_end) goto <handle exception> 14089 * <access okay> 14090 * 14091 * r2 = r3; 14092 * r2 += 8; 14093 * if (r2 < pkt_end) goto <access okay> 14094 * <handle exception> 14095 * 14096 * Where: 14097 * r2 == dst_reg, pkt_end == src_reg 14098 * r2=pkt(id=n,off=8,r=0) 14099 * r3=pkt(id=n,off=0,r=0) 14100 * 14101 * pkt_data in src register: 14102 * 14103 * r2 = r3; 14104 * r2 += 8; 14105 * if (pkt_end >= r2) goto <access okay> 14106 * <handle exception> 14107 * 14108 * r2 = r3; 14109 * r2 += 8; 14110 * if (pkt_end <= r2) goto <handle exception> 14111 * <access okay> 14112 * 14113 * Where: 14114 * pkt_end == dst_reg, r2 == src_reg 14115 * r2=pkt(id=n,off=8,r=0) 14116 * r3=pkt(id=n,off=0,r=0) 14117 * 14118 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 14119 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 14120 * and [r3, r3 + 8-1) respectively is safe to access depending on 14121 * the check. 14122 */ 14123 14124 /* If our ids match, then we must have the same max_value. And we 14125 * don't care about the other reg's fixed offset, since if it's too big 14126 * the range won't allow anything. 14127 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 14128 */ 14129 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14130 if (reg->type == type && reg->id == dst_reg->id) 14131 /* keep the maximum range already checked */ 14132 reg->range = max(reg->range, new_range); 14133 })); 14134 } 14135 14136 /* 14137 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 14138 */ 14139 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14140 u8 opcode, bool is_jmp32) 14141 { 14142 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 14143 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 14144 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value; 14145 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value; 14146 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value; 14147 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value; 14148 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value; 14149 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value; 14150 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value; 14151 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value; 14152 14153 switch (opcode) { 14154 case BPF_JEQ: 14155 /* constants, umin/umax and smin/smax checks would be 14156 * redundant in this case because they all should match 14157 */ 14158 if (tnum_is_const(t1) && tnum_is_const(t2)) 14159 return t1.value == t2.value; 14160 /* non-overlapping ranges */ 14161 if (umin1 > umax2 || umax1 < umin2) 14162 return 0; 14163 if (smin1 > smax2 || smax1 < smin2) 14164 return 0; 14165 if (!is_jmp32) { 14166 /* if 64-bit ranges are inconclusive, see if we can 14167 * utilize 32-bit subrange knowledge to eliminate 14168 * branches that can't be taken a priori 14169 */ 14170 if (reg1->u32_min_value > reg2->u32_max_value || 14171 reg1->u32_max_value < reg2->u32_min_value) 14172 return 0; 14173 if (reg1->s32_min_value > reg2->s32_max_value || 14174 reg1->s32_max_value < reg2->s32_min_value) 14175 return 0; 14176 } 14177 break; 14178 case BPF_JNE: 14179 /* constants, umin/umax and smin/smax checks would be 14180 * redundant in this case because they all should match 14181 */ 14182 if (tnum_is_const(t1) && tnum_is_const(t2)) 14183 return t1.value != t2.value; 14184 /* non-overlapping ranges */ 14185 if (umin1 > umax2 || umax1 < umin2) 14186 return 1; 14187 if (smin1 > smax2 || smax1 < smin2) 14188 return 1; 14189 if (!is_jmp32) { 14190 /* if 64-bit ranges are inconclusive, see if we can 14191 * utilize 32-bit subrange knowledge to eliminate 14192 * branches that can't be taken a priori 14193 */ 14194 if (reg1->u32_min_value > reg2->u32_max_value || 14195 reg1->u32_max_value < reg2->u32_min_value) 14196 return 1; 14197 if (reg1->s32_min_value > reg2->s32_max_value || 14198 reg1->s32_max_value < reg2->s32_min_value) 14199 return 1; 14200 } 14201 break; 14202 case BPF_JSET: 14203 if (!is_reg_const(reg2, is_jmp32)) { 14204 swap(reg1, reg2); 14205 swap(t1, t2); 14206 } 14207 if (!is_reg_const(reg2, is_jmp32)) 14208 return -1; 14209 if ((~t1.mask & t1.value) & t2.value) 14210 return 1; 14211 if (!((t1.mask | t1.value) & t2.value)) 14212 return 0; 14213 break; 14214 case BPF_JGT: 14215 if (umin1 > umax2) 14216 return 1; 14217 else if (umax1 <= umin2) 14218 return 0; 14219 break; 14220 case BPF_JSGT: 14221 if (smin1 > smax2) 14222 return 1; 14223 else if (smax1 <= smin2) 14224 return 0; 14225 break; 14226 case BPF_JLT: 14227 if (umax1 < umin2) 14228 return 1; 14229 else if (umin1 >= umax2) 14230 return 0; 14231 break; 14232 case BPF_JSLT: 14233 if (smax1 < smin2) 14234 return 1; 14235 else if (smin1 >= smax2) 14236 return 0; 14237 break; 14238 case BPF_JGE: 14239 if (umin1 >= umax2) 14240 return 1; 14241 else if (umax1 < umin2) 14242 return 0; 14243 break; 14244 case BPF_JSGE: 14245 if (smin1 >= smax2) 14246 return 1; 14247 else if (smax1 < smin2) 14248 return 0; 14249 break; 14250 case BPF_JLE: 14251 if (umax1 <= umin2) 14252 return 1; 14253 else if (umin1 > umax2) 14254 return 0; 14255 break; 14256 case BPF_JSLE: 14257 if (smax1 <= smin2) 14258 return 1; 14259 else if (smin1 > smax2) 14260 return 0; 14261 break; 14262 } 14263 14264 return -1; 14265 } 14266 14267 static int flip_opcode(u32 opcode) 14268 { 14269 /* How can we transform "a <op> b" into "b <op> a"? */ 14270 static const u8 opcode_flip[16] = { 14271 /* these stay the same */ 14272 [BPF_JEQ >> 4] = BPF_JEQ, 14273 [BPF_JNE >> 4] = BPF_JNE, 14274 [BPF_JSET >> 4] = BPF_JSET, 14275 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 14276 [BPF_JGE >> 4] = BPF_JLE, 14277 [BPF_JGT >> 4] = BPF_JLT, 14278 [BPF_JLE >> 4] = BPF_JGE, 14279 [BPF_JLT >> 4] = BPF_JGT, 14280 [BPF_JSGE >> 4] = BPF_JSLE, 14281 [BPF_JSGT >> 4] = BPF_JSLT, 14282 [BPF_JSLE >> 4] = BPF_JSGE, 14283 [BPF_JSLT >> 4] = BPF_JSGT 14284 }; 14285 return opcode_flip[opcode >> 4]; 14286 } 14287 14288 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 14289 struct bpf_reg_state *src_reg, 14290 u8 opcode) 14291 { 14292 struct bpf_reg_state *pkt; 14293 14294 if (src_reg->type == PTR_TO_PACKET_END) { 14295 pkt = dst_reg; 14296 } else if (dst_reg->type == PTR_TO_PACKET_END) { 14297 pkt = src_reg; 14298 opcode = flip_opcode(opcode); 14299 } else { 14300 return -1; 14301 } 14302 14303 if (pkt->range >= 0) 14304 return -1; 14305 14306 switch (opcode) { 14307 case BPF_JLE: 14308 /* pkt <= pkt_end */ 14309 fallthrough; 14310 case BPF_JGT: 14311 /* pkt > pkt_end */ 14312 if (pkt->range == BEYOND_PKT_END) 14313 /* pkt has at last one extra byte beyond pkt_end */ 14314 return opcode == BPF_JGT; 14315 break; 14316 case BPF_JLT: 14317 /* pkt < pkt_end */ 14318 fallthrough; 14319 case BPF_JGE: 14320 /* pkt >= pkt_end */ 14321 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 14322 return opcode == BPF_JGE; 14323 break; 14324 } 14325 return -1; 14326 } 14327 14328 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 14329 * and return: 14330 * 1 - branch will be taken and "goto target" will be executed 14331 * 0 - branch will not be taken and fall-through to next insn 14332 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 14333 * range [0,10] 14334 */ 14335 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14336 u8 opcode, bool is_jmp32) 14337 { 14338 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 14339 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 14340 14341 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 14342 u64 val; 14343 14344 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 14345 if (!is_reg_const(reg2, is_jmp32)) { 14346 opcode = flip_opcode(opcode); 14347 swap(reg1, reg2); 14348 } 14349 /* and ensure that reg2 is a constant */ 14350 if (!is_reg_const(reg2, is_jmp32)) 14351 return -1; 14352 14353 if (!reg_not_null(reg1)) 14354 return -1; 14355 14356 /* If pointer is valid tests against zero will fail so we can 14357 * use this to direct branch taken. 14358 */ 14359 val = reg_const_value(reg2, is_jmp32); 14360 if (val != 0) 14361 return -1; 14362 14363 switch (opcode) { 14364 case BPF_JEQ: 14365 return 0; 14366 case BPF_JNE: 14367 return 1; 14368 default: 14369 return -1; 14370 } 14371 } 14372 14373 /* now deal with two scalars, but not necessarily constants */ 14374 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32); 14375 } 14376 14377 /* Opcode that corresponds to a *false* branch condition. 14378 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 14379 */ 14380 static u8 rev_opcode(u8 opcode) 14381 { 14382 switch (opcode) { 14383 case BPF_JEQ: return BPF_JNE; 14384 case BPF_JNE: return BPF_JEQ; 14385 /* JSET doesn't have it's reverse opcode in BPF, so add 14386 * BPF_X flag to denote the reverse of that operation 14387 */ 14388 case BPF_JSET: return BPF_JSET | BPF_X; 14389 case BPF_JSET | BPF_X: return BPF_JSET; 14390 case BPF_JGE: return BPF_JLT; 14391 case BPF_JGT: return BPF_JLE; 14392 case BPF_JLE: return BPF_JGT; 14393 case BPF_JLT: return BPF_JGE; 14394 case BPF_JSGE: return BPF_JSLT; 14395 case BPF_JSGT: return BPF_JSLE; 14396 case BPF_JSLE: return BPF_JSGT; 14397 case BPF_JSLT: return BPF_JSGE; 14398 default: return 0; 14399 } 14400 } 14401 14402 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 14403 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14404 u8 opcode, bool is_jmp32) 14405 { 14406 struct tnum t; 14407 u64 val; 14408 14409 again: 14410 switch (opcode) { 14411 case BPF_JEQ: 14412 if (is_jmp32) { 14413 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14414 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14415 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14416 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14417 reg2->u32_min_value = reg1->u32_min_value; 14418 reg2->u32_max_value = reg1->u32_max_value; 14419 reg2->s32_min_value = reg1->s32_min_value; 14420 reg2->s32_max_value = reg1->s32_max_value; 14421 14422 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 14423 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14424 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 14425 } else { 14426 reg1->umin_value = max(reg1->umin_value, reg2->umin_value); 14427 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14428 reg1->smin_value = max(reg1->smin_value, reg2->smin_value); 14429 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14430 reg2->umin_value = reg1->umin_value; 14431 reg2->umax_value = reg1->umax_value; 14432 reg2->smin_value = reg1->smin_value; 14433 reg2->smax_value = reg1->smax_value; 14434 14435 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 14436 reg2->var_off = reg1->var_off; 14437 } 14438 break; 14439 case BPF_JNE: 14440 if (!is_reg_const(reg2, is_jmp32)) 14441 swap(reg1, reg2); 14442 if (!is_reg_const(reg2, is_jmp32)) 14443 break; 14444 14445 /* try to recompute the bound of reg1 if reg2 is a const and 14446 * is exactly the edge of reg1. 14447 */ 14448 val = reg_const_value(reg2, is_jmp32); 14449 if (is_jmp32) { 14450 /* u32_min_value is not equal to 0xffffffff at this point, 14451 * because otherwise u32_max_value is 0xffffffff as well, 14452 * in such a case both reg1 and reg2 would be constants, 14453 * jump would be predicted and reg_set_min_max() won't 14454 * be called. 14455 * 14456 * Same reasoning works for all {u,s}{min,max}{32,64} cases 14457 * below. 14458 */ 14459 if (reg1->u32_min_value == (u32)val) 14460 reg1->u32_min_value++; 14461 if (reg1->u32_max_value == (u32)val) 14462 reg1->u32_max_value--; 14463 if (reg1->s32_min_value == (s32)val) 14464 reg1->s32_min_value++; 14465 if (reg1->s32_max_value == (s32)val) 14466 reg1->s32_max_value--; 14467 } else { 14468 if (reg1->umin_value == (u64)val) 14469 reg1->umin_value++; 14470 if (reg1->umax_value == (u64)val) 14471 reg1->umax_value--; 14472 if (reg1->smin_value == (s64)val) 14473 reg1->smin_value++; 14474 if (reg1->smax_value == (s64)val) 14475 reg1->smax_value--; 14476 } 14477 break; 14478 case BPF_JSET: 14479 if (!is_reg_const(reg2, is_jmp32)) 14480 swap(reg1, reg2); 14481 if (!is_reg_const(reg2, is_jmp32)) 14482 break; 14483 val = reg_const_value(reg2, is_jmp32); 14484 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 14485 * requires single bit to learn something useful. E.g., if we 14486 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 14487 * are actually set? We can learn something definite only if 14488 * it's a single-bit value to begin with. 14489 * 14490 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 14491 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 14492 * bit 1 is set, which we can readily use in adjustments. 14493 */ 14494 if (!is_power_of_2(val)) 14495 break; 14496 if (is_jmp32) { 14497 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 14498 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14499 } else { 14500 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 14501 } 14502 break; 14503 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 14504 if (!is_reg_const(reg2, is_jmp32)) 14505 swap(reg1, reg2); 14506 if (!is_reg_const(reg2, is_jmp32)) 14507 break; 14508 val = reg_const_value(reg2, is_jmp32); 14509 if (is_jmp32) { 14510 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 14511 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14512 } else { 14513 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 14514 } 14515 break; 14516 case BPF_JLE: 14517 if (is_jmp32) { 14518 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14519 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14520 } else { 14521 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14522 reg2->umin_value = max(reg1->umin_value, reg2->umin_value); 14523 } 14524 break; 14525 case BPF_JLT: 14526 if (is_jmp32) { 14527 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1); 14528 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value); 14529 } else { 14530 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1); 14531 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value); 14532 } 14533 break; 14534 case BPF_JSLE: 14535 if (is_jmp32) { 14536 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14537 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14538 } else { 14539 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14540 reg2->smin_value = max(reg1->smin_value, reg2->smin_value); 14541 } 14542 break; 14543 case BPF_JSLT: 14544 if (is_jmp32) { 14545 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1); 14546 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value); 14547 } else { 14548 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1); 14549 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value); 14550 } 14551 break; 14552 case BPF_JGE: 14553 case BPF_JGT: 14554 case BPF_JSGE: 14555 case BPF_JSGT: 14556 /* just reuse LE/LT logic above */ 14557 opcode = flip_opcode(opcode); 14558 swap(reg1, reg2); 14559 goto again; 14560 default: 14561 return; 14562 } 14563 } 14564 14565 /* Adjusts the register min/max values in the case that the dst_reg and 14566 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K 14567 * check, in which case we havea fake SCALAR_VALUE representing insn->imm). 14568 * Technically we can do similar adjustments for pointers to the same object, 14569 * but we don't support that right now. 14570 */ 14571 static int reg_set_min_max(struct bpf_verifier_env *env, 14572 struct bpf_reg_state *true_reg1, 14573 struct bpf_reg_state *true_reg2, 14574 struct bpf_reg_state *false_reg1, 14575 struct bpf_reg_state *false_reg2, 14576 u8 opcode, bool is_jmp32) 14577 { 14578 int err; 14579 14580 /* If either register is a pointer, we can't learn anything about its 14581 * variable offset from the compare (unless they were a pointer into 14582 * the same object, but we don't bother with that). 14583 */ 14584 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE) 14585 return 0; 14586 14587 /* fallthrough (FALSE) branch */ 14588 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32); 14589 reg_bounds_sync(false_reg1); 14590 reg_bounds_sync(false_reg2); 14591 14592 /* jump (TRUE) branch */ 14593 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32); 14594 reg_bounds_sync(true_reg1); 14595 reg_bounds_sync(true_reg2); 14596 14597 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1"); 14598 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2"); 14599 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1"); 14600 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2"); 14601 return err; 14602 } 14603 14604 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 14605 struct bpf_reg_state *reg, u32 id, 14606 bool is_null) 14607 { 14608 if (type_may_be_null(reg->type) && reg->id == id && 14609 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 14610 /* Old offset (both fixed and variable parts) should have been 14611 * known-zero, because we don't allow pointer arithmetic on 14612 * pointers that might be NULL. If we see this happening, don't 14613 * convert the register. 14614 * 14615 * But in some cases, some helpers that return local kptrs 14616 * advance offset for the returned pointer. In those cases, it 14617 * is fine to expect to see reg->off. 14618 */ 14619 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 14620 return; 14621 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 14622 WARN_ON_ONCE(reg->off)) 14623 return; 14624 14625 if (is_null) { 14626 reg->type = SCALAR_VALUE; 14627 /* We don't need id and ref_obj_id from this point 14628 * onwards anymore, thus we should better reset it, 14629 * so that state pruning has chances to take effect. 14630 */ 14631 reg->id = 0; 14632 reg->ref_obj_id = 0; 14633 14634 return; 14635 } 14636 14637 mark_ptr_not_null_reg(reg); 14638 14639 if (!reg_may_point_to_spin_lock(reg)) { 14640 /* For not-NULL ptr, reg->ref_obj_id will be reset 14641 * in release_reference(). 14642 * 14643 * reg->id is still used by spin_lock ptr. Other 14644 * than spin_lock ptr type, reg->id can be reset. 14645 */ 14646 reg->id = 0; 14647 } 14648 } 14649 } 14650 14651 /* The logic is similar to find_good_pkt_pointers(), both could eventually 14652 * be folded together at some point. 14653 */ 14654 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 14655 bool is_null) 14656 { 14657 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14658 struct bpf_reg_state *regs = state->regs, *reg; 14659 u32 ref_obj_id = regs[regno].ref_obj_id; 14660 u32 id = regs[regno].id; 14661 14662 if (ref_obj_id && ref_obj_id == id && is_null) 14663 /* regs[regno] is in the " == NULL" branch. 14664 * No one could have freed the reference state before 14665 * doing the NULL check. 14666 */ 14667 WARN_ON_ONCE(release_reference_state(state, id)); 14668 14669 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14670 mark_ptr_or_null_reg(state, reg, id, is_null); 14671 })); 14672 } 14673 14674 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 14675 struct bpf_reg_state *dst_reg, 14676 struct bpf_reg_state *src_reg, 14677 struct bpf_verifier_state *this_branch, 14678 struct bpf_verifier_state *other_branch) 14679 { 14680 if (BPF_SRC(insn->code) != BPF_X) 14681 return false; 14682 14683 /* Pointers are always 64-bit. */ 14684 if (BPF_CLASS(insn->code) == BPF_JMP32) 14685 return false; 14686 14687 switch (BPF_OP(insn->code)) { 14688 case BPF_JGT: 14689 if ((dst_reg->type == PTR_TO_PACKET && 14690 src_reg->type == PTR_TO_PACKET_END) || 14691 (dst_reg->type == PTR_TO_PACKET_META && 14692 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14693 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 14694 find_good_pkt_pointers(this_branch, dst_reg, 14695 dst_reg->type, false); 14696 mark_pkt_end(other_branch, insn->dst_reg, true); 14697 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14698 src_reg->type == PTR_TO_PACKET) || 14699 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14700 src_reg->type == PTR_TO_PACKET_META)) { 14701 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 14702 find_good_pkt_pointers(other_branch, src_reg, 14703 src_reg->type, true); 14704 mark_pkt_end(this_branch, insn->src_reg, false); 14705 } else { 14706 return false; 14707 } 14708 break; 14709 case BPF_JLT: 14710 if ((dst_reg->type == PTR_TO_PACKET && 14711 src_reg->type == PTR_TO_PACKET_END) || 14712 (dst_reg->type == PTR_TO_PACKET_META && 14713 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14714 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 14715 find_good_pkt_pointers(other_branch, dst_reg, 14716 dst_reg->type, true); 14717 mark_pkt_end(this_branch, insn->dst_reg, false); 14718 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14719 src_reg->type == PTR_TO_PACKET) || 14720 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14721 src_reg->type == PTR_TO_PACKET_META)) { 14722 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 14723 find_good_pkt_pointers(this_branch, src_reg, 14724 src_reg->type, false); 14725 mark_pkt_end(other_branch, insn->src_reg, true); 14726 } else { 14727 return false; 14728 } 14729 break; 14730 case BPF_JGE: 14731 if ((dst_reg->type == PTR_TO_PACKET && 14732 src_reg->type == PTR_TO_PACKET_END) || 14733 (dst_reg->type == PTR_TO_PACKET_META && 14734 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14735 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 14736 find_good_pkt_pointers(this_branch, dst_reg, 14737 dst_reg->type, true); 14738 mark_pkt_end(other_branch, insn->dst_reg, false); 14739 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14740 src_reg->type == PTR_TO_PACKET) || 14741 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14742 src_reg->type == PTR_TO_PACKET_META)) { 14743 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 14744 find_good_pkt_pointers(other_branch, src_reg, 14745 src_reg->type, false); 14746 mark_pkt_end(this_branch, insn->src_reg, true); 14747 } else { 14748 return false; 14749 } 14750 break; 14751 case BPF_JLE: 14752 if ((dst_reg->type == PTR_TO_PACKET && 14753 src_reg->type == PTR_TO_PACKET_END) || 14754 (dst_reg->type == PTR_TO_PACKET_META && 14755 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14756 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 14757 find_good_pkt_pointers(other_branch, dst_reg, 14758 dst_reg->type, false); 14759 mark_pkt_end(this_branch, insn->dst_reg, true); 14760 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14761 src_reg->type == PTR_TO_PACKET) || 14762 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14763 src_reg->type == PTR_TO_PACKET_META)) { 14764 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 14765 find_good_pkt_pointers(this_branch, src_reg, 14766 src_reg->type, true); 14767 mark_pkt_end(other_branch, insn->src_reg, false); 14768 } else { 14769 return false; 14770 } 14771 break; 14772 default: 14773 return false; 14774 } 14775 14776 return true; 14777 } 14778 14779 static void find_equal_scalars(struct bpf_verifier_state *vstate, 14780 struct bpf_reg_state *known_reg) 14781 { 14782 struct bpf_func_state *state; 14783 struct bpf_reg_state *reg; 14784 14785 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14786 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 14787 copy_register_state(reg, known_reg); 14788 })); 14789 } 14790 14791 static int check_cond_jmp_op(struct bpf_verifier_env *env, 14792 struct bpf_insn *insn, int *insn_idx) 14793 { 14794 struct bpf_verifier_state *this_branch = env->cur_state; 14795 struct bpf_verifier_state *other_branch; 14796 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 14797 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 14798 struct bpf_reg_state *eq_branch_regs; 14799 struct bpf_reg_state fake_reg = {}; 14800 u8 opcode = BPF_OP(insn->code); 14801 bool is_jmp32; 14802 int pred = -1; 14803 int err; 14804 14805 /* Only conditional jumps are expected to reach here. */ 14806 if (opcode == BPF_JA || opcode > BPF_JSLE) { 14807 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 14808 return -EINVAL; 14809 } 14810 14811 /* check src2 operand */ 14812 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14813 if (err) 14814 return err; 14815 14816 dst_reg = ®s[insn->dst_reg]; 14817 if (BPF_SRC(insn->code) == BPF_X) { 14818 if (insn->imm != 0) { 14819 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14820 return -EINVAL; 14821 } 14822 14823 /* check src1 operand */ 14824 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14825 if (err) 14826 return err; 14827 14828 src_reg = ®s[insn->src_reg]; 14829 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 14830 is_pointer_value(env, insn->src_reg)) { 14831 verbose(env, "R%d pointer comparison prohibited\n", 14832 insn->src_reg); 14833 return -EACCES; 14834 } 14835 } else { 14836 if (insn->src_reg != BPF_REG_0) { 14837 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14838 return -EINVAL; 14839 } 14840 src_reg = &fake_reg; 14841 src_reg->type = SCALAR_VALUE; 14842 __mark_reg_known(src_reg, insn->imm); 14843 } 14844 14845 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 14846 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32); 14847 if (pred >= 0) { 14848 /* If we get here with a dst_reg pointer type it is because 14849 * above is_branch_taken() special cased the 0 comparison. 14850 */ 14851 if (!__is_pointer_value(false, dst_reg)) 14852 err = mark_chain_precision(env, insn->dst_reg); 14853 if (BPF_SRC(insn->code) == BPF_X && !err && 14854 !__is_pointer_value(false, src_reg)) 14855 err = mark_chain_precision(env, insn->src_reg); 14856 if (err) 14857 return err; 14858 } 14859 14860 if (pred == 1) { 14861 /* Only follow the goto, ignore fall-through. If needed, push 14862 * the fall-through branch for simulation under speculative 14863 * execution. 14864 */ 14865 if (!env->bypass_spec_v1 && 14866 !sanitize_speculative_path(env, insn, *insn_idx + 1, 14867 *insn_idx)) 14868 return -EFAULT; 14869 if (env->log.level & BPF_LOG_LEVEL) 14870 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14871 *insn_idx += insn->off; 14872 return 0; 14873 } else if (pred == 0) { 14874 /* Only follow the fall-through branch, since that's where the 14875 * program will go. If needed, push the goto branch for 14876 * simulation under speculative execution. 14877 */ 14878 if (!env->bypass_spec_v1 && 14879 !sanitize_speculative_path(env, insn, 14880 *insn_idx + insn->off + 1, 14881 *insn_idx)) 14882 return -EFAULT; 14883 if (env->log.level & BPF_LOG_LEVEL) 14884 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14885 return 0; 14886 } 14887 14888 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 14889 false); 14890 if (!other_branch) 14891 return -EFAULT; 14892 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 14893 14894 if (BPF_SRC(insn->code) == BPF_X) { 14895 err = reg_set_min_max(env, 14896 &other_branch_regs[insn->dst_reg], 14897 &other_branch_regs[insn->src_reg], 14898 dst_reg, src_reg, opcode, is_jmp32); 14899 } else /* BPF_SRC(insn->code) == BPF_K */ { 14900 err = reg_set_min_max(env, 14901 &other_branch_regs[insn->dst_reg], 14902 src_reg /* fake one */, 14903 dst_reg, src_reg /* same fake one */, 14904 opcode, is_jmp32); 14905 } 14906 if (err) 14907 return err; 14908 14909 if (BPF_SRC(insn->code) == BPF_X && 14910 src_reg->type == SCALAR_VALUE && src_reg->id && 14911 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 14912 find_equal_scalars(this_branch, src_reg); 14913 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 14914 } 14915 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 14916 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 14917 find_equal_scalars(this_branch, dst_reg); 14918 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 14919 } 14920 14921 /* if one pointer register is compared to another pointer 14922 * register check if PTR_MAYBE_NULL could be lifted. 14923 * E.g. register A - maybe null 14924 * register B - not null 14925 * for JNE A, B, ... - A is not null in the false branch; 14926 * for JEQ A, B, ... - A is not null in the true branch. 14927 * 14928 * Since PTR_TO_BTF_ID points to a kernel struct that does 14929 * not need to be null checked by the BPF program, i.e., 14930 * could be null even without PTR_MAYBE_NULL marking, so 14931 * only propagate nullness when neither reg is that type. 14932 */ 14933 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 14934 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 14935 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 14936 base_type(src_reg->type) != PTR_TO_BTF_ID && 14937 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 14938 eq_branch_regs = NULL; 14939 switch (opcode) { 14940 case BPF_JEQ: 14941 eq_branch_regs = other_branch_regs; 14942 break; 14943 case BPF_JNE: 14944 eq_branch_regs = regs; 14945 break; 14946 default: 14947 /* do nothing */ 14948 break; 14949 } 14950 if (eq_branch_regs) { 14951 if (type_may_be_null(src_reg->type)) 14952 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 14953 else 14954 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 14955 } 14956 } 14957 14958 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 14959 * NOTE: these optimizations below are related with pointer comparison 14960 * which will never be JMP32. 14961 */ 14962 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 14963 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 14964 type_may_be_null(dst_reg->type)) { 14965 /* Mark all identical registers in each branch as either 14966 * safe or unknown depending R == 0 or R != 0 conditional. 14967 */ 14968 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 14969 opcode == BPF_JNE); 14970 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 14971 opcode == BPF_JEQ); 14972 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 14973 this_branch, other_branch) && 14974 is_pointer_value(env, insn->dst_reg)) { 14975 verbose(env, "R%d pointer comparison prohibited\n", 14976 insn->dst_reg); 14977 return -EACCES; 14978 } 14979 if (env->log.level & BPF_LOG_LEVEL) 14980 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14981 return 0; 14982 } 14983 14984 /* verify BPF_LD_IMM64 instruction */ 14985 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 14986 { 14987 struct bpf_insn_aux_data *aux = cur_aux(env); 14988 struct bpf_reg_state *regs = cur_regs(env); 14989 struct bpf_reg_state *dst_reg; 14990 struct bpf_map *map; 14991 int err; 14992 14993 if (BPF_SIZE(insn->code) != BPF_DW) { 14994 verbose(env, "invalid BPF_LD_IMM insn\n"); 14995 return -EINVAL; 14996 } 14997 if (insn->off != 0) { 14998 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 14999 return -EINVAL; 15000 } 15001 15002 err = check_reg_arg(env, insn->dst_reg, DST_OP); 15003 if (err) 15004 return err; 15005 15006 dst_reg = ®s[insn->dst_reg]; 15007 if (insn->src_reg == 0) { 15008 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 15009 15010 dst_reg->type = SCALAR_VALUE; 15011 __mark_reg_known(®s[insn->dst_reg], imm); 15012 return 0; 15013 } 15014 15015 /* All special src_reg cases are listed below. From this point onwards 15016 * we either succeed and assign a corresponding dst_reg->type after 15017 * zeroing the offset, or fail and reject the program. 15018 */ 15019 mark_reg_known_zero(env, regs, insn->dst_reg); 15020 15021 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 15022 dst_reg->type = aux->btf_var.reg_type; 15023 switch (base_type(dst_reg->type)) { 15024 case PTR_TO_MEM: 15025 dst_reg->mem_size = aux->btf_var.mem_size; 15026 break; 15027 case PTR_TO_BTF_ID: 15028 dst_reg->btf = aux->btf_var.btf; 15029 dst_reg->btf_id = aux->btf_var.btf_id; 15030 break; 15031 default: 15032 verbose(env, "bpf verifier is misconfigured\n"); 15033 return -EFAULT; 15034 } 15035 return 0; 15036 } 15037 15038 if (insn->src_reg == BPF_PSEUDO_FUNC) { 15039 struct bpf_prog_aux *aux = env->prog->aux; 15040 u32 subprogno = find_subprog(env, 15041 env->insn_idx + insn->imm + 1); 15042 15043 if (!aux->func_info) { 15044 verbose(env, "missing btf func_info\n"); 15045 return -EINVAL; 15046 } 15047 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 15048 verbose(env, "callback function not static\n"); 15049 return -EINVAL; 15050 } 15051 15052 dst_reg->type = PTR_TO_FUNC; 15053 dst_reg->subprogno = subprogno; 15054 return 0; 15055 } 15056 15057 map = env->used_maps[aux->map_index]; 15058 dst_reg->map_ptr = map; 15059 15060 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 15061 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 15062 dst_reg->type = PTR_TO_MAP_VALUE; 15063 dst_reg->off = aux->map_off; 15064 WARN_ON_ONCE(map->max_entries != 1); 15065 /* We want reg->id to be same (0) as map_value is not distinct */ 15066 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 15067 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 15068 dst_reg->type = CONST_PTR_TO_MAP; 15069 } else { 15070 verbose(env, "bpf verifier is misconfigured\n"); 15071 return -EINVAL; 15072 } 15073 15074 return 0; 15075 } 15076 15077 static bool may_access_skb(enum bpf_prog_type type) 15078 { 15079 switch (type) { 15080 case BPF_PROG_TYPE_SOCKET_FILTER: 15081 case BPF_PROG_TYPE_SCHED_CLS: 15082 case BPF_PROG_TYPE_SCHED_ACT: 15083 return true; 15084 default: 15085 return false; 15086 } 15087 } 15088 15089 /* verify safety of LD_ABS|LD_IND instructions: 15090 * - they can only appear in the programs where ctx == skb 15091 * - since they are wrappers of function calls, they scratch R1-R5 registers, 15092 * preserve R6-R9, and store return value into R0 15093 * 15094 * Implicit input: 15095 * ctx == skb == R6 == CTX 15096 * 15097 * Explicit input: 15098 * SRC == any register 15099 * IMM == 32-bit immediate 15100 * 15101 * Output: 15102 * R0 - 8/16/32-bit skb data converted to cpu endianness 15103 */ 15104 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 15105 { 15106 struct bpf_reg_state *regs = cur_regs(env); 15107 static const int ctx_reg = BPF_REG_6; 15108 u8 mode = BPF_MODE(insn->code); 15109 int i, err; 15110 15111 if (!may_access_skb(resolve_prog_type(env->prog))) { 15112 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 15113 return -EINVAL; 15114 } 15115 15116 if (!env->ops->gen_ld_abs) { 15117 verbose(env, "bpf verifier is misconfigured\n"); 15118 return -EINVAL; 15119 } 15120 15121 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 15122 BPF_SIZE(insn->code) == BPF_DW || 15123 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 15124 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 15125 return -EINVAL; 15126 } 15127 15128 /* check whether implicit source operand (register R6) is readable */ 15129 err = check_reg_arg(env, ctx_reg, SRC_OP); 15130 if (err) 15131 return err; 15132 15133 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 15134 * gen_ld_abs() may terminate the program at runtime, leading to 15135 * reference leak. 15136 */ 15137 err = check_reference_leak(env, false); 15138 if (err) { 15139 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 15140 return err; 15141 } 15142 15143 if (env->cur_state->active_lock.ptr) { 15144 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 15145 return -EINVAL; 15146 } 15147 15148 if (env->cur_state->active_rcu_lock) { 15149 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 15150 return -EINVAL; 15151 } 15152 15153 if (regs[ctx_reg].type != PTR_TO_CTX) { 15154 verbose(env, 15155 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 15156 return -EINVAL; 15157 } 15158 15159 if (mode == BPF_IND) { 15160 /* check explicit source operand */ 15161 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15162 if (err) 15163 return err; 15164 } 15165 15166 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 15167 if (err < 0) 15168 return err; 15169 15170 /* reset caller saved regs to unreadable */ 15171 for (i = 0; i < CALLER_SAVED_REGS; i++) { 15172 mark_reg_not_init(env, regs, caller_saved[i]); 15173 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 15174 } 15175 15176 /* mark destination R0 register as readable, since it contains 15177 * the value fetched from the packet. 15178 * Already marked as written above. 15179 */ 15180 mark_reg_unknown(env, regs, BPF_REG_0); 15181 /* ld_abs load up to 32-bit skb data. */ 15182 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 15183 return 0; 15184 } 15185 15186 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 15187 { 15188 const char *exit_ctx = "At program exit"; 15189 struct tnum enforce_attach_type_range = tnum_unknown; 15190 const struct bpf_prog *prog = env->prog; 15191 struct bpf_reg_state *reg; 15192 struct bpf_retval_range range = retval_range(0, 1); 15193 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 15194 int err; 15195 struct bpf_func_state *frame = env->cur_state->frame[0]; 15196 const bool is_subprog = frame->subprogno; 15197 15198 /* LSM and struct_ops func-ptr's return type could be "void" */ 15199 if (!is_subprog || frame->in_exception_callback_fn) { 15200 switch (prog_type) { 15201 case BPF_PROG_TYPE_LSM: 15202 if (prog->expected_attach_type == BPF_LSM_CGROUP) 15203 /* See below, can be 0 or 0-1 depending on hook. */ 15204 break; 15205 fallthrough; 15206 case BPF_PROG_TYPE_STRUCT_OPS: 15207 if (!prog->aux->attach_func_proto->type) 15208 return 0; 15209 break; 15210 default: 15211 break; 15212 } 15213 } 15214 15215 /* eBPF calling convention is such that R0 is used 15216 * to return the value from eBPF program. 15217 * Make sure that it's readable at this time 15218 * of bpf_exit, which means that program wrote 15219 * something into it earlier 15220 */ 15221 err = check_reg_arg(env, regno, SRC_OP); 15222 if (err) 15223 return err; 15224 15225 if (is_pointer_value(env, regno)) { 15226 verbose(env, "R%d leaks addr as return value\n", regno); 15227 return -EACCES; 15228 } 15229 15230 reg = cur_regs(env) + regno; 15231 15232 if (frame->in_async_callback_fn) { 15233 /* enforce return zero from async callbacks like timer */ 15234 exit_ctx = "At async callback return"; 15235 range = retval_range(0, 0); 15236 goto enforce_retval; 15237 } 15238 15239 if (is_subprog && !frame->in_exception_callback_fn) { 15240 if (reg->type != SCALAR_VALUE) { 15241 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 15242 regno, reg_type_str(env, reg->type)); 15243 return -EINVAL; 15244 } 15245 return 0; 15246 } 15247 15248 switch (prog_type) { 15249 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 15250 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 15251 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 15252 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG || 15253 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 15254 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 15255 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME || 15256 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 15257 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME || 15258 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME) 15259 range = retval_range(1, 1); 15260 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 15261 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 15262 range = retval_range(0, 3); 15263 break; 15264 case BPF_PROG_TYPE_CGROUP_SKB: 15265 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 15266 range = retval_range(0, 3); 15267 enforce_attach_type_range = tnum_range(2, 3); 15268 } 15269 break; 15270 case BPF_PROG_TYPE_CGROUP_SOCK: 15271 case BPF_PROG_TYPE_SOCK_OPS: 15272 case BPF_PROG_TYPE_CGROUP_DEVICE: 15273 case BPF_PROG_TYPE_CGROUP_SYSCTL: 15274 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 15275 break; 15276 case BPF_PROG_TYPE_RAW_TRACEPOINT: 15277 if (!env->prog->aux->attach_btf_id) 15278 return 0; 15279 range = retval_range(0, 0); 15280 break; 15281 case BPF_PROG_TYPE_TRACING: 15282 switch (env->prog->expected_attach_type) { 15283 case BPF_TRACE_FENTRY: 15284 case BPF_TRACE_FEXIT: 15285 range = retval_range(0, 0); 15286 break; 15287 case BPF_TRACE_RAW_TP: 15288 case BPF_MODIFY_RETURN: 15289 return 0; 15290 case BPF_TRACE_ITER: 15291 break; 15292 default: 15293 return -ENOTSUPP; 15294 } 15295 break; 15296 case BPF_PROG_TYPE_SK_LOOKUP: 15297 range = retval_range(SK_DROP, SK_PASS); 15298 break; 15299 15300 case BPF_PROG_TYPE_LSM: 15301 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 15302 /* Regular BPF_PROG_TYPE_LSM programs can return 15303 * any value. 15304 */ 15305 return 0; 15306 } 15307 if (!env->prog->aux->attach_func_proto->type) { 15308 /* Make sure programs that attach to void 15309 * hooks don't try to modify return value. 15310 */ 15311 range = retval_range(1, 1); 15312 } 15313 break; 15314 15315 case BPF_PROG_TYPE_NETFILTER: 15316 range = retval_range(NF_DROP, NF_ACCEPT); 15317 break; 15318 case BPF_PROG_TYPE_EXT: 15319 /* freplace program can return anything as its return value 15320 * depends on the to-be-replaced kernel func or bpf program. 15321 */ 15322 default: 15323 return 0; 15324 } 15325 15326 enforce_retval: 15327 if (reg->type != SCALAR_VALUE) { 15328 verbose(env, "%s the register R%d is not a known value (%s)\n", 15329 exit_ctx, regno, reg_type_str(env, reg->type)); 15330 return -EINVAL; 15331 } 15332 15333 err = mark_chain_precision(env, regno); 15334 if (err) 15335 return err; 15336 15337 if (!retval_range_within(range, reg)) { 15338 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 15339 if (!is_subprog && 15340 prog->expected_attach_type == BPF_LSM_CGROUP && 15341 prog_type == BPF_PROG_TYPE_LSM && 15342 !prog->aux->attach_func_proto->type) 15343 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 15344 return -EINVAL; 15345 } 15346 15347 if (!tnum_is_unknown(enforce_attach_type_range) && 15348 tnum_in(enforce_attach_type_range, reg->var_off)) 15349 env->prog->enforce_expected_attach_type = 1; 15350 return 0; 15351 } 15352 15353 /* non-recursive DFS pseudo code 15354 * 1 procedure DFS-iterative(G,v): 15355 * 2 label v as discovered 15356 * 3 let S be a stack 15357 * 4 S.push(v) 15358 * 5 while S is not empty 15359 * 6 t <- S.peek() 15360 * 7 if t is what we're looking for: 15361 * 8 return t 15362 * 9 for all edges e in G.adjacentEdges(t) do 15363 * 10 if edge e is already labelled 15364 * 11 continue with the next edge 15365 * 12 w <- G.adjacentVertex(t,e) 15366 * 13 if vertex w is not discovered and not explored 15367 * 14 label e as tree-edge 15368 * 15 label w as discovered 15369 * 16 S.push(w) 15370 * 17 continue at 5 15371 * 18 else if vertex w is discovered 15372 * 19 label e as back-edge 15373 * 20 else 15374 * 21 // vertex w is explored 15375 * 22 label e as forward- or cross-edge 15376 * 23 label t as explored 15377 * 24 S.pop() 15378 * 15379 * convention: 15380 * 0x10 - discovered 15381 * 0x11 - discovered and fall-through edge labelled 15382 * 0x12 - discovered and fall-through and branch edges labelled 15383 * 0x20 - explored 15384 */ 15385 15386 enum { 15387 DISCOVERED = 0x10, 15388 EXPLORED = 0x20, 15389 FALLTHROUGH = 1, 15390 BRANCH = 2, 15391 }; 15392 15393 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 15394 { 15395 env->insn_aux_data[idx].prune_point = true; 15396 } 15397 15398 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 15399 { 15400 return env->insn_aux_data[insn_idx].prune_point; 15401 } 15402 15403 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 15404 { 15405 env->insn_aux_data[idx].force_checkpoint = true; 15406 } 15407 15408 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 15409 { 15410 return env->insn_aux_data[insn_idx].force_checkpoint; 15411 } 15412 15413 static void mark_calls_callback(struct bpf_verifier_env *env, int idx) 15414 { 15415 env->insn_aux_data[idx].calls_callback = true; 15416 } 15417 15418 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx) 15419 { 15420 return env->insn_aux_data[insn_idx].calls_callback; 15421 } 15422 15423 enum { 15424 DONE_EXPLORING = 0, 15425 KEEP_EXPLORING = 1, 15426 }; 15427 15428 /* t, w, e - match pseudo-code above: 15429 * t - index of current instruction 15430 * w - next instruction 15431 * e - edge 15432 */ 15433 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 15434 { 15435 int *insn_stack = env->cfg.insn_stack; 15436 int *insn_state = env->cfg.insn_state; 15437 15438 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 15439 return DONE_EXPLORING; 15440 15441 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 15442 return DONE_EXPLORING; 15443 15444 if (w < 0 || w >= env->prog->len) { 15445 verbose_linfo(env, t, "%d: ", t); 15446 verbose(env, "jump out of range from insn %d to %d\n", t, w); 15447 return -EINVAL; 15448 } 15449 15450 if (e == BRANCH) { 15451 /* mark branch target for state pruning */ 15452 mark_prune_point(env, w); 15453 mark_jmp_point(env, w); 15454 } 15455 15456 if (insn_state[w] == 0) { 15457 /* tree-edge */ 15458 insn_state[t] = DISCOVERED | e; 15459 insn_state[w] = DISCOVERED; 15460 if (env->cfg.cur_stack >= env->prog->len) 15461 return -E2BIG; 15462 insn_stack[env->cfg.cur_stack++] = w; 15463 return KEEP_EXPLORING; 15464 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 15465 if (env->bpf_capable) 15466 return DONE_EXPLORING; 15467 verbose_linfo(env, t, "%d: ", t); 15468 verbose_linfo(env, w, "%d: ", w); 15469 verbose(env, "back-edge from insn %d to %d\n", t, w); 15470 return -EINVAL; 15471 } else if (insn_state[w] == EXPLORED) { 15472 /* forward- or cross-edge */ 15473 insn_state[t] = DISCOVERED | e; 15474 } else { 15475 verbose(env, "insn state internal bug\n"); 15476 return -EFAULT; 15477 } 15478 return DONE_EXPLORING; 15479 } 15480 15481 static int visit_func_call_insn(int t, struct bpf_insn *insns, 15482 struct bpf_verifier_env *env, 15483 bool visit_callee) 15484 { 15485 int ret, insn_sz; 15486 15487 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 15488 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 15489 if (ret) 15490 return ret; 15491 15492 mark_prune_point(env, t + insn_sz); 15493 /* when we exit from subprog, we need to record non-linear history */ 15494 mark_jmp_point(env, t + insn_sz); 15495 15496 if (visit_callee) { 15497 mark_prune_point(env, t); 15498 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env); 15499 } 15500 return ret; 15501 } 15502 15503 /* Visits the instruction at index t and returns one of the following: 15504 * < 0 - an error occurred 15505 * DONE_EXPLORING - the instruction was fully explored 15506 * KEEP_EXPLORING - there is still work to be done before it is fully explored 15507 */ 15508 static int visit_insn(int t, struct bpf_verifier_env *env) 15509 { 15510 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 15511 int ret, off, insn_sz; 15512 15513 if (bpf_pseudo_func(insn)) 15514 return visit_func_call_insn(t, insns, env, true); 15515 15516 /* All non-branch instructions have a single fall-through edge. */ 15517 if (BPF_CLASS(insn->code) != BPF_JMP && 15518 BPF_CLASS(insn->code) != BPF_JMP32) { 15519 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 15520 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 15521 } 15522 15523 switch (BPF_OP(insn->code)) { 15524 case BPF_EXIT: 15525 return DONE_EXPLORING; 15526 15527 case BPF_CALL: 15528 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback) 15529 /* Mark this call insn as a prune point to trigger 15530 * is_state_visited() check before call itself is 15531 * processed by __check_func_call(). Otherwise new 15532 * async state will be pushed for further exploration. 15533 */ 15534 mark_prune_point(env, t); 15535 /* For functions that invoke callbacks it is not known how many times 15536 * callback would be called. Verifier models callback calling functions 15537 * by repeatedly visiting callback bodies and returning to origin call 15538 * instruction. 15539 * In order to stop such iteration verifier needs to identify when a 15540 * state identical some state from a previous iteration is reached. 15541 * Check below forces creation of checkpoint before callback calling 15542 * instruction to allow search for such identical states. 15543 */ 15544 if (is_sync_callback_calling_insn(insn)) { 15545 mark_calls_callback(env, t); 15546 mark_force_checkpoint(env, t); 15547 mark_prune_point(env, t); 15548 mark_jmp_point(env, t); 15549 } 15550 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 15551 struct bpf_kfunc_call_arg_meta meta; 15552 15553 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 15554 if (ret == 0 && is_iter_next_kfunc(&meta)) { 15555 mark_prune_point(env, t); 15556 /* Checking and saving state checkpoints at iter_next() call 15557 * is crucial for fast convergence of open-coded iterator loop 15558 * logic, so we need to force it. If we don't do that, 15559 * is_state_visited() might skip saving a checkpoint, causing 15560 * unnecessarily long sequence of not checkpointed 15561 * instructions and jumps, leading to exhaustion of jump 15562 * history buffer, and potentially other undesired outcomes. 15563 * It is expected that with correct open-coded iterators 15564 * convergence will happen quickly, so we don't run a risk of 15565 * exhausting memory. 15566 */ 15567 mark_force_checkpoint(env, t); 15568 } 15569 } 15570 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 15571 15572 case BPF_JA: 15573 if (BPF_SRC(insn->code) != BPF_K) 15574 return -EINVAL; 15575 15576 if (BPF_CLASS(insn->code) == BPF_JMP) 15577 off = insn->off; 15578 else 15579 off = insn->imm; 15580 15581 /* unconditional jump with single edge */ 15582 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 15583 if (ret) 15584 return ret; 15585 15586 mark_prune_point(env, t + off + 1); 15587 mark_jmp_point(env, t + off + 1); 15588 15589 return ret; 15590 15591 default: 15592 /* conditional jump with two edges */ 15593 mark_prune_point(env, t); 15594 15595 ret = push_insn(t, t + 1, FALLTHROUGH, env); 15596 if (ret) 15597 return ret; 15598 15599 return push_insn(t, t + insn->off + 1, BRANCH, env); 15600 } 15601 } 15602 15603 /* non-recursive depth-first-search to detect loops in BPF program 15604 * loop == back-edge in directed graph 15605 */ 15606 static int check_cfg(struct bpf_verifier_env *env) 15607 { 15608 int insn_cnt = env->prog->len; 15609 int *insn_stack, *insn_state; 15610 int ex_insn_beg, i, ret = 0; 15611 bool ex_done = false; 15612 15613 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15614 if (!insn_state) 15615 return -ENOMEM; 15616 15617 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15618 if (!insn_stack) { 15619 kvfree(insn_state); 15620 return -ENOMEM; 15621 } 15622 15623 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 15624 insn_stack[0] = 0; /* 0 is the first instruction */ 15625 env->cfg.cur_stack = 1; 15626 15627 walk_cfg: 15628 while (env->cfg.cur_stack > 0) { 15629 int t = insn_stack[env->cfg.cur_stack - 1]; 15630 15631 ret = visit_insn(t, env); 15632 switch (ret) { 15633 case DONE_EXPLORING: 15634 insn_state[t] = EXPLORED; 15635 env->cfg.cur_stack--; 15636 break; 15637 case KEEP_EXPLORING: 15638 break; 15639 default: 15640 if (ret > 0) { 15641 verbose(env, "visit_insn internal bug\n"); 15642 ret = -EFAULT; 15643 } 15644 goto err_free; 15645 } 15646 } 15647 15648 if (env->cfg.cur_stack < 0) { 15649 verbose(env, "pop stack internal bug\n"); 15650 ret = -EFAULT; 15651 goto err_free; 15652 } 15653 15654 if (env->exception_callback_subprog && !ex_done) { 15655 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start; 15656 15657 insn_state[ex_insn_beg] = DISCOVERED; 15658 insn_stack[0] = ex_insn_beg; 15659 env->cfg.cur_stack = 1; 15660 ex_done = true; 15661 goto walk_cfg; 15662 } 15663 15664 for (i = 0; i < insn_cnt; i++) { 15665 struct bpf_insn *insn = &env->prog->insnsi[i]; 15666 15667 if (insn_state[i] != EXPLORED) { 15668 verbose(env, "unreachable insn %d\n", i); 15669 ret = -EINVAL; 15670 goto err_free; 15671 } 15672 if (bpf_is_ldimm64(insn)) { 15673 if (insn_state[i + 1] != 0) { 15674 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 15675 ret = -EINVAL; 15676 goto err_free; 15677 } 15678 i++; /* skip second half of ldimm64 */ 15679 } 15680 } 15681 ret = 0; /* cfg looks good */ 15682 15683 err_free: 15684 kvfree(insn_state); 15685 kvfree(insn_stack); 15686 env->cfg.insn_state = env->cfg.insn_stack = NULL; 15687 return ret; 15688 } 15689 15690 static int check_abnormal_return(struct bpf_verifier_env *env) 15691 { 15692 int i; 15693 15694 for (i = 1; i < env->subprog_cnt; i++) { 15695 if (env->subprog_info[i].has_ld_abs) { 15696 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 15697 return -EINVAL; 15698 } 15699 if (env->subprog_info[i].has_tail_call) { 15700 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 15701 return -EINVAL; 15702 } 15703 } 15704 return 0; 15705 } 15706 15707 /* The minimum supported BTF func info size */ 15708 #define MIN_BPF_FUNCINFO_SIZE 8 15709 #define MAX_FUNCINFO_REC_SIZE 252 15710 15711 static int check_btf_func_early(struct bpf_verifier_env *env, 15712 const union bpf_attr *attr, 15713 bpfptr_t uattr) 15714 { 15715 u32 krec_size = sizeof(struct bpf_func_info); 15716 const struct btf_type *type, *func_proto; 15717 u32 i, nfuncs, urec_size, min_size; 15718 struct bpf_func_info *krecord; 15719 struct bpf_prog *prog; 15720 const struct btf *btf; 15721 u32 prev_offset = 0; 15722 bpfptr_t urecord; 15723 int ret = -ENOMEM; 15724 15725 nfuncs = attr->func_info_cnt; 15726 if (!nfuncs) { 15727 if (check_abnormal_return(env)) 15728 return -EINVAL; 15729 return 0; 15730 } 15731 15732 urec_size = attr->func_info_rec_size; 15733 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 15734 urec_size > MAX_FUNCINFO_REC_SIZE || 15735 urec_size % sizeof(u32)) { 15736 verbose(env, "invalid func info rec size %u\n", urec_size); 15737 return -EINVAL; 15738 } 15739 15740 prog = env->prog; 15741 btf = prog->aux->btf; 15742 15743 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15744 min_size = min_t(u32, krec_size, urec_size); 15745 15746 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 15747 if (!krecord) 15748 return -ENOMEM; 15749 15750 for (i = 0; i < nfuncs; i++) { 15751 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 15752 if (ret) { 15753 if (ret == -E2BIG) { 15754 verbose(env, "nonzero tailing record in func info"); 15755 /* set the size kernel expects so loader can zero 15756 * out the rest of the record. 15757 */ 15758 if (copy_to_bpfptr_offset(uattr, 15759 offsetof(union bpf_attr, func_info_rec_size), 15760 &min_size, sizeof(min_size))) 15761 ret = -EFAULT; 15762 } 15763 goto err_free; 15764 } 15765 15766 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 15767 ret = -EFAULT; 15768 goto err_free; 15769 } 15770 15771 /* check insn_off */ 15772 ret = -EINVAL; 15773 if (i == 0) { 15774 if (krecord[i].insn_off) { 15775 verbose(env, 15776 "nonzero insn_off %u for the first func info record", 15777 krecord[i].insn_off); 15778 goto err_free; 15779 } 15780 } else if (krecord[i].insn_off <= prev_offset) { 15781 verbose(env, 15782 "same or smaller insn offset (%u) than previous func info record (%u)", 15783 krecord[i].insn_off, prev_offset); 15784 goto err_free; 15785 } 15786 15787 /* check type_id */ 15788 type = btf_type_by_id(btf, krecord[i].type_id); 15789 if (!type || !btf_type_is_func(type)) { 15790 verbose(env, "invalid type id %d in func info", 15791 krecord[i].type_id); 15792 goto err_free; 15793 } 15794 15795 func_proto = btf_type_by_id(btf, type->type); 15796 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 15797 /* btf_func_check() already verified it during BTF load */ 15798 goto err_free; 15799 15800 prev_offset = krecord[i].insn_off; 15801 bpfptr_add(&urecord, urec_size); 15802 } 15803 15804 prog->aux->func_info = krecord; 15805 prog->aux->func_info_cnt = nfuncs; 15806 return 0; 15807 15808 err_free: 15809 kvfree(krecord); 15810 return ret; 15811 } 15812 15813 static int check_btf_func(struct bpf_verifier_env *env, 15814 const union bpf_attr *attr, 15815 bpfptr_t uattr) 15816 { 15817 const struct btf_type *type, *func_proto, *ret_type; 15818 u32 i, nfuncs, urec_size; 15819 struct bpf_func_info *krecord; 15820 struct bpf_func_info_aux *info_aux = NULL; 15821 struct bpf_prog *prog; 15822 const struct btf *btf; 15823 bpfptr_t urecord; 15824 bool scalar_return; 15825 int ret = -ENOMEM; 15826 15827 nfuncs = attr->func_info_cnt; 15828 if (!nfuncs) { 15829 if (check_abnormal_return(env)) 15830 return -EINVAL; 15831 return 0; 15832 } 15833 if (nfuncs != env->subprog_cnt) { 15834 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 15835 return -EINVAL; 15836 } 15837 15838 urec_size = attr->func_info_rec_size; 15839 15840 prog = env->prog; 15841 btf = prog->aux->btf; 15842 15843 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15844 15845 krecord = prog->aux->func_info; 15846 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 15847 if (!info_aux) 15848 return -ENOMEM; 15849 15850 for (i = 0; i < nfuncs; i++) { 15851 /* check insn_off */ 15852 ret = -EINVAL; 15853 15854 if (env->subprog_info[i].start != krecord[i].insn_off) { 15855 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 15856 goto err_free; 15857 } 15858 15859 /* Already checked type_id */ 15860 type = btf_type_by_id(btf, krecord[i].type_id); 15861 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 15862 /* Already checked func_proto */ 15863 func_proto = btf_type_by_id(btf, type->type); 15864 15865 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 15866 scalar_return = 15867 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 15868 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 15869 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 15870 goto err_free; 15871 } 15872 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 15873 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 15874 goto err_free; 15875 } 15876 15877 bpfptr_add(&urecord, urec_size); 15878 } 15879 15880 prog->aux->func_info_aux = info_aux; 15881 return 0; 15882 15883 err_free: 15884 kfree(info_aux); 15885 return ret; 15886 } 15887 15888 static void adjust_btf_func(struct bpf_verifier_env *env) 15889 { 15890 struct bpf_prog_aux *aux = env->prog->aux; 15891 int i; 15892 15893 if (!aux->func_info) 15894 return; 15895 15896 /* func_info is not available for hidden subprogs */ 15897 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 15898 aux->func_info[i].insn_off = env->subprog_info[i].start; 15899 } 15900 15901 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 15902 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 15903 15904 static int check_btf_line(struct bpf_verifier_env *env, 15905 const union bpf_attr *attr, 15906 bpfptr_t uattr) 15907 { 15908 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 15909 struct bpf_subprog_info *sub; 15910 struct bpf_line_info *linfo; 15911 struct bpf_prog *prog; 15912 const struct btf *btf; 15913 bpfptr_t ulinfo; 15914 int err; 15915 15916 nr_linfo = attr->line_info_cnt; 15917 if (!nr_linfo) 15918 return 0; 15919 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 15920 return -EINVAL; 15921 15922 rec_size = attr->line_info_rec_size; 15923 if (rec_size < MIN_BPF_LINEINFO_SIZE || 15924 rec_size > MAX_LINEINFO_REC_SIZE || 15925 rec_size & (sizeof(u32) - 1)) 15926 return -EINVAL; 15927 15928 /* Need to zero it in case the userspace may 15929 * pass in a smaller bpf_line_info object. 15930 */ 15931 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 15932 GFP_KERNEL | __GFP_NOWARN); 15933 if (!linfo) 15934 return -ENOMEM; 15935 15936 prog = env->prog; 15937 btf = prog->aux->btf; 15938 15939 s = 0; 15940 sub = env->subprog_info; 15941 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 15942 expected_size = sizeof(struct bpf_line_info); 15943 ncopy = min_t(u32, expected_size, rec_size); 15944 for (i = 0; i < nr_linfo; i++) { 15945 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 15946 if (err) { 15947 if (err == -E2BIG) { 15948 verbose(env, "nonzero tailing record in line_info"); 15949 if (copy_to_bpfptr_offset(uattr, 15950 offsetof(union bpf_attr, line_info_rec_size), 15951 &expected_size, sizeof(expected_size))) 15952 err = -EFAULT; 15953 } 15954 goto err_free; 15955 } 15956 15957 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 15958 err = -EFAULT; 15959 goto err_free; 15960 } 15961 15962 /* 15963 * Check insn_off to ensure 15964 * 1) strictly increasing AND 15965 * 2) bounded by prog->len 15966 * 15967 * The linfo[0].insn_off == 0 check logically falls into 15968 * the later "missing bpf_line_info for func..." case 15969 * because the first linfo[0].insn_off must be the 15970 * first sub also and the first sub must have 15971 * subprog_info[0].start == 0. 15972 */ 15973 if ((i && linfo[i].insn_off <= prev_offset) || 15974 linfo[i].insn_off >= prog->len) { 15975 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 15976 i, linfo[i].insn_off, prev_offset, 15977 prog->len); 15978 err = -EINVAL; 15979 goto err_free; 15980 } 15981 15982 if (!prog->insnsi[linfo[i].insn_off].code) { 15983 verbose(env, 15984 "Invalid insn code at line_info[%u].insn_off\n", 15985 i); 15986 err = -EINVAL; 15987 goto err_free; 15988 } 15989 15990 if (!btf_name_by_offset(btf, linfo[i].line_off) || 15991 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 15992 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 15993 err = -EINVAL; 15994 goto err_free; 15995 } 15996 15997 if (s != env->subprog_cnt) { 15998 if (linfo[i].insn_off == sub[s].start) { 15999 sub[s].linfo_idx = i; 16000 s++; 16001 } else if (sub[s].start < linfo[i].insn_off) { 16002 verbose(env, "missing bpf_line_info for func#%u\n", s); 16003 err = -EINVAL; 16004 goto err_free; 16005 } 16006 } 16007 16008 prev_offset = linfo[i].insn_off; 16009 bpfptr_add(&ulinfo, rec_size); 16010 } 16011 16012 if (s != env->subprog_cnt) { 16013 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 16014 env->subprog_cnt - s, s); 16015 err = -EINVAL; 16016 goto err_free; 16017 } 16018 16019 prog->aux->linfo = linfo; 16020 prog->aux->nr_linfo = nr_linfo; 16021 16022 return 0; 16023 16024 err_free: 16025 kvfree(linfo); 16026 return err; 16027 } 16028 16029 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 16030 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 16031 16032 static int check_core_relo(struct bpf_verifier_env *env, 16033 const union bpf_attr *attr, 16034 bpfptr_t uattr) 16035 { 16036 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 16037 struct bpf_core_relo core_relo = {}; 16038 struct bpf_prog *prog = env->prog; 16039 const struct btf *btf = prog->aux->btf; 16040 struct bpf_core_ctx ctx = { 16041 .log = &env->log, 16042 .btf = btf, 16043 }; 16044 bpfptr_t u_core_relo; 16045 int err; 16046 16047 nr_core_relo = attr->core_relo_cnt; 16048 if (!nr_core_relo) 16049 return 0; 16050 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 16051 return -EINVAL; 16052 16053 rec_size = attr->core_relo_rec_size; 16054 if (rec_size < MIN_CORE_RELO_SIZE || 16055 rec_size > MAX_CORE_RELO_SIZE || 16056 rec_size % sizeof(u32)) 16057 return -EINVAL; 16058 16059 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 16060 expected_size = sizeof(struct bpf_core_relo); 16061 ncopy = min_t(u32, expected_size, rec_size); 16062 16063 /* Unlike func_info and line_info, copy and apply each CO-RE 16064 * relocation record one at a time. 16065 */ 16066 for (i = 0; i < nr_core_relo; i++) { 16067 /* future proofing when sizeof(bpf_core_relo) changes */ 16068 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 16069 if (err) { 16070 if (err == -E2BIG) { 16071 verbose(env, "nonzero tailing record in core_relo"); 16072 if (copy_to_bpfptr_offset(uattr, 16073 offsetof(union bpf_attr, core_relo_rec_size), 16074 &expected_size, sizeof(expected_size))) 16075 err = -EFAULT; 16076 } 16077 break; 16078 } 16079 16080 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 16081 err = -EFAULT; 16082 break; 16083 } 16084 16085 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 16086 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 16087 i, core_relo.insn_off, prog->len); 16088 err = -EINVAL; 16089 break; 16090 } 16091 16092 err = bpf_core_apply(&ctx, &core_relo, i, 16093 &prog->insnsi[core_relo.insn_off / 8]); 16094 if (err) 16095 break; 16096 bpfptr_add(&u_core_relo, rec_size); 16097 } 16098 return err; 16099 } 16100 16101 static int check_btf_info_early(struct bpf_verifier_env *env, 16102 const union bpf_attr *attr, 16103 bpfptr_t uattr) 16104 { 16105 struct btf *btf; 16106 int err; 16107 16108 if (!attr->func_info_cnt && !attr->line_info_cnt) { 16109 if (check_abnormal_return(env)) 16110 return -EINVAL; 16111 return 0; 16112 } 16113 16114 btf = btf_get_by_fd(attr->prog_btf_fd); 16115 if (IS_ERR(btf)) 16116 return PTR_ERR(btf); 16117 if (btf_is_kernel(btf)) { 16118 btf_put(btf); 16119 return -EACCES; 16120 } 16121 env->prog->aux->btf = btf; 16122 16123 err = check_btf_func_early(env, attr, uattr); 16124 if (err) 16125 return err; 16126 return 0; 16127 } 16128 16129 static int check_btf_info(struct bpf_verifier_env *env, 16130 const union bpf_attr *attr, 16131 bpfptr_t uattr) 16132 { 16133 int err; 16134 16135 if (!attr->func_info_cnt && !attr->line_info_cnt) { 16136 if (check_abnormal_return(env)) 16137 return -EINVAL; 16138 return 0; 16139 } 16140 16141 err = check_btf_func(env, attr, uattr); 16142 if (err) 16143 return err; 16144 16145 err = check_btf_line(env, attr, uattr); 16146 if (err) 16147 return err; 16148 16149 err = check_core_relo(env, attr, uattr); 16150 if (err) 16151 return err; 16152 16153 return 0; 16154 } 16155 16156 /* check %cur's range satisfies %old's */ 16157 static bool range_within(struct bpf_reg_state *old, 16158 struct bpf_reg_state *cur) 16159 { 16160 return old->umin_value <= cur->umin_value && 16161 old->umax_value >= cur->umax_value && 16162 old->smin_value <= cur->smin_value && 16163 old->smax_value >= cur->smax_value && 16164 old->u32_min_value <= cur->u32_min_value && 16165 old->u32_max_value >= cur->u32_max_value && 16166 old->s32_min_value <= cur->s32_min_value && 16167 old->s32_max_value >= cur->s32_max_value; 16168 } 16169 16170 /* If in the old state two registers had the same id, then they need to have 16171 * the same id in the new state as well. But that id could be different from 16172 * the old state, so we need to track the mapping from old to new ids. 16173 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 16174 * regs with old id 5 must also have new id 9 for the new state to be safe. But 16175 * regs with a different old id could still have new id 9, we don't care about 16176 * that. 16177 * So we look through our idmap to see if this old id has been seen before. If 16178 * so, we require the new id to match; otherwise, we add the id pair to the map. 16179 */ 16180 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 16181 { 16182 struct bpf_id_pair *map = idmap->map; 16183 unsigned int i; 16184 16185 /* either both IDs should be set or both should be zero */ 16186 if (!!old_id != !!cur_id) 16187 return false; 16188 16189 if (old_id == 0) /* cur_id == 0 as well */ 16190 return true; 16191 16192 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 16193 if (!map[i].old) { 16194 /* Reached an empty slot; haven't seen this id before */ 16195 map[i].old = old_id; 16196 map[i].cur = cur_id; 16197 return true; 16198 } 16199 if (map[i].old == old_id) 16200 return map[i].cur == cur_id; 16201 if (map[i].cur == cur_id) 16202 return false; 16203 } 16204 /* We ran out of idmap slots, which should be impossible */ 16205 WARN_ON_ONCE(1); 16206 return false; 16207 } 16208 16209 /* Similar to check_ids(), but allocate a unique temporary ID 16210 * for 'old_id' or 'cur_id' of zero. 16211 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 16212 */ 16213 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 16214 { 16215 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 16216 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 16217 16218 return check_ids(old_id, cur_id, idmap); 16219 } 16220 16221 static void clean_func_state(struct bpf_verifier_env *env, 16222 struct bpf_func_state *st) 16223 { 16224 enum bpf_reg_liveness live; 16225 int i, j; 16226 16227 for (i = 0; i < BPF_REG_FP; i++) { 16228 live = st->regs[i].live; 16229 /* liveness must not touch this register anymore */ 16230 st->regs[i].live |= REG_LIVE_DONE; 16231 if (!(live & REG_LIVE_READ)) 16232 /* since the register is unused, clear its state 16233 * to make further comparison simpler 16234 */ 16235 __mark_reg_not_init(env, &st->regs[i]); 16236 } 16237 16238 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 16239 live = st->stack[i].spilled_ptr.live; 16240 /* liveness must not touch this stack slot anymore */ 16241 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 16242 if (!(live & REG_LIVE_READ)) { 16243 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 16244 for (j = 0; j < BPF_REG_SIZE; j++) 16245 st->stack[i].slot_type[j] = STACK_INVALID; 16246 } 16247 } 16248 } 16249 16250 static void clean_verifier_state(struct bpf_verifier_env *env, 16251 struct bpf_verifier_state *st) 16252 { 16253 int i; 16254 16255 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 16256 /* all regs in this state in all frames were already marked */ 16257 return; 16258 16259 for (i = 0; i <= st->curframe; i++) 16260 clean_func_state(env, st->frame[i]); 16261 } 16262 16263 /* the parentage chains form a tree. 16264 * the verifier states are added to state lists at given insn and 16265 * pushed into state stack for future exploration. 16266 * when the verifier reaches bpf_exit insn some of the verifer states 16267 * stored in the state lists have their final liveness state already, 16268 * but a lot of states will get revised from liveness point of view when 16269 * the verifier explores other branches. 16270 * Example: 16271 * 1: r0 = 1 16272 * 2: if r1 == 100 goto pc+1 16273 * 3: r0 = 2 16274 * 4: exit 16275 * when the verifier reaches exit insn the register r0 in the state list of 16276 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 16277 * of insn 2 and goes exploring further. At the insn 4 it will walk the 16278 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 16279 * 16280 * Since the verifier pushes the branch states as it sees them while exploring 16281 * the program the condition of walking the branch instruction for the second 16282 * time means that all states below this branch were already explored and 16283 * their final liveness marks are already propagated. 16284 * Hence when the verifier completes the search of state list in is_state_visited() 16285 * we can call this clean_live_states() function to mark all liveness states 16286 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 16287 * will not be used. 16288 * This function also clears the registers and stack for states that !READ 16289 * to simplify state merging. 16290 * 16291 * Important note here that walking the same branch instruction in the callee 16292 * doesn't meant that the states are DONE. The verifier has to compare 16293 * the callsites 16294 */ 16295 static void clean_live_states(struct bpf_verifier_env *env, int insn, 16296 struct bpf_verifier_state *cur) 16297 { 16298 struct bpf_verifier_state_list *sl; 16299 16300 sl = *explored_state(env, insn); 16301 while (sl) { 16302 if (sl->state.branches) 16303 goto next; 16304 if (sl->state.insn_idx != insn || 16305 !same_callsites(&sl->state, cur)) 16306 goto next; 16307 clean_verifier_state(env, &sl->state); 16308 next: 16309 sl = sl->next; 16310 } 16311 } 16312 16313 static bool regs_exact(const struct bpf_reg_state *rold, 16314 const struct bpf_reg_state *rcur, 16315 struct bpf_idmap *idmap) 16316 { 16317 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16318 check_ids(rold->id, rcur->id, idmap) && 16319 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16320 } 16321 16322 /* Returns true if (rold safe implies rcur safe) */ 16323 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 16324 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact) 16325 { 16326 if (exact) 16327 return regs_exact(rold, rcur, idmap); 16328 16329 if (!(rold->live & REG_LIVE_READ)) 16330 /* explored state didn't use this */ 16331 return true; 16332 if (rold->type == NOT_INIT) 16333 /* explored state can't have used this */ 16334 return true; 16335 if (rcur->type == NOT_INIT) 16336 return false; 16337 16338 /* Enforce that register types have to match exactly, including their 16339 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 16340 * rule. 16341 * 16342 * One can make a point that using a pointer register as unbounded 16343 * SCALAR would be technically acceptable, but this could lead to 16344 * pointer leaks because scalars are allowed to leak while pointers 16345 * are not. We could make this safe in special cases if root is 16346 * calling us, but it's probably not worth the hassle. 16347 * 16348 * Also, register types that are *not* MAYBE_NULL could technically be 16349 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 16350 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 16351 * to the same map). 16352 * However, if the old MAYBE_NULL register then got NULL checked, 16353 * doing so could have affected others with the same id, and we can't 16354 * check for that because we lost the id when we converted to 16355 * a non-MAYBE_NULL variant. 16356 * So, as a general rule we don't allow mixing MAYBE_NULL and 16357 * non-MAYBE_NULL registers as well. 16358 */ 16359 if (rold->type != rcur->type) 16360 return false; 16361 16362 switch (base_type(rold->type)) { 16363 case SCALAR_VALUE: 16364 if (env->explore_alu_limits) { 16365 /* explore_alu_limits disables tnum_in() and range_within() 16366 * logic and requires everything to be strict 16367 */ 16368 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16369 check_scalar_ids(rold->id, rcur->id, idmap); 16370 } 16371 if (!rold->precise) 16372 return true; 16373 /* Why check_ids() for scalar registers? 16374 * 16375 * Consider the following BPF code: 16376 * 1: r6 = ... unbound scalar, ID=a ... 16377 * 2: r7 = ... unbound scalar, ID=b ... 16378 * 3: if (r6 > r7) goto +1 16379 * 4: r6 = r7 16380 * 5: if (r6 > X) goto ... 16381 * 6: ... memory operation using r7 ... 16382 * 16383 * First verification path is [1-6]: 16384 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 16385 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark 16386 * r7 <= X, because r6 and r7 share same id. 16387 * Next verification path is [1-4, 6]. 16388 * 16389 * Instruction (6) would be reached in two states: 16390 * I. r6{.id=b}, r7{.id=b} via path 1-6; 16391 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 16392 * 16393 * Use check_ids() to distinguish these states. 16394 * --- 16395 * Also verify that new value satisfies old value range knowledge. 16396 */ 16397 return range_within(rold, rcur) && 16398 tnum_in(rold->var_off, rcur->var_off) && 16399 check_scalar_ids(rold->id, rcur->id, idmap); 16400 case PTR_TO_MAP_KEY: 16401 case PTR_TO_MAP_VALUE: 16402 case PTR_TO_MEM: 16403 case PTR_TO_BUF: 16404 case PTR_TO_TP_BUFFER: 16405 /* If the new min/max/var_off satisfy the old ones and 16406 * everything else matches, we are OK. 16407 */ 16408 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 16409 range_within(rold, rcur) && 16410 tnum_in(rold->var_off, rcur->var_off) && 16411 check_ids(rold->id, rcur->id, idmap) && 16412 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16413 case PTR_TO_PACKET_META: 16414 case PTR_TO_PACKET: 16415 /* We must have at least as much range as the old ptr 16416 * did, so that any accesses which were safe before are 16417 * still safe. This is true even if old range < old off, 16418 * since someone could have accessed through (ptr - k), or 16419 * even done ptr -= k in a register, to get a safe access. 16420 */ 16421 if (rold->range > rcur->range) 16422 return false; 16423 /* If the offsets don't match, we can't trust our alignment; 16424 * nor can we be sure that we won't fall out of range. 16425 */ 16426 if (rold->off != rcur->off) 16427 return false; 16428 /* id relations must be preserved */ 16429 if (!check_ids(rold->id, rcur->id, idmap)) 16430 return false; 16431 /* new val must satisfy old val knowledge */ 16432 return range_within(rold, rcur) && 16433 tnum_in(rold->var_off, rcur->var_off); 16434 case PTR_TO_STACK: 16435 /* two stack pointers are equal only if they're pointing to 16436 * the same stack frame, since fp-8 in foo != fp-8 in bar 16437 */ 16438 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 16439 default: 16440 return regs_exact(rold, rcur, idmap); 16441 } 16442 } 16443 16444 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 16445 struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact) 16446 { 16447 int i, spi; 16448 16449 /* walk slots of the explored stack and ignore any additional 16450 * slots in the current stack, since explored(safe) state 16451 * didn't use them 16452 */ 16453 for (i = 0; i < old->allocated_stack; i++) { 16454 struct bpf_reg_state *old_reg, *cur_reg; 16455 16456 spi = i / BPF_REG_SIZE; 16457 16458 if (exact && 16459 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16460 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16461 return false; 16462 16463 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) { 16464 i += BPF_REG_SIZE - 1; 16465 /* explored state didn't use this */ 16466 continue; 16467 } 16468 16469 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 16470 continue; 16471 16472 if (env->allow_uninit_stack && 16473 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 16474 continue; 16475 16476 /* explored stack has more populated slots than current stack 16477 * and these slots were used 16478 */ 16479 if (i >= cur->allocated_stack) 16480 return false; 16481 16482 /* if old state was safe with misc data in the stack 16483 * it will be safe with zero-initialized stack. 16484 * The opposite is not true 16485 */ 16486 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 16487 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 16488 continue; 16489 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16490 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16491 /* Ex: old explored (safe) state has STACK_SPILL in 16492 * this stack slot, but current has STACK_MISC -> 16493 * this verifier states are not equivalent, 16494 * return false to continue verification of this path 16495 */ 16496 return false; 16497 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 16498 continue; 16499 /* Both old and cur are having same slot_type */ 16500 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 16501 case STACK_SPILL: 16502 /* when explored and current stack slot are both storing 16503 * spilled registers, check that stored pointers types 16504 * are the same as well. 16505 * Ex: explored safe path could have stored 16506 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 16507 * but current path has stored: 16508 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 16509 * such verifier states are not equivalent. 16510 * return false to continue verification of this path 16511 */ 16512 if (!regsafe(env, &old->stack[spi].spilled_ptr, 16513 &cur->stack[spi].spilled_ptr, idmap, exact)) 16514 return false; 16515 break; 16516 case STACK_DYNPTR: 16517 old_reg = &old->stack[spi].spilled_ptr; 16518 cur_reg = &cur->stack[spi].spilled_ptr; 16519 if (old_reg->dynptr.type != cur_reg->dynptr.type || 16520 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 16521 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16522 return false; 16523 break; 16524 case STACK_ITER: 16525 old_reg = &old->stack[spi].spilled_ptr; 16526 cur_reg = &cur->stack[spi].spilled_ptr; 16527 /* iter.depth is not compared between states as it 16528 * doesn't matter for correctness and would otherwise 16529 * prevent convergence; we maintain it only to prevent 16530 * infinite loop check triggering, see 16531 * iter_active_depths_differ() 16532 */ 16533 if (old_reg->iter.btf != cur_reg->iter.btf || 16534 old_reg->iter.btf_id != cur_reg->iter.btf_id || 16535 old_reg->iter.state != cur_reg->iter.state || 16536 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 16537 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16538 return false; 16539 break; 16540 case STACK_MISC: 16541 case STACK_ZERO: 16542 case STACK_INVALID: 16543 continue; 16544 /* Ensure that new unhandled slot types return false by default */ 16545 default: 16546 return false; 16547 } 16548 } 16549 return true; 16550 } 16551 16552 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 16553 struct bpf_idmap *idmap) 16554 { 16555 int i; 16556 16557 if (old->acquired_refs != cur->acquired_refs) 16558 return false; 16559 16560 for (i = 0; i < old->acquired_refs; i++) { 16561 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 16562 return false; 16563 } 16564 16565 return true; 16566 } 16567 16568 /* compare two verifier states 16569 * 16570 * all states stored in state_list are known to be valid, since 16571 * verifier reached 'bpf_exit' instruction through them 16572 * 16573 * this function is called when verifier exploring different branches of 16574 * execution popped from the state stack. If it sees an old state that has 16575 * more strict register state and more strict stack state then this execution 16576 * branch doesn't need to be explored further, since verifier already 16577 * concluded that more strict state leads to valid finish. 16578 * 16579 * Therefore two states are equivalent if register state is more conservative 16580 * and explored stack state is more conservative than the current one. 16581 * Example: 16582 * explored current 16583 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 16584 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 16585 * 16586 * In other words if current stack state (one being explored) has more 16587 * valid slots than old one that already passed validation, it means 16588 * the verifier can stop exploring and conclude that current state is valid too 16589 * 16590 * Similarly with registers. If explored state has register type as invalid 16591 * whereas register type in current state is meaningful, it means that 16592 * the current state will reach 'bpf_exit' instruction safely 16593 */ 16594 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 16595 struct bpf_func_state *cur, bool exact) 16596 { 16597 int i; 16598 16599 for (i = 0; i < MAX_BPF_REG; i++) 16600 if (!regsafe(env, &old->regs[i], &cur->regs[i], 16601 &env->idmap_scratch, exact)) 16602 return false; 16603 16604 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 16605 return false; 16606 16607 if (!refsafe(old, cur, &env->idmap_scratch)) 16608 return false; 16609 16610 return true; 16611 } 16612 16613 static void reset_idmap_scratch(struct bpf_verifier_env *env) 16614 { 16615 env->idmap_scratch.tmp_id_gen = env->id_gen; 16616 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 16617 } 16618 16619 static bool states_equal(struct bpf_verifier_env *env, 16620 struct bpf_verifier_state *old, 16621 struct bpf_verifier_state *cur, 16622 bool exact) 16623 { 16624 int i; 16625 16626 if (old->curframe != cur->curframe) 16627 return false; 16628 16629 reset_idmap_scratch(env); 16630 16631 /* Verification state from speculative execution simulation 16632 * must never prune a non-speculative execution one. 16633 */ 16634 if (old->speculative && !cur->speculative) 16635 return false; 16636 16637 if (old->active_lock.ptr != cur->active_lock.ptr) 16638 return false; 16639 16640 /* Old and cur active_lock's have to be either both present 16641 * or both absent. 16642 */ 16643 if (!!old->active_lock.id != !!cur->active_lock.id) 16644 return false; 16645 16646 if (old->active_lock.id && 16647 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch)) 16648 return false; 16649 16650 if (old->active_rcu_lock != cur->active_rcu_lock) 16651 return false; 16652 16653 /* for states to be equal callsites have to be the same 16654 * and all frame states need to be equivalent 16655 */ 16656 for (i = 0; i <= old->curframe; i++) { 16657 if (old->frame[i]->callsite != cur->frame[i]->callsite) 16658 return false; 16659 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact)) 16660 return false; 16661 } 16662 return true; 16663 } 16664 16665 /* Return 0 if no propagation happened. Return negative error code if error 16666 * happened. Otherwise, return the propagated bit. 16667 */ 16668 static int propagate_liveness_reg(struct bpf_verifier_env *env, 16669 struct bpf_reg_state *reg, 16670 struct bpf_reg_state *parent_reg) 16671 { 16672 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 16673 u8 flag = reg->live & REG_LIVE_READ; 16674 int err; 16675 16676 /* When comes here, read flags of PARENT_REG or REG could be any of 16677 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 16678 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 16679 */ 16680 if (parent_flag == REG_LIVE_READ64 || 16681 /* Or if there is no read flag from REG. */ 16682 !flag || 16683 /* Or if the read flag from REG is the same as PARENT_REG. */ 16684 parent_flag == flag) 16685 return 0; 16686 16687 err = mark_reg_read(env, reg, parent_reg, flag); 16688 if (err) 16689 return err; 16690 16691 return flag; 16692 } 16693 16694 /* A write screens off any subsequent reads; but write marks come from the 16695 * straight-line code between a state and its parent. When we arrive at an 16696 * equivalent state (jump target or such) we didn't arrive by the straight-line 16697 * code, so read marks in the state must propagate to the parent regardless 16698 * of the state's write marks. That's what 'parent == state->parent' comparison 16699 * in mark_reg_read() is for. 16700 */ 16701 static int propagate_liveness(struct bpf_verifier_env *env, 16702 const struct bpf_verifier_state *vstate, 16703 struct bpf_verifier_state *vparent) 16704 { 16705 struct bpf_reg_state *state_reg, *parent_reg; 16706 struct bpf_func_state *state, *parent; 16707 int i, frame, err = 0; 16708 16709 if (vparent->curframe != vstate->curframe) { 16710 WARN(1, "propagate_live: parent frame %d current frame %d\n", 16711 vparent->curframe, vstate->curframe); 16712 return -EFAULT; 16713 } 16714 /* Propagate read liveness of registers... */ 16715 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 16716 for (frame = 0; frame <= vstate->curframe; frame++) { 16717 parent = vparent->frame[frame]; 16718 state = vstate->frame[frame]; 16719 parent_reg = parent->regs; 16720 state_reg = state->regs; 16721 /* We don't need to worry about FP liveness, it's read-only */ 16722 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 16723 err = propagate_liveness_reg(env, &state_reg[i], 16724 &parent_reg[i]); 16725 if (err < 0) 16726 return err; 16727 if (err == REG_LIVE_READ64) 16728 mark_insn_zext(env, &parent_reg[i]); 16729 } 16730 16731 /* Propagate stack slots. */ 16732 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 16733 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 16734 parent_reg = &parent->stack[i].spilled_ptr; 16735 state_reg = &state->stack[i].spilled_ptr; 16736 err = propagate_liveness_reg(env, state_reg, 16737 parent_reg); 16738 if (err < 0) 16739 return err; 16740 } 16741 } 16742 return 0; 16743 } 16744 16745 /* find precise scalars in the previous equivalent state and 16746 * propagate them into the current state 16747 */ 16748 static int propagate_precision(struct bpf_verifier_env *env, 16749 const struct bpf_verifier_state *old) 16750 { 16751 struct bpf_reg_state *state_reg; 16752 struct bpf_func_state *state; 16753 int i, err = 0, fr; 16754 bool first; 16755 16756 for (fr = old->curframe; fr >= 0; fr--) { 16757 state = old->frame[fr]; 16758 state_reg = state->regs; 16759 first = true; 16760 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 16761 if (state_reg->type != SCALAR_VALUE || 16762 !state_reg->precise || 16763 !(state_reg->live & REG_LIVE_READ)) 16764 continue; 16765 if (env->log.level & BPF_LOG_LEVEL2) { 16766 if (first) 16767 verbose(env, "frame %d: propagating r%d", fr, i); 16768 else 16769 verbose(env, ",r%d", i); 16770 } 16771 bt_set_frame_reg(&env->bt, fr, i); 16772 first = false; 16773 } 16774 16775 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16776 if (!is_spilled_reg(&state->stack[i])) 16777 continue; 16778 state_reg = &state->stack[i].spilled_ptr; 16779 if (state_reg->type != SCALAR_VALUE || 16780 !state_reg->precise || 16781 !(state_reg->live & REG_LIVE_READ)) 16782 continue; 16783 if (env->log.level & BPF_LOG_LEVEL2) { 16784 if (first) 16785 verbose(env, "frame %d: propagating fp%d", 16786 fr, (-i - 1) * BPF_REG_SIZE); 16787 else 16788 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 16789 } 16790 bt_set_frame_slot(&env->bt, fr, i); 16791 first = false; 16792 } 16793 if (!first) 16794 verbose(env, "\n"); 16795 } 16796 16797 err = mark_chain_precision_batch(env); 16798 if (err < 0) 16799 return err; 16800 16801 return 0; 16802 } 16803 16804 static bool states_maybe_looping(struct bpf_verifier_state *old, 16805 struct bpf_verifier_state *cur) 16806 { 16807 struct bpf_func_state *fold, *fcur; 16808 int i, fr = cur->curframe; 16809 16810 if (old->curframe != fr) 16811 return false; 16812 16813 fold = old->frame[fr]; 16814 fcur = cur->frame[fr]; 16815 for (i = 0; i < MAX_BPF_REG; i++) 16816 if (memcmp(&fold->regs[i], &fcur->regs[i], 16817 offsetof(struct bpf_reg_state, parent))) 16818 return false; 16819 return true; 16820 } 16821 16822 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 16823 { 16824 return env->insn_aux_data[insn_idx].is_iter_next; 16825 } 16826 16827 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 16828 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 16829 * states to match, which otherwise would look like an infinite loop. So while 16830 * iter_next() calls are taken care of, we still need to be careful and 16831 * prevent erroneous and too eager declaration of "ininite loop", when 16832 * iterators are involved. 16833 * 16834 * Here's a situation in pseudo-BPF assembly form: 16835 * 16836 * 0: again: ; set up iter_next() call args 16837 * 1: r1 = &it ; <CHECKPOINT HERE> 16838 * 2: call bpf_iter_num_next ; this is iter_next() call 16839 * 3: if r0 == 0 goto done 16840 * 4: ... something useful here ... 16841 * 5: goto again ; another iteration 16842 * 6: done: 16843 * 7: r1 = &it 16844 * 8: call bpf_iter_num_destroy ; clean up iter state 16845 * 9: exit 16846 * 16847 * This is a typical loop. Let's assume that we have a prune point at 1:, 16848 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 16849 * again`, assuming other heuristics don't get in a way). 16850 * 16851 * When we first time come to 1:, let's say we have some state X. We proceed 16852 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 16853 * Now we come back to validate that forked ACTIVE state. We proceed through 16854 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 16855 * are converging. But the problem is that we don't know that yet, as this 16856 * convergence has to happen at iter_next() call site only. So if nothing is 16857 * done, at 1: verifier will use bounded loop logic and declare infinite 16858 * looping (and would be *technically* correct, if not for iterator's 16859 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 16860 * don't want that. So what we do in process_iter_next_call() when we go on 16861 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 16862 * a different iteration. So when we suspect an infinite loop, we additionally 16863 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 16864 * pretend we are not looping and wait for next iter_next() call. 16865 * 16866 * This only applies to ACTIVE state. In DRAINED state we don't expect to 16867 * loop, because that would actually mean infinite loop, as DRAINED state is 16868 * "sticky", and so we'll keep returning into the same instruction with the 16869 * same state (at least in one of possible code paths). 16870 * 16871 * This approach allows to keep infinite loop heuristic even in the face of 16872 * active iterator. E.g., C snippet below is and will be detected as 16873 * inifintely looping: 16874 * 16875 * struct bpf_iter_num it; 16876 * int *p, x; 16877 * 16878 * bpf_iter_num_new(&it, 0, 10); 16879 * while ((p = bpf_iter_num_next(&t))) { 16880 * x = p; 16881 * while (x--) {} // <<-- infinite loop here 16882 * } 16883 * 16884 */ 16885 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 16886 { 16887 struct bpf_reg_state *slot, *cur_slot; 16888 struct bpf_func_state *state; 16889 int i, fr; 16890 16891 for (fr = old->curframe; fr >= 0; fr--) { 16892 state = old->frame[fr]; 16893 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16894 if (state->stack[i].slot_type[0] != STACK_ITER) 16895 continue; 16896 16897 slot = &state->stack[i].spilled_ptr; 16898 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 16899 continue; 16900 16901 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 16902 if (cur_slot->iter.depth != slot->iter.depth) 16903 return true; 16904 } 16905 } 16906 return false; 16907 } 16908 16909 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 16910 { 16911 struct bpf_verifier_state_list *new_sl; 16912 struct bpf_verifier_state_list *sl, **pprev; 16913 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry; 16914 int i, j, n, err, states_cnt = 0; 16915 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx); 16916 bool add_new_state = force_new_state; 16917 bool force_exact; 16918 16919 /* bpf progs typically have pruning point every 4 instructions 16920 * http://vger.kernel.org/bpfconf2019.html#session-1 16921 * Do not add new state for future pruning if the verifier hasn't seen 16922 * at least 2 jumps and at least 8 instructions. 16923 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 16924 * In tests that amounts to up to 50% reduction into total verifier 16925 * memory consumption and 20% verifier time speedup. 16926 */ 16927 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 16928 env->insn_processed - env->prev_insn_processed >= 8) 16929 add_new_state = true; 16930 16931 pprev = explored_state(env, insn_idx); 16932 sl = *pprev; 16933 16934 clean_live_states(env, insn_idx, cur); 16935 16936 while (sl) { 16937 states_cnt++; 16938 if (sl->state.insn_idx != insn_idx) 16939 goto next; 16940 16941 if (sl->state.branches) { 16942 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 16943 16944 if (frame->in_async_callback_fn && 16945 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 16946 /* Different async_entry_cnt means that the verifier is 16947 * processing another entry into async callback. 16948 * Seeing the same state is not an indication of infinite 16949 * loop or infinite recursion. 16950 * But finding the same state doesn't mean that it's safe 16951 * to stop processing the current state. The previous state 16952 * hasn't yet reached bpf_exit, since state.branches > 0. 16953 * Checking in_async_callback_fn alone is not enough either. 16954 * Since the verifier still needs to catch infinite loops 16955 * inside async callbacks. 16956 */ 16957 goto skip_inf_loop_check; 16958 } 16959 /* BPF open-coded iterators loop detection is special. 16960 * states_maybe_looping() logic is too simplistic in detecting 16961 * states that *might* be equivalent, because it doesn't know 16962 * about ID remapping, so don't even perform it. 16963 * See process_iter_next_call() and iter_active_depths_differ() 16964 * for overview of the logic. When current and one of parent 16965 * states are detected as equivalent, it's a good thing: we prove 16966 * convergence and can stop simulating further iterations. 16967 * It's safe to assume that iterator loop will finish, taking into 16968 * account iter_next() contract of eventually returning 16969 * sticky NULL result. 16970 * 16971 * Note, that states have to be compared exactly in this case because 16972 * read and precision marks might not be finalized inside the loop. 16973 * E.g. as in the program below: 16974 * 16975 * 1. r7 = -16 16976 * 2. r6 = bpf_get_prandom_u32() 16977 * 3. while (bpf_iter_num_next(&fp[-8])) { 16978 * 4. if (r6 != 42) { 16979 * 5. r7 = -32 16980 * 6. r6 = bpf_get_prandom_u32() 16981 * 7. continue 16982 * 8. } 16983 * 9. r0 = r10 16984 * 10. r0 += r7 16985 * 11. r8 = *(u64 *)(r0 + 0) 16986 * 12. r6 = bpf_get_prandom_u32() 16987 * 13. } 16988 * 16989 * Here verifier would first visit path 1-3, create a checkpoint at 3 16990 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 16991 * not have read or precision mark for r7 yet, thus inexact states 16992 * comparison would discard current state with r7=-32 16993 * => unsafe memory access at 11 would not be caught. 16994 */ 16995 if (is_iter_next_insn(env, insn_idx)) { 16996 if (states_equal(env, &sl->state, cur, true)) { 16997 struct bpf_func_state *cur_frame; 16998 struct bpf_reg_state *iter_state, *iter_reg; 16999 int spi; 17000 17001 cur_frame = cur->frame[cur->curframe]; 17002 /* btf_check_iter_kfuncs() enforces that 17003 * iter state pointer is always the first arg 17004 */ 17005 iter_reg = &cur_frame->regs[BPF_REG_1]; 17006 /* current state is valid due to states_equal(), 17007 * so we can assume valid iter and reg state, 17008 * no need for extra (re-)validations 17009 */ 17010 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 17011 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 17012 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 17013 update_loop_entry(cur, &sl->state); 17014 goto hit; 17015 } 17016 } 17017 goto skip_inf_loop_check; 17018 } 17019 if (calls_callback(env, insn_idx)) { 17020 if (states_equal(env, &sl->state, cur, true)) 17021 goto hit; 17022 goto skip_inf_loop_check; 17023 } 17024 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 17025 if (states_maybe_looping(&sl->state, cur) && 17026 states_equal(env, &sl->state, cur, false) && 17027 !iter_active_depths_differ(&sl->state, cur) && 17028 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 17029 verbose_linfo(env, insn_idx, "; "); 17030 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 17031 verbose(env, "cur state:"); 17032 print_verifier_state(env, cur->frame[cur->curframe], true); 17033 verbose(env, "old state:"); 17034 print_verifier_state(env, sl->state.frame[cur->curframe], true); 17035 return -EINVAL; 17036 } 17037 /* if the verifier is processing a loop, avoid adding new state 17038 * too often, since different loop iterations have distinct 17039 * states and may not help future pruning. 17040 * This threshold shouldn't be too low to make sure that 17041 * a loop with large bound will be rejected quickly. 17042 * The most abusive loop will be: 17043 * r1 += 1 17044 * if r1 < 1000000 goto pc-2 17045 * 1M insn_procssed limit / 100 == 10k peak states. 17046 * This threshold shouldn't be too high either, since states 17047 * at the end of the loop are likely to be useful in pruning. 17048 */ 17049 skip_inf_loop_check: 17050 if (!force_new_state && 17051 env->jmps_processed - env->prev_jmps_processed < 20 && 17052 env->insn_processed - env->prev_insn_processed < 100) 17053 add_new_state = false; 17054 goto miss; 17055 } 17056 /* If sl->state is a part of a loop and this loop's entry is a part of 17057 * current verification path then states have to be compared exactly. 17058 * 'force_exact' is needed to catch the following case: 17059 * 17060 * initial Here state 'succ' was processed first, 17061 * | it was eventually tracked to produce a 17062 * V state identical to 'hdr'. 17063 * .---------> hdr All branches from 'succ' had been explored 17064 * | | and thus 'succ' has its .branches == 0. 17065 * | V 17066 * | .------... Suppose states 'cur' and 'succ' correspond 17067 * | | | to the same instruction + callsites. 17068 * | V V In such case it is necessary to check 17069 * | ... ... if 'succ' and 'cur' are states_equal(). 17070 * | | | If 'succ' and 'cur' are a part of the 17071 * | V V same loop exact flag has to be set. 17072 * | succ <- cur To check if that is the case, verify 17073 * | | if loop entry of 'succ' is in current 17074 * | V DFS path. 17075 * | ... 17076 * | | 17077 * '----' 17078 * 17079 * Additional details are in the comment before get_loop_entry(). 17080 */ 17081 loop_entry = get_loop_entry(&sl->state); 17082 force_exact = loop_entry && loop_entry->branches > 0; 17083 if (states_equal(env, &sl->state, cur, force_exact)) { 17084 if (force_exact) 17085 update_loop_entry(cur, loop_entry); 17086 hit: 17087 sl->hit_cnt++; 17088 /* reached equivalent register/stack state, 17089 * prune the search. 17090 * Registers read by the continuation are read by us. 17091 * If we have any write marks in env->cur_state, they 17092 * will prevent corresponding reads in the continuation 17093 * from reaching our parent (an explored_state). Our 17094 * own state will get the read marks recorded, but 17095 * they'll be immediately forgotten as we're pruning 17096 * this state and will pop a new one. 17097 */ 17098 err = propagate_liveness(env, &sl->state, cur); 17099 17100 /* if previous state reached the exit with precision and 17101 * current state is equivalent to it (except precsion marks) 17102 * the precision needs to be propagated back in 17103 * the current state. 17104 */ 17105 if (is_jmp_point(env, env->insn_idx)) 17106 err = err ? : push_jmp_history(env, cur, 0); 17107 err = err ? : propagate_precision(env, &sl->state); 17108 if (err) 17109 return err; 17110 return 1; 17111 } 17112 miss: 17113 /* when new state is not going to be added do not increase miss count. 17114 * Otherwise several loop iterations will remove the state 17115 * recorded earlier. The goal of these heuristics is to have 17116 * states from some iterations of the loop (some in the beginning 17117 * and some at the end) to help pruning. 17118 */ 17119 if (add_new_state) 17120 sl->miss_cnt++; 17121 /* heuristic to determine whether this state is beneficial 17122 * to keep checking from state equivalence point of view. 17123 * Higher numbers increase max_states_per_insn and verification time, 17124 * but do not meaningfully decrease insn_processed. 17125 * 'n' controls how many times state could miss before eviction. 17126 * Use bigger 'n' for checkpoints because evicting checkpoint states 17127 * too early would hinder iterator convergence. 17128 */ 17129 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 17130 if (sl->miss_cnt > sl->hit_cnt * n + n) { 17131 /* the state is unlikely to be useful. Remove it to 17132 * speed up verification 17133 */ 17134 *pprev = sl->next; 17135 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE && 17136 !sl->state.used_as_loop_entry) { 17137 u32 br = sl->state.branches; 17138 17139 WARN_ONCE(br, 17140 "BUG live_done but branches_to_explore %d\n", 17141 br); 17142 free_verifier_state(&sl->state, false); 17143 kfree(sl); 17144 env->peak_states--; 17145 } else { 17146 /* cannot free this state, since parentage chain may 17147 * walk it later. Add it for free_list instead to 17148 * be freed at the end of verification 17149 */ 17150 sl->next = env->free_list; 17151 env->free_list = sl; 17152 } 17153 sl = *pprev; 17154 continue; 17155 } 17156 next: 17157 pprev = &sl->next; 17158 sl = *pprev; 17159 } 17160 17161 if (env->max_states_per_insn < states_cnt) 17162 env->max_states_per_insn = states_cnt; 17163 17164 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 17165 return 0; 17166 17167 if (!add_new_state) 17168 return 0; 17169 17170 /* There were no equivalent states, remember the current one. 17171 * Technically the current state is not proven to be safe yet, 17172 * but it will either reach outer most bpf_exit (which means it's safe) 17173 * or it will be rejected. When there are no loops the verifier won't be 17174 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 17175 * again on the way to bpf_exit. 17176 * When looping the sl->state.branches will be > 0 and this state 17177 * will not be considered for equivalence until branches == 0. 17178 */ 17179 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 17180 if (!new_sl) 17181 return -ENOMEM; 17182 env->total_states++; 17183 env->peak_states++; 17184 env->prev_jmps_processed = env->jmps_processed; 17185 env->prev_insn_processed = env->insn_processed; 17186 17187 /* forget precise markings we inherited, see __mark_chain_precision */ 17188 if (env->bpf_capable) 17189 mark_all_scalars_imprecise(env, cur); 17190 17191 /* add new state to the head of linked list */ 17192 new = &new_sl->state; 17193 err = copy_verifier_state(new, cur); 17194 if (err) { 17195 free_verifier_state(new, false); 17196 kfree(new_sl); 17197 return err; 17198 } 17199 new->insn_idx = insn_idx; 17200 WARN_ONCE(new->branches != 1, 17201 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 17202 17203 cur->parent = new; 17204 cur->first_insn_idx = insn_idx; 17205 cur->dfs_depth = new->dfs_depth + 1; 17206 clear_jmp_history(cur); 17207 new_sl->next = *explored_state(env, insn_idx); 17208 *explored_state(env, insn_idx) = new_sl; 17209 /* connect new state to parentage chain. Current frame needs all 17210 * registers connected. Only r6 - r9 of the callers are alive (pushed 17211 * to the stack implicitly by JITs) so in callers' frames connect just 17212 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 17213 * the state of the call instruction (with WRITTEN set), and r0 comes 17214 * from callee with its full parentage chain, anyway. 17215 */ 17216 /* clear write marks in current state: the writes we did are not writes 17217 * our child did, so they don't screen off its reads from us. 17218 * (There are no read marks in current state, because reads always mark 17219 * their parent and current state never has children yet. Only 17220 * explored_states can get read marks.) 17221 */ 17222 for (j = 0; j <= cur->curframe; j++) { 17223 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 17224 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 17225 for (i = 0; i < BPF_REG_FP; i++) 17226 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 17227 } 17228 17229 /* all stack frames are accessible from callee, clear them all */ 17230 for (j = 0; j <= cur->curframe; j++) { 17231 struct bpf_func_state *frame = cur->frame[j]; 17232 struct bpf_func_state *newframe = new->frame[j]; 17233 17234 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 17235 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 17236 frame->stack[i].spilled_ptr.parent = 17237 &newframe->stack[i].spilled_ptr; 17238 } 17239 } 17240 return 0; 17241 } 17242 17243 /* Return true if it's OK to have the same insn return a different type. */ 17244 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 17245 { 17246 switch (base_type(type)) { 17247 case PTR_TO_CTX: 17248 case PTR_TO_SOCKET: 17249 case PTR_TO_SOCK_COMMON: 17250 case PTR_TO_TCP_SOCK: 17251 case PTR_TO_XDP_SOCK: 17252 case PTR_TO_BTF_ID: 17253 return false; 17254 default: 17255 return true; 17256 } 17257 } 17258 17259 /* If an instruction was previously used with particular pointer types, then we 17260 * need to be careful to avoid cases such as the below, where it may be ok 17261 * for one branch accessing the pointer, but not ok for the other branch: 17262 * 17263 * R1 = sock_ptr 17264 * goto X; 17265 * ... 17266 * R1 = some_other_valid_ptr; 17267 * goto X; 17268 * ... 17269 * R2 = *(u32 *)(R1 + 0); 17270 */ 17271 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 17272 { 17273 return src != prev && (!reg_type_mismatch_ok(src) || 17274 !reg_type_mismatch_ok(prev)); 17275 } 17276 17277 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 17278 bool allow_trust_missmatch) 17279 { 17280 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 17281 17282 if (*prev_type == NOT_INIT) { 17283 /* Saw a valid insn 17284 * dst_reg = *(u32 *)(src_reg + off) 17285 * save type to validate intersecting paths 17286 */ 17287 *prev_type = type; 17288 } else if (reg_type_mismatch(type, *prev_type)) { 17289 /* Abuser program is trying to use the same insn 17290 * dst_reg = *(u32*) (src_reg + off) 17291 * with different pointer types: 17292 * src_reg == ctx in one branch and 17293 * src_reg == stack|map in some other branch. 17294 * Reject it. 17295 */ 17296 if (allow_trust_missmatch && 17297 base_type(type) == PTR_TO_BTF_ID && 17298 base_type(*prev_type) == PTR_TO_BTF_ID) { 17299 /* 17300 * Have to support a use case when one path through 17301 * the program yields TRUSTED pointer while another 17302 * is UNTRUSTED. Fallback to UNTRUSTED to generate 17303 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 17304 */ 17305 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 17306 } else { 17307 verbose(env, "same insn cannot be used with different pointers\n"); 17308 return -EINVAL; 17309 } 17310 } 17311 17312 return 0; 17313 } 17314 17315 static int do_check(struct bpf_verifier_env *env) 17316 { 17317 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17318 struct bpf_verifier_state *state = env->cur_state; 17319 struct bpf_insn *insns = env->prog->insnsi; 17320 struct bpf_reg_state *regs; 17321 int insn_cnt = env->prog->len; 17322 bool do_print_state = false; 17323 int prev_insn_idx = -1; 17324 17325 for (;;) { 17326 bool exception_exit = false; 17327 struct bpf_insn *insn; 17328 u8 class; 17329 int err; 17330 17331 /* reset current history entry on each new instruction */ 17332 env->cur_hist_ent = NULL; 17333 17334 env->prev_insn_idx = prev_insn_idx; 17335 if (env->insn_idx >= insn_cnt) { 17336 verbose(env, "invalid insn idx %d insn_cnt %d\n", 17337 env->insn_idx, insn_cnt); 17338 return -EFAULT; 17339 } 17340 17341 insn = &insns[env->insn_idx]; 17342 class = BPF_CLASS(insn->code); 17343 17344 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 17345 verbose(env, 17346 "BPF program is too large. Processed %d insn\n", 17347 env->insn_processed); 17348 return -E2BIG; 17349 } 17350 17351 state->last_insn_idx = env->prev_insn_idx; 17352 17353 if (is_prune_point(env, env->insn_idx)) { 17354 err = is_state_visited(env, env->insn_idx); 17355 if (err < 0) 17356 return err; 17357 if (err == 1) { 17358 /* found equivalent state, can prune the search */ 17359 if (env->log.level & BPF_LOG_LEVEL) { 17360 if (do_print_state) 17361 verbose(env, "\nfrom %d to %d%s: safe\n", 17362 env->prev_insn_idx, env->insn_idx, 17363 env->cur_state->speculative ? 17364 " (speculative execution)" : ""); 17365 else 17366 verbose(env, "%d: safe\n", env->insn_idx); 17367 } 17368 goto process_bpf_exit; 17369 } 17370 } 17371 17372 if (is_jmp_point(env, env->insn_idx)) { 17373 err = push_jmp_history(env, state, 0); 17374 if (err) 17375 return err; 17376 } 17377 17378 if (signal_pending(current)) 17379 return -EAGAIN; 17380 17381 if (need_resched()) 17382 cond_resched(); 17383 17384 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17385 verbose(env, "\nfrom %d to %d%s:", 17386 env->prev_insn_idx, env->insn_idx, 17387 env->cur_state->speculative ? 17388 " (speculative execution)" : ""); 17389 print_verifier_state(env, state->frame[state->curframe], true); 17390 do_print_state = false; 17391 } 17392 17393 if (env->log.level & BPF_LOG_LEVEL) { 17394 const struct bpf_insn_cbs cbs = { 17395 .cb_call = disasm_kfunc_name, 17396 .cb_print = verbose, 17397 .private_data = env, 17398 }; 17399 17400 if (verifier_state_scratched(env)) 17401 print_insn_state(env, state->frame[state->curframe]); 17402 17403 verbose_linfo(env, env->insn_idx, "; "); 17404 env->prev_log_pos = env->log.end_pos; 17405 verbose(env, "%d: ", env->insn_idx); 17406 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 17407 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17408 env->prev_log_pos = env->log.end_pos; 17409 } 17410 17411 if (bpf_prog_is_offloaded(env->prog->aux)) { 17412 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17413 env->prev_insn_idx); 17414 if (err) 17415 return err; 17416 } 17417 17418 regs = cur_regs(env); 17419 sanitize_mark_insn_seen(env); 17420 prev_insn_idx = env->insn_idx; 17421 17422 if (class == BPF_ALU || class == BPF_ALU64) { 17423 err = check_alu_op(env, insn); 17424 if (err) 17425 return err; 17426 17427 } else if (class == BPF_LDX) { 17428 enum bpf_reg_type src_reg_type; 17429 17430 /* check for reserved fields is already done */ 17431 17432 /* check src operand */ 17433 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17434 if (err) 17435 return err; 17436 17437 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 17438 if (err) 17439 return err; 17440 17441 src_reg_type = regs[insn->src_reg].type; 17442 17443 /* check that memory (src_reg + off) is readable, 17444 * the state of dst_reg will be updated by this func 17445 */ 17446 err = check_mem_access(env, env->insn_idx, insn->src_reg, 17447 insn->off, BPF_SIZE(insn->code), 17448 BPF_READ, insn->dst_reg, false, 17449 BPF_MODE(insn->code) == BPF_MEMSX); 17450 err = err ?: save_aux_ptr_type(env, src_reg_type, true); 17451 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], "ldx"); 17452 if (err) 17453 return err; 17454 } else if (class == BPF_STX) { 17455 enum bpf_reg_type dst_reg_type; 17456 17457 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 17458 err = check_atomic(env, env->insn_idx, insn); 17459 if (err) 17460 return err; 17461 env->insn_idx++; 17462 continue; 17463 } 17464 17465 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 17466 verbose(env, "BPF_STX uses reserved fields\n"); 17467 return -EINVAL; 17468 } 17469 17470 /* check src1 operand */ 17471 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17472 if (err) 17473 return err; 17474 /* check src2 operand */ 17475 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17476 if (err) 17477 return err; 17478 17479 dst_reg_type = regs[insn->dst_reg].type; 17480 17481 /* check that memory (dst_reg + off) is writeable */ 17482 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17483 insn->off, BPF_SIZE(insn->code), 17484 BPF_WRITE, insn->src_reg, false, false); 17485 if (err) 17486 return err; 17487 17488 err = save_aux_ptr_type(env, dst_reg_type, false); 17489 if (err) 17490 return err; 17491 } else if (class == BPF_ST) { 17492 enum bpf_reg_type dst_reg_type; 17493 17494 if (BPF_MODE(insn->code) != BPF_MEM || 17495 insn->src_reg != BPF_REG_0) { 17496 verbose(env, "BPF_ST uses reserved fields\n"); 17497 return -EINVAL; 17498 } 17499 /* check src operand */ 17500 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17501 if (err) 17502 return err; 17503 17504 dst_reg_type = regs[insn->dst_reg].type; 17505 17506 /* check that memory (dst_reg + off) is writeable */ 17507 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17508 insn->off, BPF_SIZE(insn->code), 17509 BPF_WRITE, -1, false, false); 17510 if (err) 17511 return err; 17512 17513 err = save_aux_ptr_type(env, dst_reg_type, false); 17514 if (err) 17515 return err; 17516 } else if (class == BPF_JMP || class == BPF_JMP32) { 17517 u8 opcode = BPF_OP(insn->code); 17518 17519 env->jmps_processed++; 17520 if (opcode == BPF_CALL) { 17521 if (BPF_SRC(insn->code) != BPF_K || 17522 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 17523 && insn->off != 0) || 17524 (insn->src_reg != BPF_REG_0 && 17525 insn->src_reg != BPF_PSEUDO_CALL && 17526 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 17527 insn->dst_reg != BPF_REG_0 || 17528 class == BPF_JMP32) { 17529 verbose(env, "BPF_CALL uses reserved fields\n"); 17530 return -EINVAL; 17531 } 17532 17533 if (env->cur_state->active_lock.ptr) { 17534 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 17535 (insn->src_reg == BPF_PSEUDO_CALL) || 17536 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17537 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 17538 verbose(env, "function calls are not allowed while holding a lock\n"); 17539 return -EINVAL; 17540 } 17541 } 17542 if (insn->src_reg == BPF_PSEUDO_CALL) { 17543 err = check_func_call(env, insn, &env->insn_idx); 17544 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 17545 err = check_kfunc_call(env, insn, &env->insn_idx); 17546 if (!err && is_bpf_throw_kfunc(insn)) { 17547 exception_exit = true; 17548 goto process_bpf_exit_full; 17549 } 17550 } else { 17551 err = check_helper_call(env, insn, &env->insn_idx); 17552 } 17553 if (err) 17554 return err; 17555 17556 mark_reg_scratched(env, BPF_REG_0); 17557 } else if (opcode == BPF_JA) { 17558 if (BPF_SRC(insn->code) != BPF_K || 17559 insn->src_reg != BPF_REG_0 || 17560 insn->dst_reg != BPF_REG_0 || 17561 (class == BPF_JMP && insn->imm != 0) || 17562 (class == BPF_JMP32 && insn->off != 0)) { 17563 verbose(env, "BPF_JA uses reserved fields\n"); 17564 return -EINVAL; 17565 } 17566 17567 if (class == BPF_JMP) 17568 env->insn_idx += insn->off + 1; 17569 else 17570 env->insn_idx += insn->imm + 1; 17571 continue; 17572 17573 } else if (opcode == BPF_EXIT) { 17574 if (BPF_SRC(insn->code) != BPF_K || 17575 insn->imm != 0 || 17576 insn->src_reg != BPF_REG_0 || 17577 insn->dst_reg != BPF_REG_0 || 17578 class == BPF_JMP32) { 17579 verbose(env, "BPF_EXIT uses reserved fields\n"); 17580 return -EINVAL; 17581 } 17582 process_bpf_exit_full: 17583 if (env->cur_state->active_lock.ptr && 17584 !in_rbtree_lock_required_cb(env)) { 17585 verbose(env, "bpf_spin_unlock is missing\n"); 17586 return -EINVAL; 17587 } 17588 17589 if (env->cur_state->active_rcu_lock && 17590 !in_rbtree_lock_required_cb(env)) { 17591 verbose(env, "bpf_rcu_read_unlock is missing\n"); 17592 return -EINVAL; 17593 } 17594 17595 /* We must do check_reference_leak here before 17596 * prepare_func_exit to handle the case when 17597 * state->curframe > 0, it may be a callback 17598 * function, for which reference_state must 17599 * match caller reference state when it exits. 17600 */ 17601 err = check_reference_leak(env, exception_exit); 17602 if (err) 17603 return err; 17604 17605 /* The side effect of the prepare_func_exit 17606 * which is being skipped is that it frees 17607 * bpf_func_state. Typically, process_bpf_exit 17608 * will only be hit with outermost exit. 17609 * copy_verifier_state in pop_stack will handle 17610 * freeing of any extra bpf_func_state left over 17611 * from not processing all nested function 17612 * exits. We also skip return code checks as 17613 * they are not needed for exceptional exits. 17614 */ 17615 if (exception_exit) 17616 goto process_bpf_exit; 17617 17618 if (state->curframe) { 17619 /* exit from nested function */ 17620 err = prepare_func_exit(env, &env->insn_idx); 17621 if (err) 17622 return err; 17623 do_print_state = true; 17624 continue; 17625 } 17626 17627 err = check_return_code(env, BPF_REG_0, "R0"); 17628 if (err) 17629 return err; 17630 process_bpf_exit: 17631 mark_verifier_state_scratched(env); 17632 update_branch_counts(env, env->cur_state); 17633 err = pop_stack(env, &prev_insn_idx, 17634 &env->insn_idx, pop_log); 17635 if (err < 0) { 17636 if (err != -ENOENT) 17637 return err; 17638 break; 17639 } else { 17640 do_print_state = true; 17641 continue; 17642 } 17643 } else { 17644 err = check_cond_jmp_op(env, insn, &env->insn_idx); 17645 if (err) 17646 return err; 17647 } 17648 } else if (class == BPF_LD) { 17649 u8 mode = BPF_MODE(insn->code); 17650 17651 if (mode == BPF_ABS || mode == BPF_IND) { 17652 err = check_ld_abs(env, insn); 17653 if (err) 17654 return err; 17655 17656 } else if (mode == BPF_IMM) { 17657 err = check_ld_imm(env, insn); 17658 if (err) 17659 return err; 17660 17661 env->insn_idx++; 17662 sanitize_mark_insn_seen(env); 17663 } else { 17664 verbose(env, "invalid BPF_LD mode\n"); 17665 return -EINVAL; 17666 } 17667 } else { 17668 verbose(env, "unknown insn class %d\n", class); 17669 return -EINVAL; 17670 } 17671 17672 env->insn_idx++; 17673 } 17674 17675 return 0; 17676 } 17677 17678 static int find_btf_percpu_datasec(struct btf *btf) 17679 { 17680 const struct btf_type *t; 17681 const char *tname; 17682 int i, n; 17683 17684 /* 17685 * Both vmlinux and module each have their own ".data..percpu" 17686 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17687 * types to look at only module's own BTF types. 17688 */ 17689 n = btf_nr_types(btf); 17690 if (btf_is_module(btf)) 17691 i = btf_nr_types(btf_vmlinux); 17692 else 17693 i = 1; 17694 17695 for(; i < n; i++) { 17696 t = btf_type_by_id(btf, i); 17697 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17698 continue; 17699 17700 tname = btf_name_by_offset(btf, t->name_off); 17701 if (!strcmp(tname, ".data..percpu")) 17702 return i; 17703 } 17704 17705 return -ENOENT; 17706 } 17707 17708 /* replace pseudo btf_id with kernel symbol address */ 17709 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 17710 struct bpf_insn *insn, 17711 struct bpf_insn_aux_data *aux) 17712 { 17713 const struct btf_var_secinfo *vsi; 17714 const struct btf_type *datasec; 17715 struct btf_mod_pair *btf_mod; 17716 const struct btf_type *t; 17717 const char *sym_name; 17718 bool percpu = false; 17719 u32 type, id = insn->imm; 17720 struct btf *btf; 17721 s32 datasec_id; 17722 u64 addr; 17723 int i, btf_fd, err; 17724 17725 btf_fd = insn[1].imm; 17726 if (btf_fd) { 17727 btf = btf_get_by_fd(btf_fd); 17728 if (IS_ERR(btf)) { 17729 verbose(env, "invalid module BTF object FD specified.\n"); 17730 return -EINVAL; 17731 } 17732 } else { 17733 if (!btf_vmlinux) { 17734 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 17735 return -EINVAL; 17736 } 17737 btf = btf_vmlinux; 17738 btf_get(btf); 17739 } 17740 17741 t = btf_type_by_id(btf, id); 17742 if (!t) { 17743 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17744 err = -ENOENT; 17745 goto err_put; 17746 } 17747 17748 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 17749 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 17750 err = -EINVAL; 17751 goto err_put; 17752 } 17753 17754 sym_name = btf_name_by_offset(btf, t->name_off); 17755 addr = kallsyms_lookup_name(sym_name); 17756 if (!addr) { 17757 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 17758 sym_name); 17759 err = -ENOENT; 17760 goto err_put; 17761 } 17762 insn[0].imm = (u32)addr; 17763 insn[1].imm = addr >> 32; 17764 17765 if (btf_type_is_func(t)) { 17766 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17767 aux->btf_var.mem_size = 0; 17768 goto check_btf; 17769 } 17770 17771 datasec_id = find_btf_percpu_datasec(btf); 17772 if (datasec_id > 0) { 17773 datasec = btf_type_by_id(btf, datasec_id); 17774 for_each_vsi(i, datasec, vsi) { 17775 if (vsi->type == id) { 17776 percpu = true; 17777 break; 17778 } 17779 } 17780 } 17781 17782 type = t->type; 17783 t = btf_type_skip_modifiers(btf, type, NULL); 17784 if (percpu) { 17785 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 17786 aux->btf_var.btf = btf; 17787 aux->btf_var.btf_id = type; 17788 } else if (!btf_type_is_struct(t)) { 17789 const struct btf_type *ret; 17790 const char *tname; 17791 u32 tsize; 17792 17793 /* resolve the type size of ksym. */ 17794 ret = btf_resolve_size(btf, t, &tsize); 17795 if (IS_ERR(ret)) { 17796 tname = btf_name_by_offset(btf, t->name_off); 17797 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 17798 tname, PTR_ERR(ret)); 17799 err = -EINVAL; 17800 goto err_put; 17801 } 17802 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17803 aux->btf_var.mem_size = tsize; 17804 } else { 17805 aux->btf_var.reg_type = PTR_TO_BTF_ID; 17806 aux->btf_var.btf = btf; 17807 aux->btf_var.btf_id = type; 17808 } 17809 check_btf: 17810 /* check whether we recorded this BTF (and maybe module) already */ 17811 for (i = 0; i < env->used_btf_cnt; i++) { 17812 if (env->used_btfs[i].btf == btf) { 17813 btf_put(btf); 17814 return 0; 17815 } 17816 } 17817 17818 if (env->used_btf_cnt >= MAX_USED_BTFS) { 17819 err = -E2BIG; 17820 goto err_put; 17821 } 17822 17823 btf_mod = &env->used_btfs[env->used_btf_cnt]; 17824 btf_mod->btf = btf; 17825 btf_mod->module = NULL; 17826 17827 /* if we reference variables from kernel module, bump its refcount */ 17828 if (btf_is_module(btf)) { 17829 btf_mod->module = btf_try_get_module(btf); 17830 if (!btf_mod->module) { 17831 err = -ENXIO; 17832 goto err_put; 17833 } 17834 } 17835 17836 env->used_btf_cnt++; 17837 17838 return 0; 17839 err_put: 17840 btf_put(btf); 17841 return err; 17842 } 17843 17844 static bool is_tracing_prog_type(enum bpf_prog_type type) 17845 { 17846 switch (type) { 17847 case BPF_PROG_TYPE_KPROBE: 17848 case BPF_PROG_TYPE_TRACEPOINT: 17849 case BPF_PROG_TYPE_PERF_EVENT: 17850 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17851 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 17852 return true; 17853 default: 17854 return false; 17855 } 17856 } 17857 17858 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 17859 struct bpf_map *map, 17860 struct bpf_prog *prog) 17861 17862 { 17863 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17864 17865 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 17866 btf_record_has_field(map->record, BPF_RB_ROOT)) { 17867 if (is_tracing_prog_type(prog_type)) { 17868 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 17869 return -EINVAL; 17870 } 17871 } 17872 17873 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 17874 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 17875 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 17876 return -EINVAL; 17877 } 17878 17879 if (is_tracing_prog_type(prog_type)) { 17880 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 17881 return -EINVAL; 17882 } 17883 } 17884 17885 if (btf_record_has_field(map->record, BPF_TIMER)) { 17886 if (is_tracing_prog_type(prog_type)) { 17887 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 17888 return -EINVAL; 17889 } 17890 } 17891 17892 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 17893 !bpf_offload_prog_map_match(prog, map)) { 17894 verbose(env, "offload device mismatch between prog and map\n"); 17895 return -EINVAL; 17896 } 17897 17898 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 17899 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 17900 return -EINVAL; 17901 } 17902 17903 if (prog->aux->sleepable) 17904 switch (map->map_type) { 17905 case BPF_MAP_TYPE_HASH: 17906 case BPF_MAP_TYPE_LRU_HASH: 17907 case BPF_MAP_TYPE_ARRAY: 17908 case BPF_MAP_TYPE_PERCPU_HASH: 17909 case BPF_MAP_TYPE_PERCPU_ARRAY: 17910 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 17911 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 17912 case BPF_MAP_TYPE_HASH_OF_MAPS: 17913 case BPF_MAP_TYPE_RINGBUF: 17914 case BPF_MAP_TYPE_USER_RINGBUF: 17915 case BPF_MAP_TYPE_INODE_STORAGE: 17916 case BPF_MAP_TYPE_SK_STORAGE: 17917 case BPF_MAP_TYPE_TASK_STORAGE: 17918 case BPF_MAP_TYPE_CGRP_STORAGE: 17919 break; 17920 default: 17921 verbose(env, 17922 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 17923 return -EINVAL; 17924 } 17925 17926 return 0; 17927 } 17928 17929 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 17930 { 17931 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 17932 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 17933 } 17934 17935 /* find and rewrite pseudo imm in ld_imm64 instructions: 17936 * 17937 * 1. if it accesses map FD, replace it with actual map pointer. 17938 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 17939 * 17940 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 17941 */ 17942 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 17943 { 17944 struct bpf_insn *insn = env->prog->insnsi; 17945 int insn_cnt = env->prog->len; 17946 int i, j, err; 17947 17948 err = bpf_prog_calc_tag(env->prog); 17949 if (err) 17950 return err; 17951 17952 for (i = 0; i < insn_cnt; i++, insn++) { 17953 if (BPF_CLASS(insn->code) == BPF_LDX && 17954 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 17955 insn->imm != 0)) { 17956 verbose(env, "BPF_LDX uses reserved fields\n"); 17957 return -EINVAL; 17958 } 17959 17960 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 17961 struct bpf_insn_aux_data *aux; 17962 struct bpf_map *map; 17963 struct fd f; 17964 u64 addr; 17965 u32 fd; 17966 17967 if (i == insn_cnt - 1 || insn[1].code != 0 || 17968 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 17969 insn[1].off != 0) { 17970 verbose(env, "invalid bpf_ld_imm64 insn\n"); 17971 return -EINVAL; 17972 } 17973 17974 if (insn[0].src_reg == 0) 17975 /* valid generic load 64-bit imm */ 17976 goto next_insn; 17977 17978 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 17979 aux = &env->insn_aux_data[i]; 17980 err = check_pseudo_btf_id(env, insn, aux); 17981 if (err) 17982 return err; 17983 goto next_insn; 17984 } 17985 17986 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 17987 aux = &env->insn_aux_data[i]; 17988 aux->ptr_type = PTR_TO_FUNC; 17989 goto next_insn; 17990 } 17991 17992 /* In final convert_pseudo_ld_imm64() step, this is 17993 * converted into regular 64-bit imm load insn. 17994 */ 17995 switch (insn[0].src_reg) { 17996 case BPF_PSEUDO_MAP_VALUE: 17997 case BPF_PSEUDO_MAP_IDX_VALUE: 17998 break; 17999 case BPF_PSEUDO_MAP_FD: 18000 case BPF_PSEUDO_MAP_IDX: 18001 if (insn[1].imm == 0) 18002 break; 18003 fallthrough; 18004 default: 18005 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 18006 return -EINVAL; 18007 } 18008 18009 switch (insn[0].src_reg) { 18010 case BPF_PSEUDO_MAP_IDX_VALUE: 18011 case BPF_PSEUDO_MAP_IDX: 18012 if (bpfptr_is_null(env->fd_array)) { 18013 verbose(env, "fd_idx without fd_array is invalid\n"); 18014 return -EPROTO; 18015 } 18016 if (copy_from_bpfptr_offset(&fd, env->fd_array, 18017 insn[0].imm * sizeof(fd), 18018 sizeof(fd))) 18019 return -EFAULT; 18020 break; 18021 default: 18022 fd = insn[0].imm; 18023 break; 18024 } 18025 18026 f = fdget(fd); 18027 map = __bpf_map_get(f); 18028 if (IS_ERR(map)) { 18029 verbose(env, "fd %d is not pointing to valid bpf_map\n", 18030 insn[0].imm); 18031 return PTR_ERR(map); 18032 } 18033 18034 err = check_map_prog_compatibility(env, map, env->prog); 18035 if (err) { 18036 fdput(f); 18037 return err; 18038 } 18039 18040 aux = &env->insn_aux_data[i]; 18041 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 18042 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 18043 addr = (unsigned long)map; 18044 } else { 18045 u32 off = insn[1].imm; 18046 18047 if (off >= BPF_MAX_VAR_OFF) { 18048 verbose(env, "direct value offset of %u is not allowed\n", off); 18049 fdput(f); 18050 return -EINVAL; 18051 } 18052 18053 if (!map->ops->map_direct_value_addr) { 18054 verbose(env, "no direct value access support for this map type\n"); 18055 fdput(f); 18056 return -EINVAL; 18057 } 18058 18059 err = map->ops->map_direct_value_addr(map, &addr, off); 18060 if (err) { 18061 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 18062 map->value_size, off); 18063 fdput(f); 18064 return err; 18065 } 18066 18067 aux->map_off = off; 18068 addr += off; 18069 } 18070 18071 insn[0].imm = (u32)addr; 18072 insn[1].imm = addr >> 32; 18073 18074 /* check whether we recorded this map already */ 18075 for (j = 0; j < env->used_map_cnt; j++) { 18076 if (env->used_maps[j] == map) { 18077 aux->map_index = j; 18078 fdput(f); 18079 goto next_insn; 18080 } 18081 } 18082 18083 if (env->used_map_cnt >= MAX_USED_MAPS) { 18084 fdput(f); 18085 return -E2BIG; 18086 } 18087 18088 if (env->prog->aux->sleepable) 18089 atomic64_inc(&map->sleepable_refcnt); 18090 /* hold the map. If the program is rejected by verifier, 18091 * the map will be released by release_maps() or it 18092 * will be used by the valid program until it's unloaded 18093 * and all maps are released in bpf_free_used_maps() 18094 */ 18095 bpf_map_inc(map); 18096 18097 aux->map_index = env->used_map_cnt; 18098 env->used_maps[env->used_map_cnt++] = map; 18099 18100 if (bpf_map_is_cgroup_storage(map) && 18101 bpf_cgroup_storage_assign(env->prog->aux, map)) { 18102 verbose(env, "only one cgroup storage of each type is allowed\n"); 18103 fdput(f); 18104 return -EBUSY; 18105 } 18106 18107 fdput(f); 18108 next_insn: 18109 insn++; 18110 i++; 18111 continue; 18112 } 18113 18114 /* Basic sanity check before we invest more work here. */ 18115 if (!bpf_opcode_in_insntable(insn->code)) { 18116 verbose(env, "unknown opcode %02x\n", insn->code); 18117 return -EINVAL; 18118 } 18119 } 18120 18121 /* now all pseudo BPF_LD_IMM64 instructions load valid 18122 * 'struct bpf_map *' into a register instead of user map_fd. 18123 * These pointers will be used later by verifier to validate map access. 18124 */ 18125 return 0; 18126 } 18127 18128 /* drop refcnt of maps used by the rejected program */ 18129 static void release_maps(struct bpf_verifier_env *env) 18130 { 18131 __bpf_free_used_maps(env->prog->aux, env->used_maps, 18132 env->used_map_cnt); 18133 } 18134 18135 /* drop refcnt of maps used by the rejected program */ 18136 static void release_btfs(struct bpf_verifier_env *env) 18137 { 18138 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 18139 env->used_btf_cnt); 18140 } 18141 18142 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 18143 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 18144 { 18145 struct bpf_insn *insn = env->prog->insnsi; 18146 int insn_cnt = env->prog->len; 18147 int i; 18148 18149 for (i = 0; i < insn_cnt; i++, insn++) { 18150 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 18151 continue; 18152 if (insn->src_reg == BPF_PSEUDO_FUNC) 18153 continue; 18154 insn->src_reg = 0; 18155 } 18156 } 18157 18158 /* single env->prog->insni[off] instruction was replaced with the range 18159 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 18160 * [0, off) and [off, end) to new locations, so the patched range stays zero 18161 */ 18162 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 18163 struct bpf_insn_aux_data *new_data, 18164 struct bpf_prog *new_prog, u32 off, u32 cnt) 18165 { 18166 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 18167 struct bpf_insn *insn = new_prog->insnsi; 18168 u32 old_seen = old_data[off].seen; 18169 u32 prog_len; 18170 int i; 18171 18172 /* aux info at OFF always needs adjustment, no matter fast path 18173 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 18174 * original insn at old prog. 18175 */ 18176 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 18177 18178 if (cnt == 1) 18179 return; 18180 prog_len = new_prog->len; 18181 18182 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 18183 memcpy(new_data + off + cnt - 1, old_data + off, 18184 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 18185 for (i = off; i < off + cnt - 1; i++) { 18186 /* Expand insni[off]'s seen count to the patched range. */ 18187 new_data[i].seen = old_seen; 18188 new_data[i].zext_dst = insn_has_def32(env, insn + i); 18189 } 18190 env->insn_aux_data = new_data; 18191 vfree(old_data); 18192 } 18193 18194 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 18195 { 18196 int i; 18197 18198 if (len == 1) 18199 return; 18200 /* NOTE: fake 'exit' subprog should be updated as well. */ 18201 for (i = 0; i <= env->subprog_cnt; i++) { 18202 if (env->subprog_info[i].start <= off) 18203 continue; 18204 env->subprog_info[i].start += len - 1; 18205 } 18206 } 18207 18208 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 18209 { 18210 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 18211 int i, sz = prog->aux->size_poke_tab; 18212 struct bpf_jit_poke_descriptor *desc; 18213 18214 for (i = 0; i < sz; i++) { 18215 desc = &tab[i]; 18216 if (desc->insn_idx <= off) 18217 continue; 18218 desc->insn_idx += len - 1; 18219 } 18220 } 18221 18222 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 18223 const struct bpf_insn *patch, u32 len) 18224 { 18225 struct bpf_prog *new_prog; 18226 struct bpf_insn_aux_data *new_data = NULL; 18227 18228 if (len > 1) { 18229 new_data = vzalloc(array_size(env->prog->len + len - 1, 18230 sizeof(struct bpf_insn_aux_data))); 18231 if (!new_data) 18232 return NULL; 18233 } 18234 18235 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 18236 if (IS_ERR(new_prog)) { 18237 if (PTR_ERR(new_prog) == -ERANGE) 18238 verbose(env, 18239 "insn %d cannot be patched due to 16-bit range\n", 18240 env->insn_aux_data[off].orig_idx); 18241 vfree(new_data); 18242 return NULL; 18243 } 18244 adjust_insn_aux_data(env, new_data, new_prog, off, len); 18245 adjust_subprog_starts(env, off, len); 18246 adjust_poke_descs(new_prog, off, len); 18247 return new_prog; 18248 } 18249 18250 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 18251 u32 off, u32 cnt) 18252 { 18253 int i, j; 18254 18255 /* find first prog starting at or after off (first to remove) */ 18256 for (i = 0; i < env->subprog_cnt; i++) 18257 if (env->subprog_info[i].start >= off) 18258 break; 18259 /* find first prog starting at or after off + cnt (first to stay) */ 18260 for (j = i; j < env->subprog_cnt; j++) 18261 if (env->subprog_info[j].start >= off + cnt) 18262 break; 18263 /* if j doesn't start exactly at off + cnt, we are just removing 18264 * the front of previous prog 18265 */ 18266 if (env->subprog_info[j].start != off + cnt) 18267 j--; 18268 18269 if (j > i) { 18270 struct bpf_prog_aux *aux = env->prog->aux; 18271 int move; 18272 18273 /* move fake 'exit' subprog as well */ 18274 move = env->subprog_cnt + 1 - j; 18275 18276 memmove(env->subprog_info + i, 18277 env->subprog_info + j, 18278 sizeof(*env->subprog_info) * move); 18279 env->subprog_cnt -= j - i; 18280 18281 /* remove func_info */ 18282 if (aux->func_info) { 18283 move = aux->func_info_cnt - j; 18284 18285 memmove(aux->func_info + i, 18286 aux->func_info + j, 18287 sizeof(*aux->func_info) * move); 18288 aux->func_info_cnt -= j - i; 18289 /* func_info->insn_off is set after all code rewrites, 18290 * in adjust_btf_func() - no need to adjust 18291 */ 18292 } 18293 } else { 18294 /* convert i from "first prog to remove" to "first to adjust" */ 18295 if (env->subprog_info[i].start == off) 18296 i++; 18297 } 18298 18299 /* update fake 'exit' subprog as well */ 18300 for (; i <= env->subprog_cnt; i++) 18301 env->subprog_info[i].start -= cnt; 18302 18303 return 0; 18304 } 18305 18306 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 18307 u32 cnt) 18308 { 18309 struct bpf_prog *prog = env->prog; 18310 u32 i, l_off, l_cnt, nr_linfo; 18311 struct bpf_line_info *linfo; 18312 18313 nr_linfo = prog->aux->nr_linfo; 18314 if (!nr_linfo) 18315 return 0; 18316 18317 linfo = prog->aux->linfo; 18318 18319 /* find first line info to remove, count lines to be removed */ 18320 for (i = 0; i < nr_linfo; i++) 18321 if (linfo[i].insn_off >= off) 18322 break; 18323 18324 l_off = i; 18325 l_cnt = 0; 18326 for (; i < nr_linfo; i++) 18327 if (linfo[i].insn_off < off + cnt) 18328 l_cnt++; 18329 else 18330 break; 18331 18332 /* First live insn doesn't match first live linfo, it needs to "inherit" 18333 * last removed linfo. prog is already modified, so prog->len == off 18334 * means no live instructions after (tail of the program was removed). 18335 */ 18336 if (prog->len != off && l_cnt && 18337 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 18338 l_cnt--; 18339 linfo[--i].insn_off = off + cnt; 18340 } 18341 18342 /* remove the line info which refer to the removed instructions */ 18343 if (l_cnt) { 18344 memmove(linfo + l_off, linfo + i, 18345 sizeof(*linfo) * (nr_linfo - i)); 18346 18347 prog->aux->nr_linfo -= l_cnt; 18348 nr_linfo = prog->aux->nr_linfo; 18349 } 18350 18351 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 18352 for (i = l_off; i < nr_linfo; i++) 18353 linfo[i].insn_off -= cnt; 18354 18355 /* fix up all subprogs (incl. 'exit') which start >= off */ 18356 for (i = 0; i <= env->subprog_cnt; i++) 18357 if (env->subprog_info[i].linfo_idx > l_off) { 18358 /* program may have started in the removed region but 18359 * may not be fully removed 18360 */ 18361 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 18362 env->subprog_info[i].linfo_idx -= l_cnt; 18363 else 18364 env->subprog_info[i].linfo_idx = l_off; 18365 } 18366 18367 return 0; 18368 } 18369 18370 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 18371 { 18372 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18373 unsigned int orig_prog_len = env->prog->len; 18374 int err; 18375 18376 if (bpf_prog_is_offloaded(env->prog->aux)) 18377 bpf_prog_offload_remove_insns(env, off, cnt); 18378 18379 err = bpf_remove_insns(env->prog, off, cnt); 18380 if (err) 18381 return err; 18382 18383 err = adjust_subprog_starts_after_remove(env, off, cnt); 18384 if (err) 18385 return err; 18386 18387 err = bpf_adj_linfo_after_remove(env, off, cnt); 18388 if (err) 18389 return err; 18390 18391 memmove(aux_data + off, aux_data + off + cnt, 18392 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 18393 18394 return 0; 18395 } 18396 18397 /* The verifier does more data flow analysis than llvm and will not 18398 * explore branches that are dead at run time. Malicious programs can 18399 * have dead code too. Therefore replace all dead at-run-time code 18400 * with 'ja -1'. 18401 * 18402 * Just nops are not optimal, e.g. if they would sit at the end of the 18403 * program and through another bug we would manage to jump there, then 18404 * we'd execute beyond program memory otherwise. Returning exception 18405 * code also wouldn't work since we can have subprogs where the dead 18406 * code could be located. 18407 */ 18408 static void sanitize_dead_code(struct bpf_verifier_env *env) 18409 { 18410 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18411 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18412 struct bpf_insn *insn = env->prog->insnsi; 18413 const int insn_cnt = env->prog->len; 18414 int i; 18415 18416 for (i = 0; i < insn_cnt; i++) { 18417 if (aux_data[i].seen) 18418 continue; 18419 memcpy(insn + i, &trap, sizeof(trap)); 18420 aux_data[i].zext_dst = false; 18421 } 18422 } 18423 18424 static bool insn_is_cond_jump(u8 code) 18425 { 18426 u8 op; 18427 18428 op = BPF_OP(code); 18429 if (BPF_CLASS(code) == BPF_JMP32) 18430 return op != BPF_JA; 18431 18432 if (BPF_CLASS(code) != BPF_JMP) 18433 return false; 18434 18435 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 18436 } 18437 18438 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 18439 { 18440 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18441 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18442 struct bpf_insn *insn = env->prog->insnsi; 18443 const int insn_cnt = env->prog->len; 18444 int i; 18445 18446 for (i = 0; i < insn_cnt; i++, insn++) { 18447 if (!insn_is_cond_jump(insn->code)) 18448 continue; 18449 18450 if (!aux_data[i + 1].seen) 18451 ja.off = insn->off; 18452 else if (!aux_data[i + 1 + insn->off].seen) 18453 ja.off = 0; 18454 else 18455 continue; 18456 18457 if (bpf_prog_is_offloaded(env->prog->aux)) 18458 bpf_prog_offload_replace_insn(env, i, &ja); 18459 18460 memcpy(insn, &ja, sizeof(ja)); 18461 } 18462 } 18463 18464 static int opt_remove_dead_code(struct bpf_verifier_env *env) 18465 { 18466 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18467 int insn_cnt = env->prog->len; 18468 int i, err; 18469 18470 for (i = 0; i < insn_cnt; i++) { 18471 int j; 18472 18473 j = 0; 18474 while (i + j < insn_cnt && !aux_data[i + j].seen) 18475 j++; 18476 if (!j) 18477 continue; 18478 18479 err = verifier_remove_insns(env, i, j); 18480 if (err) 18481 return err; 18482 insn_cnt = env->prog->len; 18483 } 18484 18485 return 0; 18486 } 18487 18488 static int opt_remove_nops(struct bpf_verifier_env *env) 18489 { 18490 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18491 struct bpf_insn *insn = env->prog->insnsi; 18492 int insn_cnt = env->prog->len; 18493 int i, err; 18494 18495 for (i = 0; i < insn_cnt; i++) { 18496 if (memcmp(&insn[i], &ja, sizeof(ja))) 18497 continue; 18498 18499 err = verifier_remove_insns(env, i, 1); 18500 if (err) 18501 return err; 18502 insn_cnt--; 18503 i--; 18504 } 18505 18506 return 0; 18507 } 18508 18509 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 18510 const union bpf_attr *attr) 18511 { 18512 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 18513 struct bpf_insn_aux_data *aux = env->insn_aux_data; 18514 int i, patch_len, delta = 0, len = env->prog->len; 18515 struct bpf_insn *insns = env->prog->insnsi; 18516 struct bpf_prog *new_prog; 18517 bool rnd_hi32; 18518 18519 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 18520 zext_patch[1] = BPF_ZEXT_REG(0); 18521 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 18522 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 18523 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 18524 for (i = 0; i < len; i++) { 18525 int adj_idx = i + delta; 18526 struct bpf_insn insn; 18527 int load_reg; 18528 18529 insn = insns[adj_idx]; 18530 load_reg = insn_def_regno(&insn); 18531 if (!aux[adj_idx].zext_dst) { 18532 u8 code, class; 18533 u32 imm_rnd; 18534 18535 if (!rnd_hi32) 18536 continue; 18537 18538 code = insn.code; 18539 class = BPF_CLASS(code); 18540 if (load_reg == -1) 18541 continue; 18542 18543 /* NOTE: arg "reg" (the fourth one) is only used for 18544 * BPF_STX + SRC_OP, so it is safe to pass NULL 18545 * here. 18546 */ 18547 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 18548 if (class == BPF_LD && 18549 BPF_MODE(code) == BPF_IMM) 18550 i++; 18551 continue; 18552 } 18553 18554 /* ctx load could be transformed into wider load. */ 18555 if (class == BPF_LDX && 18556 aux[adj_idx].ptr_type == PTR_TO_CTX) 18557 continue; 18558 18559 imm_rnd = get_random_u32(); 18560 rnd_hi32_patch[0] = insn; 18561 rnd_hi32_patch[1].imm = imm_rnd; 18562 rnd_hi32_patch[3].dst_reg = load_reg; 18563 patch = rnd_hi32_patch; 18564 patch_len = 4; 18565 goto apply_patch_buffer; 18566 } 18567 18568 /* Add in an zero-extend instruction if a) the JIT has requested 18569 * it or b) it's a CMPXCHG. 18570 * 18571 * The latter is because: BPF_CMPXCHG always loads a value into 18572 * R0, therefore always zero-extends. However some archs' 18573 * equivalent instruction only does this load when the 18574 * comparison is successful. This detail of CMPXCHG is 18575 * orthogonal to the general zero-extension behaviour of the 18576 * CPU, so it's treated independently of bpf_jit_needs_zext. 18577 */ 18578 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 18579 continue; 18580 18581 /* Zero-extension is done by the caller. */ 18582 if (bpf_pseudo_kfunc_call(&insn)) 18583 continue; 18584 18585 if (WARN_ON(load_reg == -1)) { 18586 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 18587 return -EFAULT; 18588 } 18589 18590 zext_patch[0] = insn; 18591 zext_patch[1].dst_reg = load_reg; 18592 zext_patch[1].src_reg = load_reg; 18593 patch = zext_patch; 18594 patch_len = 2; 18595 apply_patch_buffer: 18596 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 18597 if (!new_prog) 18598 return -ENOMEM; 18599 env->prog = new_prog; 18600 insns = new_prog->insnsi; 18601 aux = env->insn_aux_data; 18602 delta += patch_len - 1; 18603 } 18604 18605 return 0; 18606 } 18607 18608 /* convert load instructions that access fields of a context type into a 18609 * sequence of instructions that access fields of the underlying structure: 18610 * struct __sk_buff -> struct sk_buff 18611 * struct bpf_sock_ops -> struct sock 18612 */ 18613 static int convert_ctx_accesses(struct bpf_verifier_env *env) 18614 { 18615 const struct bpf_verifier_ops *ops = env->ops; 18616 int i, cnt, size, ctx_field_size, delta = 0; 18617 const int insn_cnt = env->prog->len; 18618 struct bpf_insn insn_buf[16], *insn; 18619 u32 target_size, size_default, off; 18620 struct bpf_prog *new_prog; 18621 enum bpf_access_type type; 18622 bool is_narrower_load; 18623 18624 if (ops->gen_prologue || env->seen_direct_write) { 18625 if (!ops->gen_prologue) { 18626 verbose(env, "bpf verifier is misconfigured\n"); 18627 return -EINVAL; 18628 } 18629 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 18630 env->prog); 18631 if (cnt >= ARRAY_SIZE(insn_buf)) { 18632 verbose(env, "bpf verifier is misconfigured\n"); 18633 return -EINVAL; 18634 } else if (cnt) { 18635 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 18636 if (!new_prog) 18637 return -ENOMEM; 18638 18639 env->prog = new_prog; 18640 delta += cnt - 1; 18641 } 18642 } 18643 18644 if (bpf_prog_is_offloaded(env->prog->aux)) 18645 return 0; 18646 18647 insn = env->prog->insnsi + delta; 18648 18649 for (i = 0; i < insn_cnt; i++, insn++) { 18650 bpf_convert_ctx_access_t convert_ctx_access; 18651 u8 mode; 18652 18653 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 18654 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 18655 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 18656 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 18657 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 18658 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 18659 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 18660 type = BPF_READ; 18661 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 18662 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 18663 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 18664 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 18665 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 18666 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 18667 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 18668 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 18669 type = BPF_WRITE; 18670 } else { 18671 continue; 18672 } 18673 18674 if (type == BPF_WRITE && 18675 env->insn_aux_data[i + delta].sanitize_stack_spill) { 18676 struct bpf_insn patch[] = { 18677 *insn, 18678 BPF_ST_NOSPEC(), 18679 }; 18680 18681 cnt = ARRAY_SIZE(patch); 18682 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 18683 if (!new_prog) 18684 return -ENOMEM; 18685 18686 delta += cnt - 1; 18687 env->prog = new_prog; 18688 insn = new_prog->insnsi + i + delta; 18689 continue; 18690 } 18691 18692 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 18693 case PTR_TO_CTX: 18694 if (!ops->convert_ctx_access) 18695 continue; 18696 convert_ctx_access = ops->convert_ctx_access; 18697 break; 18698 case PTR_TO_SOCKET: 18699 case PTR_TO_SOCK_COMMON: 18700 convert_ctx_access = bpf_sock_convert_ctx_access; 18701 break; 18702 case PTR_TO_TCP_SOCK: 18703 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 18704 break; 18705 case PTR_TO_XDP_SOCK: 18706 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 18707 break; 18708 case PTR_TO_BTF_ID: 18709 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 18710 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 18711 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 18712 * be said once it is marked PTR_UNTRUSTED, hence we must handle 18713 * any faults for loads into such types. BPF_WRITE is disallowed 18714 * for this case. 18715 */ 18716 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 18717 if (type == BPF_READ) { 18718 if (BPF_MODE(insn->code) == BPF_MEM) 18719 insn->code = BPF_LDX | BPF_PROBE_MEM | 18720 BPF_SIZE((insn)->code); 18721 else 18722 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 18723 BPF_SIZE((insn)->code); 18724 env->prog->aux->num_exentries++; 18725 } 18726 continue; 18727 default: 18728 continue; 18729 } 18730 18731 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 18732 size = BPF_LDST_BYTES(insn); 18733 mode = BPF_MODE(insn->code); 18734 18735 /* If the read access is a narrower load of the field, 18736 * convert to a 4/8-byte load, to minimum program type specific 18737 * convert_ctx_access changes. If conversion is successful, 18738 * we will apply proper mask to the result. 18739 */ 18740 is_narrower_load = size < ctx_field_size; 18741 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 18742 off = insn->off; 18743 if (is_narrower_load) { 18744 u8 size_code; 18745 18746 if (type == BPF_WRITE) { 18747 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 18748 return -EINVAL; 18749 } 18750 18751 size_code = BPF_H; 18752 if (ctx_field_size == 4) 18753 size_code = BPF_W; 18754 else if (ctx_field_size == 8) 18755 size_code = BPF_DW; 18756 18757 insn->off = off & ~(size_default - 1); 18758 insn->code = BPF_LDX | BPF_MEM | size_code; 18759 } 18760 18761 target_size = 0; 18762 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 18763 &target_size); 18764 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 18765 (ctx_field_size && !target_size)) { 18766 verbose(env, "bpf verifier is misconfigured\n"); 18767 return -EINVAL; 18768 } 18769 18770 if (is_narrower_load && size < target_size) { 18771 u8 shift = bpf_ctx_narrow_access_offset( 18772 off, size, size_default) * 8; 18773 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 18774 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 18775 return -EINVAL; 18776 } 18777 if (ctx_field_size <= 4) { 18778 if (shift) 18779 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 18780 insn->dst_reg, 18781 shift); 18782 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18783 (1 << size * 8) - 1); 18784 } else { 18785 if (shift) 18786 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 18787 insn->dst_reg, 18788 shift); 18789 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18790 (1ULL << size * 8) - 1); 18791 } 18792 } 18793 if (mode == BPF_MEMSX) 18794 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 18795 insn->dst_reg, insn->dst_reg, 18796 size * 8, 0); 18797 18798 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18799 if (!new_prog) 18800 return -ENOMEM; 18801 18802 delta += cnt - 1; 18803 18804 /* keep walking new program and skip insns we just inserted */ 18805 env->prog = new_prog; 18806 insn = new_prog->insnsi + i + delta; 18807 } 18808 18809 return 0; 18810 } 18811 18812 static int jit_subprogs(struct bpf_verifier_env *env) 18813 { 18814 struct bpf_prog *prog = env->prog, **func, *tmp; 18815 int i, j, subprog_start, subprog_end = 0, len, subprog; 18816 struct bpf_map *map_ptr; 18817 struct bpf_insn *insn; 18818 void *old_bpf_func; 18819 int err, num_exentries; 18820 18821 if (env->subprog_cnt <= 1) 18822 return 0; 18823 18824 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18825 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 18826 continue; 18827 18828 /* Upon error here we cannot fall back to interpreter but 18829 * need a hard reject of the program. Thus -EFAULT is 18830 * propagated in any case. 18831 */ 18832 subprog = find_subprog(env, i + insn->imm + 1); 18833 if (subprog < 0) { 18834 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 18835 i + insn->imm + 1); 18836 return -EFAULT; 18837 } 18838 /* temporarily remember subprog id inside insn instead of 18839 * aux_data, since next loop will split up all insns into funcs 18840 */ 18841 insn->off = subprog; 18842 /* remember original imm in case JIT fails and fallback 18843 * to interpreter will be needed 18844 */ 18845 env->insn_aux_data[i].call_imm = insn->imm; 18846 /* point imm to __bpf_call_base+1 from JITs point of view */ 18847 insn->imm = 1; 18848 if (bpf_pseudo_func(insn)) 18849 /* jit (e.g. x86_64) may emit fewer instructions 18850 * if it learns a u32 imm is the same as a u64 imm. 18851 * Force a non zero here. 18852 */ 18853 insn[1].imm = 1; 18854 } 18855 18856 err = bpf_prog_alloc_jited_linfo(prog); 18857 if (err) 18858 goto out_undo_insn; 18859 18860 err = -ENOMEM; 18861 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 18862 if (!func) 18863 goto out_undo_insn; 18864 18865 for (i = 0; i < env->subprog_cnt; i++) { 18866 subprog_start = subprog_end; 18867 subprog_end = env->subprog_info[i + 1].start; 18868 18869 len = subprog_end - subprog_start; 18870 /* bpf_prog_run() doesn't call subprogs directly, 18871 * hence main prog stats include the runtime of subprogs. 18872 * subprogs don't have IDs and not reachable via prog_get_next_id 18873 * func[i]->stats will never be accessed and stays NULL 18874 */ 18875 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 18876 if (!func[i]) 18877 goto out_free; 18878 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 18879 len * sizeof(struct bpf_insn)); 18880 func[i]->type = prog->type; 18881 func[i]->len = len; 18882 if (bpf_prog_calc_tag(func[i])) 18883 goto out_free; 18884 func[i]->is_func = 1; 18885 func[i]->aux->func_idx = i; 18886 /* Below members will be freed only at prog->aux */ 18887 func[i]->aux->btf = prog->aux->btf; 18888 func[i]->aux->func_info = prog->aux->func_info; 18889 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 18890 func[i]->aux->poke_tab = prog->aux->poke_tab; 18891 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 18892 18893 for (j = 0; j < prog->aux->size_poke_tab; j++) { 18894 struct bpf_jit_poke_descriptor *poke; 18895 18896 poke = &prog->aux->poke_tab[j]; 18897 if (poke->insn_idx < subprog_end && 18898 poke->insn_idx >= subprog_start) 18899 poke->aux = func[i]->aux; 18900 } 18901 18902 func[i]->aux->name[0] = 'F'; 18903 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 18904 func[i]->jit_requested = 1; 18905 func[i]->blinding_requested = prog->blinding_requested; 18906 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 18907 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 18908 func[i]->aux->linfo = prog->aux->linfo; 18909 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 18910 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 18911 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 18912 num_exentries = 0; 18913 insn = func[i]->insnsi; 18914 for (j = 0; j < func[i]->len; j++, insn++) { 18915 if (BPF_CLASS(insn->code) == BPF_LDX && 18916 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 18917 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 18918 num_exentries++; 18919 } 18920 func[i]->aux->num_exentries = num_exentries; 18921 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 18922 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb; 18923 if (!i) 18924 func[i]->aux->exception_boundary = env->seen_exception; 18925 func[i] = bpf_int_jit_compile(func[i]); 18926 if (!func[i]->jited) { 18927 err = -ENOTSUPP; 18928 goto out_free; 18929 } 18930 cond_resched(); 18931 } 18932 18933 /* at this point all bpf functions were successfully JITed 18934 * now populate all bpf_calls with correct addresses and 18935 * run last pass of JIT 18936 */ 18937 for (i = 0; i < env->subprog_cnt; i++) { 18938 insn = func[i]->insnsi; 18939 for (j = 0; j < func[i]->len; j++, insn++) { 18940 if (bpf_pseudo_func(insn)) { 18941 subprog = insn->off; 18942 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 18943 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 18944 continue; 18945 } 18946 if (!bpf_pseudo_call(insn)) 18947 continue; 18948 subprog = insn->off; 18949 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 18950 } 18951 18952 /* we use the aux data to keep a list of the start addresses 18953 * of the JITed images for each function in the program 18954 * 18955 * for some architectures, such as powerpc64, the imm field 18956 * might not be large enough to hold the offset of the start 18957 * address of the callee's JITed image from __bpf_call_base 18958 * 18959 * in such cases, we can lookup the start address of a callee 18960 * by using its subprog id, available from the off field of 18961 * the call instruction, as an index for this list 18962 */ 18963 func[i]->aux->func = func; 18964 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 18965 func[i]->aux->real_func_cnt = env->subprog_cnt; 18966 } 18967 for (i = 0; i < env->subprog_cnt; i++) { 18968 old_bpf_func = func[i]->bpf_func; 18969 tmp = bpf_int_jit_compile(func[i]); 18970 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 18971 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 18972 err = -ENOTSUPP; 18973 goto out_free; 18974 } 18975 cond_resched(); 18976 } 18977 18978 /* finally lock prog and jit images for all functions and 18979 * populate kallsysm. Begin at the first subprogram, since 18980 * bpf_prog_load will add the kallsyms for the main program. 18981 */ 18982 for (i = 1; i < env->subprog_cnt; i++) { 18983 bpf_prog_lock_ro(func[i]); 18984 bpf_prog_kallsyms_add(func[i]); 18985 } 18986 18987 /* Last step: make now unused interpreter insns from main 18988 * prog consistent for later dump requests, so they can 18989 * later look the same as if they were interpreted only. 18990 */ 18991 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18992 if (bpf_pseudo_func(insn)) { 18993 insn[0].imm = env->insn_aux_data[i].call_imm; 18994 insn[1].imm = insn->off; 18995 insn->off = 0; 18996 continue; 18997 } 18998 if (!bpf_pseudo_call(insn)) 18999 continue; 19000 insn->off = env->insn_aux_data[i].call_imm; 19001 subprog = find_subprog(env, i + insn->off + 1); 19002 insn->imm = subprog; 19003 } 19004 19005 prog->jited = 1; 19006 prog->bpf_func = func[0]->bpf_func; 19007 prog->jited_len = func[0]->jited_len; 19008 prog->aux->extable = func[0]->aux->extable; 19009 prog->aux->num_exentries = func[0]->aux->num_exentries; 19010 prog->aux->func = func; 19011 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 19012 prog->aux->real_func_cnt = env->subprog_cnt; 19013 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func; 19014 prog->aux->exception_boundary = func[0]->aux->exception_boundary; 19015 bpf_prog_jit_attempt_done(prog); 19016 return 0; 19017 out_free: 19018 /* We failed JIT'ing, so at this point we need to unregister poke 19019 * descriptors from subprogs, so that kernel is not attempting to 19020 * patch it anymore as we're freeing the subprog JIT memory. 19021 */ 19022 for (i = 0; i < prog->aux->size_poke_tab; i++) { 19023 map_ptr = prog->aux->poke_tab[i].tail_call.map; 19024 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 19025 } 19026 /* At this point we're guaranteed that poke descriptors are not 19027 * live anymore. We can just unlink its descriptor table as it's 19028 * released with the main prog. 19029 */ 19030 for (i = 0; i < env->subprog_cnt; i++) { 19031 if (!func[i]) 19032 continue; 19033 func[i]->aux->poke_tab = NULL; 19034 bpf_jit_free(func[i]); 19035 } 19036 kfree(func); 19037 out_undo_insn: 19038 /* cleanup main prog to be interpreted */ 19039 prog->jit_requested = 0; 19040 prog->blinding_requested = 0; 19041 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 19042 if (!bpf_pseudo_call(insn)) 19043 continue; 19044 insn->off = 0; 19045 insn->imm = env->insn_aux_data[i].call_imm; 19046 } 19047 bpf_prog_jit_attempt_done(prog); 19048 return err; 19049 } 19050 19051 static int fixup_call_args(struct bpf_verifier_env *env) 19052 { 19053 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 19054 struct bpf_prog *prog = env->prog; 19055 struct bpf_insn *insn = prog->insnsi; 19056 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 19057 int i, depth; 19058 #endif 19059 int err = 0; 19060 19061 if (env->prog->jit_requested && 19062 !bpf_prog_is_offloaded(env->prog->aux)) { 19063 err = jit_subprogs(env); 19064 if (err == 0) 19065 return 0; 19066 if (err == -EFAULT) 19067 return err; 19068 } 19069 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 19070 if (has_kfunc_call) { 19071 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 19072 return -EINVAL; 19073 } 19074 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 19075 /* When JIT fails the progs with bpf2bpf calls and tail_calls 19076 * have to be rejected, since interpreter doesn't support them yet. 19077 */ 19078 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 19079 return -EINVAL; 19080 } 19081 for (i = 0; i < prog->len; i++, insn++) { 19082 if (bpf_pseudo_func(insn)) { 19083 /* When JIT fails the progs with callback calls 19084 * have to be rejected, since interpreter doesn't support them yet. 19085 */ 19086 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 19087 return -EINVAL; 19088 } 19089 19090 if (!bpf_pseudo_call(insn)) 19091 continue; 19092 depth = get_callee_stack_depth(env, insn, i); 19093 if (depth < 0) 19094 return depth; 19095 bpf_patch_call_args(insn, depth); 19096 } 19097 err = 0; 19098 #endif 19099 return err; 19100 } 19101 19102 /* replace a generic kfunc with a specialized version if necessary */ 19103 static void specialize_kfunc(struct bpf_verifier_env *env, 19104 u32 func_id, u16 offset, unsigned long *addr) 19105 { 19106 struct bpf_prog *prog = env->prog; 19107 bool seen_direct_write; 19108 void *xdp_kfunc; 19109 bool is_rdonly; 19110 19111 if (bpf_dev_bound_kfunc_id(func_id)) { 19112 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 19113 if (xdp_kfunc) { 19114 *addr = (unsigned long)xdp_kfunc; 19115 return; 19116 } 19117 /* fallback to default kfunc when not supported by netdev */ 19118 } 19119 19120 if (offset) 19121 return; 19122 19123 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 19124 seen_direct_write = env->seen_direct_write; 19125 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 19126 19127 if (is_rdonly) 19128 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 19129 19130 /* restore env->seen_direct_write to its original value, since 19131 * may_access_direct_pkt_data mutates it 19132 */ 19133 env->seen_direct_write = seen_direct_write; 19134 } 19135 } 19136 19137 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 19138 u16 struct_meta_reg, 19139 u16 node_offset_reg, 19140 struct bpf_insn *insn, 19141 struct bpf_insn *insn_buf, 19142 int *cnt) 19143 { 19144 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 19145 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 19146 19147 insn_buf[0] = addr[0]; 19148 insn_buf[1] = addr[1]; 19149 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 19150 insn_buf[3] = *insn; 19151 *cnt = 4; 19152 } 19153 19154 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 19155 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 19156 { 19157 const struct bpf_kfunc_desc *desc; 19158 19159 if (!insn->imm) { 19160 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 19161 return -EINVAL; 19162 } 19163 19164 *cnt = 0; 19165 19166 /* insn->imm has the btf func_id. Replace it with an offset relative to 19167 * __bpf_call_base, unless the JIT needs to call functions that are 19168 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 19169 */ 19170 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 19171 if (!desc) { 19172 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 19173 insn->imm); 19174 return -EFAULT; 19175 } 19176 19177 if (!bpf_jit_supports_far_kfunc_call()) 19178 insn->imm = BPF_CALL_IMM(desc->addr); 19179 if (insn->off) 19180 return 0; 19181 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 19182 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 19183 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19184 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19185 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 19186 19187 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) { 19188 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 19189 insn_idx); 19190 return -EFAULT; 19191 } 19192 19193 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 19194 insn_buf[1] = addr[0]; 19195 insn_buf[2] = addr[1]; 19196 insn_buf[3] = *insn; 19197 *cnt = 4; 19198 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 19199 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] || 19200 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 19201 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19202 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19203 19204 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) { 19205 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 19206 insn_idx); 19207 return -EFAULT; 19208 } 19209 19210 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 19211 !kptr_struct_meta) { 19212 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 19213 insn_idx); 19214 return -EFAULT; 19215 } 19216 19217 insn_buf[0] = addr[0]; 19218 insn_buf[1] = addr[1]; 19219 insn_buf[2] = *insn; 19220 *cnt = 3; 19221 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 19222 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 19223 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 19224 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19225 int struct_meta_reg = BPF_REG_3; 19226 int node_offset_reg = BPF_REG_4; 19227 19228 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 19229 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 19230 struct_meta_reg = BPF_REG_4; 19231 node_offset_reg = BPF_REG_5; 19232 } 19233 19234 if (!kptr_struct_meta) { 19235 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 19236 insn_idx); 19237 return -EFAULT; 19238 } 19239 19240 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 19241 node_offset_reg, insn, insn_buf, cnt); 19242 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 19243 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 19244 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 19245 *cnt = 1; 19246 } 19247 return 0; 19248 } 19249 19250 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */ 19251 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len) 19252 { 19253 struct bpf_subprog_info *info = env->subprog_info; 19254 int cnt = env->subprog_cnt; 19255 struct bpf_prog *prog; 19256 19257 /* We only reserve one slot for hidden subprogs in subprog_info. */ 19258 if (env->hidden_subprog_cnt) { 19259 verbose(env, "verifier internal error: only one hidden subprog supported\n"); 19260 return -EFAULT; 19261 } 19262 /* We're not patching any existing instruction, just appending the new 19263 * ones for the hidden subprog. Hence all of the adjustment operations 19264 * in bpf_patch_insn_data are no-ops. 19265 */ 19266 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len); 19267 if (!prog) 19268 return -ENOMEM; 19269 env->prog = prog; 19270 info[cnt + 1].start = info[cnt].start; 19271 info[cnt].start = prog->len - len + 1; 19272 env->subprog_cnt++; 19273 env->hidden_subprog_cnt++; 19274 return 0; 19275 } 19276 19277 /* Do various post-verification rewrites in a single program pass. 19278 * These rewrites simplify JIT and interpreter implementations. 19279 */ 19280 static int do_misc_fixups(struct bpf_verifier_env *env) 19281 { 19282 struct bpf_prog *prog = env->prog; 19283 enum bpf_attach_type eatype = prog->expected_attach_type; 19284 enum bpf_prog_type prog_type = resolve_prog_type(prog); 19285 struct bpf_insn *insn = prog->insnsi; 19286 const struct bpf_func_proto *fn; 19287 const int insn_cnt = prog->len; 19288 const struct bpf_map_ops *ops; 19289 struct bpf_insn_aux_data *aux; 19290 struct bpf_insn insn_buf[16]; 19291 struct bpf_prog *new_prog; 19292 struct bpf_map *map_ptr; 19293 int i, ret, cnt, delta = 0; 19294 19295 if (env->seen_exception && !env->exception_callback_subprog) { 19296 struct bpf_insn patch[] = { 19297 env->prog->insnsi[insn_cnt - 1], 19298 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1), 19299 BPF_EXIT_INSN(), 19300 }; 19301 19302 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch)); 19303 if (ret < 0) 19304 return ret; 19305 prog = env->prog; 19306 insn = prog->insnsi; 19307 19308 env->exception_callback_subprog = env->subprog_cnt - 1; 19309 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */ 19310 mark_subprog_exc_cb(env, env->exception_callback_subprog); 19311 } 19312 19313 for (i = 0; i < insn_cnt; i++, insn++) { 19314 /* Make divide-by-zero exceptions impossible. */ 19315 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 19316 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 19317 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 19318 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 19319 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 19320 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 19321 struct bpf_insn *patchlet; 19322 struct bpf_insn chk_and_div[] = { 19323 /* [R,W]x div 0 -> 0 */ 19324 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 19325 BPF_JNE | BPF_K, insn->src_reg, 19326 0, 2, 0), 19327 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 19328 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 19329 *insn, 19330 }; 19331 struct bpf_insn chk_and_mod[] = { 19332 /* [R,W]x mod 0 -> [R,W]x */ 19333 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 19334 BPF_JEQ | BPF_K, insn->src_reg, 19335 0, 1 + (is64 ? 0 : 1), 0), 19336 *insn, 19337 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 19338 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 19339 }; 19340 19341 patchlet = isdiv ? chk_and_div : chk_and_mod; 19342 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 19343 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 19344 19345 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 19346 if (!new_prog) 19347 return -ENOMEM; 19348 19349 delta += cnt - 1; 19350 env->prog = prog = new_prog; 19351 insn = new_prog->insnsi + i + delta; 19352 continue; 19353 } 19354 19355 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 19356 if (BPF_CLASS(insn->code) == BPF_LD && 19357 (BPF_MODE(insn->code) == BPF_ABS || 19358 BPF_MODE(insn->code) == BPF_IND)) { 19359 cnt = env->ops->gen_ld_abs(insn, insn_buf); 19360 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19361 verbose(env, "bpf verifier is misconfigured\n"); 19362 return -EINVAL; 19363 } 19364 19365 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19366 if (!new_prog) 19367 return -ENOMEM; 19368 19369 delta += cnt - 1; 19370 env->prog = prog = new_prog; 19371 insn = new_prog->insnsi + i + delta; 19372 continue; 19373 } 19374 19375 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 19376 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 19377 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 19378 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 19379 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 19380 struct bpf_insn *patch = &insn_buf[0]; 19381 bool issrc, isneg, isimm; 19382 u32 off_reg; 19383 19384 aux = &env->insn_aux_data[i + delta]; 19385 if (!aux->alu_state || 19386 aux->alu_state == BPF_ALU_NON_POINTER) 19387 continue; 19388 19389 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 19390 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 19391 BPF_ALU_SANITIZE_SRC; 19392 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 19393 19394 off_reg = issrc ? insn->src_reg : insn->dst_reg; 19395 if (isimm) { 19396 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19397 } else { 19398 if (isneg) 19399 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19400 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19401 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 19402 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 19403 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 19404 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 19405 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 19406 } 19407 if (!issrc) 19408 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 19409 insn->src_reg = BPF_REG_AX; 19410 if (isneg) 19411 insn->code = insn->code == code_add ? 19412 code_sub : code_add; 19413 *patch++ = *insn; 19414 if (issrc && isneg && !isimm) 19415 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19416 cnt = patch - insn_buf; 19417 19418 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19419 if (!new_prog) 19420 return -ENOMEM; 19421 19422 delta += cnt - 1; 19423 env->prog = prog = new_prog; 19424 insn = new_prog->insnsi + i + delta; 19425 continue; 19426 } 19427 19428 if (insn->code != (BPF_JMP | BPF_CALL)) 19429 continue; 19430 if (insn->src_reg == BPF_PSEUDO_CALL) 19431 continue; 19432 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 19433 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 19434 if (ret) 19435 return ret; 19436 if (cnt == 0) 19437 continue; 19438 19439 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19440 if (!new_prog) 19441 return -ENOMEM; 19442 19443 delta += cnt - 1; 19444 env->prog = prog = new_prog; 19445 insn = new_prog->insnsi + i + delta; 19446 continue; 19447 } 19448 19449 if (insn->imm == BPF_FUNC_get_route_realm) 19450 prog->dst_needed = 1; 19451 if (insn->imm == BPF_FUNC_get_prandom_u32) 19452 bpf_user_rnd_init_once(); 19453 if (insn->imm == BPF_FUNC_override_return) 19454 prog->kprobe_override = 1; 19455 if (insn->imm == BPF_FUNC_tail_call) { 19456 /* If we tail call into other programs, we 19457 * cannot make any assumptions since they can 19458 * be replaced dynamically during runtime in 19459 * the program array. 19460 */ 19461 prog->cb_access = 1; 19462 if (!allow_tail_call_in_subprogs(env)) 19463 prog->aux->stack_depth = MAX_BPF_STACK; 19464 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 19465 19466 /* mark bpf_tail_call as different opcode to avoid 19467 * conditional branch in the interpreter for every normal 19468 * call and to prevent accidental JITing by JIT compiler 19469 * that doesn't support bpf_tail_call yet 19470 */ 19471 insn->imm = 0; 19472 insn->code = BPF_JMP | BPF_TAIL_CALL; 19473 19474 aux = &env->insn_aux_data[i + delta]; 19475 if (env->bpf_capable && !prog->blinding_requested && 19476 prog->jit_requested && 19477 !bpf_map_key_poisoned(aux) && 19478 !bpf_map_ptr_poisoned(aux) && 19479 !bpf_map_ptr_unpriv(aux)) { 19480 struct bpf_jit_poke_descriptor desc = { 19481 .reason = BPF_POKE_REASON_TAIL_CALL, 19482 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 19483 .tail_call.key = bpf_map_key_immediate(aux), 19484 .insn_idx = i + delta, 19485 }; 19486 19487 ret = bpf_jit_add_poke_descriptor(prog, &desc); 19488 if (ret < 0) { 19489 verbose(env, "adding tail call poke descriptor failed\n"); 19490 return ret; 19491 } 19492 19493 insn->imm = ret + 1; 19494 continue; 19495 } 19496 19497 if (!bpf_map_ptr_unpriv(aux)) 19498 continue; 19499 19500 /* instead of changing every JIT dealing with tail_call 19501 * emit two extra insns: 19502 * if (index >= max_entries) goto out; 19503 * index &= array->index_mask; 19504 * to avoid out-of-bounds cpu speculation 19505 */ 19506 if (bpf_map_ptr_poisoned(aux)) { 19507 verbose(env, "tail_call abusing map_ptr\n"); 19508 return -EINVAL; 19509 } 19510 19511 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19512 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 19513 map_ptr->max_entries, 2); 19514 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 19515 container_of(map_ptr, 19516 struct bpf_array, 19517 map)->index_mask); 19518 insn_buf[2] = *insn; 19519 cnt = 3; 19520 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19521 if (!new_prog) 19522 return -ENOMEM; 19523 19524 delta += cnt - 1; 19525 env->prog = prog = new_prog; 19526 insn = new_prog->insnsi + i + delta; 19527 continue; 19528 } 19529 19530 if (insn->imm == BPF_FUNC_timer_set_callback) { 19531 /* The verifier will process callback_fn as many times as necessary 19532 * with different maps and the register states prepared by 19533 * set_timer_callback_state will be accurate. 19534 * 19535 * The following use case is valid: 19536 * map1 is shared by prog1, prog2, prog3. 19537 * prog1 calls bpf_timer_init for some map1 elements 19538 * prog2 calls bpf_timer_set_callback for some map1 elements. 19539 * Those that were not bpf_timer_init-ed will return -EINVAL. 19540 * prog3 calls bpf_timer_start for some map1 elements. 19541 * Those that were not both bpf_timer_init-ed and 19542 * bpf_timer_set_callback-ed will return -EINVAL. 19543 */ 19544 struct bpf_insn ld_addrs[2] = { 19545 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 19546 }; 19547 19548 insn_buf[0] = ld_addrs[0]; 19549 insn_buf[1] = ld_addrs[1]; 19550 insn_buf[2] = *insn; 19551 cnt = 3; 19552 19553 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19554 if (!new_prog) 19555 return -ENOMEM; 19556 19557 delta += cnt - 1; 19558 env->prog = prog = new_prog; 19559 insn = new_prog->insnsi + i + delta; 19560 goto patch_call_imm; 19561 } 19562 19563 if (is_storage_get_function(insn->imm)) { 19564 if (!env->prog->aux->sleepable || 19565 env->insn_aux_data[i + delta].storage_get_func_atomic) 19566 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 19567 else 19568 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 19569 insn_buf[1] = *insn; 19570 cnt = 2; 19571 19572 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19573 if (!new_prog) 19574 return -ENOMEM; 19575 19576 delta += cnt - 1; 19577 env->prog = prog = new_prog; 19578 insn = new_prog->insnsi + i + delta; 19579 goto patch_call_imm; 19580 } 19581 19582 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */ 19583 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) { 19584 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data, 19585 * bpf_mem_alloc() returns a ptr to the percpu data ptr. 19586 */ 19587 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0); 19588 insn_buf[1] = *insn; 19589 cnt = 2; 19590 19591 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19592 if (!new_prog) 19593 return -ENOMEM; 19594 19595 delta += cnt - 1; 19596 env->prog = prog = new_prog; 19597 insn = new_prog->insnsi + i + delta; 19598 goto patch_call_imm; 19599 } 19600 19601 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 19602 * and other inlining handlers are currently limited to 64 bit 19603 * only. 19604 */ 19605 if (prog->jit_requested && BITS_PER_LONG == 64 && 19606 (insn->imm == BPF_FUNC_map_lookup_elem || 19607 insn->imm == BPF_FUNC_map_update_elem || 19608 insn->imm == BPF_FUNC_map_delete_elem || 19609 insn->imm == BPF_FUNC_map_push_elem || 19610 insn->imm == BPF_FUNC_map_pop_elem || 19611 insn->imm == BPF_FUNC_map_peek_elem || 19612 insn->imm == BPF_FUNC_redirect_map || 19613 insn->imm == BPF_FUNC_for_each_map_elem || 19614 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 19615 aux = &env->insn_aux_data[i + delta]; 19616 if (bpf_map_ptr_poisoned(aux)) 19617 goto patch_call_imm; 19618 19619 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19620 ops = map_ptr->ops; 19621 if (insn->imm == BPF_FUNC_map_lookup_elem && 19622 ops->map_gen_lookup) { 19623 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 19624 if (cnt == -EOPNOTSUPP) 19625 goto patch_map_ops_generic; 19626 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19627 verbose(env, "bpf verifier is misconfigured\n"); 19628 return -EINVAL; 19629 } 19630 19631 new_prog = bpf_patch_insn_data(env, i + delta, 19632 insn_buf, cnt); 19633 if (!new_prog) 19634 return -ENOMEM; 19635 19636 delta += cnt - 1; 19637 env->prog = prog = new_prog; 19638 insn = new_prog->insnsi + i + delta; 19639 continue; 19640 } 19641 19642 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 19643 (void *(*)(struct bpf_map *map, void *key))NULL)); 19644 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 19645 (long (*)(struct bpf_map *map, void *key))NULL)); 19646 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 19647 (long (*)(struct bpf_map *map, void *key, void *value, 19648 u64 flags))NULL)); 19649 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 19650 (long (*)(struct bpf_map *map, void *value, 19651 u64 flags))NULL)); 19652 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 19653 (long (*)(struct bpf_map *map, void *value))NULL)); 19654 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 19655 (long (*)(struct bpf_map *map, void *value))NULL)); 19656 BUILD_BUG_ON(!__same_type(ops->map_redirect, 19657 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 19658 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 19659 (long (*)(struct bpf_map *map, 19660 bpf_callback_t callback_fn, 19661 void *callback_ctx, 19662 u64 flags))NULL)); 19663 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 19664 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 19665 19666 patch_map_ops_generic: 19667 switch (insn->imm) { 19668 case BPF_FUNC_map_lookup_elem: 19669 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 19670 continue; 19671 case BPF_FUNC_map_update_elem: 19672 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 19673 continue; 19674 case BPF_FUNC_map_delete_elem: 19675 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 19676 continue; 19677 case BPF_FUNC_map_push_elem: 19678 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 19679 continue; 19680 case BPF_FUNC_map_pop_elem: 19681 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 19682 continue; 19683 case BPF_FUNC_map_peek_elem: 19684 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 19685 continue; 19686 case BPF_FUNC_redirect_map: 19687 insn->imm = BPF_CALL_IMM(ops->map_redirect); 19688 continue; 19689 case BPF_FUNC_for_each_map_elem: 19690 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 19691 continue; 19692 case BPF_FUNC_map_lookup_percpu_elem: 19693 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 19694 continue; 19695 } 19696 19697 goto patch_call_imm; 19698 } 19699 19700 /* Implement bpf_jiffies64 inline. */ 19701 if (prog->jit_requested && BITS_PER_LONG == 64 && 19702 insn->imm == BPF_FUNC_jiffies64) { 19703 struct bpf_insn ld_jiffies_addr[2] = { 19704 BPF_LD_IMM64(BPF_REG_0, 19705 (unsigned long)&jiffies), 19706 }; 19707 19708 insn_buf[0] = ld_jiffies_addr[0]; 19709 insn_buf[1] = ld_jiffies_addr[1]; 19710 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 19711 BPF_REG_0, 0); 19712 cnt = 3; 19713 19714 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 19715 cnt); 19716 if (!new_prog) 19717 return -ENOMEM; 19718 19719 delta += cnt - 1; 19720 env->prog = prog = new_prog; 19721 insn = new_prog->insnsi + i + delta; 19722 continue; 19723 } 19724 19725 /* Implement bpf_get_func_arg inline. */ 19726 if (prog_type == BPF_PROG_TYPE_TRACING && 19727 insn->imm == BPF_FUNC_get_func_arg) { 19728 /* Load nr_args from ctx - 8 */ 19729 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19730 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 19731 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 19732 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 19733 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 19734 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19735 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 19736 insn_buf[7] = BPF_JMP_A(1); 19737 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 19738 cnt = 9; 19739 19740 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19741 if (!new_prog) 19742 return -ENOMEM; 19743 19744 delta += cnt - 1; 19745 env->prog = prog = new_prog; 19746 insn = new_prog->insnsi + i + delta; 19747 continue; 19748 } 19749 19750 /* Implement bpf_get_func_ret inline. */ 19751 if (prog_type == BPF_PROG_TYPE_TRACING && 19752 insn->imm == BPF_FUNC_get_func_ret) { 19753 if (eatype == BPF_TRACE_FEXIT || 19754 eatype == BPF_MODIFY_RETURN) { 19755 /* Load nr_args from ctx - 8 */ 19756 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19757 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 19758 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 19759 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19760 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 19761 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 19762 cnt = 6; 19763 } else { 19764 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 19765 cnt = 1; 19766 } 19767 19768 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19769 if (!new_prog) 19770 return -ENOMEM; 19771 19772 delta += cnt - 1; 19773 env->prog = prog = new_prog; 19774 insn = new_prog->insnsi + i + delta; 19775 continue; 19776 } 19777 19778 /* Implement get_func_arg_cnt inline. */ 19779 if (prog_type == BPF_PROG_TYPE_TRACING && 19780 insn->imm == BPF_FUNC_get_func_arg_cnt) { 19781 /* Load nr_args from ctx - 8 */ 19782 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19783 19784 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19785 if (!new_prog) 19786 return -ENOMEM; 19787 19788 env->prog = prog = new_prog; 19789 insn = new_prog->insnsi + i + delta; 19790 continue; 19791 } 19792 19793 /* Implement bpf_get_func_ip inline. */ 19794 if (prog_type == BPF_PROG_TYPE_TRACING && 19795 insn->imm == BPF_FUNC_get_func_ip) { 19796 /* Load IP address from ctx - 16 */ 19797 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 19798 19799 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19800 if (!new_prog) 19801 return -ENOMEM; 19802 19803 env->prog = prog = new_prog; 19804 insn = new_prog->insnsi + i + delta; 19805 continue; 19806 } 19807 19808 patch_call_imm: 19809 fn = env->ops->get_func_proto(insn->imm, env->prog); 19810 /* all functions that have prototype and verifier allowed 19811 * programs to call them, must be real in-kernel functions 19812 */ 19813 if (!fn->func) { 19814 verbose(env, 19815 "kernel subsystem misconfigured func %s#%d\n", 19816 func_id_name(insn->imm), insn->imm); 19817 return -EFAULT; 19818 } 19819 insn->imm = fn->func - __bpf_call_base; 19820 } 19821 19822 /* Since poke tab is now finalized, publish aux to tracker. */ 19823 for (i = 0; i < prog->aux->size_poke_tab; i++) { 19824 map_ptr = prog->aux->poke_tab[i].tail_call.map; 19825 if (!map_ptr->ops->map_poke_track || 19826 !map_ptr->ops->map_poke_untrack || 19827 !map_ptr->ops->map_poke_run) { 19828 verbose(env, "bpf verifier is misconfigured\n"); 19829 return -EINVAL; 19830 } 19831 19832 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 19833 if (ret < 0) { 19834 verbose(env, "tracking tail call prog failed\n"); 19835 return ret; 19836 } 19837 } 19838 19839 sort_kfunc_descs_by_imm_off(env->prog); 19840 19841 return 0; 19842 } 19843 19844 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 19845 int position, 19846 s32 stack_base, 19847 u32 callback_subprogno, 19848 u32 *cnt) 19849 { 19850 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 19851 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 19852 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 19853 int reg_loop_max = BPF_REG_6; 19854 int reg_loop_cnt = BPF_REG_7; 19855 int reg_loop_ctx = BPF_REG_8; 19856 19857 struct bpf_prog *new_prog; 19858 u32 callback_start; 19859 u32 call_insn_offset; 19860 s32 callback_offset; 19861 19862 /* This represents an inlined version of bpf_iter.c:bpf_loop, 19863 * be careful to modify this code in sync. 19864 */ 19865 struct bpf_insn insn_buf[] = { 19866 /* Return error and jump to the end of the patch if 19867 * expected number of iterations is too big. 19868 */ 19869 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 19870 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 19871 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 19872 /* spill R6, R7, R8 to use these as loop vars */ 19873 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 19874 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 19875 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 19876 /* initialize loop vars */ 19877 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 19878 BPF_MOV32_IMM(reg_loop_cnt, 0), 19879 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 19880 /* loop header, 19881 * if reg_loop_cnt >= reg_loop_max skip the loop body 19882 */ 19883 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 19884 /* callback call, 19885 * correct callback offset would be set after patching 19886 */ 19887 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 19888 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 19889 BPF_CALL_REL(0), 19890 /* increment loop counter */ 19891 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 19892 /* jump to loop header if callback returned 0 */ 19893 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 19894 /* return value of bpf_loop, 19895 * set R0 to the number of iterations 19896 */ 19897 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 19898 /* restore original values of R6, R7, R8 */ 19899 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 19900 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 19901 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 19902 }; 19903 19904 *cnt = ARRAY_SIZE(insn_buf); 19905 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 19906 if (!new_prog) 19907 return new_prog; 19908 19909 /* callback start is known only after patching */ 19910 callback_start = env->subprog_info[callback_subprogno].start; 19911 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 19912 call_insn_offset = position + 12; 19913 callback_offset = callback_start - call_insn_offset - 1; 19914 new_prog->insnsi[call_insn_offset].imm = callback_offset; 19915 19916 return new_prog; 19917 } 19918 19919 static bool is_bpf_loop_call(struct bpf_insn *insn) 19920 { 19921 return insn->code == (BPF_JMP | BPF_CALL) && 19922 insn->src_reg == 0 && 19923 insn->imm == BPF_FUNC_loop; 19924 } 19925 19926 /* For all sub-programs in the program (including main) check 19927 * insn_aux_data to see if there are bpf_loop calls that require 19928 * inlining. If such calls are found the calls are replaced with a 19929 * sequence of instructions produced by `inline_bpf_loop` function and 19930 * subprog stack_depth is increased by the size of 3 registers. 19931 * This stack space is used to spill values of the R6, R7, R8. These 19932 * registers are used to store the loop bound, counter and context 19933 * variables. 19934 */ 19935 static int optimize_bpf_loop(struct bpf_verifier_env *env) 19936 { 19937 struct bpf_subprog_info *subprogs = env->subprog_info; 19938 int i, cur_subprog = 0, cnt, delta = 0; 19939 struct bpf_insn *insn = env->prog->insnsi; 19940 int insn_cnt = env->prog->len; 19941 u16 stack_depth = subprogs[cur_subprog].stack_depth; 19942 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19943 u16 stack_depth_extra = 0; 19944 19945 for (i = 0; i < insn_cnt; i++, insn++) { 19946 struct bpf_loop_inline_state *inline_state = 19947 &env->insn_aux_data[i + delta].loop_inline_state; 19948 19949 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 19950 struct bpf_prog *new_prog; 19951 19952 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 19953 new_prog = inline_bpf_loop(env, 19954 i + delta, 19955 -(stack_depth + stack_depth_extra), 19956 inline_state->callback_subprogno, 19957 &cnt); 19958 if (!new_prog) 19959 return -ENOMEM; 19960 19961 delta += cnt - 1; 19962 env->prog = new_prog; 19963 insn = new_prog->insnsi + i + delta; 19964 } 19965 19966 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 19967 subprogs[cur_subprog].stack_depth += stack_depth_extra; 19968 cur_subprog++; 19969 stack_depth = subprogs[cur_subprog].stack_depth; 19970 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19971 stack_depth_extra = 0; 19972 } 19973 } 19974 19975 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 19976 19977 return 0; 19978 } 19979 19980 static void free_states(struct bpf_verifier_env *env) 19981 { 19982 struct bpf_verifier_state_list *sl, *sln; 19983 int i; 19984 19985 sl = env->free_list; 19986 while (sl) { 19987 sln = sl->next; 19988 free_verifier_state(&sl->state, false); 19989 kfree(sl); 19990 sl = sln; 19991 } 19992 env->free_list = NULL; 19993 19994 if (!env->explored_states) 19995 return; 19996 19997 for (i = 0; i < state_htab_size(env); i++) { 19998 sl = env->explored_states[i]; 19999 20000 while (sl) { 20001 sln = sl->next; 20002 free_verifier_state(&sl->state, false); 20003 kfree(sl); 20004 sl = sln; 20005 } 20006 env->explored_states[i] = NULL; 20007 } 20008 } 20009 20010 static int do_check_common(struct bpf_verifier_env *env, int subprog) 20011 { 20012 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 20013 struct bpf_subprog_info *sub = subprog_info(env, subprog); 20014 struct bpf_verifier_state *state; 20015 struct bpf_reg_state *regs; 20016 int ret, i; 20017 20018 env->prev_linfo = NULL; 20019 env->pass_cnt++; 20020 20021 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 20022 if (!state) 20023 return -ENOMEM; 20024 state->curframe = 0; 20025 state->speculative = false; 20026 state->branches = 1; 20027 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 20028 if (!state->frame[0]) { 20029 kfree(state); 20030 return -ENOMEM; 20031 } 20032 env->cur_state = state; 20033 init_func_state(env, state->frame[0], 20034 BPF_MAIN_FUNC /* callsite */, 20035 0 /* frameno */, 20036 subprog); 20037 state->first_insn_idx = env->subprog_info[subprog].start; 20038 state->last_insn_idx = -1; 20039 20040 20041 regs = state->frame[state->curframe]->regs; 20042 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 20043 const char *sub_name = subprog_name(env, subprog); 20044 struct bpf_subprog_arg_info *arg; 20045 struct bpf_reg_state *reg; 20046 20047 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 20048 ret = btf_prepare_func_args(env, subprog); 20049 if (ret) 20050 goto out; 20051 20052 if (subprog_is_exc_cb(env, subprog)) { 20053 state->frame[0]->in_exception_callback_fn = true; 20054 /* We have already ensured that the callback returns an integer, just 20055 * like all global subprogs. We need to determine it only has a single 20056 * scalar argument. 20057 */ 20058 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 20059 verbose(env, "exception cb only supports single integer argument\n"); 20060 ret = -EINVAL; 20061 goto out; 20062 } 20063 } 20064 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) { 20065 arg = &sub->args[i - BPF_REG_1]; 20066 reg = ®s[i]; 20067 20068 if (arg->arg_type == ARG_PTR_TO_CTX) { 20069 reg->type = PTR_TO_CTX; 20070 mark_reg_known_zero(env, regs, i); 20071 } else if (arg->arg_type == ARG_ANYTHING) { 20072 reg->type = SCALAR_VALUE; 20073 mark_reg_unknown(env, regs, i); 20074 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 20075 /* assume unspecial LOCAL dynptr type */ 20076 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen); 20077 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 20078 reg->type = PTR_TO_MEM; 20079 if (arg->arg_type & PTR_MAYBE_NULL) 20080 reg->type |= PTR_MAYBE_NULL; 20081 mark_reg_known_zero(env, regs, i); 20082 reg->mem_size = arg->mem_size; 20083 reg->id = ++env->id_gen; 20084 } else { 20085 WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n", 20086 i - BPF_REG_1, arg->arg_type); 20087 ret = -EFAULT; 20088 goto out; 20089 } 20090 } 20091 } else { 20092 /* if main BPF program has associated BTF info, validate that 20093 * it's matching expected signature, and otherwise mark BTF 20094 * info for main program as unreliable 20095 */ 20096 if (env->prog->aux->func_info_aux) { 20097 ret = btf_prepare_func_args(env, 0); 20098 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) 20099 env->prog->aux->func_info_aux[0].unreliable = true; 20100 } 20101 20102 /* 1st arg to a function */ 20103 regs[BPF_REG_1].type = PTR_TO_CTX; 20104 mark_reg_known_zero(env, regs, BPF_REG_1); 20105 } 20106 20107 ret = do_check(env); 20108 out: 20109 /* check for NULL is necessary, since cur_state can be freed inside 20110 * do_check() under memory pressure. 20111 */ 20112 if (env->cur_state) { 20113 free_verifier_state(env->cur_state, true); 20114 env->cur_state = NULL; 20115 } 20116 while (!pop_stack(env, NULL, NULL, false)); 20117 if (!ret && pop_log) 20118 bpf_vlog_reset(&env->log, 0); 20119 free_states(env); 20120 return ret; 20121 } 20122 20123 /* Lazily verify all global functions based on their BTF, if they are called 20124 * from main BPF program or any of subprograms transitively. 20125 * BPF global subprogs called from dead code are not validated. 20126 * All callable global functions must pass verification. 20127 * Otherwise the whole program is rejected. 20128 * Consider: 20129 * int bar(int); 20130 * int foo(int f) 20131 * { 20132 * return bar(f); 20133 * } 20134 * int bar(int b) 20135 * { 20136 * ... 20137 * } 20138 * foo() will be verified first for R1=any_scalar_value. During verification it 20139 * will be assumed that bar() already verified successfully and call to bar() 20140 * from foo() will be checked for type match only. Later bar() will be verified 20141 * independently to check that it's safe for R1=any_scalar_value. 20142 */ 20143 static int do_check_subprogs(struct bpf_verifier_env *env) 20144 { 20145 struct bpf_prog_aux *aux = env->prog->aux; 20146 struct bpf_func_info_aux *sub_aux; 20147 int i, ret, new_cnt; 20148 20149 if (!aux->func_info) 20150 return 0; 20151 20152 /* exception callback is presumed to be always called */ 20153 if (env->exception_callback_subprog) 20154 subprog_aux(env, env->exception_callback_subprog)->called = true; 20155 20156 again: 20157 new_cnt = 0; 20158 for (i = 1; i < env->subprog_cnt; i++) { 20159 if (!subprog_is_global(env, i)) 20160 continue; 20161 20162 sub_aux = subprog_aux(env, i); 20163 if (!sub_aux->called || sub_aux->verified) 20164 continue; 20165 20166 env->insn_idx = env->subprog_info[i].start; 20167 WARN_ON_ONCE(env->insn_idx == 0); 20168 ret = do_check_common(env, i); 20169 if (ret) { 20170 return ret; 20171 } else if (env->log.level & BPF_LOG_LEVEL) { 20172 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 20173 i, subprog_name(env, i)); 20174 } 20175 20176 /* We verified new global subprog, it might have called some 20177 * more global subprogs that we haven't verified yet, so we 20178 * need to do another pass over subprogs to verify those. 20179 */ 20180 sub_aux->verified = true; 20181 new_cnt++; 20182 } 20183 20184 /* We can't loop forever as we verify at least one global subprog on 20185 * each pass. 20186 */ 20187 if (new_cnt) 20188 goto again; 20189 20190 return 0; 20191 } 20192 20193 static int do_check_main(struct bpf_verifier_env *env) 20194 { 20195 int ret; 20196 20197 env->insn_idx = 0; 20198 ret = do_check_common(env, 0); 20199 if (!ret) 20200 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 20201 return ret; 20202 } 20203 20204 20205 static void print_verification_stats(struct bpf_verifier_env *env) 20206 { 20207 int i; 20208 20209 if (env->log.level & BPF_LOG_STATS) { 20210 verbose(env, "verification time %lld usec\n", 20211 div_u64(env->verification_time, 1000)); 20212 verbose(env, "stack depth "); 20213 for (i = 0; i < env->subprog_cnt; i++) { 20214 u32 depth = env->subprog_info[i].stack_depth; 20215 20216 verbose(env, "%d", depth); 20217 if (i + 1 < env->subprog_cnt) 20218 verbose(env, "+"); 20219 } 20220 verbose(env, "\n"); 20221 } 20222 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 20223 "total_states %d peak_states %d mark_read %d\n", 20224 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 20225 env->max_states_per_insn, env->total_states, 20226 env->peak_states, env->longest_mark_read_walk); 20227 } 20228 20229 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 20230 { 20231 const struct btf_type *t, *func_proto; 20232 const struct bpf_struct_ops *st_ops; 20233 const struct btf_member *member; 20234 struct bpf_prog *prog = env->prog; 20235 u32 btf_id, member_idx; 20236 const char *mname; 20237 20238 if (!prog->gpl_compatible) { 20239 verbose(env, "struct ops programs must have a GPL compatible license\n"); 20240 return -EINVAL; 20241 } 20242 20243 btf_id = prog->aux->attach_btf_id; 20244 st_ops = bpf_struct_ops_find(btf_id); 20245 if (!st_ops) { 20246 verbose(env, "attach_btf_id %u is not a supported struct\n", 20247 btf_id); 20248 return -ENOTSUPP; 20249 } 20250 20251 t = st_ops->type; 20252 member_idx = prog->expected_attach_type; 20253 if (member_idx >= btf_type_vlen(t)) { 20254 verbose(env, "attach to invalid member idx %u of struct %s\n", 20255 member_idx, st_ops->name); 20256 return -EINVAL; 20257 } 20258 20259 member = &btf_type_member(t)[member_idx]; 20260 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 20261 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 20262 NULL); 20263 if (!func_proto) { 20264 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 20265 mname, member_idx, st_ops->name); 20266 return -EINVAL; 20267 } 20268 20269 if (st_ops->check_member) { 20270 int err = st_ops->check_member(t, member, prog); 20271 20272 if (err) { 20273 verbose(env, "attach to unsupported member %s of struct %s\n", 20274 mname, st_ops->name); 20275 return err; 20276 } 20277 } 20278 20279 prog->aux->attach_func_proto = func_proto; 20280 prog->aux->attach_func_name = mname; 20281 env->ops = st_ops->verifier_ops; 20282 20283 return 0; 20284 } 20285 #define SECURITY_PREFIX "security_" 20286 20287 static int check_attach_modify_return(unsigned long addr, const char *func_name) 20288 { 20289 if (within_error_injection_list(addr) || 20290 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 20291 return 0; 20292 20293 return -EINVAL; 20294 } 20295 20296 /* list of non-sleepable functions that are otherwise on 20297 * ALLOW_ERROR_INJECTION list 20298 */ 20299 BTF_SET_START(btf_non_sleepable_error_inject) 20300 /* Three functions below can be called from sleepable and non-sleepable context. 20301 * Assume non-sleepable from bpf safety point of view. 20302 */ 20303 BTF_ID(func, __filemap_add_folio) 20304 BTF_ID(func, should_fail_alloc_page) 20305 BTF_ID(func, should_failslab) 20306 BTF_SET_END(btf_non_sleepable_error_inject) 20307 20308 static int check_non_sleepable_error_inject(u32 btf_id) 20309 { 20310 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 20311 } 20312 20313 int bpf_check_attach_target(struct bpf_verifier_log *log, 20314 const struct bpf_prog *prog, 20315 const struct bpf_prog *tgt_prog, 20316 u32 btf_id, 20317 struct bpf_attach_target_info *tgt_info) 20318 { 20319 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 20320 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 20321 const char prefix[] = "btf_trace_"; 20322 int ret = 0, subprog = -1, i; 20323 const struct btf_type *t; 20324 bool conservative = true; 20325 const char *tname; 20326 struct btf *btf; 20327 long addr = 0; 20328 struct module *mod = NULL; 20329 20330 if (!btf_id) { 20331 bpf_log(log, "Tracing programs must provide btf_id\n"); 20332 return -EINVAL; 20333 } 20334 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 20335 if (!btf) { 20336 bpf_log(log, 20337 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 20338 return -EINVAL; 20339 } 20340 t = btf_type_by_id(btf, btf_id); 20341 if (!t) { 20342 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 20343 return -EINVAL; 20344 } 20345 tname = btf_name_by_offset(btf, t->name_off); 20346 if (!tname) { 20347 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 20348 return -EINVAL; 20349 } 20350 if (tgt_prog) { 20351 struct bpf_prog_aux *aux = tgt_prog->aux; 20352 20353 if (bpf_prog_is_dev_bound(prog->aux) && 20354 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 20355 bpf_log(log, "Target program bound device mismatch"); 20356 return -EINVAL; 20357 } 20358 20359 for (i = 0; i < aux->func_info_cnt; i++) 20360 if (aux->func_info[i].type_id == btf_id) { 20361 subprog = i; 20362 break; 20363 } 20364 if (subprog == -1) { 20365 bpf_log(log, "Subprog %s doesn't exist\n", tname); 20366 return -EINVAL; 20367 } 20368 if (aux->func && aux->func[subprog]->aux->exception_cb) { 20369 bpf_log(log, 20370 "%s programs cannot attach to exception callback\n", 20371 prog_extension ? "Extension" : "FENTRY/FEXIT"); 20372 return -EINVAL; 20373 } 20374 conservative = aux->func_info_aux[subprog].unreliable; 20375 if (prog_extension) { 20376 if (conservative) { 20377 bpf_log(log, 20378 "Cannot replace static functions\n"); 20379 return -EINVAL; 20380 } 20381 if (!prog->jit_requested) { 20382 bpf_log(log, 20383 "Extension programs should be JITed\n"); 20384 return -EINVAL; 20385 } 20386 } 20387 if (!tgt_prog->jited) { 20388 bpf_log(log, "Can attach to only JITed progs\n"); 20389 return -EINVAL; 20390 } 20391 if (prog_tracing) { 20392 if (aux->attach_tracing_prog) { 20393 /* 20394 * Target program is an fentry/fexit which is already attached 20395 * to another tracing program. More levels of nesting 20396 * attachment are not allowed. 20397 */ 20398 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 20399 return -EINVAL; 20400 } 20401 } else if (tgt_prog->type == prog->type) { 20402 /* 20403 * To avoid potential call chain cycles, prevent attaching of a 20404 * program extension to another extension. It's ok to attach 20405 * fentry/fexit to extension program. 20406 */ 20407 bpf_log(log, "Cannot recursively attach\n"); 20408 return -EINVAL; 20409 } 20410 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 20411 prog_extension && 20412 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 20413 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 20414 /* Program extensions can extend all program types 20415 * except fentry/fexit. The reason is the following. 20416 * The fentry/fexit programs are used for performance 20417 * analysis, stats and can be attached to any program 20418 * type. When extension program is replacing XDP function 20419 * it is necessary to allow performance analysis of all 20420 * functions. Both original XDP program and its program 20421 * extension. Hence attaching fentry/fexit to 20422 * BPF_PROG_TYPE_EXT is allowed. If extending of 20423 * fentry/fexit was allowed it would be possible to create 20424 * long call chain fentry->extension->fentry->extension 20425 * beyond reasonable stack size. Hence extending fentry 20426 * is not allowed. 20427 */ 20428 bpf_log(log, "Cannot extend fentry/fexit\n"); 20429 return -EINVAL; 20430 } 20431 } else { 20432 if (prog_extension) { 20433 bpf_log(log, "Cannot replace kernel functions\n"); 20434 return -EINVAL; 20435 } 20436 } 20437 20438 switch (prog->expected_attach_type) { 20439 case BPF_TRACE_RAW_TP: 20440 if (tgt_prog) { 20441 bpf_log(log, 20442 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 20443 return -EINVAL; 20444 } 20445 if (!btf_type_is_typedef(t)) { 20446 bpf_log(log, "attach_btf_id %u is not a typedef\n", 20447 btf_id); 20448 return -EINVAL; 20449 } 20450 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 20451 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 20452 btf_id, tname); 20453 return -EINVAL; 20454 } 20455 tname += sizeof(prefix) - 1; 20456 t = btf_type_by_id(btf, t->type); 20457 if (!btf_type_is_ptr(t)) 20458 /* should never happen in valid vmlinux build */ 20459 return -EINVAL; 20460 t = btf_type_by_id(btf, t->type); 20461 if (!btf_type_is_func_proto(t)) 20462 /* should never happen in valid vmlinux build */ 20463 return -EINVAL; 20464 20465 break; 20466 case BPF_TRACE_ITER: 20467 if (!btf_type_is_func(t)) { 20468 bpf_log(log, "attach_btf_id %u is not a function\n", 20469 btf_id); 20470 return -EINVAL; 20471 } 20472 t = btf_type_by_id(btf, t->type); 20473 if (!btf_type_is_func_proto(t)) 20474 return -EINVAL; 20475 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 20476 if (ret) 20477 return ret; 20478 break; 20479 default: 20480 if (!prog_extension) 20481 return -EINVAL; 20482 fallthrough; 20483 case BPF_MODIFY_RETURN: 20484 case BPF_LSM_MAC: 20485 case BPF_LSM_CGROUP: 20486 case BPF_TRACE_FENTRY: 20487 case BPF_TRACE_FEXIT: 20488 if (!btf_type_is_func(t)) { 20489 bpf_log(log, "attach_btf_id %u is not a function\n", 20490 btf_id); 20491 return -EINVAL; 20492 } 20493 if (prog_extension && 20494 btf_check_type_match(log, prog, btf, t)) 20495 return -EINVAL; 20496 t = btf_type_by_id(btf, t->type); 20497 if (!btf_type_is_func_proto(t)) 20498 return -EINVAL; 20499 20500 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 20501 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 20502 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 20503 return -EINVAL; 20504 20505 if (tgt_prog && conservative) 20506 t = NULL; 20507 20508 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 20509 if (ret < 0) 20510 return ret; 20511 20512 if (tgt_prog) { 20513 if (subprog == 0) 20514 addr = (long) tgt_prog->bpf_func; 20515 else 20516 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 20517 } else { 20518 if (btf_is_module(btf)) { 20519 mod = btf_try_get_module(btf); 20520 if (mod) 20521 addr = find_kallsyms_symbol_value(mod, tname); 20522 else 20523 addr = 0; 20524 } else { 20525 addr = kallsyms_lookup_name(tname); 20526 } 20527 if (!addr) { 20528 module_put(mod); 20529 bpf_log(log, 20530 "The address of function %s cannot be found\n", 20531 tname); 20532 return -ENOENT; 20533 } 20534 } 20535 20536 if (prog->aux->sleepable) { 20537 ret = -EINVAL; 20538 switch (prog->type) { 20539 case BPF_PROG_TYPE_TRACING: 20540 20541 /* fentry/fexit/fmod_ret progs can be sleepable if they are 20542 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 20543 */ 20544 if (!check_non_sleepable_error_inject(btf_id) && 20545 within_error_injection_list(addr)) 20546 ret = 0; 20547 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 20548 * in the fmodret id set with the KF_SLEEPABLE flag. 20549 */ 20550 else { 20551 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 20552 prog); 20553 20554 if (flags && (*flags & KF_SLEEPABLE)) 20555 ret = 0; 20556 } 20557 break; 20558 case BPF_PROG_TYPE_LSM: 20559 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 20560 * Only some of them are sleepable. 20561 */ 20562 if (bpf_lsm_is_sleepable_hook(btf_id)) 20563 ret = 0; 20564 break; 20565 default: 20566 break; 20567 } 20568 if (ret) { 20569 module_put(mod); 20570 bpf_log(log, "%s is not sleepable\n", tname); 20571 return ret; 20572 } 20573 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 20574 if (tgt_prog) { 20575 module_put(mod); 20576 bpf_log(log, "can't modify return codes of BPF programs\n"); 20577 return -EINVAL; 20578 } 20579 ret = -EINVAL; 20580 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 20581 !check_attach_modify_return(addr, tname)) 20582 ret = 0; 20583 if (ret) { 20584 module_put(mod); 20585 bpf_log(log, "%s() is not modifiable\n", tname); 20586 return ret; 20587 } 20588 } 20589 20590 break; 20591 } 20592 tgt_info->tgt_addr = addr; 20593 tgt_info->tgt_name = tname; 20594 tgt_info->tgt_type = t; 20595 tgt_info->tgt_mod = mod; 20596 return 0; 20597 } 20598 20599 BTF_SET_START(btf_id_deny) 20600 BTF_ID_UNUSED 20601 #ifdef CONFIG_SMP 20602 BTF_ID(func, migrate_disable) 20603 BTF_ID(func, migrate_enable) 20604 #endif 20605 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 20606 BTF_ID(func, rcu_read_unlock_strict) 20607 #endif 20608 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 20609 BTF_ID(func, preempt_count_add) 20610 BTF_ID(func, preempt_count_sub) 20611 #endif 20612 #ifdef CONFIG_PREEMPT_RCU 20613 BTF_ID(func, __rcu_read_lock) 20614 BTF_ID(func, __rcu_read_unlock) 20615 #endif 20616 BTF_SET_END(btf_id_deny) 20617 20618 static bool can_be_sleepable(struct bpf_prog *prog) 20619 { 20620 if (prog->type == BPF_PROG_TYPE_TRACING) { 20621 switch (prog->expected_attach_type) { 20622 case BPF_TRACE_FENTRY: 20623 case BPF_TRACE_FEXIT: 20624 case BPF_MODIFY_RETURN: 20625 case BPF_TRACE_ITER: 20626 return true; 20627 default: 20628 return false; 20629 } 20630 } 20631 return prog->type == BPF_PROG_TYPE_LSM || 20632 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 20633 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 20634 } 20635 20636 static int check_attach_btf_id(struct bpf_verifier_env *env) 20637 { 20638 struct bpf_prog *prog = env->prog; 20639 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 20640 struct bpf_attach_target_info tgt_info = {}; 20641 u32 btf_id = prog->aux->attach_btf_id; 20642 struct bpf_trampoline *tr; 20643 int ret; 20644 u64 key; 20645 20646 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 20647 if (prog->aux->sleepable) 20648 /* attach_btf_id checked to be zero already */ 20649 return 0; 20650 verbose(env, "Syscall programs can only be sleepable\n"); 20651 return -EINVAL; 20652 } 20653 20654 if (prog->aux->sleepable && !can_be_sleepable(prog)) { 20655 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 20656 return -EINVAL; 20657 } 20658 20659 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 20660 return check_struct_ops_btf_id(env); 20661 20662 if (prog->type != BPF_PROG_TYPE_TRACING && 20663 prog->type != BPF_PROG_TYPE_LSM && 20664 prog->type != BPF_PROG_TYPE_EXT) 20665 return 0; 20666 20667 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 20668 if (ret) 20669 return ret; 20670 20671 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 20672 /* to make freplace equivalent to their targets, they need to 20673 * inherit env->ops and expected_attach_type for the rest of the 20674 * verification 20675 */ 20676 env->ops = bpf_verifier_ops[tgt_prog->type]; 20677 prog->expected_attach_type = tgt_prog->expected_attach_type; 20678 } 20679 20680 /* store info about the attachment target that will be used later */ 20681 prog->aux->attach_func_proto = tgt_info.tgt_type; 20682 prog->aux->attach_func_name = tgt_info.tgt_name; 20683 prog->aux->mod = tgt_info.tgt_mod; 20684 20685 if (tgt_prog) { 20686 prog->aux->saved_dst_prog_type = tgt_prog->type; 20687 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 20688 } 20689 20690 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 20691 prog->aux->attach_btf_trace = true; 20692 return 0; 20693 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 20694 if (!bpf_iter_prog_supported(prog)) 20695 return -EINVAL; 20696 return 0; 20697 } 20698 20699 if (prog->type == BPF_PROG_TYPE_LSM) { 20700 ret = bpf_lsm_verify_prog(&env->log, prog); 20701 if (ret < 0) 20702 return ret; 20703 } else if (prog->type == BPF_PROG_TYPE_TRACING && 20704 btf_id_set_contains(&btf_id_deny, btf_id)) { 20705 return -EINVAL; 20706 } 20707 20708 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 20709 tr = bpf_trampoline_get(key, &tgt_info); 20710 if (!tr) 20711 return -ENOMEM; 20712 20713 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 20714 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 20715 20716 prog->aux->dst_trampoline = tr; 20717 return 0; 20718 } 20719 20720 struct btf *bpf_get_btf_vmlinux(void) 20721 { 20722 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 20723 mutex_lock(&bpf_verifier_lock); 20724 if (!btf_vmlinux) 20725 btf_vmlinux = btf_parse_vmlinux(); 20726 mutex_unlock(&bpf_verifier_lock); 20727 } 20728 return btf_vmlinux; 20729 } 20730 20731 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 20732 { 20733 u64 start_time = ktime_get_ns(); 20734 struct bpf_verifier_env *env; 20735 int i, len, ret = -EINVAL, err; 20736 u32 log_true_size; 20737 bool is_priv; 20738 20739 /* no program is valid */ 20740 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 20741 return -EINVAL; 20742 20743 /* 'struct bpf_verifier_env' can be global, but since it's not small, 20744 * allocate/free it every time bpf_check() is called 20745 */ 20746 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 20747 if (!env) 20748 return -ENOMEM; 20749 20750 env->bt.env = env; 20751 20752 len = (*prog)->len; 20753 env->insn_aux_data = 20754 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 20755 ret = -ENOMEM; 20756 if (!env->insn_aux_data) 20757 goto err_free_env; 20758 for (i = 0; i < len; i++) 20759 env->insn_aux_data[i].orig_idx = i; 20760 env->prog = *prog; 20761 env->ops = bpf_verifier_ops[env->prog->type]; 20762 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 20763 is_priv = bpf_capable(); 20764 20765 bpf_get_btf_vmlinux(); 20766 20767 /* grab the mutex to protect few globals used by verifier */ 20768 if (!is_priv) 20769 mutex_lock(&bpf_verifier_lock); 20770 20771 /* user could have requested verbose verifier output 20772 * and supplied buffer to store the verification trace 20773 */ 20774 ret = bpf_vlog_init(&env->log, attr->log_level, 20775 (char __user *) (unsigned long) attr->log_buf, 20776 attr->log_size); 20777 if (ret) 20778 goto err_unlock; 20779 20780 mark_verifier_state_clean(env); 20781 20782 if (IS_ERR(btf_vmlinux)) { 20783 /* Either gcc or pahole or kernel are broken. */ 20784 verbose(env, "in-kernel BTF is malformed\n"); 20785 ret = PTR_ERR(btf_vmlinux); 20786 goto skip_full_check; 20787 } 20788 20789 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 20790 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 20791 env->strict_alignment = true; 20792 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 20793 env->strict_alignment = false; 20794 20795 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 20796 env->allow_uninit_stack = bpf_allow_uninit_stack(); 20797 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 20798 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 20799 env->bpf_capable = bpf_capable(); 20800 20801 if (is_priv) 20802 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 20803 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 20804 20805 env->explored_states = kvcalloc(state_htab_size(env), 20806 sizeof(struct bpf_verifier_state_list *), 20807 GFP_USER); 20808 ret = -ENOMEM; 20809 if (!env->explored_states) 20810 goto skip_full_check; 20811 20812 ret = check_btf_info_early(env, attr, uattr); 20813 if (ret < 0) 20814 goto skip_full_check; 20815 20816 ret = add_subprog_and_kfunc(env); 20817 if (ret < 0) 20818 goto skip_full_check; 20819 20820 ret = check_subprogs(env); 20821 if (ret < 0) 20822 goto skip_full_check; 20823 20824 ret = check_btf_info(env, attr, uattr); 20825 if (ret < 0) 20826 goto skip_full_check; 20827 20828 ret = check_attach_btf_id(env); 20829 if (ret) 20830 goto skip_full_check; 20831 20832 ret = resolve_pseudo_ldimm64(env); 20833 if (ret < 0) 20834 goto skip_full_check; 20835 20836 if (bpf_prog_is_offloaded(env->prog->aux)) { 20837 ret = bpf_prog_offload_verifier_prep(env->prog); 20838 if (ret) 20839 goto skip_full_check; 20840 } 20841 20842 ret = check_cfg(env); 20843 if (ret < 0) 20844 goto skip_full_check; 20845 20846 ret = do_check_main(env); 20847 ret = ret ?: do_check_subprogs(env); 20848 20849 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 20850 ret = bpf_prog_offload_finalize(env); 20851 20852 skip_full_check: 20853 kvfree(env->explored_states); 20854 20855 if (ret == 0) 20856 ret = check_max_stack_depth(env); 20857 20858 /* instruction rewrites happen after this point */ 20859 if (ret == 0) 20860 ret = optimize_bpf_loop(env); 20861 20862 if (is_priv) { 20863 if (ret == 0) 20864 opt_hard_wire_dead_code_branches(env); 20865 if (ret == 0) 20866 ret = opt_remove_dead_code(env); 20867 if (ret == 0) 20868 ret = opt_remove_nops(env); 20869 } else { 20870 if (ret == 0) 20871 sanitize_dead_code(env); 20872 } 20873 20874 if (ret == 0) 20875 /* program is valid, convert *(u32*)(ctx + off) accesses */ 20876 ret = convert_ctx_accesses(env); 20877 20878 if (ret == 0) 20879 ret = do_misc_fixups(env); 20880 20881 /* do 32-bit optimization after insn patching has done so those patched 20882 * insns could be handled correctly. 20883 */ 20884 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 20885 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 20886 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 20887 : false; 20888 } 20889 20890 if (ret == 0) 20891 ret = fixup_call_args(env); 20892 20893 env->verification_time = ktime_get_ns() - start_time; 20894 print_verification_stats(env); 20895 env->prog->aux->verified_insns = env->insn_processed; 20896 20897 /* preserve original error even if log finalization is successful */ 20898 err = bpf_vlog_finalize(&env->log, &log_true_size); 20899 if (err) 20900 ret = err; 20901 20902 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 20903 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 20904 &log_true_size, sizeof(log_true_size))) { 20905 ret = -EFAULT; 20906 goto err_release_maps; 20907 } 20908 20909 if (ret) 20910 goto err_release_maps; 20911 20912 if (env->used_map_cnt) { 20913 /* if program passed verifier, update used_maps in bpf_prog_info */ 20914 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 20915 sizeof(env->used_maps[0]), 20916 GFP_KERNEL); 20917 20918 if (!env->prog->aux->used_maps) { 20919 ret = -ENOMEM; 20920 goto err_release_maps; 20921 } 20922 20923 memcpy(env->prog->aux->used_maps, env->used_maps, 20924 sizeof(env->used_maps[0]) * env->used_map_cnt); 20925 env->prog->aux->used_map_cnt = env->used_map_cnt; 20926 } 20927 if (env->used_btf_cnt) { 20928 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 20929 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 20930 sizeof(env->used_btfs[0]), 20931 GFP_KERNEL); 20932 if (!env->prog->aux->used_btfs) { 20933 ret = -ENOMEM; 20934 goto err_release_maps; 20935 } 20936 20937 memcpy(env->prog->aux->used_btfs, env->used_btfs, 20938 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 20939 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 20940 } 20941 if (env->used_map_cnt || env->used_btf_cnt) { 20942 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 20943 * bpf_ld_imm64 instructions 20944 */ 20945 convert_pseudo_ld_imm64(env); 20946 } 20947 20948 adjust_btf_func(env); 20949 20950 err_release_maps: 20951 if (!env->prog->aux->used_maps) 20952 /* if we didn't copy map pointers into bpf_prog_info, release 20953 * them now. Otherwise free_used_maps() will release them. 20954 */ 20955 release_maps(env); 20956 if (!env->prog->aux->used_btfs) 20957 release_btfs(env); 20958 20959 /* extension progs temporarily inherit the attach_type of their targets 20960 for verification purposes, so set it back to zero before returning 20961 */ 20962 if (env->prog->type == BPF_PROG_TYPE_EXT) 20963 env->prog->expected_attach_type = 0; 20964 20965 *prog = env->prog; 20966 err_unlock: 20967 if (!is_priv) 20968 mutex_unlock(&bpf_verifier_lock); 20969 vfree(env->insn_aux_data); 20970 err_free_env: 20971 kfree(env); 20972 return ret; 20973 } 20974