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 #ifdef CONFIG_BPF_JIT 5231 BTF_ID(struct, bpf_cpumask) 5232 #endif 5233 BTF_ID(struct, task_struct) 5234 BTF_SET_END(rcu_protected_types) 5235 5236 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5237 { 5238 if (!btf_is_kernel(btf)) 5239 return true; 5240 return btf_id_set_contains(&rcu_protected_types, btf_id); 5241 } 5242 5243 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 5244 { 5245 struct btf_struct_meta *meta; 5246 5247 if (btf_is_kernel(kptr_field->kptr.btf)) 5248 return NULL; 5249 5250 meta = btf_find_struct_meta(kptr_field->kptr.btf, 5251 kptr_field->kptr.btf_id); 5252 5253 return meta ? meta->record : NULL; 5254 } 5255 5256 static bool rcu_safe_kptr(const struct btf_field *field) 5257 { 5258 const struct btf_field_kptr *kptr = &field->kptr; 5259 5260 return field->type == BPF_KPTR_PERCPU || 5261 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 5262 } 5263 5264 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 5265 { 5266 struct btf_record *rec; 5267 u32 ret; 5268 5269 ret = PTR_MAYBE_NULL; 5270 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 5271 ret |= MEM_RCU; 5272 if (kptr_field->type == BPF_KPTR_PERCPU) 5273 ret |= MEM_PERCPU; 5274 else if (!btf_is_kernel(kptr_field->kptr.btf)) 5275 ret |= MEM_ALLOC; 5276 5277 rec = kptr_pointee_btf_record(kptr_field); 5278 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 5279 ret |= NON_OWN_REF; 5280 } else { 5281 ret |= PTR_UNTRUSTED; 5282 } 5283 5284 return ret; 5285 } 5286 5287 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5288 int value_regno, int insn_idx, 5289 struct btf_field *kptr_field) 5290 { 5291 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5292 int class = BPF_CLASS(insn->code); 5293 struct bpf_reg_state *val_reg; 5294 5295 /* Things we already checked for in check_map_access and caller: 5296 * - Reject cases where variable offset may touch kptr 5297 * - size of access (must be BPF_DW) 5298 * - tnum_is_const(reg->var_off) 5299 * - kptr_field->offset == off + reg->var_off.value 5300 */ 5301 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5302 if (BPF_MODE(insn->code) != BPF_MEM) { 5303 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5304 return -EACCES; 5305 } 5306 5307 /* We only allow loading referenced kptr, since it will be marked as 5308 * untrusted, similar to unreferenced kptr. 5309 */ 5310 if (class != BPF_LDX && 5311 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 5312 verbose(env, "store to referenced kptr disallowed\n"); 5313 return -EACCES; 5314 } 5315 5316 if (class == BPF_LDX) { 5317 val_reg = reg_state(env, value_regno); 5318 /* We can simply mark the value_regno receiving the pointer 5319 * value from map as PTR_TO_BTF_ID, with the correct type. 5320 */ 5321 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5322 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field)); 5323 /* For mark_ptr_or_null_reg */ 5324 val_reg->id = ++env->id_gen; 5325 } else if (class == BPF_STX) { 5326 val_reg = reg_state(env, value_regno); 5327 if (!register_is_null(val_reg) && 5328 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5329 return -EACCES; 5330 } else if (class == BPF_ST) { 5331 if (insn->imm) { 5332 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5333 kptr_field->offset); 5334 return -EACCES; 5335 } 5336 } else { 5337 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5338 return -EACCES; 5339 } 5340 return 0; 5341 } 5342 5343 /* check read/write into a map element with possible variable offset */ 5344 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5345 int off, int size, bool zero_size_allowed, 5346 enum bpf_access_src src) 5347 { 5348 struct bpf_verifier_state *vstate = env->cur_state; 5349 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5350 struct bpf_reg_state *reg = &state->regs[regno]; 5351 struct bpf_map *map = reg->map_ptr; 5352 struct btf_record *rec; 5353 int err, i; 5354 5355 err = check_mem_region_access(env, regno, off, size, map->value_size, 5356 zero_size_allowed); 5357 if (err) 5358 return err; 5359 5360 if (IS_ERR_OR_NULL(map->record)) 5361 return 0; 5362 rec = map->record; 5363 for (i = 0; i < rec->cnt; i++) { 5364 struct btf_field *field = &rec->fields[i]; 5365 u32 p = field->offset; 5366 5367 /* If any part of a field can be touched by load/store, reject 5368 * this program. To check that [x1, x2) overlaps with [y1, y2), 5369 * it is sufficient to check x1 < y2 && y1 < x2. 5370 */ 5371 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 5372 p < reg->umax_value + off + size) { 5373 switch (field->type) { 5374 case BPF_KPTR_UNREF: 5375 case BPF_KPTR_REF: 5376 case BPF_KPTR_PERCPU: 5377 if (src != ACCESS_DIRECT) { 5378 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 5379 return -EACCES; 5380 } 5381 if (!tnum_is_const(reg->var_off)) { 5382 verbose(env, "kptr access cannot have variable offset\n"); 5383 return -EACCES; 5384 } 5385 if (p != off + reg->var_off.value) { 5386 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 5387 p, off + reg->var_off.value); 5388 return -EACCES; 5389 } 5390 if (size != bpf_size_to_bytes(BPF_DW)) { 5391 verbose(env, "kptr access size must be BPF_DW\n"); 5392 return -EACCES; 5393 } 5394 break; 5395 default: 5396 verbose(env, "%s cannot be accessed directly by load/store\n", 5397 btf_field_type_name(field->type)); 5398 return -EACCES; 5399 } 5400 } 5401 } 5402 return 0; 5403 } 5404 5405 #define MAX_PACKET_OFF 0xffff 5406 5407 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5408 const struct bpf_call_arg_meta *meta, 5409 enum bpf_access_type t) 5410 { 5411 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5412 5413 switch (prog_type) { 5414 /* Program types only with direct read access go here! */ 5415 case BPF_PROG_TYPE_LWT_IN: 5416 case BPF_PROG_TYPE_LWT_OUT: 5417 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5418 case BPF_PROG_TYPE_SK_REUSEPORT: 5419 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5420 case BPF_PROG_TYPE_CGROUP_SKB: 5421 if (t == BPF_WRITE) 5422 return false; 5423 fallthrough; 5424 5425 /* Program types with direct read + write access go here! */ 5426 case BPF_PROG_TYPE_SCHED_CLS: 5427 case BPF_PROG_TYPE_SCHED_ACT: 5428 case BPF_PROG_TYPE_XDP: 5429 case BPF_PROG_TYPE_LWT_XMIT: 5430 case BPF_PROG_TYPE_SK_SKB: 5431 case BPF_PROG_TYPE_SK_MSG: 5432 if (meta) 5433 return meta->pkt_access; 5434 5435 env->seen_direct_write = true; 5436 return true; 5437 5438 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5439 if (t == BPF_WRITE) 5440 env->seen_direct_write = true; 5441 5442 return true; 5443 5444 default: 5445 return false; 5446 } 5447 } 5448 5449 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5450 int size, bool zero_size_allowed) 5451 { 5452 struct bpf_reg_state *regs = cur_regs(env); 5453 struct bpf_reg_state *reg = ®s[regno]; 5454 int err; 5455 5456 /* We may have added a variable offset to the packet pointer; but any 5457 * reg->range we have comes after that. We are only checking the fixed 5458 * offset. 5459 */ 5460 5461 /* We don't allow negative numbers, because we aren't tracking enough 5462 * detail to prove they're safe. 5463 */ 5464 if (reg->smin_value < 0) { 5465 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5466 regno); 5467 return -EACCES; 5468 } 5469 5470 err = reg->range < 0 ? -EINVAL : 5471 __check_mem_access(env, regno, off, size, reg->range, 5472 zero_size_allowed); 5473 if (err) { 5474 verbose(env, "R%d offset is outside of the packet\n", regno); 5475 return err; 5476 } 5477 5478 /* __check_mem_access has made sure "off + size - 1" is within u16. 5479 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5480 * otherwise find_good_pkt_pointers would have refused to set range info 5481 * that __check_mem_access would have rejected this pkt access. 5482 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5483 */ 5484 env->prog->aux->max_pkt_offset = 5485 max_t(u32, env->prog->aux->max_pkt_offset, 5486 off + reg->umax_value + size - 1); 5487 5488 return err; 5489 } 5490 5491 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5492 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5493 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5494 struct btf **btf, u32 *btf_id) 5495 { 5496 struct bpf_insn_access_aux info = { 5497 .reg_type = *reg_type, 5498 .log = &env->log, 5499 }; 5500 5501 if (env->ops->is_valid_access && 5502 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5503 /* A non zero info.ctx_field_size indicates that this field is a 5504 * candidate for later verifier transformation to load the whole 5505 * field and then apply a mask when accessed with a narrower 5506 * access than actual ctx access size. A zero info.ctx_field_size 5507 * will only allow for whole field access and rejects any other 5508 * type of narrower access. 5509 */ 5510 *reg_type = info.reg_type; 5511 5512 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5513 *btf = info.btf; 5514 *btf_id = info.btf_id; 5515 } else { 5516 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5517 } 5518 /* remember the offset of last byte accessed in ctx */ 5519 if (env->prog->aux->max_ctx_offset < off + size) 5520 env->prog->aux->max_ctx_offset = off + size; 5521 return 0; 5522 } 5523 5524 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5525 return -EACCES; 5526 } 5527 5528 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5529 int size) 5530 { 5531 if (size < 0 || off < 0 || 5532 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5533 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5534 off, size); 5535 return -EACCES; 5536 } 5537 return 0; 5538 } 5539 5540 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5541 u32 regno, int off, int size, 5542 enum bpf_access_type t) 5543 { 5544 struct bpf_reg_state *regs = cur_regs(env); 5545 struct bpf_reg_state *reg = ®s[regno]; 5546 struct bpf_insn_access_aux info = {}; 5547 bool valid; 5548 5549 if (reg->smin_value < 0) { 5550 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5551 regno); 5552 return -EACCES; 5553 } 5554 5555 switch (reg->type) { 5556 case PTR_TO_SOCK_COMMON: 5557 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5558 break; 5559 case PTR_TO_SOCKET: 5560 valid = bpf_sock_is_valid_access(off, size, t, &info); 5561 break; 5562 case PTR_TO_TCP_SOCK: 5563 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5564 break; 5565 case PTR_TO_XDP_SOCK: 5566 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5567 break; 5568 default: 5569 valid = false; 5570 } 5571 5572 5573 if (valid) { 5574 env->insn_aux_data[insn_idx].ctx_field_size = 5575 info.ctx_field_size; 5576 return 0; 5577 } 5578 5579 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5580 regno, reg_type_str(env, reg->type), off, size); 5581 5582 return -EACCES; 5583 } 5584 5585 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5586 { 5587 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5588 } 5589 5590 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5591 { 5592 const struct bpf_reg_state *reg = reg_state(env, regno); 5593 5594 return reg->type == PTR_TO_CTX; 5595 } 5596 5597 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5598 { 5599 const struct bpf_reg_state *reg = reg_state(env, regno); 5600 5601 return type_is_sk_pointer(reg->type); 5602 } 5603 5604 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5605 { 5606 const struct bpf_reg_state *reg = reg_state(env, regno); 5607 5608 return type_is_pkt_pointer(reg->type); 5609 } 5610 5611 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5612 { 5613 const struct bpf_reg_state *reg = reg_state(env, regno); 5614 5615 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5616 return reg->type == PTR_TO_FLOW_KEYS; 5617 } 5618 5619 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5620 #ifdef CONFIG_NET 5621 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5622 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5623 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5624 #endif 5625 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5626 }; 5627 5628 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5629 { 5630 /* A referenced register is always trusted. */ 5631 if (reg->ref_obj_id) 5632 return true; 5633 5634 /* Types listed in the reg2btf_ids are always trusted */ 5635 if (reg2btf_ids[base_type(reg->type)]) 5636 return true; 5637 5638 /* If a register is not referenced, it is trusted if it has the 5639 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5640 * other type modifiers may be safe, but we elect to take an opt-in 5641 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5642 * not. 5643 * 5644 * Eventually, we should make PTR_TRUSTED the single source of truth 5645 * for whether a register is trusted. 5646 */ 5647 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5648 !bpf_type_has_unsafe_modifiers(reg->type); 5649 } 5650 5651 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5652 { 5653 return reg->type & MEM_RCU; 5654 } 5655 5656 static void clear_trusted_flags(enum bpf_type_flag *flag) 5657 { 5658 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5659 } 5660 5661 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5662 const struct bpf_reg_state *reg, 5663 int off, int size, bool strict) 5664 { 5665 struct tnum reg_off; 5666 int ip_align; 5667 5668 /* Byte size accesses are always allowed. */ 5669 if (!strict || size == 1) 5670 return 0; 5671 5672 /* For platforms that do not have a Kconfig enabling 5673 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5674 * NET_IP_ALIGN is universally set to '2'. And on platforms 5675 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5676 * to this code only in strict mode where we want to emulate 5677 * the NET_IP_ALIGN==2 checking. Therefore use an 5678 * unconditional IP align value of '2'. 5679 */ 5680 ip_align = 2; 5681 5682 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5683 if (!tnum_is_aligned(reg_off, size)) { 5684 char tn_buf[48]; 5685 5686 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5687 verbose(env, 5688 "misaligned packet access off %d+%s+%d+%d size %d\n", 5689 ip_align, tn_buf, reg->off, off, size); 5690 return -EACCES; 5691 } 5692 5693 return 0; 5694 } 5695 5696 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5697 const struct bpf_reg_state *reg, 5698 const char *pointer_desc, 5699 int off, int size, bool strict) 5700 { 5701 struct tnum reg_off; 5702 5703 /* Byte size accesses are always allowed. */ 5704 if (!strict || size == 1) 5705 return 0; 5706 5707 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5708 if (!tnum_is_aligned(reg_off, size)) { 5709 char tn_buf[48]; 5710 5711 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5712 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5713 pointer_desc, tn_buf, reg->off, off, size); 5714 return -EACCES; 5715 } 5716 5717 return 0; 5718 } 5719 5720 static int check_ptr_alignment(struct bpf_verifier_env *env, 5721 const struct bpf_reg_state *reg, int off, 5722 int size, bool strict_alignment_once) 5723 { 5724 bool strict = env->strict_alignment || strict_alignment_once; 5725 const char *pointer_desc = ""; 5726 5727 switch (reg->type) { 5728 case PTR_TO_PACKET: 5729 case PTR_TO_PACKET_META: 5730 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5731 * right in front, treat it the very same way. 5732 */ 5733 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5734 case PTR_TO_FLOW_KEYS: 5735 pointer_desc = "flow keys "; 5736 break; 5737 case PTR_TO_MAP_KEY: 5738 pointer_desc = "key "; 5739 break; 5740 case PTR_TO_MAP_VALUE: 5741 pointer_desc = "value "; 5742 break; 5743 case PTR_TO_CTX: 5744 pointer_desc = "context "; 5745 break; 5746 case PTR_TO_STACK: 5747 pointer_desc = "stack "; 5748 /* The stack spill tracking logic in check_stack_write_fixed_off() 5749 * and check_stack_read_fixed_off() relies on stack accesses being 5750 * aligned. 5751 */ 5752 strict = true; 5753 break; 5754 case PTR_TO_SOCKET: 5755 pointer_desc = "sock "; 5756 break; 5757 case PTR_TO_SOCK_COMMON: 5758 pointer_desc = "sock_common "; 5759 break; 5760 case PTR_TO_TCP_SOCK: 5761 pointer_desc = "tcp_sock "; 5762 break; 5763 case PTR_TO_XDP_SOCK: 5764 pointer_desc = "xdp_sock "; 5765 break; 5766 default: 5767 break; 5768 } 5769 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5770 strict); 5771 } 5772 5773 /* starting from main bpf function walk all instructions of the function 5774 * and recursively walk all callees that given function can call. 5775 * Ignore jump and exit insns. 5776 * Since recursion is prevented by check_cfg() this algorithm 5777 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 5778 */ 5779 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx) 5780 { 5781 struct bpf_subprog_info *subprog = env->subprog_info; 5782 struct bpf_insn *insn = env->prog->insnsi; 5783 int depth = 0, frame = 0, i, subprog_end; 5784 bool tail_call_reachable = false; 5785 int ret_insn[MAX_CALL_FRAMES]; 5786 int ret_prog[MAX_CALL_FRAMES]; 5787 int j; 5788 5789 i = subprog[idx].start; 5790 process_func: 5791 /* protect against potential stack overflow that might happen when 5792 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5793 * depth for such case down to 256 so that the worst case scenario 5794 * would result in 8k stack size (32 which is tailcall limit * 256 = 5795 * 8k). 5796 * 5797 * To get the idea what might happen, see an example: 5798 * func1 -> sub rsp, 128 5799 * subfunc1 -> sub rsp, 256 5800 * tailcall1 -> add rsp, 256 5801 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5802 * subfunc2 -> sub rsp, 64 5803 * subfunc22 -> sub rsp, 128 5804 * tailcall2 -> add rsp, 128 5805 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5806 * 5807 * tailcall will unwind the current stack frame but it will not get rid 5808 * of caller's stack as shown on the example above. 5809 */ 5810 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5811 verbose(env, 5812 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5813 depth); 5814 return -EACCES; 5815 } 5816 /* round up to 32-bytes, since this is granularity 5817 * of interpreter stack size 5818 */ 5819 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5820 if (depth > MAX_BPF_STACK) { 5821 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5822 frame + 1, depth); 5823 return -EACCES; 5824 } 5825 continue_func: 5826 subprog_end = subprog[idx + 1].start; 5827 for (; i < subprog_end; i++) { 5828 int next_insn, sidx; 5829 5830 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 5831 bool err = false; 5832 5833 if (!is_bpf_throw_kfunc(insn + i)) 5834 continue; 5835 if (subprog[idx].is_cb) 5836 err = true; 5837 for (int c = 0; c < frame && !err; c++) { 5838 if (subprog[ret_prog[c]].is_cb) { 5839 err = true; 5840 break; 5841 } 5842 } 5843 if (!err) 5844 continue; 5845 verbose(env, 5846 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 5847 i, idx); 5848 return -EINVAL; 5849 } 5850 5851 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5852 continue; 5853 /* remember insn and function to return to */ 5854 ret_insn[frame] = i + 1; 5855 ret_prog[frame] = idx; 5856 5857 /* find the callee */ 5858 next_insn = i + insn[i].imm + 1; 5859 sidx = find_subprog(env, next_insn); 5860 if (sidx < 0) { 5861 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5862 next_insn); 5863 return -EFAULT; 5864 } 5865 if (subprog[sidx].is_async_cb) { 5866 if (subprog[sidx].has_tail_call) { 5867 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 5868 return -EFAULT; 5869 } 5870 /* async callbacks don't increase bpf prog stack size unless called directly */ 5871 if (!bpf_pseudo_call(insn + i)) 5872 continue; 5873 if (subprog[sidx].is_exception_cb) { 5874 verbose(env, "insn %d cannot call exception cb directly\n", i); 5875 return -EINVAL; 5876 } 5877 } 5878 i = next_insn; 5879 idx = sidx; 5880 5881 if (subprog[idx].has_tail_call) 5882 tail_call_reachable = true; 5883 5884 frame++; 5885 if (frame >= MAX_CALL_FRAMES) { 5886 verbose(env, "the call stack of %d frames is too deep !\n", 5887 frame); 5888 return -E2BIG; 5889 } 5890 goto process_func; 5891 } 5892 /* if tail call got detected across bpf2bpf calls then mark each of the 5893 * currently present subprog frames as tail call reachable subprogs; 5894 * this info will be utilized by JIT so that we will be preserving the 5895 * tail call counter throughout bpf2bpf calls combined with tailcalls 5896 */ 5897 if (tail_call_reachable) 5898 for (j = 0; j < frame; j++) { 5899 if (subprog[ret_prog[j]].is_exception_cb) { 5900 verbose(env, "cannot tail call within exception cb\n"); 5901 return -EINVAL; 5902 } 5903 subprog[ret_prog[j]].tail_call_reachable = true; 5904 } 5905 if (subprog[0].tail_call_reachable) 5906 env->prog->aux->tail_call_reachable = true; 5907 5908 /* end of for() loop means the last insn of the 'subprog' 5909 * was reached. Doesn't matter whether it was JA or EXIT 5910 */ 5911 if (frame == 0) 5912 return 0; 5913 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5914 frame--; 5915 i = ret_insn[frame]; 5916 idx = ret_prog[frame]; 5917 goto continue_func; 5918 } 5919 5920 static int check_max_stack_depth(struct bpf_verifier_env *env) 5921 { 5922 struct bpf_subprog_info *si = env->subprog_info; 5923 int ret; 5924 5925 for (int i = 0; i < env->subprog_cnt; i++) { 5926 if (!i || si[i].is_async_cb) { 5927 ret = check_max_stack_depth_subprog(env, i); 5928 if (ret < 0) 5929 return ret; 5930 } 5931 continue; 5932 } 5933 return 0; 5934 } 5935 5936 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 5937 static int get_callee_stack_depth(struct bpf_verifier_env *env, 5938 const struct bpf_insn *insn, int idx) 5939 { 5940 int start = idx + insn->imm + 1, subprog; 5941 5942 subprog = find_subprog(env, start); 5943 if (subprog < 0) { 5944 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5945 start); 5946 return -EFAULT; 5947 } 5948 return env->subprog_info[subprog].stack_depth; 5949 } 5950 #endif 5951 5952 static int __check_buffer_access(struct bpf_verifier_env *env, 5953 const char *buf_info, 5954 const struct bpf_reg_state *reg, 5955 int regno, int off, int size) 5956 { 5957 if (off < 0) { 5958 verbose(env, 5959 "R%d invalid %s buffer access: off=%d, size=%d\n", 5960 regno, buf_info, off, size); 5961 return -EACCES; 5962 } 5963 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5964 char tn_buf[48]; 5965 5966 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5967 verbose(env, 5968 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 5969 regno, off, tn_buf); 5970 return -EACCES; 5971 } 5972 5973 return 0; 5974 } 5975 5976 static int check_tp_buffer_access(struct bpf_verifier_env *env, 5977 const struct bpf_reg_state *reg, 5978 int regno, int off, int size) 5979 { 5980 int err; 5981 5982 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 5983 if (err) 5984 return err; 5985 5986 if (off + size > env->prog->aux->max_tp_access) 5987 env->prog->aux->max_tp_access = off + size; 5988 5989 return 0; 5990 } 5991 5992 static int check_buffer_access(struct bpf_verifier_env *env, 5993 const struct bpf_reg_state *reg, 5994 int regno, int off, int size, 5995 bool zero_size_allowed, 5996 u32 *max_access) 5997 { 5998 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 5999 int err; 6000 6001 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 6002 if (err) 6003 return err; 6004 6005 if (off + size > *max_access) 6006 *max_access = off + size; 6007 6008 return 0; 6009 } 6010 6011 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 6012 static void zext_32_to_64(struct bpf_reg_state *reg) 6013 { 6014 reg->var_off = tnum_subreg(reg->var_off); 6015 __reg_assign_32_into_64(reg); 6016 } 6017 6018 /* truncate register to smaller size (in bytes) 6019 * must be called with size < BPF_REG_SIZE 6020 */ 6021 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 6022 { 6023 u64 mask; 6024 6025 /* clear high bits in bit representation */ 6026 reg->var_off = tnum_cast(reg->var_off, size); 6027 6028 /* fix arithmetic bounds */ 6029 mask = ((u64)1 << (size * 8)) - 1; 6030 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 6031 reg->umin_value &= mask; 6032 reg->umax_value &= mask; 6033 } else { 6034 reg->umin_value = 0; 6035 reg->umax_value = mask; 6036 } 6037 reg->smin_value = reg->umin_value; 6038 reg->smax_value = reg->umax_value; 6039 6040 /* If size is smaller than 32bit register the 32bit register 6041 * values are also truncated so we push 64-bit bounds into 6042 * 32-bit bounds. Above were truncated < 32-bits already. 6043 */ 6044 if (size < 4) { 6045 __mark_reg32_unbounded(reg); 6046 reg_bounds_sync(reg); 6047 } 6048 } 6049 6050 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 6051 { 6052 if (size == 1) { 6053 reg->smin_value = reg->s32_min_value = S8_MIN; 6054 reg->smax_value = reg->s32_max_value = S8_MAX; 6055 } else if (size == 2) { 6056 reg->smin_value = reg->s32_min_value = S16_MIN; 6057 reg->smax_value = reg->s32_max_value = S16_MAX; 6058 } else { 6059 /* size == 4 */ 6060 reg->smin_value = reg->s32_min_value = S32_MIN; 6061 reg->smax_value = reg->s32_max_value = S32_MAX; 6062 } 6063 reg->umin_value = reg->u32_min_value = 0; 6064 reg->umax_value = U64_MAX; 6065 reg->u32_max_value = U32_MAX; 6066 reg->var_off = tnum_unknown; 6067 } 6068 6069 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6070 { 6071 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6072 u64 top_smax_value, top_smin_value; 6073 u64 num_bits = size * 8; 6074 6075 if (tnum_is_const(reg->var_off)) { 6076 u64_cval = reg->var_off.value; 6077 if (size == 1) 6078 reg->var_off = tnum_const((s8)u64_cval); 6079 else if (size == 2) 6080 reg->var_off = tnum_const((s16)u64_cval); 6081 else 6082 /* size == 4 */ 6083 reg->var_off = tnum_const((s32)u64_cval); 6084 6085 u64_cval = reg->var_off.value; 6086 reg->smax_value = reg->smin_value = u64_cval; 6087 reg->umax_value = reg->umin_value = u64_cval; 6088 reg->s32_max_value = reg->s32_min_value = u64_cval; 6089 reg->u32_max_value = reg->u32_min_value = u64_cval; 6090 return; 6091 } 6092 6093 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6094 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6095 6096 if (top_smax_value != top_smin_value) 6097 goto out; 6098 6099 /* find the s64_min and s64_min after sign extension */ 6100 if (size == 1) { 6101 init_s64_max = (s8)reg->smax_value; 6102 init_s64_min = (s8)reg->smin_value; 6103 } else if (size == 2) { 6104 init_s64_max = (s16)reg->smax_value; 6105 init_s64_min = (s16)reg->smin_value; 6106 } else { 6107 init_s64_max = (s32)reg->smax_value; 6108 init_s64_min = (s32)reg->smin_value; 6109 } 6110 6111 s64_max = max(init_s64_max, init_s64_min); 6112 s64_min = min(init_s64_max, init_s64_min); 6113 6114 /* both of s64_max/s64_min positive or negative */ 6115 if ((s64_max >= 0) == (s64_min >= 0)) { 6116 reg->smin_value = reg->s32_min_value = s64_min; 6117 reg->smax_value = reg->s32_max_value = s64_max; 6118 reg->umin_value = reg->u32_min_value = s64_min; 6119 reg->umax_value = reg->u32_max_value = s64_max; 6120 reg->var_off = tnum_range(s64_min, s64_max); 6121 return; 6122 } 6123 6124 out: 6125 set_sext64_default_val(reg, size); 6126 } 6127 6128 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6129 { 6130 if (size == 1) { 6131 reg->s32_min_value = S8_MIN; 6132 reg->s32_max_value = S8_MAX; 6133 } else { 6134 /* size == 2 */ 6135 reg->s32_min_value = S16_MIN; 6136 reg->s32_max_value = S16_MAX; 6137 } 6138 reg->u32_min_value = 0; 6139 reg->u32_max_value = U32_MAX; 6140 } 6141 6142 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6143 { 6144 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6145 u32 top_smax_value, top_smin_value; 6146 u32 num_bits = size * 8; 6147 6148 if (tnum_is_const(reg->var_off)) { 6149 u32_val = reg->var_off.value; 6150 if (size == 1) 6151 reg->var_off = tnum_const((s8)u32_val); 6152 else 6153 reg->var_off = tnum_const((s16)u32_val); 6154 6155 u32_val = reg->var_off.value; 6156 reg->s32_min_value = reg->s32_max_value = u32_val; 6157 reg->u32_min_value = reg->u32_max_value = u32_val; 6158 return; 6159 } 6160 6161 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 6162 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 6163 6164 if (top_smax_value != top_smin_value) 6165 goto out; 6166 6167 /* find the s32_min and s32_min after sign extension */ 6168 if (size == 1) { 6169 init_s32_max = (s8)reg->s32_max_value; 6170 init_s32_min = (s8)reg->s32_min_value; 6171 } else { 6172 /* size == 2 */ 6173 init_s32_max = (s16)reg->s32_max_value; 6174 init_s32_min = (s16)reg->s32_min_value; 6175 } 6176 s32_max = max(init_s32_max, init_s32_min); 6177 s32_min = min(init_s32_max, init_s32_min); 6178 6179 if ((s32_min >= 0) == (s32_max >= 0)) { 6180 reg->s32_min_value = s32_min; 6181 reg->s32_max_value = s32_max; 6182 reg->u32_min_value = (u32)s32_min; 6183 reg->u32_max_value = (u32)s32_max; 6184 return; 6185 } 6186 6187 out: 6188 set_sext32_default_val(reg, size); 6189 } 6190 6191 static bool bpf_map_is_rdonly(const struct bpf_map *map) 6192 { 6193 /* A map is considered read-only if the following condition are true: 6194 * 6195 * 1) BPF program side cannot change any of the map content. The 6196 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6197 * and was set at map creation time. 6198 * 2) The map value(s) have been initialized from user space by a 6199 * loader and then "frozen", such that no new map update/delete 6200 * operations from syscall side are possible for the rest of 6201 * the map's lifetime from that point onwards. 6202 * 3) Any parallel/pending map update/delete operations from syscall 6203 * side have been completed. Only after that point, it's safe to 6204 * assume that map value(s) are immutable. 6205 */ 6206 return (map->map_flags & BPF_F_RDONLY_PROG) && 6207 READ_ONCE(map->frozen) && 6208 !bpf_map_write_active(map); 6209 } 6210 6211 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6212 bool is_ldsx) 6213 { 6214 void *ptr; 6215 u64 addr; 6216 int err; 6217 6218 err = map->ops->map_direct_value_addr(map, &addr, off); 6219 if (err) 6220 return err; 6221 ptr = (void *)(long)addr + off; 6222 6223 switch (size) { 6224 case sizeof(u8): 6225 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6226 break; 6227 case sizeof(u16): 6228 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6229 break; 6230 case sizeof(u32): 6231 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6232 break; 6233 case sizeof(u64): 6234 *val = *(u64 *)ptr; 6235 break; 6236 default: 6237 return -EINVAL; 6238 } 6239 return 0; 6240 } 6241 6242 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6243 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6244 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6245 6246 /* 6247 * Allow list few fields as RCU trusted or full trusted. 6248 * This logic doesn't allow mix tagging and will be removed once GCC supports 6249 * btf_type_tag. 6250 */ 6251 6252 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6253 BTF_TYPE_SAFE_RCU(struct task_struct) { 6254 const cpumask_t *cpus_ptr; 6255 struct css_set __rcu *cgroups; 6256 struct task_struct __rcu *real_parent; 6257 struct task_struct *group_leader; 6258 }; 6259 6260 BTF_TYPE_SAFE_RCU(struct cgroup) { 6261 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6262 struct kernfs_node *kn; 6263 }; 6264 6265 BTF_TYPE_SAFE_RCU(struct css_set) { 6266 struct cgroup *dfl_cgrp; 6267 }; 6268 6269 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6270 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6271 struct file __rcu *exe_file; 6272 }; 6273 6274 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6275 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6276 */ 6277 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6278 struct sock *sk; 6279 }; 6280 6281 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6282 struct sock *sk; 6283 }; 6284 6285 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6286 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6287 struct seq_file *seq; 6288 }; 6289 6290 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6291 struct bpf_iter_meta *meta; 6292 struct task_struct *task; 6293 }; 6294 6295 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6296 struct file *file; 6297 }; 6298 6299 BTF_TYPE_SAFE_TRUSTED(struct file) { 6300 struct inode *f_inode; 6301 }; 6302 6303 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 6304 /* no negative dentry-s in places where bpf can see it */ 6305 struct inode *d_inode; 6306 }; 6307 6308 BTF_TYPE_SAFE_TRUSTED(struct socket) { 6309 struct sock *sk; 6310 }; 6311 6312 static bool type_is_rcu(struct bpf_verifier_env *env, 6313 struct bpf_reg_state *reg, 6314 const char *field_name, u32 btf_id) 6315 { 6316 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6317 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6318 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6319 6320 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6321 } 6322 6323 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6324 struct bpf_reg_state *reg, 6325 const char *field_name, u32 btf_id) 6326 { 6327 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6328 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6329 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6330 6331 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6332 } 6333 6334 static bool type_is_trusted(struct bpf_verifier_env *env, 6335 struct bpf_reg_state *reg, 6336 const char *field_name, u32 btf_id) 6337 { 6338 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 6339 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6340 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6341 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6342 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 6343 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket)); 6344 6345 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6346 } 6347 6348 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6349 struct bpf_reg_state *regs, 6350 int regno, int off, int size, 6351 enum bpf_access_type atype, 6352 int value_regno) 6353 { 6354 struct bpf_reg_state *reg = regs + regno; 6355 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6356 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6357 const char *field_name = NULL; 6358 enum bpf_type_flag flag = 0; 6359 u32 btf_id = 0; 6360 int ret; 6361 6362 if (!env->allow_ptr_leaks) { 6363 verbose(env, 6364 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6365 tname); 6366 return -EPERM; 6367 } 6368 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6369 verbose(env, 6370 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6371 tname); 6372 return -EINVAL; 6373 } 6374 if (off < 0) { 6375 verbose(env, 6376 "R%d is ptr_%s invalid negative access: off=%d\n", 6377 regno, tname, off); 6378 return -EACCES; 6379 } 6380 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6381 char tn_buf[48]; 6382 6383 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6384 verbose(env, 6385 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6386 regno, tname, off, tn_buf); 6387 return -EACCES; 6388 } 6389 6390 if (reg->type & MEM_USER) { 6391 verbose(env, 6392 "R%d is ptr_%s access user memory: off=%d\n", 6393 regno, tname, off); 6394 return -EACCES; 6395 } 6396 6397 if (reg->type & MEM_PERCPU) { 6398 verbose(env, 6399 "R%d is ptr_%s access percpu memory: off=%d\n", 6400 regno, tname, off); 6401 return -EACCES; 6402 } 6403 6404 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6405 if (!btf_is_kernel(reg->btf)) { 6406 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 6407 return -EFAULT; 6408 } 6409 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6410 } else { 6411 /* Writes are permitted with default btf_struct_access for 6412 * program allocated objects (which always have ref_obj_id > 0), 6413 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6414 */ 6415 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6416 verbose(env, "only read is supported\n"); 6417 return -EACCES; 6418 } 6419 6420 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6421 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 6422 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 6423 return -EFAULT; 6424 } 6425 6426 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6427 } 6428 6429 if (ret < 0) 6430 return ret; 6431 6432 if (ret != PTR_TO_BTF_ID) { 6433 /* just mark; */ 6434 6435 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6436 /* If this is an untrusted pointer, all pointers formed by walking it 6437 * also inherit the untrusted flag. 6438 */ 6439 flag = PTR_UNTRUSTED; 6440 6441 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6442 /* By default any pointer obtained from walking a trusted pointer is no 6443 * longer trusted, unless the field being accessed has explicitly been 6444 * marked as inheriting its parent's state of trust (either full or RCU). 6445 * For example: 6446 * 'cgroups' pointer is untrusted if task->cgroups dereference 6447 * happened in a sleepable program outside of bpf_rcu_read_lock() 6448 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6449 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6450 * 6451 * A regular RCU-protected pointer with __rcu tag can also be deemed 6452 * trusted if we are in an RCU CS. Such pointer can be NULL. 6453 */ 6454 if (type_is_trusted(env, reg, field_name, btf_id)) { 6455 flag |= PTR_TRUSTED; 6456 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6457 if (type_is_rcu(env, reg, field_name, btf_id)) { 6458 /* ignore __rcu tag and mark it MEM_RCU */ 6459 flag |= MEM_RCU; 6460 } else if (flag & MEM_RCU || 6461 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6462 /* __rcu tagged pointers can be NULL */ 6463 flag |= MEM_RCU | PTR_MAYBE_NULL; 6464 6465 /* We always trust them */ 6466 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6467 flag & PTR_UNTRUSTED) 6468 flag &= ~PTR_UNTRUSTED; 6469 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6470 /* keep as-is */ 6471 } else { 6472 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6473 clear_trusted_flags(&flag); 6474 } 6475 } else { 6476 /* 6477 * If not in RCU CS or MEM_RCU pointer can be NULL then 6478 * aggressively mark as untrusted otherwise such 6479 * pointers will be plain PTR_TO_BTF_ID without flags 6480 * and will be allowed to be passed into helpers for 6481 * compat reasons. 6482 */ 6483 flag = PTR_UNTRUSTED; 6484 } 6485 } else { 6486 /* Old compat. Deprecated */ 6487 clear_trusted_flags(&flag); 6488 } 6489 6490 if (atype == BPF_READ && value_regno >= 0) 6491 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6492 6493 return 0; 6494 } 6495 6496 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6497 struct bpf_reg_state *regs, 6498 int regno, int off, int size, 6499 enum bpf_access_type atype, 6500 int value_regno) 6501 { 6502 struct bpf_reg_state *reg = regs + regno; 6503 struct bpf_map *map = reg->map_ptr; 6504 struct bpf_reg_state map_reg; 6505 enum bpf_type_flag flag = 0; 6506 const struct btf_type *t; 6507 const char *tname; 6508 u32 btf_id; 6509 int ret; 6510 6511 if (!btf_vmlinux) { 6512 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6513 return -ENOTSUPP; 6514 } 6515 6516 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6517 verbose(env, "map_ptr access not supported for map type %d\n", 6518 map->map_type); 6519 return -ENOTSUPP; 6520 } 6521 6522 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6523 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6524 6525 if (!env->allow_ptr_leaks) { 6526 verbose(env, 6527 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6528 tname); 6529 return -EPERM; 6530 } 6531 6532 if (off < 0) { 6533 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6534 regno, tname, off); 6535 return -EACCES; 6536 } 6537 6538 if (atype != BPF_READ) { 6539 verbose(env, "only read from %s is supported\n", tname); 6540 return -EACCES; 6541 } 6542 6543 /* Simulate access to a PTR_TO_BTF_ID */ 6544 memset(&map_reg, 0, sizeof(map_reg)); 6545 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6546 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6547 if (ret < 0) 6548 return ret; 6549 6550 if (value_regno >= 0) 6551 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6552 6553 return 0; 6554 } 6555 6556 /* Check that the stack access at the given offset is within bounds. The 6557 * maximum valid offset is -1. 6558 * 6559 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6560 * -state->allocated_stack for reads. 6561 */ 6562 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 6563 s64 off, 6564 struct bpf_func_state *state, 6565 enum bpf_access_type t) 6566 { 6567 int min_valid_off; 6568 6569 if (t == BPF_WRITE || env->allow_uninit_stack) 6570 min_valid_off = -MAX_BPF_STACK; 6571 else 6572 min_valid_off = -state->allocated_stack; 6573 6574 if (off < min_valid_off || off > -1) 6575 return -EACCES; 6576 return 0; 6577 } 6578 6579 /* Check that the stack access at 'regno + off' falls within the maximum stack 6580 * bounds. 6581 * 6582 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6583 */ 6584 static int check_stack_access_within_bounds( 6585 struct bpf_verifier_env *env, 6586 int regno, int off, int access_size, 6587 enum bpf_access_src src, enum bpf_access_type type) 6588 { 6589 struct bpf_reg_state *regs = cur_regs(env); 6590 struct bpf_reg_state *reg = regs + regno; 6591 struct bpf_func_state *state = func(env, reg); 6592 s64 min_off, max_off; 6593 int err; 6594 char *err_extra; 6595 6596 if (src == ACCESS_HELPER) 6597 /* We don't know if helpers are reading or writing (or both). */ 6598 err_extra = " indirect access to"; 6599 else if (type == BPF_READ) 6600 err_extra = " read from"; 6601 else 6602 err_extra = " write to"; 6603 6604 if (tnum_is_const(reg->var_off)) { 6605 min_off = (s64)reg->var_off.value + off; 6606 max_off = min_off + access_size; 6607 } else { 6608 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6609 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6610 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6611 err_extra, regno); 6612 return -EACCES; 6613 } 6614 min_off = reg->smin_value + off; 6615 max_off = reg->smax_value + off + access_size; 6616 } 6617 6618 err = check_stack_slot_within_bounds(env, min_off, state, type); 6619 if (!err && max_off > 0) 6620 err = -EINVAL; /* out of stack access into non-negative offsets */ 6621 6622 if (err) { 6623 if (tnum_is_const(reg->var_off)) { 6624 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 6625 err_extra, regno, off, access_size); 6626 } else { 6627 char tn_buf[48]; 6628 6629 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6630 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n", 6631 err_extra, regno, tn_buf, off, access_size); 6632 } 6633 return err; 6634 } 6635 6636 /* Note that there is no stack access with offset zero, so the needed stack 6637 * size is -min_off, not -min_off+1. 6638 */ 6639 return grow_stack_state(env, state, -min_off /* size */); 6640 } 6641 6642 /* check whether memory at (regno + off) is accessible for t = (read | write) 6643 * if t==write, value_regno is a register which value is stored into memory 6644 * if t==read, value_regno is a register which will receive the value from memory 6645 * if t==write && value_regno==-1, some unknown value is stored into memory 6646 * if t==read && value_regno==-1, don't care what we read from memory 6647 */ 6648 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6649 int off, int bpf_size, enum bpf_access_type t, 6650 int value_regno, bool strict_alignment_once, bool is_ldsx) 6651 { 6652 struct bpf_reg_state *regs = cur_regs(env); 6653 struct bpf_reg_state *reg = regs + regno; 6654 int size, err = 0; 6655 6656 size = bpf_size_to_bytes(bpf_size); 6657 if (size < 0) 6658 return size; 6659 6660 /* alignment checks will add in reg->off themselves */ 6661 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6662 if (err) 6663 return err; 6664 6665 /* for access checks, reg->off is just part of off */ 6666 off += reg->off; 6667 6668 if (reg->type == PTR_TO_MAP_KEY) { 6669 if (t == BPF_WRITE) { 6670 verbose(env, "write to change key R%d not allowed\n", regno); 6671 return -EACCES; 6672 } 6673 6674 err = check_mem_region_access(env, regno, off, size, 6675 reg->map_ptr->key_size, false); 6676 if (err) 6677 return err; 6678 if (value_regno >= 0) 6679 mark_reg_unknown(env, regs, value_regno); 6680 } else if (reg->type == PTR_TO_MAP_VALUE) { 6681 struct btf_field *kptr_field = NULL; 6682 6683 if (t == BPF_WRITE && value_regno >= 0 && 6684 is_pointer_value(env, value_regno)) { 6685 verbose(env, "R%d leaks addr into map\n", value_regno); 6686 return -EACCES; 6687 } 6688 err = check_map_access_type(env, regno, off, size, t); 6689 if (err) 6690 return err; 6691 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6692 if (err) 6693 return err; 6694 if (tnum_is_const(reg->var_off)) 6695 kptr_field = btf_record_find(reg->map_ptr->record, 6696 off + reg->var_off.value, BPF_KPTR); 6697 if (kptr_field) { 6698 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6699 } else if (t == BPF_READ && value_regno >= 0) { 6700 struct bpf_map *map = reg->map_ptr; 6701 6702 /* if map is read-only, track its contents as scalars */ 6703 if (tnum_is_const(reg->var_off) && 6704 bpf_map_is_rdonly(map) && 6705 map->ops->map_direct_value_addr) { 6706 int map_off = off + reg->var_off.value; 6707 u64 val = 0; 6708 6709 err = bpf_map_direct_read(map, map_off, size, 6710 &val, is_ldsx); 6711 if (err) 6712 return err; 6713 6714 regs[value_regno].type = SCALAR_VALUE; 6715 __mark_reg_known(®s[value_regno], val); 6716 } else { 6717 mark_reg_unknown(env, regs, value_regno); 6718 } 6719 } 6720 } else if (base_type(reg->type) == PTR_TO_MEM) { 6721 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6722 6723 if (type_may_be_null(reg->type)) { 6724 verbose(env, "R%d invalid mem access '%s'\n", regno, 6725 reg_type_str(env, reg->type)); 6726 return -EACCES; 6727 } 6728 6729 if (t == BPF_WRITE && rdonly_mem) { 6730 verbose(env, "R%d cannot write into %s\n", 6731 regno, reg_type_str(env, reg->type)); 6732 return -EACCES; 6733 } 6734 6735 if (t == BPF_WRITE && value_regno >= 0 && 6736 is_pointer_value(env, value_regno)) { 6737 verbose(env, "R%d leaks addr into mem\n", value_regno); 6738 return -EACCES; 6739 } 6740 6741 err = check_mem_region_access(env, regno, off, size, 6742 reg->mem_size, false); 6743 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6744 mark_reg_unknown(env, regs, value_regno); 6745 } else if (reg->type == PTR_TO_CTX) { 6746 enum bpf_reg_type reg_type = SCALAR_VALUE; 6747 struct btf *btf = NULL; 6748 u32 btf_id = 0; 6749 6750 if (t == BPF_WRITE && value_regno >= 0 && 6751 is_pointer_value(env, value_regno)) { 6752 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6753 return -EACCES; 6754 } 6755 6756 err = check_ptr_off_reg(env, reg, regno); 6757 if (err < 0) 6758 return err; 6759 6760 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 6761 &btf_id); 6762 if (err) 6763 verbose_linfo(env, insn_idx, "; "); 6764 if (!err && t == BPF_READ && value_regno >= 0) { 6765 /* ctx access returns either a scalar, or a 6766 * PTR_TO_PACKET[_META,_END]. In the latter 6767 * case, we know the offset is zero. 6768 */ 6769 if (reg_type == SCALAR_VALUE) { 6770 mark_reg_unknown(env, regs, value_regno); 6771 } else { 6772 mark_reg_known_zero(env, regs, 6773 value_regno); 6774 if (type_may_be_null(reg_type)) 6775 regs[value_regno].id = ++env->id_gen; 6776 /* A load of ctx field could have different 6777 * actual load size with the one encoded in the 6778 * insn. When the dst is PTR, it is for sure not 6779 * a sub-register. 6780 */ 6781 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6782 if (base_type(reg_type) == PTR_TO_BTF_ID) { 6783 regs[value_regno].btf = btf; 6784 regs[value_regno].btf_id = btf_id; 6785 } 6786 } 6787 regs[value_regno].type = reg_type; 6788 } 6789 6790 } else if (reg->type == PTR_TO_STACK) { 6791 /* Basic bounds checks. */ 6792 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 6793 if (err) 6794 return err; 6795 6796 if (t == BPF_READ) 6797 err = check_stack_read(env, regno, off, size, 6798 value_regno); 6799 else 6800 err = check_stack_write(env, regno, off, size, 6801 value_regno, insn_idx); 6802 } else if (reg_is_pkt_pointer(reg)) { 6803 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6804 verbose(env, "cannot write into packet\n"); 6805 return -EACCES; 6806 } 6807 if (t == BPF_WRITE && value_regno >= 0 && 6808 is_pointer_value(env, value_regno)) { 6809 verbose(env, "R%d leaks addr into packet\n", 6810 value_regno); 6811 return -EACCES; 6812 } 6813 err = check_packet_access(env, regno, off, size, false); 6814 if (!err && t == BPF_READ && value_regno >= 0) 6815 mark_reg_unknown(env, regs, value_regno); 6816 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6817 if (t == BPF_WRITE && value_regno >= 0 && 6818 is_pointer_value(env, value_regno)) { 6819 verbose(env, "R%d leaks addr into flow keys\n", 6820 value_regno); 6821 return -EACCES; 6822 } 6823 6824 err = check_flow_keys_access(env, off, size); 6825 if (!err && t == BPF_READ && value_regno >= 0) 6826 mark_reg_unknown(env, regs, value_regno); 6827 } else if (type_is_sk_pointer(reg->type)) { 6828 if (t == BPF_WRITE) { 6829 verbose(env, "R%d cannot write into %s\n", 6830 regno, reg_type_str(env, reg->type)); 6831 return -EACCES; 6832 } 6833 err = check_sock_access(env, insn_idx, regno, off, size, t); 6834 if (!err && value_regno >= 0) 6835 mark_reg_unknown(env, regs, value_regno); 6836 } else if (reg->type == PTR_TO_TP_BUFFER) { 6837 err = check_tp_buffer_access(env, reg, regno, off, size); 6838 if (!err && t == BPF_READ && value_regno >= 0) 6839 mark_reg_unknown(env, regs, value_regno); 6840 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6841 !type_may_be_null(reg->type)) { 6842 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 6843 value_regno); 6844 } else if (reg->type == CONST_PTR_TO_MAP) { 6845 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 6846 value_regno); 6847 } else if (base_type(reg->type) == PTR_TO_BUF) { 6848 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6849 u32 *max_access; 6850 6851 if (rdonly_mem) { 6852 if (t == BPF_WRITE) { 6853 verbose(env, "R%d cannot write into %s\n", 6854 regno, reg_type_str(env, reg->type)); 6855 return -EACCES; 6856 } 6857 max_access = &env->prog->aux->max_rdonly_access; 6858 } else { 6859 max_access = &env->prog->aux->max_rdwr_access; 6860 } 6861 6862 err = check_buffer_access(env, reg, regno, off, size, false, 6863 max_access); 6864 6865 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6866 mark_reg_unknown(env, regs, value_regno); 6867 } else { 6868 verbose(env, "R%d invalid mem access '%s'\n", regno, 6869 reg_type_str(env, reg->type)); 6870 return -EACCES; 6871 } 6872 6873 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6874 regs[value_regno].type == SCALAR_VALUE) { 6875 if (!is_ldsx) 6876 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6877 coerce_reg_to_size(®s[value_regno], size); 6878 else 6879 coerce_reg_to_size_sx(®s[value_regno], size); 6880 } 6881 return err; 6882 } 6883 6884 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 6885 { 6886 int load_reg; 6887 int err; 6888 6889 switch (insn->imm) { 6890 case BPF_ADD: 6891 case BPF_ADD | BPF_FETCH: 6892 case BPF_AND: 6893 case BPF_AND | BPF_FETCH: 6894 case BPF_OR: 6895 case BPF_OR | BPF_FETCH: 6896 case BPF_XOR: 6897 case BPF_XOR | BPF_FETCH: 6898 case BPF_XCHG: 6899 case BPF_CMPXCHG: 6900 break; 6901 default: 6902 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 6903 return -EINVAL; 6904 } 6905 6906 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6907 verbose(env, "invalid atomic operand size\n"); 6908 return -EINVAL; 6909 } 6910 6911 /* check src1 operand */ 6912 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6913 if (err) 6914 return err; 6915 6916 /* check src2 operand */ 6917 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6918 if (err) 6919 return err; 6920 6921 if (insn->imm == BPF_CMPXCHG) { 6922 /* Check comparison of R0 with memory location */ 6923 const u32 aux_reg = BPF_REG_0; 6924 6925 err = check_reg_arg(env, aux_reg, SRC_OP); 6926 if (err) 6927 return err; 6928 6929 if (is_pointer_value(env, aux_reg)) { 6930 verbose(env, "R%d leaks addr into mem\n", aux_reg); 6931 return -EACCES; 6932 } 6933 } 6934 6935 if (is_pointer_value(env, insn->src_reg)) { 6936 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 6937 return -EACCES; 6938 } 6939 6940 if (is_ctx_reg(env, insn->dst_reg) || 6941 is_pkt_reg(env, insn->dst_reg) || 6942 is_flow_key_reg(env, insn->dst_reg) || 6943 is_sk_reg(env, insn->dst_reg)) { 6944 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6945 insn->dst_reg, 6946 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6947 return -EACCES; 6948 } 6949 6950 if (insn->imm & BPF_FETCH) { 6951 if (insn->imm == BPF_CMPXCHG) 6952 load_reg = BPF_REG_0; 6953 else 6954 load_reg = insn->src_reg; 6955 6956 /* check and record load of old value */ 6957 err = check_reg_arg(env, load_reg, DST_OP); 6958 if (err) 6959 return err; 6960 } else { 6961 /* This instruction accesses a memory location but doesn't 6962 * actually load it into a register. 6963 */ 6964 load_reg = -1; 6965 } 6966 6967 /* Check whether we can read the memory, with second call for fetch 6968 * case to simulate the register fill. 6969 */ 6970 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6971 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 6972 if (!err && load_reg >= 0) 6973 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6974 BPF_SIZE(insn->code), BPF_READ, load_reg, 6975 true, false); 6976 if (err) 6977 return err; 6978 6979 /* Check whether we can write into the same memory. */ 6980 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6981 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 6982 if (err) 6983 return err; 6984 return 0; 6985 } 6986 6987 /* When register 'regno' is used to read the stack (either directly or through 6988 * a helper function) make sure that it's within stack boundary and, depending 6989 * on the access type and privileges, that all elements of the stack are 6990 * initialized. 6991 * 6992 * 'off' includes 'regno->off', but not its dynamic part (if any). 6993 * 6994 * All registers that have been spilled on the stack in the slots within the 6995 * read offsets are marked as read. 6996 */ 6997 static int check_stack_range_initialized( 6998 struct bpf_verifier_env *env, int regno, int off, 6999 int access_size, bool zero_size_allowed, 7000 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 7001 { 7002 struct bpf_reg_state *reg = reg_state(env, regno); 7003 struct bpf_func_state *state = func(env, reg); 7004 int err, min_off, max_off, i, j, slot, spi; 7005 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 7006 enum bpf_access_type bounds_check_type; 7007 /* Some accesses can write anything into the stack, others are 7008 * read-only. 7009 */ 7010 bool clobber = false; 7011 7012 if (access_size == 0 && !zero_size_allowed) { 7013 verbose(env, "invalid zero-sized read\n"); 7014 return -EACCES; 7015 } 7016 7017 if (type == ACCESS_HELPER) { 7018 /* The bounds checks for writes are more permissive than for 7019 * reads. However, if raw_mode is not set, we'll do extra 7020 * checks below. 7021 */ 7022 bounds_check_type = BPF_WRITE; 7023 clobber = true; 7024 } else { 7025 bounds_check_type = BPF_READ; 7026 } 7027 err = check_stack_access_within_bounds(env, regno, off, access_size, 7028 type, bounds_check_type); 7029 if (err) 7030 return err; 7031 7032 7033 if (tnum_is_const(reg->var_off)) { 7034 min_off = max_off = reg->var_off.value + off; 7035 } else { 7036 /* Variable offset is prohibited for unprivileged mode for 7037 * simplicity since it requires corresponding support in 7038 * Spectre masking for stack ALU. 7039 * See also retrieve_ptr_limit(). 7040 */ 7041 if (!env->bypass_spec_v1) { 7042 char tn_buf[48]; 7043 7044 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7045 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 7046 regno, err_extra, tn_buf); 7047 return -EACCES; 7048 } 7049 /* Only initialized buffer on stack is allowed to be accessed 7050 * with variable offset. With uninitialized buffer it's hard to 7051 * guarantee that whole memory is marked as initialized on 7052 * helper return since specific bounds are unknown what may 7053 * cause uninitialized stack leaking. 7054 */ 7055 if (meta && meta->raw_mode) 7056 meta = NULL; 7057 7058 min_off = reg->smin_value + off; 7059 max_off = reg->smax_value + off; 7060 } 7061 7062 if (meta && meta->raw_mode) { 7063 /* Ensure we won't be overwriting dynptrs when simulating byte 7064 * by byte access in check_helper_call using meta.access_size. 7065 * This would be a problem if we have a helper in the future 7066 * which takes: 7067 * 7068 * helper(uninit_mem, len, dynptr) 7069 * 7070 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 7071 * may end up writing to dynptr itself when touching memory from 7072 * arg 1. This can be relaxed on a case by case basis for known 7073 * safe cases, but reject due to the possibilitiy of aliasing by 7074 * default. 7075 */ 7076 for (i = min_off; i < max_off + access_size; i++) { 7077 int stack_off = -i - 1; 7078 7079 spi = __get_spi(i); 7080 /* raw_mode may write past allocated_stack */ 7081 if (state->allocated_stack <= stack_off) 7082 continue; 7083 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 7084 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 7085 return -EACCES; 7086 } 7087 } 7088 meta->access_size = access_size; 7089 meta->regno = regno; 7090 return 0; 7091 } 7092 7093 for (i = min_off; i < max_off + access_size; i++) { 7094 u8 *stype; 7095 7096 slot = -i - 1; 7097 spi = slot / BPF_REG_SIZE; 7098 if (state->allocated_stack <= slot) { 7099 verbose(env, "verifier bug: allocated_stack too small"); 7100 return -EFAULT; 7101 } 7102 7103 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 7104 if (*stype == STACK_MISC) 7105 goto mark; 7106 if ((*stype == STACK_ZERO) || 7107 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 7108 if (clobber) { 7109 /* helper can write anything into the stack */ 7110 *stype = STACK_MISC; 7111 } 7112 goto mark; 7113 } 7114 7115 if (is_spilled_reg(&state->stack[spi]) && 7116 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 7117 env->allow_ptr_leaks)) { 7118 if (clobber) { 7119 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 7120 for (j = 0; j < BPF_REG_SIZE; j++) 7121 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 7122 } 7123 goto mark; 7124 } 7125 7126 if (tnum_is_const(reg->var_off)) { 7127 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 7128 err_extra, regno, min_off, i - min_off, access_size); 7129 } else { 7130 char tn_buf[48]; 7131 7132 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7133 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 7134 err_extra, regno, tn_buf, i - min_off, access_size); 7135 } 7136 return -EACCES; 7137 mark: 7138 /* reading any byte out of 8-byte 'spill_slot' will cause 7139 * the whole slot to be marked as 'read' 7140 */ 7141 mark_reg_read(env, &state->stack[spi].spilled_ptr, 7142 state->stack[spi].spilled_ptr.parent, 7143 REG_LIVE_READ64); 7144 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 7145 * be sure that whether stack slot is written to or not. Hence, 7146 * we must still conservatively propagate reads upwards even if 7147 * helper may write to the entire memory range. 7148 */ 7149 } 7150 return 0; 7151 } 7152 7153 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 7154 int access_size, bool zero_size_allowed, 7155 struct bpf_call_arg_meta *meta) 7156 { 7157 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7158 u32 *max_access; 7159 7160 switch (base_type(reg->type)) { 7161 case PTR_TO_PACKET: 7162 case PTR_TO_PACKET_META: 7163 return check_packet_access(env, regno, reg->off, access_size, 7164 zero_size_allowed); 7165 case PTR_TO_MAP_KEY: 7166 if (meta && meta->raw_mode) { 7167 verbose(env, "R%d cannot write into %s\n", regno, 7168 reg_type_str(env, reg->type)); 7169 return -EACCES; 7170 } 7171 return check_mem_region_access(env, regno, reg->off, access_size, 7172 reg->map_ptr->key_size, false); 7173 case PTR_TO_MAP_VALUE: 7174 if (check_map_access_type(env, regno, reg->off, access_size, 7175 meta && meta->raw_mode ? BPF_WRITE : 7176 BPF_READ)) 7177 return -EACCES; 7178 return check_map_access(env, regno, reg->off, access_size, 7179 zero_size_allowed, ACCESS_HELPER); 7180 case PTR_TO_MEM: 7181 if (type_is_rdonly_mem(reg->type)) { 7182 if (meta && meta->raw_mode) { 7183 verbose(env, "R%d cannot write into %s\n", regno, 7184 reg_type_str(env, reg->type)); 7185 return -EACCES; 7186 } 7187 } 7188 return check_mem_region_access(env, regno, reg->off, 7189 access_size, reg->mem_size, 7190 zero_size_allowed); 7191 case PTR_TO_BUF: 7192 if (type_is_rdonly_mem(reg->type)) { 7193 if (meta && meta->raw_mode) { 7194 verbose(env, "R%d cannot write into %s\n", regno, 7195 reg_type_str(env, reg->type)); 7196 return -EACCES; 7197 } 7198 7199 max_access = &env->prog->aux->max_rdonly_access; 7200 } else { 7201 max_access = &env->prog->aux->max_rdwr_access; 7202 } 7203 return check_buffer_access(env, reg, regno, reg->off, 7204 access_size, zero_size_allowed, 7205 max_access); 7206 case PTR_TO_STACK: 7207 return check_stack_range_initialized( 7208 env, 7209 regno, reg->off, access_size, 7210 zero_size_allowed, ACCESS_HELPER, meta); 7211 case PTR_TO_BTF_ID: 7212 return check_ptr_to_btf_access(env, regs, regno, reg->off, 7213 access_size, BPF_READ, -1); 7214 case PTR_TO_CTX: 7215 /* in case the function doesn't know how to access the context, 7216 * (because we are in a program of type SYSCALL for example), we 7217 * can not statically check its size. 7218 * Dynamically check it now. 7219 */ 7220 if (!env->ops->convert_ctx_access) { 7221 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 7222 int offset = access_size - 1; 7223 7224 /* Allow zero-byte read from PTR_TO_CTX */ 7225 if (access_size == 0) 7226 return zero_size_allowed ? 0 : -EACCES; 7227 7228 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 7229 atype, -1, false, false); 7230 } 7231 7232 fallthrough; 7233 default: /* scalar_value or invalid ptr */ 7234 /* Allow zero-byte read from NULL, regardless of pointer type */ 7235 if (zero_size_allowed && access_size == 0 && 7236 register_is_null(reg)) 7237 return 0; 7238 7239 verbose(env, "R%d type=%s ", regno, 7240 reg_type_str(env, reg->type)); 7241 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7242 return -EACCES; 7243 } 7244 } 7245 7246 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 7247 * size. 7248 * 7249 * @regno is the register containing the access size. regno-1 is the register 7250 * containing the pointer. 7251 */ 7252 static int check_mem_size_reg(struct bpf_verifier_env *env, 7253 struct bpf_reg_state *reg, u32 regno, 7254 bool zero_size_allowed, 7255 struct bpf_call_arg_meta *meta) 7256 { 7257 int err; 7258 7259 /* This is used to refine r0 return value bounds for helpers 7260 * that enforce this value as an upper bound on return values. 7261 * See do_refine_retval_range() for helpers that can refine 7262 * the return value. C type of helper is u32 so we pull register 7263 * bound from umax_value however, if negative verifier errors 7264 * out. Only upper bounds can be learned because retval is an 7265 * int type and negative retvals are allowed. 7266 */ 7267 meta->msize_max_value = reg->umax_value; 7268 7269 /* The register is SCALAR_VALUE; the access check 7270 * happens using its boundaries. 7271 */ 7272 if (!tnum_is_const(reg->var_off)) 7273 /* For unprivileged variable accesses, disable raw 7274 * mode so that the program is required to 7275 * initialize all the memory that the helper could 7276 * just partially fill up. 7277 */ 7278 meta = NULL; 7279 7280 if (reg->smin_value < 0) { 7281 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7282 regno); 7283 return -EACCES; 7284 } 7285 7286 if (reg->umin_value == 0 && !zero_size_allowed) { 7287 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n", 7288 regno, reg->umin_value, reg->umax_value); 7289 return -EACCES; 7290 } 7291 7292 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7293 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7294 regno); 7295 return -EACCES; 7296 } 7297 err = check_helper_mem_access(env, regno - 1, 7298 reg->umax_value, 7299 zero_size_allowed, meta); 7300 if (!err) 7301 err = mark_chain_precision(env, regno); 7302 return err; 7303 } 7304 7305 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7306 u32 regno, u32 mem_size) 7307 { 7308 bool may_be_null = type_may_be_null(reg->type); 7309 struct bpf_reg_state saved_reg; 7310 struct bpf_call_arg_meta meta; 7311 int err; 7312 7313 if (register_is_null(reg)) 7314 return 0; 7315 7316 memset(&meta, 0, sizeof(meta)); 7317 /* Assuming that the register contains a value check if the memory 7318 * access is safe. Temporarily save and restore the register's state as 7319 * the conversion shouldn't be visible to a caller. 7320 */ 7321 if (may_be_null) { 7322 saved_reg = *reg; 7323 mark_ptr_not_null_reg(reg); 7324 } 7325 7326 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 7327 /* Check access for BPF_WRITE */ 7328 meta.raw_mode = true; 7329 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 7330 7331 if (may_be_null) 7332 *reg = saved_reg; 7333 7334 return err; 7335 } 7336 7337 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7338 u32 regno) 7339 { 7340 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7341 bool may_be_null = type_may_be_null(mem_reg->type); 7342 struct bpf_reg_state saved_reg; 7343 struct bpf_call_arg_meta meta; 7344 int err; 7345 7346 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7347 7348 memset(&meta, 0, sizeof(meta)); 7349 7350 if (may_be_null) { 7351 saved_reg = *mem_reg; 7352 mark_ptr_not_null_reg(mem_reg); 7353 } 7354 7355 err = check_mem_size_reg(env, reg, regno, true, &meta); 7356 /* Check access for BPF_WRITE */ 7357 meta.raw_mode = true; 7358 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 7359 7360 if (may_be_null) 7361 *mem_reg = saved_reg; 7362 return err; 7363 } 7364 7365 /* Implementation details: 7366 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7367 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7368 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7369 * Two separate bpf_obj_new will also have different reg->id. 7370 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7371 * clears reg->id after value_or_null->value transition, since the verifier only 7372 * cares about the range of access to valid map value pointer and doesn't care 7373 * about actual address of the map element. 7374 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7375 * reg->id > 0 after value_or_null->value transition. By doing so 7376 * two bpf_map_lookups will be considered two different pointers that 7377 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7378 * returned from bpf_obj_new. 7379 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7380 * dead-locks. 7381 * Since only one bpf_spin_lock is allowed the checks are simpler than 7382 * reg_is_refcounted() logic. The verifier needs to remember only 7383 * one spin_lock instead of array of acquired_refs. 7384 * cur_state->active_lock remembers which map value element or allocated 7385 * object got locked and clears it after bpf_spin_unlock. 7386 */ 7387 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 7388 bool is_lock) 7389 { 7390 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7391 struct bpf_verifier_state *cur = env->cur_state; 7392 bool is_const = tnum_is_const(reg->var_off); 7393 u64 val = reg->var_off.value; 7394 struct bpf_map *map = NULL; 7395 struct btf *btf = NULL; 7396 struct btf_record *rec; 7397 7398 if (!is_const) { 7399 verbose(env, 7400 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 7401 regno); 7402 return -EINVAL; 7403 } 7404 if (reg->type == PTR_TO_MAP_VALUE) { 7405 map = reg->map_ptr; 7406 if (!map->btf) { 7407 verbose(env, 7408 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 7409 map->name); 7410 return -EINVAL; 7411 } 7412 } else { 7413 btf = reg->btf; 7414 } 7415 7416 rec = reg_btf_record(reg); 7417 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 7418 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 7419 map ? map->name : "kptr"); 7420 return -EINVAL; 7421 } 7422 if (rec->spin_lock_off != val + reg->off) { 7423 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 7424 val + reg->off, rec->spin_lock_off); 7425 return -EINVAL; 7426 } 7427 if (is_lock) { 7428 if (cur->active_lock.ptr) { 7429 verbose(env, 7430 "Locking two bpf_spin_locks are not allowed\n"); 7431 return -EINVAL; 7432 } 7433 if (map) 7434 cur->active_lock.ptr = map; 7435 else 7436 cur->active_lock.ptr = btf; 7437 cur->active_lock.id = reg->id; 7438 } else { 7439 void *ptr; 7440 7441 if (map) 7442 ptr = map; 7443 else 7444 ptr = btf; 7445 7446 if (!cur->active_lock.ptr) { 7447 verbose(env, "bpf_spin_unlock without taking a lock\n"); 7448 return -EINVAL; 7449 } 7450 if (cur->active_lock.ptr != ptr || 7451 cur->active_lock.id != reg->id) { 7452 verbose(env, "bpf_spin_unlock of different lock\n"); 7453 return -EINVAL; 7454 } 7455 7456 invalidate_non_owning_refs(env); 7457 7458 cur->active_lock.ptr = NULL; 7459 cur->active_lock.id = 0; 7460 } 7461 return 0; 7462 } 7463 7464 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7465 struct bpf_call_arg_meta *meta) 7466 { 7467 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7468 bool is_const = tnum_is_const(reg->var_off); 7469 struct bpf_map *map = reg->map_ptr; 7470 u64 val = reg->var_off.value; 7471 7472 if (!is_const) { 7473 verbose(env, 7474 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 7475 regno); 7476 return -EINVAL; 7477 } 7478 if (!map->btf) { 7479 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 7480 map->name); 7481 return -EINVAL; 7482 } 7483 if (!btf_record_has_field(map->record, BPF_TIMER)) { 7484 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 7485 return -EINVAL; 7486 } 7487 if (map->record->timer_off != val + reg->off) { 7488 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 7489 val + reg->off, map->record->timer_off); 7490 return -EINVAL; 7491 } 7492 if (meta->map_ptr) { 7493 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 7494 return -EFAULT; 7495 } 7496 meta->map_uid = reg->map_uid; 7497 meta->map_ptr = map; 7498 return 0; 7499 } 7500 7501 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7502 struct bpf_call_arg_meta *meta) 7503 { 7504 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7505 struct bpf_map *map_ptr = reg->map_ptr; 7506 struct btf_field *kptr_field; 7507 u32 kptr_off; 7508 7509 if (!tnum_is_const(reg->var_off)) { 7510 verbose(env, 7511 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7512 regno); 7513 return -EINVAL; 7514 } 7515 if (!map_ptr->btf) { 7516 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7517 map_ptr->name); 7518 return -EINVAL; 7519 } 7520 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 7521 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 7522 return -EINVAL; 7523 } 7524 7525 meta->map_ptr = map_ptr; 7526 kptr_off = reg->off + reg->var_off.value; 7527 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 7528 if (!kptr_field) { 7529 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7530 return -EACCES; 7531 } 7532 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7533 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7534 return -EACCES; 7535 } 7536 meta->kptr_field = kptr_field; 7537 return 0; 7538 } 7539 7540 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7541 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7542 * 7543 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7544 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7545 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7546 * 7547 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7548 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7549 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7550 * mutate the view of the dynptr and also possibly destroy it. In the latter 7551 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7552 * memory that dynptr points to. 7553 * 7554 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7555 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7556 * readonly dynptr view yet, hence only the first case is tracked and checked. 7557 * 7558 * This is consistent with how C applies the const modifier to a struct object, 7559 * where the pointer itself inside bpf_dynptr becomes const but not what it 7560 * points to. 7561 * 7562 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7563 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7564 */ 7565 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7566 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7567 { 7568 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7569 int err; 7570 7571 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7572 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7573 */ 7574 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7575 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 7576 return -EFAULT; 7577 } 7578 7579 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7580 * constructing a mutable bpf_dynptr object. 7581 * 7582 * Currently, this is only possible with PTR_TO_STACK 7583 * pointing to a region of at least 16 bytes which doesn't 7584 * contain an existing bpf_dynptr. 7585 * 7586 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7587 * mutated or destroyed. However, the memory it points to 7588 * may be mutated. 7589 * 7590 * None - Points to a initialized dynptr that can be mutated and 7591 * destroyed, including mutation of the memory it points 7592 * to. 7593 */ 7594 if (arg_type & MEM_UNINIT) { 7595 int i; 7596 7597 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7598 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7599 return -EINVAL; 7600 } 7601 7602 /* we write BPF_DW bits (8 bytes) at a time */ 7603 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7604 err = check_mem_access(env, insn_idx, regno, 7605 i, BPF_DW, BPF_WRITE, -1, false, false); 7606 if (err) 7607 return err; 7608 } 7609 7610 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7611 } else /* MEM_RDONLY and None case from above */ { 7612 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7613 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7614 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7615 return -EINVAL; 7616 } 7617 7618 if (!is_dynptr_reg_valid_init(env, reg)) { 7619 verbose(env, 7620 "Expected an initialized dynptr as arg #%d\n", 7621 regno); 7622 return -EINVAL; 7623 } 7624 7625 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7626 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7627 verbose(env, 7628 "Expected a dynptr of type %s as arg #%d\n", 7629 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 7630 return -EINVAL; 7631 } 7632 7633 err = mark_dynptr_read(env, reg); 7634 } 7635 return err; 7636 } 7637 7638 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7639 { 7640 struct bpf_func_state *state = func(env, reg); 7641 7642 return state->stack[spi].spilled_ptr.ref_obj_id; 7643 } 7644 7645 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7646 { 7647 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7648 } 7649 7650 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7651 { 7652 return meta->kfunc_flags & KF_ITER_NEW; 7653 } 7654 7655 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7656 { 7657 return meta->kfunc_flags & KF_ITER_NEXT; 7658 } 7659 7660 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7661 { 7662 return meta->kfunc_flags & KF_ITER_DESTROY; 7663 } 7664 7665 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg) 7666 { 7667 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7668 * kfunc is iter state pointer 7669 */ 7670 return arg == 0 && is_iter_kfunc(meta); 7671 } 7672 7673 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7674 struct bpf_kfunc_call_arg_meta *meta) 7675 { 7676 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7677 const struct btf_type *t; 7678 const struct btf_param *arg; 7679 int spi, err, i, nr_slots; 7680 u32 btf_id; 7681 7682 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */ 7683 arg = &btf_params(meta->func_proto)[0]; 7684 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */ 7685 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */ 7686 nr_slots = t->size / BPF_REG_SIZE; 7687 7688 if (is_iter_new_kfunc(meta)) { 7689 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7690 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7691 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 7692 iter_type_str(meta->btf, btf_id), regno); 7693 return -EINVAL; 7694 } 7695 7696 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7697 err = check_mem_access(env, insn_idx, regno, 7698 i, BPF_DW, BPF_WRITE, -1, false, false); 7699 if (err) 7700 return err; 7701 } 7702 7703 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 7704 if (err) 7705 return err; 7706 } else { 7707 /* iter_next() or iter_destroy() expect initialized iter state*/ 7708 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 7709 switch (err) { 7710 case 0: 7711 break; 7712 case -EINVAL: 7713 verbose(env, "expected an initialized iter_%s as arg #%d\n", 7714 iter_type_str(meta->btf, btf_id), regno); 7715 return err; 7716 case -EPROTO: 7717 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 7718 return err; 7719 default: 7720 return err; 7721 } 7722 7723 spi = iter_get_spi(env, reg, nr_slots); 7724 if (spi < 0) 7725 return spi; 7726 7727 err = mark_iter_read(env, reg, spi, nr_slots); 7728 if (err) 7729 return err; 7730 7731 /* remember meta->iter info for process_iter_next_call() */ 7732 meta->iter.spi = spi; 7733 meta->iter.frameno = reg->frameno; 7734 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 7735 7736 if (is_iter_destroy_kfunc(meta)) { 7737 err = unmark_stack_slots_iter(env, reg, nr_slots); 7738 if (err) 7739 return err; 7740 } 7741 } 7742 7743 return 0; 7744 } 7745 7746 /* Look for a previous loop entry at insn_idx: nearest parent state 7747 * stopped at insn_idx with callsites matching those in cur->frame. 7748 */ 7749 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 7750 struct bpf_verifier_state *cur, 7751 int insn_idx) 7752 { 7753 struct bpf_verifier_state_list *sl; 7754 struct bpf_verifier_state *st; 7755 7756 /* Explored states are pushed in stack order, most recent states come first */ 7757 sl = *explored_state(env, insn_idx); 7758 for (; sl; sl = sl->next) { 7759 /* If st->branches != 0 state is a part of current DFS verification path, 7760 * hence cur & st for a loop. 7761 */ 7762 st = &sl->state; 7763 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 7764 st->dfs_depth < cur->dfs_depth) 7765 return st; 7766 } 7767 7768 return NULL; 7769 } 7770 7771 static void reset_idmap_scratch(struct bpf_verifier_env *env); 7772 static bool regs_exact(const struct bpf_reg_state *rold, 7773 const struct bpf_reg_state *rcur, 7774 struct bpf_idmap *idmap); 7775 7776 static void maybe_widen_reg(struct bpf_verifier_env *env, 7777 struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 7778 struct bpf_idmap *idmap) 7779 { 7780 if (rold->type != SCALAR_VALUE) 7781 return; 7782 if (rold->type != rcur->type) 7783 return; 7784 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap)) 7785 return; 7786 __mark_reg_unknown(env, rcur); 7787 } 7788 7789 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 7790 struct bpf_verifier_state *old, 7791 struct bpf_verifier_state *cur) 7792 { 7793 struct bpf_func_state *fold, *fcur; 7794 int i, fr; 7795 7796 reset_idmap_scratch(env); 7797 for (fr = old->curframe; fr >= 0; fr--) { 7798 fold = old->frame[fr]; 7799 fcur = cur->frame[fr]; 7800 7801 for (i = 0; i < MAX_BPF_REG; i++) 7802 maybe_widen_reg(env, 7803 &fold->regs[i], 7804 &fcur->regs[i], 7805 &env->idmap_scratch); 7806 7807 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) { 7808 if (!is_spilled_reg(&fold->stack[i]) || 7809 !is_spilled_reg(&fcur->stack[i])) 7810 continue; 7811 7812 maybe_widen_reg(env, 7813 &fold->stack[i].spilled_ptr, 7814 &fcur->stack[i].spilled_ptr, 7815 &env->idmap_scratch); 7816 } 7817 } 7818 return 0; 7819 } 7820 7821 /* process_iter_next_call() is called when verifier gets to iterator's next 7822 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7823 * to it as just "iter_next()" in comments below. 7824 * 7825 * BPF verifier relies on a crucial contract for any iter_next() 7826 * implementation: it should *eventually* return NULL, and once that happens 7827 * it should keep returning NULL. That is, once iterator exhausts elements to 7828 * iterate, it should never reset or spuriously return new elements. 7829 * 7830 * With the assumption of such contract, process_iter_next_call() simulates 7831 * a fork in the verifier state to validate loop logic correctness and safety 7832 * without having to simulate infinite amount of iterations. 7833 * 7834 * In current state, we first assume that iter_next() returned NULL and 7835 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7836 * conditions we should not form an infinite loop and should eventually reach 7837 * exit. 7838 * 7839 * Besides that, we also fork current state and enqueue it for later 7840 * verification. In a forked state we keep iterator state as ACTIVE 7841 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7842 * also bump iteration depth to prevent erroneous infinite loop detection 7843 * later on (see iter_active_depths_differ() comment for details). In this 7844 * state we assume that we'll eventually loop back to another iter_next() 7845 * calls (it could be in exactly same location or in some other instruction, 7846 * it doesn't matter, we don't make any unnecessary assumptions about this, 7847 * everything revolves around iterator state in a stack slot, not which 7848 * instruction is calling iter_next()). When that happens, we either will come 7849 * to iter_next() with equivalent state and can conclude that next iteration 7850 * will proceed in exactly the same way as we just verified, so it's safe to 7851 * assume that loop converges. If not, we'll go on another iteration 7852 * simulation with a different input state, until all possible starting states 7853 * are validated or we reach maximum number of instructions limit. 7854 * 7855 * This way, we will either exhaustively discover all possible input states 7856 * that iterator loop can start with and eventually will converge, or we'll 7857 * effectively regress into bounded loop simulation logic and either reach 7858 * maximum number of instructions if loop is not provably convergent, or there 7859 * is some statically known limit on number of iterations (e.g., if there is 7860 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7861 * 7862 * Iteration convergence logic in is_state_visited() relies on exact 7863 * states comparison, which ignores read and precision marks. 7864 * This is necessary because read and precision marks are not finalized 7865 * while in the loop. Exact comparison might preclude convergence for 7866 * simple programs like below: 7867 * 7868 * i = 0; 7869 * while(iter_next(&it)) 7870 * i++; 7871 * 7872 * At each iteration step i++ would produce a new distinct state and 7873 * eventually instruction processing limit would be reached. 7874 * 7875 * To avoid such behavior speculatively forget (widen) range for 7876 * imprecise scalar registers, if those registers were not precise at the 7877 * end of the previous iteration and do not match exactly. 7878 * 7879 * This is a conservative heuristic that allows to verify wide range of programs, 7880 * however it precludes verification of programs that conjure an 7881 * imprecise value on the first loop iteration and use it as precise on a second. 7882 * For example, the following safe program would fail to verify: 7883 * 7884 * struct bpf_num_iter it; 7885 * int arr[10]; 7886 * int i = 0, a = 0; 7887 * bpf_iter_num_new(&it, 0, 10); 7888 * while (bpf_iter_num_next(&it)) { 7889 * if (a == 0) { 7890 * a = 1; 7891 * i = 7; // Because i changed verifier would forget 7892 * // it's range on second loop entry. 7893 * } else { 7894 * arr[i] = 42; // This would fail to verify. 7895 * } 7896 * } 7897 * bpf_iter_num_destroy(&it); 7898 */ 7899 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7900 struct bpf_kfunc_call_arg_meta *meta) 7901 { 7902 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 7903 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7904 struct bpf_reg_state *cur_iter, *queued_iter; 7905 int iter_frameno = meta->iter.frameno; 7906 int iter_spi = meta->iter.spi; 7907 7908 BTF_TYPE_EMIT(struct bpf_iter); 7909 7910 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7911 7912 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 7913 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 7914 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 7915 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 7916 return -EFAULT; 7917 } 7918 7919 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 7920 /* Because iter_next() call is a checkpoint is_state_visitied() 7921 * should guarantee parent state with same call sites and insn_idx. 7922 */ 7923 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 7924 !same_callsites(cur_st->parent, cur_st)) { 7925 verbose(env, "bug: bad parent state for iter next call"); 7926 return -EFAULT; 7927 } 7928 /* Note cur_st->parent in the call below, it is necessary to skip 7929 * checkpoint created for cur_st by is_state_visited() 7930 * right at this instruction. 7931 */ 7932 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 7933 /* branch out active iter state */ 7934 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 7935 if (!queued_st) 7936 return -ENOMEM; 7937 7938 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7939 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 7940 queued_iter->iter.depth++; 7941 if (prev_st) 7942 widen_imprecise_scalars(env, prev_st, queued_st); 7943 7944 queued_fr = queued_st->frame[queued_st->curframe]; 7945 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 7946 } 7947 7948 /* switch to DRAINED state, but keep the depth unchanged */ 7949 /* mark current iter state as drained and assume returned NULL */ 7950 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 7951 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 7952 7953 return 0; 7954 } 7955 7956 static bool arg_type_is_mem_size(enum bpf_arg_type type) 7957 { 7958 return type == ARG_CONST_SIZE || 7959 type == ARG_CONST_SIZE_OR_ZERO; 7960 } 7961 7962 static bool arg_type_is_release(enum bpf_arg_type type) 7963 { 7964 return type & OBJ_RELEASE; 7965 } 7966 7967 static bool arg_type_is_dynptr(enum bpf_arg_type type) 7968 { 7969 return base_type(type) == ARG_PTR_TO_DYNPTR; 7970 } 7971 7972 static int int_ptr_type_to_size(enum bpf_arg_type type) 7973 { 7974 if (type == ARG_PTR_TO_INT) 7975 return sizeof(u32); 7976 else if (type == ARG_PTR_TO_LONG) 7977 return sizeof(u64); 7978 7979 return -EINVAL; 7980 } 7981 7982 static int resolve_map_arg_type(struct bpf_verifier_env *env, 7983 const struct bpf_call_arg_meta *meta, 7984 enum bpf_arg_type *arg_type) 7985 { 7986 if (!meta->map_ptr) { 7987 /* kernel subsystem misconfigured verifier */ 7988 verbose(env, "invalid map_ptr to access map->type\n"); 7989 return -EACCES; 7990 } 7991 7992 switch (meta->map_ptr->map_type) { 7993 case BPF_MAP_TYPE_SOCKMAP: 7994 case BPF_MAP_TYPE_SOCKHASH: 7995 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 7996 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 7997 } else { 7998 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 7999 return -EINVAL; 8000 } 8001 break; 8002 case BPF_MAP_TYPE_BLOOM_FILTER: 8003 if (meta->func_id == BPF_FUNC_map_peek_elem) 8004 *arg_type = ARG_PTR_TO_MAP_VALUE; 8005 break; 8006 default: 8007 break; 8008 } 8009 return 0; 8010 } 8011 8012 struct bpf_reg_types { 8013 const enum bpf_reg_type types[10]; 8014 u32 *btf_id; 8015 }; 8016 8017 static const struct bpf_reg_types sock_types = { 8018 .types = { 8019 PTR_TO_SOCK_COMMON, 8020 PTR_TO_SOCKET, 8021 PTR_TO_TCP_SOCK, 8022 PTR_TO_XDP_SOCK, 8023 }, 8024 }; 8025 8026 #ifdef CONFIG_NET 8027 static const struct bpf_reg_types btf_id_sock_common_types = { 8028 .types = { 8029 PTR_TO_SOCK_COMMON, 8030 PTR_TO_SOCKET, 8031 PTR_TO_TCP_SOCK, 8032 PTR_TO_XDP_SOCK, 8033 PTR_TO_BTF_ID, 8034 PTR_TO_BTF_ID | PTR_TRUSTED, 8035 }, 8036 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 8037 }; 8038 #endif 8039 8040 static const struct bpf_reg_types mem_types = { 8041 .types = { 8042 PTR_TO_STACK, 8043 PTR_TO_PACKET, 8044 PTR_TO_PACKET_META, 8045 PTR_TO_MAP_KEY, 8046 PTR_TO_MAP_VALUE, 8047 PTR_TO_MEM, 8048 PTR_TO_MEM | MEM_RINGBUF, 8049 PTR_TO_BUF, 8050 PTR_TO_BTF_ID | PTR_TRUSTED, 8051 }, 8052 }; 8053 8054 static const struct bpf_reg_types int_ptr_types = { 8055 .types = { 8056 PTR_TO_STACK, 8057 PTR_TO_PACKET, 8058 PTR_TO_PACKET_META, 8059 PTR_TO_MAP_KEY, 8060 PTR_TO_MAP_VALUE, 8061 }, 8062 }; 8063 8064 static const struct bpf_reg_types spin_lock_types = { 8065 .types = { 8066 PTR_TO_MAP_VALUE, 8067 PTR_TO_BTF_ID | MEM_ALLOC, 8068 } 8069 }; 8070 8071 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 8072 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 8073 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 8074 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 8075 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 8076 static const struct bpf_reg_types btf_ptr_types = { 8077 .types = { 8078 PTR_TO_BTF_ID, 8079 PTR_TO_BTF_ID | PTR_TRUSTED, 8080 PTR_TO_BTF_ID | MEM_RCU, 8081 }, 8082 }; 8083 static const struct bpf_reg_types percpu_btf_ptr_types = { 8084 .types = { 8085 PTR_TO_BTF_ID | MEM_PERCPU, 8086 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 8087 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 8088 } 8089 }; 8090 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 8091 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 8092 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8093 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 8094 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8095 static const struct bpf_reg_types dynptr_types = { 8096 .types = { 8097 PTR_TO_STACK, 8098 CONST_PTR_TO_DYNPTR, 8099 } 8100 }; 8101 8102 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 8103 [ARG_PTR_TO_MAP_KEY] = &mem_types, 8104 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 8105 [ARG_CONST_SIZE] = &scalar_types, 8106 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 8107 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 8108 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 8109 [ARG_PTR_TO_CTX] = &context_types, 8110 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 8111 #ifdef CONFIG_NET 8112 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 8113 #endif 8114 [ARG_PTR_TO_SOCKET] = &fullsock_types, 8115 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 8116 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 8117 [ARG_PTR_TO_MEM] = &mem_types, 8118 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 8119 [ARG_PTR_TO_INT] = &int_ptr_types, 8120 [ARG_PTR_TO_LONG] = &int_ptr_types, 8121 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 8122 [ARG_PTR_TO_FUNC] = &func_ptr_types, 8123 [ARG_PTR_TO_STACK] = &stack_ptr_types, 8124 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 8125 [ARG_PTR_TO_TIMER] = &timer_types, 8126 [ARG_PTR_TO_KPTR] = &kptr_types, 8127 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 8128 }; 8129 8130 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 8131 enum bpf_arg_type arg_type, 8132 const u32 *arg_btf_id, 8133 struct bpf_call_arg_meta *meta) 8134 { 8135 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8136 enum bpf_reg_type expected, type = reg->type; 8137 const struct bpf_reg_types *compatible; 8138 int i, j; 8139 8140 compatible = compatible_reg_types[base_type(arg_type)]; 8141 if (!compatible) { 8142 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 8143 return -EFAULT; 8144 } 8145 8146 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 8147 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 8148 * 8149 * Same for MAYBE_NULL: 8150 * 8151 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 8152 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 8153 * 8154 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 8155 * 8156 * Therefore we fold these flags depending on the arg_type before comparison. 8157 */ 8158 if (arg_type & MEM_RDONLY) 8159 type &= ~MEM_RDONLY; 8160 if (arg_type & PTR_MAYBE_NULL) 8161 type &= ~PTR_MAYBE_NULL; 8162 if (base_type(arg_type) == ARG_PTR_TO_MEM) 8163 type &= ~DYNPTR_TYPE_FLAG_MASK; 8164 8165 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) { 8166 type &= ~MEM_ALLOC; 8167 type &= ~MEM_PERCPU; 8168 } 8169 8170 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 8171 expected = compatible->types[i]; 8172 if (expected == NOT_INIT) 8173 break; 8174 8175 if (type == expected) 8176 goto found; 8177 } 8178 8179 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 8180 for (j = 0; j + 1 < i; j++) 8181 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 8182 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 8183 return -EACCES; 8184 8185 found: 8186 if (base_type(reg->type) != PTR_TO_BTF_ID) 8187 return 0; 8188 8189 if (compatible == &mem_types) { 8190 if (!(arg_type & MEM_RDONLY)) { 8191 verbose(env, 8192 "%s() may write into memory pointed by R%d type=%s\n", 8193 func_id_name(meta->func_id), 8194 regno, reg_type_str(env, reg->type)); 8195 return -EACCES; 8196 } 8197 return 0; 8198 } 8199 8200 switch ((int)reg->type) { 8201 case PTR_TO_BTF_ID: 8202 case PTR_TO_BTF_ID | PTR_TRUSTED: 8203 case PTR_TO_BTF_ID | MEM_RCU: 8204 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 8205 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 8206 { 8207 /* For bpf_sk_release, it needs to match against first member 8208 * 'struct sock_common', hence make an exception for it. This 8209 * allows bpf_sk_release to work for multiple socket types. 8210 */ 8211 bool strict_type_match = arg_type_is_release(arg_type) && 8212 meta->func_id != BPF_FUNC_sk_release; 8213 8214 if (type_may_be_null(reg->type) && 8215 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 8216 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 8217 return -EACCES; 8218 } 8219 8220 if (!arg_btf_id) { 8221 if (!compatible->btf_id) { 8222 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 8223 return -EFAULT; 8224 } 8225 arg_btf_id = compatible->btf_id; 8226 } 8227 8228 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8229 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8230 return -EACCES; 8231 } else { 8232 if (arg_btf_id == BPF_PTR_POISON) { 8233 verbose(env, "verifier internal error:"); 8234 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 8235 regno); 8236 return -EACCES; 8237 } 8238 8239 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 8240 btf_vmlinux, *arg_btf_id, 8241 strict_type_match)) { 8242 verbose(env, "R%d is of type %s but %s is expected\n", 8243 regno, btf_type_name(reg->btf, reg->btf_id), 8244 btf_type_name(btf_vmlinux, *arg_btf_id)); 8245 return -EACCES; 8246 } 8247 } 8248 break; 8249 } 8250 case PTR_TO_BTF_ID | MEM_ALLOC: 8251 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 8252 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8253 meta->func_id != BPF_FUNC_kptr_xchg) { 8254 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 8255 return -EFAULT; 8256 } 8257 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8258 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8259 return -EACCES; 8260 } 8261 break; 8262 case PTR_TO_BTF_ID | MEM_PERCPU: 8263 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 8264 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8265 /* Handled by helper specific checks */ 8266 break; 8267 default: 8268 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 8269 return -EFAULT; 8270 } 8271 return 0; 8272 } 8273 8274 static struct btf_field * 8275 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8276 { 8277 struct btf_field *field; 8278 struct btf_record *rec; 8279 8280 rec = reg_btf_record(reg); 8281 if (!rec) 8282 return NULL; 8283 8284 field = btf_record_find(rec, off, fields); 8285 if (!field) 8286 return NULL; 8287 8288 return field; 8289 } 8290 8291 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 8292 const struct bpf_reg_state *reg, int regno, 8293 enum bpf_arg_type arg_type) 8294 { 8295 u32 type = reg->type; 8296 8297 /* When referenced register is passed to release function, its fixed 8298 * offset must be 0. 8299 * 8300 * We will check arg_type_is_release reg has ref_obj_id when storing 8301 * meta->release_regno. 8302 */ 8303 if (arg_type_is_release(arg_type)) { 8304 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8305 * may not directly point to the object being released, but to 8306 * dynptr pointing to such object, which might be at some offset 8307 * on the stack. In that case, we simply to fallback to the 8308 * default handling. 8309 */ 8310 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8311 return 0; 8312 8313 /* Doing check_ptr_off_reg check for the offset will catch this 8314 * because fixed_off_ok is false, but checking here allows us 8315 * to give the user a better error message. 8316 */ 8317 if (reg->off) { 8318 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 8319 regno); 8320 return -EINVAL; 8321 } 8322 return __check_ptr_off_reg(env, reg, regno, false); 8323 } 8324 8325 switch (type) { 8326 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8327 case PTR_TO_STACK: 8328 case PTR_TO_PACKET: 8329 case PTR_TO_PACKET_META: 8330 case PTR_TO_MAP_KEY: 8331 case PTR_TO_MAP_VALUE: 8332 case PTR_TO_MEM: 8333 case PTR_TO_MEM | MEM_RDONLY: 8334 case PTR_TO_MEM | MEM_RINGBUF: 8335 case PTR_TO_BUF: 8336 case PTR_TO_BUF | MEM_RDONLY: 8337 case SCALAR_VALUE: 8338 return 0; 8339 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8340 * fixed offset. 8341 */ 8342 case PTR_TO_BTF_ID: 8343 case PTR_TO_BTF_ID | MEM_ALLOC: 8344 case PTR_TO_BTF_ID | PTR_TRUSTED: 8345 case PTR_TO_BTF_ID | MEM_RCU: 8346 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8347 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8348 /* When referenced PTR_TO_BTF_ID is passed to release function, 8349 * its fixed offset must be 0. In the other cases, fixed offset 8350 * can be non-zero. This was already checked above. So pass 8351 * fixed_off_ok as true to allow fixed offset for all other 8352 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8353 * still need to do checks instead of returning. 8354 */ 8355 return __check_ptr_off_reg(env, reg, regno, true); 8356 default: 8357 return __check_ptr_off_reg(env, reg, regno, false); 8358 } 8359 } 8360 8361 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8362 const struct bpf_func_proto *fn, 8363 struct bpf_reg_state *regs) 8364 { 8365 struct bpf_reg_state *state = NULL; 8366 int i; 8367 8368 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8369 if (arg_type_is_dynptr(fn->arg_type[i])) { 8370 if (state) { 8371 verbose(env, "verifier internal error: multiple dynptr args\n"); 8372 return NULL; 8373 } 8374 state = ®s[BPF_REG_1 + i]; 8375 } 8376 8377 if (!state) 8378 verbose(env, "verifier internal error: no dynptr arg found\n"); 8379 8380 return state; 8381 } 8382 8383 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8384 { 8385 struct bpf_func_state *state = func(env, reg); 8386 int spi; 8387 8388 if (reg->type == CONST_PTR_TO_DYNPTR) 8389 return reg->id; 8390 spi = dynptr_get_spi(env, reg); 8391 if (spi < 0) 8392 return spi; 8393 return state->stack[spi].spilled_ptr.id; 8394 } 8395 8396 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8397 { 8398 struct bpf_func_state *state = func(env, reg); 8399 int spi; 8400 8401 if (reg->type == CONST_PTR_TO_DYNPTR) 8402 return reg->ref_obj_id; 8403 spi = dynptr_get_spi(env, reg); 8404 if (spi < 0) 8405 return spi; 8406 return state->stack[spi].spilled_ptr.ref_obj_id; 8407 } 8408 8409 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8410 struct bpf_reg_state *reg) 8411 { 8412 struct bpf_func_state *state = func(env, reg); 8413 int spi; 8414 8415 if (reg->type == CONST_PTR_TO_DYNPTR) 8416 return reg->dynptr.type; 8417 8418 spi = __get_spi(reg->off); 8419 if (spi < 0) { 8420 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8421 return BPF_DYNPTR_TYPE_INVALID; 8422 } 8423 8424 return state->stack[spi].spilled_ptr.dynptr.type; 8425 } 8426 8427 static int check_reg_const_str(struct bpf_verifier_env *env, 8428 struct bpf_reg_state *reg, u32 regno) 8429 { 8430 struct bpf_map *map = reg->map_ptr; 8431 int err; 8432 int map_off; 8433 u64 map_addr; 8434 char *str_ptr; 8435 8436 if (reg->type != PTR_TO_MAP_VALUE) 8437 return -EINVAL; 8438 8439 if (!bpf_map_is_rdonly(map)) { 8440 verbose(env, "R%d does not point to a readonly map'\n", regno); 8441 return -EACCES; 8442 } 8443 8444 if (!tnum_is_const(reg->var_off)) { 8445 verbose(env, "R%d is not a constant address'\n", regno); 8446 return -EACCES; 8447 } 8448 8449 if (!map->ops->map_direct_value_addr) { 8450 verbose(env, "no direct value access support for this map type\n"); 8451 return -EACCES; 8452 } 8453 8454 err = check_map_access(env, regno, reg->off, 8455 map->value_size - reg->off, false, 8456 ACCESS_HELPER); 8457 if (err) 8458 return err; 8459 8460 map_off = reg->off + reg->var_off.value; 8461 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8462 if (err) { 8463 verbose(env, "direct value access on string failed\n"); 8464 return err; 8465 } 8466 8467 str_ptr = (char *)(long)(map_addr); 8468 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8469 verbose(env, "string is not zero-terminated\n"); 8470 return -EINVAL; 8471 } 8472 return 0; 8473 } 8474 8475 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8476 struct bpf_call_arg_meta *meta, 8477 const struct bpf_func_proto *fn, 8478 int insn_idx) 8479 { 8480 u32 regno = BPF_REG_1 + arg; 8481 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8482 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8483 enum bpf_reg_type type = reg->type; 8484 u32 *arg_btf_id = NULL; 8485 int err = 0; 8486 8487 if (arg_type == ARG_DONTCARE) 8488 return 0; 8489 8490 err = check_reg_arg(env, regno, SRC_OP); 8491 if (err) 8492 return err; 8493 8494 if (arg_type == ARG_ANYTHING) { 8495 if (is_pointer_value(env, regno)) { 8496 verbose(env, "R%d leaks addr into helper function\n", 8497 regno); 8498 return -EACCES; 8499 } 8500 return 0; 8501 } 8502 8503 if (type_is_pkt_pointer(type) && 8504 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8505 verbose(env, "helper access to the packet is not allowed\n"); 8506 return -EACCES; 8507 } 8508 8509 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8510 err = resolve_map_arg_type(env, meta, &arg_type); 8511 if (err) 8512 return err; 8513 } 8514 8515 if (register_is_null(reg) && type_may_be_null(arg_type)) 8516 /* A NULL register has a SCALAR_VALUE type, so skip 8517 * type checking. 8518 */ 8519 goto skip_type_check; 8520 8521 /* arg_btf_id and arg_size are in a union. */ 8522 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8523 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8524 arg_btf_id = fn->arg_btf_id[arg]; 8525 8526 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 8527 if (err) 8528 return err; 8529 8530 err = check_func_arg_reg_off(env, reg, regno, arg_type); 8531 if (err) 8532 return err; 8533 8534 skip_type_check: 8535 if (arg_type_is_release(arg_type)) { 8536 if (arg_type_is_dynptr(arg_type)) { 8537 struct bpf_func_state *state = func(env, reg); 8538 int spi; 8539 8540 /* Only dynptr created on stack can be released, thus 8541 * the get_spi and stack state checks for spilled_ptr 8542 * should only be done before process_dynptr_func for 8543 * PTR_TO_STACK. 8544 */ 8545 if (reg->type == PTR_TO_STACK) { 8546 spi = dynptr_get_spi(env, reg); 8547 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8548 verbose(env, "arg %d is an unacquired reference\n", regno); 8549 return -EINVAL; 8550 } 8551 } else { 8552 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8553 return -EINVAL; 8554 } 8555 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 8556 verbose(env, "R%d must be referenced when passed to release function\n", 8557 regno); 8558 return -EINVAL; 8559 } 8560 if (meta->release_regno) { 8561 verbose(env, "verifier internal error: more than one release argument\n"); 8562 return -EFAULT; 8563 } 8564 meta->release_regno = regno; 8565 } 8566 8567 if (reg->ref_obj_id) { 8568 if (meta->ref_obj_id) { 8569 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 8570 regno, reg->ref_obj_id, 8571 meta->ref_obj_id); 8572 return -EFAULT; 8573 } 8574 meta->ref_obj_id = reg->ref_obj_id; 8575 } 8576 8577 switch (base_type(arg_type)) { 8578 case ARG_CONST_MAP_PTR: 8579 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8580 if (meta->map_ptr) { 8581 /* Use map_uid (which is unique id of inner map) to reject: 8582 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8583 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8584 * if (inner_map1 && inner_map2) { 8585 * timer = bpf_map_lookup_elem(inner_map1); 8586 * if (timer) 8587 * // mismatch would have been allowed 8588 * bpf_timer_init(timer, inner_map2); 8589 * } 8590 * 8591 * Comparing map_ptr is enough to distinguish normal and outer maps. 8592 */ 8593 if (meta->map_ptr != reg->map_ptr || 8594 meta->map_uid != reg->map_uid) { 8595 verbose(env, 8596 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8597 meta->map_uid, reg->map_uid); 8598 return -EINVAL; 8599 } 8600 } 8601 meta->map_ptr = reg->map_ptr; 8602 meta->map_uid = reg->map_uid; 8603 break; 8604 case ARG_PTR_TO_MAP_KEY: 8605 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8606 * check that [key, key + map->key_size) are within 8607 * stack limits and initialized 8608 */ 8609 if (!meta->map_ptr) { 8610 /* in function declaration map_ptr must come before 8611 * map_key, so that it's verified and known before 8612 * we have to check map_key here. Otherwise it means 8613 * that kernel subsystem misconfigured verifier 8614 */ 8615 verbose(env, "invalid map_ptr to access map->key\n"); 8616 return -EACCES; 8617 } 8618 err = check_helper_mem_access(env, regno, 8619 meta->map_ptr->key_size, false, 8620 NULL); 8621 break; 8622 case ARG_PTR_TO_MAP_VALUE: 8623 if (type_may_be_null(arg_type) && register_is_null(reg)) 8624 return 0; 8625 8626 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8627 * check [value, value + map->value_size) validity 8628 */ 8629 if (!meta->map_ptr) { 8630 /* kernel subsystem misconfigured verifier */ 8631 verbose(env, "invalid map_ptr to access map->value\n"); 8632 return -EACCES; 8633 } 8634 meta->raw_mode = arg_type & MEM_UNINIT; 8635 err = check_helper_mem_access(env, regno, 8636 meta->map_ptr->value_size, false, 8637 meta); 8638 break; 8639 case ARG_PTR_TO_PERCPU_BTF_ID: 8640 if (!reg->btf_id) { 8641 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8642 return -EACCES; 8643 } 8644 meta->ret_btf = reg->btf; 8645 meta->ret_btf_id = reg->btf_id; 8646 break; 8647 case ARG_PTR_TO_SPIN_LOCK: 8648 if (in_rbtree_lock_required_cb(env)) { 8649 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8650 return -EACCES; 8651 } 8652 if (meta->func_id == BPF_FUNC_spin_lock) { 8653 err = process_spin_lock(env, regno, true); 8654 if (err) 8655 return err; 8656 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8657 err = process_spin_lock(env, regno, false); 8658 if (err) 8659 return err; 8660 } else { 8661 verbose(env, "verifier internal error\n"); 8662 return -EFAULT; 8663 } 8664 break; 8665 case ARG_PTR_TO_TIMER: 8666 err = process_timer_func(env, regno, meta); 8667 if (err) 8668 return err; 8669 break; 8670 case ARG_PTR_TO_FUNC: 8671 meta->subprogno = reg->subprogno; 8672 break; 8673 case ARG_PTR_TO_MEM: 8674 /* The access to this pointer is only checked when we hit the 8675 * next is_mem_size argument below. 8676 */ 8677 meta->raw_mode = arg_type & MEM_UNINIT; 8678 if (arg_type & MEM_FIXED_SIZE) { 8679 err = check_helper_mem_access(env, regno, 8680 fn->arg_size[arg], false, 8681 meta); 8682 } 8683 break; 8684 case ARG_CONST_SIZE: 8685 err = check_mem_size_reg(env, reg, regno, false, meta); 8686 break; 8687 case ARG_CONST_SIZE_OR_ZERO: 8688 err = check_mem_size_reg(env, reg, regno, true, meta); 8689 break; 8690 case ARG_PTR_TO_DYNPTR: 8691 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 8692 if (err) 8693 return err; 8694 break; 8695 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8696 if (!tnum_is_const(reg->var_off)) { 8697 verbose(env, "R%d is not a known constant'\n", 8698 regno); 8699 return -EACCES; 8700 } 8701 meta->mem_size = reg->var_off.value; 8702 err = mark_chain_precision(env, regno); 8703 if (err) 8704 return err; 8705 break; 8706 case ARG_PTR_TO_INT: 8707 case ARG_PTR_TO_LONG: 8708 { 8709 int size = int_ptr_type_to_size(arg_type); 8710 8711 err = check_helper_mem_access(env, regno, size, false, meta); 8712 if (err) 8713 return err; 8714 err = check_ptr_alignment(env, reg, 0, size, true); 8715 break; 8716 } 8717 case ARG_PTR_TO_CONST_STR: 8718 { 8719 err = check_reg_const_str(env, reg, regno); 8720 if (err) 8721 return err; 8722 break; 8723 } 8724 case ARG_PTR_TO_KPTR: 8725 err = process_kptr_func(env, regno, meta); 8726 if (err) 8727 return err; 8728 break; 8729 } 8730 8731 return err; 8732 } 8733 8734 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8735 { 8736 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8737 enum bpf_prog_type type = resolve_prog_type(env->prog); 8738 8739 if (func_id != BPF_FUNC_map_update_elem) 8740 return false; 8741 8742 /* It's not possible to get access to a locked struct sock in these 8743 * contexts, so updating is safe. 8744 */ 8745 switch (type) { 8746 case BPF_PROG_TYPE_TRACING: 8747 if (eatype == BPF_TRACE_ITER) 8748 return true; 8749 break; 8750 case BPF_PROG_TYPE_SOCKET_FILTER: 8751 case BPF_PROG_TYPE_SCHED_CLS: 8752 case BPF_PROG_TYPE_SCHED_ACT: 8753 case BPF_PROG_TYPE_XDP: 8754 case BPF_PROG_TYPE_SK_REUSEPORT: 8755 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8756 case BPF_PROG_TYPE_SK_LOOKUP: 8757 return true; 8758 default: 8759 break; 8760 } 8761 8762 verbose(env, "cannot update sockmap in this context\n"); 8763 return false; 8764 } 8765 8766 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8767 { 8768 return env->prog->jit_requested && 8769 bpf_jit_supports_subprog_tailcalls(); 8770 } 8771 8772 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8773 struct bpf_map *map, int func_id) 8774 { 8775 if (!map) 8776 return 0; 8777 8778 /* We need a two way check, first is from map perspective ... */ 8779 switch (map->map_type) { 8780 case BPF_MAP_TYPE_PROG_ARRAY: 8781 if (func_id != BPF_FUNC_tail_call) 8782 goto error; 8783 break; 8784 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8785 if (func_id != BPF_FUNC_perf_event_read && 8786 func_id != BPF_FUNC_perf_event_output && 8787 func_id != BPF_FUNC_skb_output && 8788 func_id != BPF_FUNC_perf_event_read_value && 8789 func_id != BPF_FUNC_xdp_output) 8790 goto error; 8791 break; 8792 case BPF_MAP_TYPE_RINGBUF: 8793 if (func_id != BPF_FUNC_ringbuf_output && 8794 func_id != BPF_FUNC_ringbuf_reserve && 8795 func_id != BPF_FUNC_ringbuf_query && 8796 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8797 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8798 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8799 goto error; 8800 break; 8801 case BPF_MAP_TYPE_USER_RINGBUF: 8802 if (func_id != BPF_FUNC_user_ringbuf_drain) 8803 goto error; 8804 break; 8805 case BPF_MAP_TYPE_STACK_TRACE: 8806 if (func_id != BPF_FUNC_get_stackid) 8807 goto error; 8808 break; 8809 case BPF_MAP_TYPE_CGROUP_ARRAY: 8810 if (func_id != BPF_FUNC_skb_under_cgroup && 8811 func_id != BPF_FUNC_current_task_under_cgroup) 8812 goto error; 8813 break; 8814 case BPF_MAP_TYPE_CGROUP_STORAGE: 8815 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8816 if (func_id != BPF_FUNC_get_local_storage) 8817 goto error; 8818 break; 8819 case BPF_MAP_TYPE_DEVMAP: 8820 case BPF_MAP_TYPE_DEVMAP_HASH: 8821 if (func_id != BPF_FUNC_redirect_map && 8822 func_id != BPF_FUNC_map_lookup_elem) 8823 goto error; 8824 break; 8825 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8826 * appear. 8827 */ 8828 case BPF_MAP_TYPE_CPUMAP: 8829 if (func_id != BPF_FUNC_redirect_map) 8830 goto error; 8831 break; 8832 case BPF_MAP_TYPE_XSKMAP: 8833 if (func_id != BPF_FUNC_redirect_map && 8834 func_id != BPF_FUNC_map_lookup_elem) 8835 goto error; 8836 break; 8837 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8838 case BPF_MAP_TYPE_HASH_OF_MAPS: 8839 if (func_id != BPF_FUNC_map_lookup_elem) 8840 goto error; 8841 break; 8842 case BPF_MAP_TYPE_SOCKMAP: 8843 if (func_id != BPF_FUNC_sk_redirect_map && 8844 func_id != BPF_FUNC_sock_map_update && 8845 func_id != BPF_FUNC_map_delete_elem && 8846 func_id != BPF_FUNC_msg_redirect_map && 8847 func_id != BPF_FUNC_sk_select_reuseport && 8848 func_id != BPF_FUNC_map_lookup_elem && 8849 !may_update_sockmap(env, func_id)) 8850 goto error; 8851 break; 8852 case BPF_MAP_TYPE_SOCKHASH: 8853 if (func_id != BPF_FUNC_sk_redirect_hash && 8854 func_id != BPF_FUNC_sock_hash_update && 8855 func_id != BPF_FUNC_map_delete_elem && 8856 func_id != BPF_FUNC_msg_redirect_hash && 8857 func_id != BPF_FUNC_sk_select_reuseport && 8858 func_id != BPF_FUNC_map_lookup_elem && 8859 !may_update_sockmap(env, func_id)) 8860 goto error; 8861 break; 8862 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8863 if (func_id != BPF_FUNC_sk_select_reuseport) 8864 goto error; 8865 break; 8866 case BPF_MAP_TYPE_QUEUE: 8867 case BPF_MAP_TYPE_STACK: 8868 if (func_id != BPF_FUNC_map_peek_elem && 8869 func_id != BPF_FUNC_map_pop_elem && 8870 func_id != BPF_FUNC_map_push_elem) 8871 goto error; 8872 break; 8873 case BPF_MAP_TYPE_SK_STORAGE: 8874 if (func_id != BPF_FUNC_sk_storage_get && 8875 func_id != BPF_FUNC_sk_storage_delete && 8876 func_id != BPF_FUNC_kptr_xchg) 8877 goto error; 8878 break; 8879 case BPF_MAP_TYPE_INODE_STORAGE: 8880 if (func_id != BPF_FUNC_inode_storage_get && 8881 func_id != BPF_FUNC_inode_storage_delete && 8882 func_id != BPF_FUNC_kptr_xchg) 8883 goto error; 8884 break; 8885 case BPF_MAP_TYPE_TASK_STORAGE: 8886 if (func_id != BPF_FUNC_task_storage_get && 8887 func_id != BPF_FUNC_task_storage_delete && 8888 func_id != BPF_FUNC_kptr_xchg) 8889 goto error; 8890 break; 8891 case BPF_MAP_TYPE_CGRP_STORAGE: 8892 if (func_id != BPF_FUNC_cgrp_storage_get && 8893 func_id != BPF_FUNC_cgrp_storage_delete && 8894 func_id != BPF_FUNC_kptr_xchg) 8895 goto error; 8896 break; 8897 case BPF_MAP_TYPE_BLOOM_FILTER: 8898 if (func_id != BPF_FUNC_map_peek_elem && 8899 func_id != BPF_FUNC_map_push_elem) 8900 goto error; 8901 break; 8902 default: 8903 break; 8904 } 8905 8906 /* ... and second from the function itself. */ 8907 switch (func_id) { 8908 case BPF_FUNC_tail_call: 8909 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8910 goto error; 8911 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 8912 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 8913 return -EINVAL; 8914 } 8915 break; 8916 case BPF_FUNC_perf_event_read: 8917 case BPF_FUNC_perf_event_output: 8918 case BPF_FUNC_perf_event_read_value: 8919 case BPF_FUNC_skb_output: 8920 case BPF_FUNC_xdp_output: 8921 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 8922 goto error; 8923 break; 8924 case BPF_FUNC_ringbuf_output: 8925 case BPF_FUNC_ringbuf_reserve: 8926 case BPF_FUNC_ringbuf_query: 8927 case BPF_FUNC_ringbuf_reserve_dynptr: 8928 case BPF_FUNC_ringbuf_submit_dynptr: 8929 case BPF_FUNC_ringbuf_discard_dynptr: 8930 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 8931 goto error; 8932 break; 8933 case BPF_FUNC_user_ringbuf_drain: 8934 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 8935 goto error; 8936 break; 8937 case BPF_FUNC_get_stackid: 8938 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 8939 goto error; 8940 break; 8941 case BPF_FUNC_current_task_under_cgroup: 8942 case BPF_FUNC_skb_under_cgroup: 8943 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 8944 goto error; 8945 break; 8946 case BPF_FUNC_redirect_map: 8947 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 8948 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 8949 map->map_type != BPF_MAP_TYPE_CPUMAP && 8950 map->map_type != BPF_MAP_TYPE_XSKMAP) 8951 goto error; 8952 break; 8953 case BPF_FUNC_sk_redirect_map: 8954 case BPF_FUNC_msg_redirect_map: 8955 case BPF_FUNC_sock_map_update: 8956 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 8957 goto error; 8958 break; 8959 case BPF_FUNC_sk_redirect_hash: 8960 case BPF_FUNC_msg_redirect_hash: 8961 case BPF_FUNC_sock_hash_update: 8962 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 8963 goto error; 8964 break; 8965 case BPF_FUNC_get_local_storage: 8966 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 8967 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 8968 goto error; 8969 break; 8970 case BPF_FUNC_sk_select_reuseport: 8971 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 8972 map->map_type != BPF_MAP_TYPE_SOCKMAP && 8973 map->map_type != BPF_MAP_TYPE_SOCKHASH) 8974 goto error; 8975 break; 8976 case BPF_FUNC_map_pop_elem: 8977 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8978 map->map_type != BPF_MAP_TYPE_STACK) 8979 goto error; 8980 break; 8981 case BPF_FUNC_map_peek_elem: 8982 case BPF_FUNC_map_push_elem: 8983 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8984 map->map_type != BPF_MAP_TYPE_STACK && 8985 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 8986 goto error; 8987 break; 8988 case BPF_FUNC_map_lookup_percpu_elem: 8989 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 8990 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 8991 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 8992 goto error; 8993 break; 8994 case BPF_FUNC_sk_storage_get: 8995 case BPF_FUNC_sk_storage_delete: 8996 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 8997 goto error; 8998 break; 8999 case BPF_FUNC_inode_storage_get: 9000 case BPF_FUNC_inode_storage_delete: 9001 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 9002 goto error; 9003 break; 9004 case BPF_FUNC_task_storage_get: 9005 case BPF_FUNC_task_storage_delete: 9006 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 9007 goto error; 9008 break; 9009 case BPF_FUNC_cgrp_storage_get: 9010 case BPF_FUNC_cgrp_storage_delete: 9011 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 9012 goto error; 9013 break; 9014 default: 9015 break; 9016 } 9017 9018 return 0; 9019 error: 9020 verbose(env, "cannot pass map_type %d into func %s#%d\n", 9021 map->map_type, func_id_name(func_id), func_id); 9022 return -EINVAL; 9023 } 9024 9025 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 9026 { 9027 int count = 0; 9028 9029 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 9030 count++; 9031 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 9032 count++; 9033 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 9034 count++; 9035 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 9036 count++; 9037 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 9038 count++; 9039 9040 /* We only support one arg being in raw mode at the moment, 9041 * which is sufficient for the helper functions we have 9042 * right now. 9043 */ 9044 return count <= 1; 9045 } 9046 9047 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 9048 { 9049 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 9050 bool has_size = fn->arg_size[arg] != 0; 9051 bool is_next_size = false; 9052 9053 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 9054 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 9055 9056 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 9057 return is_next_size; 9058 9059 return has_size == is_next_size || is_next_size == is_fixed; 9060 } 9061 9062 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 9063 { 9064 /* bpf_xxx(..., buf, len) call will access 'len' 9065 * bytes from memory 'buf'. Both arg types need 9066 * to be paired, so make sure there's no buggy 9067 * helper function specification. 9068 */ 9069 if (arg_type_is_mem_size(fn->arg1_type) || 9070 check_args_pair_invalid(fn, 0) || 9071 check_args_pair_invalid(fn, 1) || 9072 check_args_pair_invalid(fn, 2) || 9073 check_args_pair_invalid(fn, 3) || 9074 check_args_pair_invalid(fn, 4)) 9075 return false; 9076 9077 return true; 9078 } 9079 9080 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 9081 { 9082 int i; 9083 9084 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 9085 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 9086 return !!fn->arg_btf_id[i]; 9087 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 9088 return fn->arg_btf_id[i] == BPF_PTR_POISON; 9089 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 9090 /* arg_btf_id and arg_size are in a union. */ 9091 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 9092 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 9093 return false; 9094 } 9095 9096 return true; 9097 } 9098 9099 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 9100 { 9101 return check_raw_mode_ok(fn) && 9102 check_arg_pair_ok(fn) && 9103 check_btf_id_ok(fn) ? 0 : -EINVAL; 9104 } 9105 9106 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 9107 * are now invalid, so turn them into unknown SCALAR_VALUE. 9108 * 9109 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 9110 * since these slices point to packet data. 9111 */ 9112 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 9113 { 9114 struct bpf_func_state *state; 9115 struct bpf_reg_state *reg; 9116 9117 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9118 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 9119 mark_reg_invalid(env, reg); 9120 })); 9121 } 9122 9123 enum { 9124 AT_PKT_END = -1, 9125 BEYOND_PKT_END = -2, 9126 }; 9127 9128 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 9129 { 9130 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9131 struct bpf_reg_state *reg = &state->regs[regn]; 9132 9133 if (reg->type != PTR_TO_PACKET) 9134 /* PTR_TO_PACKET_META is not supported yet */ 9135 return; 9136 9137 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 9138 * How far beyond pkt_end it goes is unknown. 9139 * if (!range_open) it's the case of pkt >= pkt_end 9140 * if (range_open) it's the case of pkt > pkt_end 9141 * hence this pointer is at least 1 byte bigger than pkt_end 9142 */ 9143 if (range_open) 9144 reg->range = BEYOND_PKT_END; 9145 else 9146 reg->range = AT_PKT_END; 9147 } 9148 9149 /* The pointer with the specified id has released its reference to kernel 9150 * resources. Identify all copies of the same pointer and clear the reference. 9151 */ 9152 static int release_reference(struct bpf_verifier_env *env, 9153 int ref_obj_id) 9154 { 9155 struct bpf_func_state *state; 9156 struct bpf_reg_state *reg; 9157 int err; 9158 9159 err = release_reference_state(cur_func(env), ref_obj_id); 9160 if (err) 9161 return err; 9162 9163 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9164 if (reg->ref_obj_id == ref_obj_id) 9165 mark_reg_invalid(env, reg); 9166 })); 9167 9168 return 0; 9169 } 9170 9171 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9172 { 9173 struct bpf_func_state *unused; 9174 struct bpf_reg_state *reg; 9175 9176 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9177 if (type_is_non_owning_ref(reg->type)) 9178 mark_reg_invalid(env, reg); 9179 })); 9180 } 9181 9182 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9183 struct bpf_reg_state *regs) 9184 { 9185 int i; 9186 9187 /* after the call registers r0 - r5 were scratched */ 9188 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9189 mark_reg_not_init(env, regs, caller_saved[i]); 9190 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9191 } 9192 } 9193 9194 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9195 struct bpf_func_state *caller, 9196 struct bpf_func_state *callee, 9197 int insn_idx); 9198 9199 static int set_callee_state(struct bpf_verifier_env *env, 9200 struct bpf_func_state *caller, 9201 struct bpf_func_state *callee, int insn_idx); 9202 9203 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9204 set_callee_state_fn set_callee_state_cb, 9205 struct bpf_verifier_state *state) 9206 { 9207 struct bpf_func_state *caller, *callee; 9208 int err; 9209 9210 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9211 verbose(env, "the call stack of %d frames is too deep\n", 9212 state->curframe + 2); 9213 return -E2BIG; 9214 } 9215 9216 if (state->frame[state->curframe + 1]) { 9217 verbose(env, "verifier bug. Frame %d already allocated\n", 9218 state->curframe + 1); 9219 return -EFAULT; 9220 } 9221 9222 caller = state->frame[state->curframe]; 9223 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 9224 if (!callee) 9225 return -ENOMEM; 9226 state->frame[state->curframe + 1] = callee; 9227 9228 /* callee cannot access r0, r6 - r9 for reading and has to write 9229 * into its own stack before reading from it. 9230 * callee can read/write into caller's stack 9231 */ 9232 init_func_state(env, callee, 9233 /* remember the callsite, it will be used by bpf_exit */ 9234 callsite, 9235 state->curframe + 1 /* frameno within this callchain */, 9236 subprog /* subprog number within this prog */); 9237 /* Transfer references to the callee */ 9238 err = copy_reference_state(callee, caller); 9239 err = err ?: set_callee_state_cb(env, caller, callee, callsite); 9240 if (err) 9241 goto err_out; 9242 9243 /* only increment it after check_reg_arg() finished */ 9244 state->curframe++; 9245 9246 return 0; 9247 9248 err_out: 9249 free_func_state(callee); 9250 state->frame[state->curframe + 1] = NULL; 9251 return err; 9252 } 9253 9254 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, 9255 const struct btf *btf, 9256 struct bpf_reg_state *regs) 9257 { 9258 struct bpf_subprog_info *sub = subprog_info(env, subprog); 9259 struct bpf_verifier_log *log = &env->log; 9260 u32 i; 9261 int ret; 9262 9263 ret = btf_prepare_func_args(env, subprog); 9264 if (ret) 9265 return ret; 9266 9267 /* check that BTF function arguments match actual types that the 9268 * verifier sees. 9269 */ 9270 for (i = 0; i < sub->arg_cnt; i++) { 9271 u32 regno = i + 1; 9272 struct bpf_reg_state *reg = ®s[regno]; 9273 struct bpf_subprog_arg_info *arg = &sub->args[i]; 9274 9275 if (arg->arg_type == ARG_ANYTHING) { 9276 if (reg->type != SCALAR_VALUE) { 9277 bpf_log(log, "R%d is not a scalar\n", regno); 9278 return -EINVAL; 9279 } 9280 } else if (arg->arg_type == ARG_PTR_TO_CTX) { 9281 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9282 if (ret < 0) 9283 return ret; 9284 /* If function expects ctx type in BTF check that caller 9285 * is passing PTR_TO_CTX. 9286 */ 9287 if (reg->type != PTR_TO_CTX) { 9288 bpf_log(log, "arg#%d expects pointer to ctx\n", i); 9289 return -EINVAL; 9290 } 9291 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 9292 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9293 if (ret < 0) 9294 return ret; 9295 if (check_mem_reg(env, reg, regno, arg->mem_size)) 9296 return -EINVAL; 9297 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) { 9298 bpf_log(log, "arg#%d is expected to be non-NULL\n", i); 9299 return -EINVAL; 9300 } 9301 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 9302 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0); 9303 if (ret) 9304 return ret; 9305 } else { 9306 bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n", 9307 i, arg->arg_type); 9308 return -EFAULT; 9309 } 9310 } 9311 9312 return 0; 9313 } 9314 9315 /* Compare BTF of a function call with given bpf_reg_state. 9316 * Returns: 9317 * EFAULT - there is a verifier bug. Abort verification. 9318 * EINVAL - there is a type mismatch or BTF is not available. 9319 * 0 - BTF matches with what bpf_reg_state expects. 9320 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized. 9321 */ 9322 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog, 9323 struct bpf_reg_state *regs) 9324 { 9325 struct bpf_prog *prog = env->prog; 9326 struct btf *btf = prog->aux->btf; 9327 u32 btf_id; 9328 int err; 9329 9330 if (!prog->aux->func_info) 9331 return -EINVAL; 9332 9333 btf_id = prog->aux->func_info[subprog].type_id; 9334 if (!btf_id) 9335 return -EFAULT; 9336 9337 if (prog->aux->func_info_aux[subprog].unreliable) 9338 return -EINVAL; 9339 9340 err = btf_check_func_arg_match(env, subprog, btf, regs); 9341 /* Compiler optimizations can remove arguments from static functions 9342 * or mismatched type can be passed into a global function. 9343 * In such cases mark the function as unreliable from BTF point of view. 9344 */ 9345 if (err) 9346 prog->aux->func_info_aux[subprog].unreliable = true; 9347 return err; 9348 } 9349 9350 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9351 int insn_idx, int subprog, 9352 set_callee_state_fn set_callee_state_cb) 9353 { 9354 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9355 struct bpf_func_state *caller, *callee; 9356 int err; 9357 9358 caller = state->frame[state->curframe]; 9359 err = btf_check_subprog_call(env, subprog, caller->regs); 9360 if (err == -EFAULT) 9361 return err; 9362 9363 /* set_callee_state is used for direct subprog calls, but we are 9364 * interested in validating only BPF helpers that can call subprogs as 9365 * callbacks 9366 */ 9367 env->subprog_info[subprog].is_cb = true; 9368 if (bpf_pseudo_kfunc_call(insn) && 9369 !is_sync_callback_calling_kfunc(insn->imm)) { 9370 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 9371 func_id_name(insn->imm), insn->imm); 9372 return -EFAULT; 9373 } else if (!bpf_pseudo_kfunc_call(insn) && 9374 !is_callback_calling_function(insn->imm)) { /* helper */ 9375 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 9376 func_id_name(insn->imm), insn->imm); 9377 return -EFAULT; 9378 } 9379 9380 if (insn->code == (BPF_JMP | BPF_CALL) && 9381 insn->src_reg == 0 && 9382 insn->imm == BPF_FUNC_timer_set_callback) { 9383 struct bpf_verifier_state *async_cb; 9384 9385 /* there is no real recursion here. timer callbacks are async */ 9386 env->subprog_info[subprog].is_async_cb = true; 9387 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9388 insn_idx, subprog); 9389 if (!async_cb) 9390 return -EFAULT; 9391 callee = async_cb->frame[0]; 9392 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9393 9394 /* Convert bpf_timer_set_callback() args into timer callback args */ 9395 err = set_callee_state_cb(env, caller, callee, insn_idx); 9396 if (err) 9397 return err; 9398 9399 return 0; 9400 } 9401 9402 /* for callback functions enqueue entry to callback and 9403 * proceed with next instruction within current frame. 9404 */ 9405 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9406 if (!callback_state) 9407 return -ENOMEM; 9408 9409 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9410 callback_state); 9411 if (err) 9412 return err; 9413 9414 callback_state->callback_unroll_depth++; 9415 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9416 caller->callback_depth = 0; 9417 return 0; 9418 } 9419 9420 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9421 int *insn_idx) 9422 { 9423 struct bpf_verifier_state *state = env->cur_state; 9424 struct bpf_func_state *caller; 9425 int err, subprog, target_insn; 9426 9427 target_insn = *insn_idx + insn->imm + 1; 9428 subprog = find_subprog(env, target_insn); 9429 if (subprog < 0) { 9430 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn); 9431 return -EFAULT; 9432 } 9433 9434 caller = state->frame[state->curframe]; 9435 err = btf_check_subprog_call(env, subprog, caller->regs); 9436 if (err == -EFAULT) 9437 return err; 9438 if (subprog_is_global(env, subprog)) { 9439 const char *sub_name = subprog_name(env, subprog); 9440 9441 if (err) { 9442 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 9443 subprog, sub_name); 9444 return err; 9445 } 9446 9447 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 9448 subprog, sub_name); 9449 /* mark global subprog for verifying after main prog */ 9450 subprog_aux(env, subprog)->called = true; 9451 clear_caller_saved_regs(env, caller->regs); 9452 9453 /* All global functions return a 64-bit SCALAR_VALUE */ 9454 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9455 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9456 9457 /* continue with next insn after call */ 9458 return 0; 9459 } 9460 9461 /* for regular function entry setup new frame and continue 9462 * from that frame. 9463 */ 9464 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9465 if (err) 9466 return err; 9467 9468 clear_caller_saved_regs(env, caller->regs); 9469 9470 /* and go analyze first insn of the callee */ 9471 *insn_idx = env->subprog_info[subprog].start - 1; 9472 9473 if (env->log.level & BPF_LOG_LEVEL) { 9474 verbose(env, "caller:\n"); 9475 print_verifier_state(env, caller, true); 9476 verbose(env, "callee:\n"); 9477 print_verifier_state(env, state->frame[state->curframe], true); 9478 } 9479 9480 return 0; 9481 } 9482 9483 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9484 struct bpf_func_state *caller, 9485 struct bpf_func_state *callee) 9486 { 9487 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9488 * void *callback_ctx, u64 flags); 9489 * callback_fn(struct bpf_map *map, void *key, void *value, 9490 * void *callback_ctx); 9491 */ 9492 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9493 9494 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9495 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9496 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9497 9498 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9499 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9500 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9501 9502 /* pointer to stack or null */ 9503 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9504 9505 /* unused */ 9506 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9507 return 0; 9508 } 9509 9510 static int set_callee_state(struct bpf_verifier_env *env, 9511 struct bpf_func_state *caller, 9512 struct bpf_func_state *callee, int insn_idx) 9513 { 9514 int i; 9515 9516 /* copy r1 - r5 args that callee can access. The copy includes parent 9517 * pointers, which connects us up to the liveness chain 9518 */ 9519 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9520 callee->regs[i] = caller->regs[i]; 9521 return 0; 9522 } 9523 9524 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9525 struct bpf_func_state *caller, 9526 struct bpf_func_state *callee, 9527 int insn_idx) 9528 { 9529 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9530 struct bpf_map *map; 9531 int err; 9532 9533 if (bpf_map_ptr_poisoned(insn_aux)) { 9534 verbose(env, "tail_call abusing map_ptr\n"); 9535 return -EINVAL; 9536 } 9537 9538 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 9539 if (!map->ops->map_set_for_each_callback_args || 9540 !map->ops->map_for_each_callback) { 9541 verbose(env, "callback function not allowed for map\n"); 9542 return -ENOTSUPP; 9543 } 9544 9545 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9546 if (err) 9547 return err; 9548 9549 callee->in_callback_fn = true; 9550 callee->callback_ret_range = retval_range(0, 1); 9551 return 0; 9552 } 9553 9554 static int set_loop_callback_state(struct bpf_verifier_env *env, 9555 struct bpf_func_state *caller, 9556 struct bpf_func_state *callee, 9557 int insn_idx) 9558 { 9559 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9560 * u64 flags); 9561 * callback_fn(u32 index, void *callback_ctx); 9562 */ 9563 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9564 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9565 9566 /* unused */ 9567 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9568 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9569 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9570 9571 callee->in_callback_fn = true; 9572 callee->callback_ret_range = retval_range(0, 1); 9573 return 0; 9574 } 9575 9576 static int set_timer_callback_state(struct bpf_verifier_env *env, 9577 struct bpf_func_state *caller, 9578 struct bpf_func_state *callee, 9579 int insn_idx) 9580 { 9581 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9582 9583 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9584 * callback_fn(struct bpf_map *map, void *key, void *value); 9585 */ 9586 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9587 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9588 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9589 9590 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9591 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9592 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9593 9594 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9595 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9596 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9597 9598 /* unused */ 9599 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9600 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9601 callee->in_async_callback_fn = true; 9602 callee->callback_ret_range = retval_range(0, 1); 9603 return 0; 9604 } 9605 9606 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9607 struct bpf_func_state *caller, 9608 struct bpf_func_state *callee, 9609 int insn_idx) 9610 { 9611 /* bpf_find_vma(struct task_struct *task, u64 addr, 9612 * void *callback_fn, void *callback_ctx, u64 flags) 9613 * (callback_fn)(struct task_struct *task, 9614 * struct vm_area_struct *vma, void *callback_ctx); 9615 */ 9616 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9617 9618 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9619 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9620 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9621 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 9622 9623 /* pointer to stack or null */ 9624 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9625 9626 /* unused */ 9627 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9628 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9629 callee->in_callback_fn = true; 9630 callee->callback_ret_range = retval_range(0, 1); 9631 return 0; 9632 } 9633 9634 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9635 struct bpf_func_state *caller, 9636 struct bpf_func_state *callee, 9637 int insn_idx) 9638 { 9639 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9640 * callback_ctx, u64 flags); 9641 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9642 */ 9643 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9644 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9645 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9646 9647 /* unused */ 9648 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9649 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9650 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9651 9652 callee->in_callback_fn = true; 9653 callee->callback_ret_range = retval_range(0, 1); 9654 return 0; 9655 } 9656 9657 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9658 struct bpf_func_state *caller, 9659 struct bpf_func_state *callee, 9660 int insn_idx) 9661 { 9662 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9663 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9664 * 9665 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9666 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9667 * by this point, so look at 'root' 9668 */ 9669 struct btf_field *field; 9670 9671 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 9672 BPF_RB_ROOT); 9673 if (!field || !field->graph_root.value_btf_id) 9674 return -EFAULT; 9675 9676 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9677 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9678 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9679 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9680 9681 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9682 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9683 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9684 callee->in_callback_fn = true; 9685 callee->callback_ret_range = retval_range(0, 1); 9686 return 0; 9687 } 9688 9689 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9690 9691 /* Are we currently verifying the callback for a rbtree helper that must 9692 * be called with lock held? If so, no need to complain about unreleased 9693 * lock 9694 */ 9695 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9696 { 9697 struct bpf_verifier_state *state = env->cur_state; 9698 struct bpf_insn *insn = env->prog->insnsi; 9699 struct bpf_func_state *callee; 9700 int kfunc_btf_id; 9701 9702 if (!state->curframe) 9703 return false; 9704 9705 callee = state->frame[state->curframe]; 9706 9707 if (!callee->in_callback_fn) 9708 return false; 9709 9710 kfunc_btf_id = insn[callee->callsite].imm; 9711 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9712 } 9713 9714 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg) 9715 { 9716 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval; 9717 } 9718 9719 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9720 { 9721 struct bpf_verifier_state *state = env->cur_state, *prev_st; 9722 struct bpf_func_state *caller, *callee; 9723 struct bpf_reg_state *r0; 9724 bool in_callback_fn; 9725 int err; 9726 9727 callee = state->frame[state->curframe]; 9728 r0 = &callee->regs[BPF_REG_0]; 9729 if (r0->type == PTR_TO_STACK) { 9730 /* technically it's ok to return caller's stack pointer 9731 * (or caller's caller's pointer) back to the caller, 9732 * since these pointers are valid. Only current stack 9733 * pointer will be invalid as soon as function exits, 9734 * but let's be conservative 9735 */ 9736 verbose(env, "cannot return stack pointer to the caller\n"); 9737 return -EINVAL; 9738 } 9739 9740 caller = state->frame[state->curframe - 1]; 9741 if (callee->in_callback_fn) { 9742 if (r0->type != SCALAR_VALUE) { 9743 verbose(env, "R0 not a scalar value\n"); 9744 return -EACCES; 9745 } 9746 9747 /* we are going to rely on register's precise value */ 9748 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64); 9749 err = err ?: mark_chain_precision(env, BPF_REG_0); 9750 if (err) 9751 return err; 9752 9753 /* enforce R0 return value range */ 9754 if (!retval_range_within(callee->callback_ret_range, r0)) { 9755 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 9756 "At callback return", "R0"); 9757 return -EINVAL; 9758 } 9759 if (!calls_callback(env, callee->callsite)) { 9760 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n", 9761 *insn_idx, callee->callsite); 9762 return -EFAULT; 9763 } 9764 } else { 9765 /* return to the caller whatever r0 had in the callee */ 9766 caller->regs[BPF_REG_0] = *r0; 9767 } 9768 9769 /* callback_fn frame should have released its own additions to parent's 9770 * reference state at this point, or check_reference_leak would 9771 * complain, hence it must be the same as the caller. There is no need 9772 * to copy it back. 9773 */ 9774 if (!callee->in_callback_fn) { 9775 /* Transfer references to the caller */ 9776 err = copy_reference_state(caller, callee); 9777 if (err) 9778 return err; 9779 } 9780 9781 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 9782 * there function call logic would reschedule callback visit. If iteration 9783 * converges is_state_visited() would prune that visit eventually. 9784 */ 9785 in_callback_fn = callee->in_callback_fn; 9786 if (in_callback_fn) 9787 *insn_idx = callee->callsite; 9788 else 9789 *insn_idx = callee->callsite + 1; 9790 9791 if (env->log.level & BPF_LOG_LEVEL) { 9792 verbose(env, "returning from callee:\n"); 9793 print_verifier_state(env, callee, true); 9794 verbose(env, "to caller at %d:\n", *insn_idx); 9795 print_verifier_state(env, caller, true); 9796 } 9797 /* clear everything in the callee. In case of exceptional exits using 9798 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 9799 free_func_state(callee); 9800 state->frame[state->curframe--] = NULL; 9801 9802 /* for callbacks widen imprecise scalars to make programs like below verify: 9803 * 9804 * struct ctx { int i; } 9805 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 9806 * ... 9807 * struct ctx = { .i = 0; } 9808 * bpf_loop(100, cb, &ctx, 0); 9809 * 9810 * This is similar to what is done in process_iter_next_call() for open 9811 * coded iterators. 9812 */ 9813 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 9814 if (prev_st) { 9815 err = widen_imprecise_scalars(env, prev_st, state); 9816 if (err) 9817 return err; 9818 } 9819 return 0; 9820 } 9821 9822 static int do_refine_retval_range(struct bpf_verifier_env *env, 9823 struct bpf_reg_state *regs, int ret_type, 9824 int func_id, 9825 struct bpf_call_arg_meta *meta) 9826 { 9827 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 9828 9829 if (ret_type != RET_INTEGER) 9830 return 0; 9831 9832 switch (func_id) { 9833 case BPF_FUNC_get_stack: 9834 case BPF_FUNC_get_task_stack: 9835 case BPF_FUNC_probe_read_str: 9836 case BPF_FUNC_probe_read_kernel_str: 9837 case BPF_FUNC_probe_read_user_str: 9838 ret_reg->smax_value = meta->msize_max_value; 9839 ret_reg->s32_max_value = meta->msize_max_value; 9840 ret_reg->smin_value = -MAX_ERRNO; 9841 ret_reg->s32_min_value = -MAX_ERRNO; 9842 reg_bounds_sync(ret_reg); 9843 break; 9844 case BPF_FUNC_get_smp_processor_id: 9845 ret_reg->umax_value = nr_cpu_ids - 1; 9846 ret_reg->u32_max_value = nr_cpu_ids - 1; 9847 ret_reg->smax_value = nr_cpu_ids - 1; 9848 ret_reg->s32_max_value = nr_cpu_ids - 1; 9849 ret_reg->umin_value = 0; 9850 ret_reg->u32_min_value = 0; 9851 ret_reg->smin_value = 0; 9852 ret_reg->s32_min_value = 0; 9853 reg_bounds_sync(ret_reg); 9854 break; 9855 } 9856 9857 return reg_bounds_sanity_check(env, ret_reg, "retval"); 9858 } 9859 9860 static int 9861 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9862 int func_id, int insn_idx) 9863 { 9864 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9865 struct bpf_map *map = meta->map_ptr; 9866 9867 if (func_id != BPF_FUNC_tail_call && 9868 func_id != BPF_FUNC_map_lookup_elem && 9869 func_id != BPF_FUNC_map_update_elem && 9870 func_id != BPF_FUNC_map_delete_elem && 9871 func_id != BPF_FUNC_map_push_elem && 9872 func_id != BPF_FUNC_map_pop_elem && 9873 func_id != BPF_FUNC_map_peek_elem && 9874 func_id != BPF_FUNC_for_each_map_elem && 9875 func_id != BPF_FUNC_redirect_map && 9876 func_id != BPF_FUNC_map_lookup_percpu_elem) 9877 return 0; 9878 9879 if (map == NULL) { 9880 verbose(env, "kernel subsystem misconfigured verifier\n"); 9881 return -EINVAL; 9882 } 9883 9884 /* In case of read-only, some additional restrictions 9885 * need to be applied in order to prevent altering the 9886 * state of the map from program side. 9887 */ 9888 if ((map->map_flags & BPF_F_RDONLY_PROG) && 9889 (func_id == BPF_FUNC_map_delete_elem || 9890 func_id == BPF_FUNC_map_update_elem || 9891 func_id == BPF_FUNC_map_push_elem || 9892 func_id == BPF_FUNC_map_pop_elem)) { 9893 verbose(env, "write into map forbidden\n"); 9894 return -EACCES; 9895 } 9896 9897 if (!BPF_MAP_PTR(aux->map_ptr_state)) 9898 bpf_map_ptr_store(aux, meta->map_ptr, 9899 !meta->map_ptr->bypass_spec_v1); 9900 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 9901 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 9902 !meta->map_ptr->bypass_spec_v1); 9903 return 0; 9904 } 9905 9906 static int 9907 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9908 int func_id, int insn_idx) 9909 { 9910 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9911 struct bpf_reg_state *regs = cur_regs(env), *reg; 9912 struct bpf_map *map = meta->map_ptr; 9913 u64 val, max; 9914 int err; 9915 9916 if (func_id != BPF_FUNC_tail_call) 9917 return 0; 9918 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 9919 verbose(env, "kernel subsystem misconfigured verifier\n"); 9920 return -EINVAL; 9921 } 9922 9923 reg = ®s[BPF_REG_3]; 9924 val = reg->var_off.value; 9925 max = map->max_entries; 9926 9927 if (!(is_reg_const(reg, false) && val < max)) { 9928 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9929 return 0; 9930 } 9931 9932 err = mark_chain_precision(env, BPF_REG_3); 9933 if (err) 9934 return err; 9935 if (bpf_map_key_unseen(aux)) 9936 bpf_map_key_store(aux, val); 9937 else if (!bpf_map_key_poisoned(aux) && 9938 bpf_map_key_immediate(aux) != val) 9939 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9940 return 0; 9941 } 9942 9943 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 9944 { 9945 struct bpf_func_state *state = cur_func(env); 9946 bool refs_lingering = false; 9947 int i; 9948 9949 if (!exception_exit && state->frameno && !state->in_callback_fn) 9950 return 0; 9951 9952 for (i = 0; i < state->acquired_refs; i++) { 9953 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 9954 continue; 9955 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 9956 state->refs[i].id, state->refs[i].insn_idx); 9957 refs_lingering = true; 9958 } 9959 return refs_lingering ? -EINVAL : 0; 9960 } 9961 9962 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 9963 struct bpf_reg_state *regs) 9964 { 9965 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 9966 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 9967 struct bpf_map *fmt_map = fmt_reg->map_ptr; 9968 struct bpf_bprintf_data data = {}; 9969 int err, fmt_map_off, num_args; 9970 u64 fmt_addr; 9971 char *fmt; 9972 9973 /* data must be an array of u64 */ 9974 if (data_len_reg->var_off.value % 8) 9975 return -EINVAL; 9976 num_args = data_len_reg->var_off.value / 8; 9977 9978 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 9979 * and map_direct_value_addr is set. 9980 */ 9981 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 9982 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 9983 fmt_map_off); 9984 if (err) { 9985 verbose(env, "verifier bug\n"); 9986 return -EFAULT; 9987 } 9988 fmt = (char *)(long)fmt_addr + fmt_map_off; 9989 9990 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 9991 * can focus on validating the format specifiers. 9992 */ 9993 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 9994 if (err < 0) 9995 verbose(env, "Invalid format string\n"); 9996 9997 return err; 9998 } 9999 10000 static int check_get_func_ip(struct bpf_verifier_env *env) 10001 { 10002 enum bpf_prog_type type = resolve_prog_type(env->prog); 10003 int func_id = BPF_FUNC_get_func_ip; 10004 10005 if (type == BPF_PROG_TYPE_TRACING) { 10006 if (!bpf_prog_has_trampoline(env->prog)) { 10007 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 10008 func_id_name(func_id), func_id); 10009 return -ENOTSUPP; 10010 } 10011 return 0; 10012 } else if (type == BPF_PROG_TYPE_KPROBE) { 10013 return 0; 10014 } 10015 10016 verbose(env, "func %s#%d not supported for program type %d\n", 10017 func_id_name(func_id), func_id, type); 10018 return -ENOTSUPP; 10019 } 10020 10021 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 10022 { 10023 return &env->insn_aux_data[env->insn_idx]; 10024 } 10025 10026 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 10027 { 10028 struct bpf_reg_state *regs = cur_regs(env); 10029 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 10030 bool reg_is_null = register_is_null(reg); 10031 10032 if (reg_is_null) 10033 mark_chain_precision(env, BPF_REG_4); 10034 10035 return reg_is_null; 10036 } 10037 10038 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 10039 { 10040 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 10041 10042 if (!state->initialized) { 10043 state->initialized = 1; 10044 state->fit_for_inline = loop_flag_is_zero(env); 10045 state->callback_subprogno = subprogno; 10046 return; 10047 } 10048 10049 if (!state->fit_for_inline) 10050 return; 10051 10052 state->fit_for_inline = (loop_flag_is_zero(env) && 10053 state->callback_subprogno == subprogno); 10054 } 10055 10056 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10057 int *insn_idx_p) 10058 { 10059 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 10060 bool returns_cpu_specific_alloc_ptr = false; 10061 const struct bpf_func_proto *fn = NULL; 10062 enum bpf_return_type ret_type; 10063 enum bpf_type_flag ret_flag; 10064 struct bpf_reg_state *regs; 10065 struct bpf_call_arg_meta meta; 10066 int insn_idx = *insn_idx_p; 10067 bool changes_data; 10068 int i, err, func_id; 10069 10070 /* find function prototype */ 10071 func_id = insn->imm; 10072 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 10073 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 10074 func_id); 10075 return -EINVAL; 10076 } 10077 10078 if (env->ops->get_func_proto) 10079 fn = env->ops->get_func_proto(func_id, env->prog); 10080 if (!fn) { 10081 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 10082 func_id); 10083 return -EINVAL; 10084 } 10085 10086 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 10087 if (!env->prog->gpl_compatible && fn->gpl_only) { 10088 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10089 return -EINVAL; 10090 } 10091 10092 if (fn->allowed && !fn->allowed(env->prog)) { 10093 verbose(env, "helper call is not allowed in probe\n"); 10094 return -EINVAL; 10095 } 10096 10097 if (!env->prog->aux->sleepable && fn->might_sleep) { 10098 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 10099 return -EINVAL; 10100 } 10101 10102 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10103 changes_data = bpf_helper_changes_pkt_data(fn->func); 10104 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10105 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 10106 func_id_name(func_id), func_id); 10107 return -EINVAL; 10108 } 10109 10110 memset(&meta, 0, sizeof(meta)); 10111 meta.pkt_access = fn->pkt_access; 10112 10113 err = check_func_proto(fn, func_id); 10114 if (err) { 10115 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 10116 func_id_name(func_id), func_id); 10117 return err; 10118 } 10119 10120 if (env->cur_state->active_rcu_lock) { 10121 if (fn->might_sleep) { 10122 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 10123 func_id_name(func_id), func_id); 10124 return -EINVAL; 10125 } 10126 10127 if (env->prog->aux->sleepable && is_storage_get_function(func_id)) 10128 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10129 } 10130 10131 meta.func_id = func_id; 10132 /* check args */ 10133 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10134 err = check_func_arg(env, i, &meta, fn, insn_idx); 10135 if (err) 10136 return err; 10137 } 10138 10139 err = record_func_map(env, &meta, func_id, insn_idx); 10140 if (err) 10141 return err; 10142 10143 err = record_func_key(env, &meta, func_id, insn_idx); 10144 if (err) 10145 return err; 10146 10147 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10148 * is inferred from register state. 10149 */ 10150 for (i = 0; i < meta.access_size; i++) { 10151 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 10152 BPF_WRITE, -1, false, false); 10153 if (err) 10154 return err; 10155 } 10156 10157 regs = cur_regs(env); 10158 10159 if (meta.release_regno) { 10160 err = -EINVAL; 10161 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 10162 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 10163 * is safe to do directly. 10164 */ 10165 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 10166 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 10167 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 10168 return -EFAULT; 10169 } 10170 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 10171 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 10172 u32 ref_obj_id = meta.ref_obj_id; 10173 bool in_rcu = in_rcu_cs(env); 10174 struct bpf_func_state *state; 10175 struct bpf_reg_state *reg; 10176 10177 err = release_reference_state(cur_func(env), ref_obj_id); 10178 if (!err) { 10179 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10180 if (reg->ref_obj_id == ref_obj_id) { 10181 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 10182 reg->ref_obj_id = 0; 10183 reg->type &= ~MEM_ALLOC; 10184 reg->type |= MEM_RCU; 10185 } else { 10186 mark_reg_invalid(env, reg); 10187 } 10188 } 10189 })); 10190 } 10191 } else if (meta.ref_obj_id) { 10192 err = release_reference(env, meta.ref_obj_id); 10193 } else if (register_is_null(®s[meta.release_regno])) { 10194 /* meta.ref_obj_id can only be 0 if register that is meant to be 10195 * released is NULL, which must be > R0. 10196 */ 10197 err = 0; 10198 } 10199 if (err) { 10200 verbose(env, "func %s#%d reference has not been acquired before\n", 10201 func_id_name(func_id), func_id); 10202 return err; 10203 } 10204 } 10205 10206 switch (func_id) { 10207 case BPF_FUNC_tail_call: 10208 err = check_reference_leak(env, false); 10209 if (err) { 10210 verbose(env, "tail_call would lead to reference leak\n"); 10211 return err; 10212 } 10213 break; 10214 case BPF_FUNC_get_local_storage: 10215 /* check that flags argument in get_local_storage(map, flags) is 0, 10216 * this is required because get_local_storage() can't return an error. 10217 */ 10218 if (!register_is_null(®s[BPF_REG_2])) { 10219 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10220 return -EINVAL; 10221 } 10222 break; 10223 case BPF_FUNC_for_each_map_elem: 10224 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10225 set_map_elem_callback_state); 10226 break; 10227 case BPF_FUNC_timer_set_callback: 10228 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10229 set_timer_callback_state); 10230 break; 10231 case BPF_FUNC_find_vma: 10232 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10233 set_find_vma_callback_state); 10234 break; 10235 case BPF_FUNC_snprintf: 10236 err = check_bpf_snprintf_call(env, regs); 10237 break; 10238 case BPF_FUNC_loop: 10239 update_loop_inline_state(env, meta.subprogno); 10240 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10241 * is finished, thus mark it precise. 10242 */ 10243 err = mark_chain_precision(env, BPF_REG_1); 10244 if (err) 10245 return err; 10246 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) { 10247 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10248 set_loop_callback_state); 10249 } else { 10250 cur_func(env)->callback_depth = 0; 10251 if (env->log.level & BPF_LOG_LEVEL2) 10252 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10253 env->cur_state->curframe); 10254 } 10255 break; 10256 case BPF_FUNC_dynptr_from_mem: 10257 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10258 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10259 reg_type_str(env, regs[BPF_REG_1].type)); 10260 return -EACCES; 10261 } 10262 break; 10263 case BPF_FUNC_set_retval: 10264 if (prog_type == BPF_PROG_TYPE_LSM && 10265 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10266 if (!env->prog->aux->attach_func_proto->type) { 10267 /* Make sure programs that attach to void 10268 * hooks don't try to modify return value. 10269 */ 10270 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10271 return -EINVAL; 10272 } 10273 } 10274 break; 10275 case BPF_FUNC_dynptr_data: 10276 { 10277 struct bpf_reg_state *reg; 10278 int id, ref_obj_id; 10279 10280 reg = get_dynptr_arg_reg(env, fn, regs); 10281 if (!reg) 10282 return -EFAULT; 10283 10284 10285 if (meta.dynptr_id) { 10286 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 10287 return -EFAULT; 10288 } 10289 if (meta.ref_obj_id) { 10290 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 10291 return -EFAULT; 10292 } 10293 10294 id = dynptr_id(env, reg); 10295 if (id < 0) { 10296 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 10297 return id; 10298 } 10299 10300 ref_obj_id = dynptr_ref_obj_id(env, reg); 10301 if (ref_obj_id < 0) { 10302 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 10303 return ref_obj_id; 10304 } 10305 10306 meta.dynptr_id = id; 10307 meta.ref_obj_id = ref_obj_id; 10308 10309 break; 10310 } 10311 case BPF_FUNC_dynptr_write: 10312 { 10313 enum bpf_dynptr_type dynptr_type; 10314 struct bpf_reg_state *reg; 10315 10316 reg = get_dynptr_arg_reg(env, fn, regs); 10317 if (!reg) 10318 return -EFAULT; 10319 10320 dynptr_type = dynptr_get_type(env, reg); 10321 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10322 return -EFAULT; 10323 10324 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 10325 /* this will trigger clear_all_pkt_pointers(), which will 10326 * invalidate all dynptr slices associated with the skb 10327 */ 10328 changes_data = true; 10329 10330 break; 10331 } 10332 case BPF_FUNC_per_cpu_ptr: 10333 case BPF_FUNC_this_cpu_ptr: 10334 { 10335 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 10336 const struct btf_type *type; 10337 10338 if (reg->type & MEM_RCU) { 10339 type = btf_type_by_id(reg->btf, reg->btf_id); 10340 if (!type || !btf_type_is_struct(type)) { 10341 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 10342 return -EFAULT; 10343 } 10344 returns_cpu_specific_alloc_ptr = true; 10345 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 10346 } 10347 break; 10348 } 10349 case BPF_FUNC_user_ringbuf_drain: 10350 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10351 set_user_ringbuf_callback_state); 10352 break; 10353 } 10354 10355 if (err) 10356 return err; 10357 10358 /* reset caller saved regs */ 10359 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10360 mark_reg_not_init(env, regs, caller_saved[i]); 10361 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10362 } 10363 10364 /* helper call returns 64-bit value. */ 10365 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10366 10367 /* update return register (already marked as written above) */ 10368 ret_type = fn->ret_type; 10369 ret_flag = type_flag(ret_type); 10370 10371 switch (base_type(ret_type)) { 10372 case RET_INTEGER: 10373 /* sets type to SCALAR_VALUE */ 10374 mark_reg_unknown(env, regs, BPF_REG_0); 10375 break; 10376 case RET_VOID: 10377 regs[BPF_REG_0].type = NOT_INIT; 10378 break; 10379 case RET_PTR_TO_MAP_VALUE: 10380 /* There is no offset yet applied, variable or fixed */ 10381 mark_reg_known_zero(env, regs, BPF_REG_0); 10382 /* remember map_ptr, so that check_map_access() 10383 * can check 'value_size' boundary of memory access 10384 * to map element returned from bpf_map_lookup_elem() 10385 */ 10386 if (meta.map_ptr == NULL) { 10387 verbose(env, 10388 "kernel subsystem misconfigured verifier\n"); 10389 return -EINVAL; 10390 } 10391 regs[BPF_REG_0].map_ptr = meta.map_ptr; 10392 regs[BPF_REG_0].map_uid = meta.map_uid; 10393 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10394 if (!type_may_be_null(ret_type) && 10395 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 10396 regs[BPF_REG_0].id = ++env->id_gen; 10397 } 10398 break; 10399 case RET_PTR_TO_SOCKET: 10400 mark_reg_known_zero(env, regs, BPF_REG_0); 10401 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10402 break; 10403 case RET_PTR_TO_SOCK_COMMON: 10404 mark_reg_known_zero(env, regs, BPF_REG_0); 10405 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10406 break; 10407 case RET_PTR_TO_TCP_SOCK: 10408 mark_reg_known_zero(env, regs, BPF_REG_0); 10409 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10410 break; 10411 case RET_PTR_TO_MEM: 10412 mark_reg_known_zero(env, regs, BPF_REG_0); 10413 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10414 regs[BPF_REG_0].mem_size = meta.mem_size; 10415 break; 10416 case RET_PTR_TO_MEM_OR_BTF_ID: 10417 { 10418 const struct btf_type *t; 10419 10420 mark_reg_known_zero(env, regs, BPF_REG_0); 10421 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10422 if (!btf_type_is_struct(t)) { 10423 u32 tsize; 10424 const struct btf_type *ret; 10425 const char *tname; 10426 10427 /* resolve the type size of ksym. */ 10428 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10429 if (IS_ERR(ret)) { 10430 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10431 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10432 tname, PTR_ERR(ret)); 10433 return -EINVAL; 10434 } 10435 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10436 regs[BPF_REG_0].mem_size = tsize; 10437 } else { 10438 if (returns_cpu_specific_alloc_ptr) { 10439 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10440 } else { 10441 /* MEM_RDONLY may be carried from ret_flag, but it 10442 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10443 * it will confuse the check of PTR_TO_BTF_ID in 10444 * check_mem_access(). 10445 */ 10446 ret_flag &= ~MEM_RDONLY; 10447 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10448 } 10449 10450 regs[BPF_REG_0].btf = meta.ret_btf; 10451 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10452 } 10453 break; 10454 } 10455 case RET_PTR_TO_BTF_ID: 10456 { 10457 struct btf *ret_btf; 10458 int ret_btf_id; 10459 10460 mark_reg_known_zero(env, regs, BPF_REG_0); 10461 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10462 if (func_id == BPF_FUNC_kptr_xchg) { 10463 ret_btf = meta.kptr_field->kptr.btf; 10464 ret_btf_id = meta.kptr_field->kptr.btf_id; 10465 if (!btf_is_kernel(ret_btf)) { 10466 regs[BPF_REG_0].type |= MEM_ALLOC; 10467 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10468 regs[BPF_REG_0].type |= MEM_PERCPU; 10469 } 10470 } else { 10471 if (fn->ret_btf_id == BPF_PTR_POISON) { 10472 verbose(env, "verifier internal error:"); 10473 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 10474 func_id_name(func_id)); 10475 return -EINVAL; 10476 } 10477 ret_btf = btf_vmlinux; 10478 ret_btf_id = *fn->ret_btf_id; 10479 } 10480 if (ret_btf_id == 0) { 10481 verbose(env, "invalid return type %u of func %s#%d\n", 10482 base_type(ret_type), func_id_name(func_id), 10483 func_id); 10484 return -EINVAL; 10485 } 10486 regs[BPF_REG_0].btf = ret_btf; 10487 regs[BPF_REG_0].btf_id = ret_btf_id; 10488 break; 10489 } 10490 default: 10491 verbose(env, "unknown return type %u of func %s#%d\n", 10492 base_type(ret_type), func_id_name(func_id), func_id); 10493 return -EINVAL; 10494 } 10495 10496 if (type_may_be_null(regs[BPF_REG_0].type)) 10497 regs[BPF_REG_0].id = ++env->id_gen; 10498 10499 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 10500 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 10501 func_id_name(func_id), func_id); 10502 return -EFAULT; 10503 } 10504 10505 if (is_dynptr_ref_function(func_id)) 10506 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 10507 10508 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 10509 /* For release_reference() */ 10510 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10511 } else if (is_acquire_function(func_id, meta.map_ptr)) { 10512 int id = acquire_reference_state(env, insn_idx); 10513 10514 if (id < 0) 10515 return id; 10516 /* For mark_ptr_or_null_reg() */ 10517 regs[BPF_REG_0].id = id; 10518 /* For release_reference() */ 10519 regs[BPF_REG_0].ref_obj_id = id; 10520 } 10521 10522 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 10523 if (err) 10524 return err; 10525 10526 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 10527 if (err) 10528 return err; 10529 10530 if ((func_id == BPF_FUNC_get_stack || 10531 func_id == BPF_FUNC_get_task_stack) && 10532 !env->prog->has_callchain_buf) { 10533 const char *err_str; 10534 10535 #ifdef CONFIG_PERF_EVENTS 10536 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10537 err_str = "cannot get callchain buffer for func %s#%d\n"; 10538 #else 10539 err = -ENOTSUPP; 10540 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10541 #endif 10542 if (err) { 10543 verbose(env, err_str, func_id_name(func_id), func_id); 10544 return err; 10545 } 10546 10547 env->prog->has_callchain_buf = true; 10548 } 10549 10550 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10551 env->prog->call_get_stack = true; 10552 10553 if (func_id == BPF_FUNC_get_func_ip) { 10554 if (check_get_func_ip(env)) 10555 return -ENOTSUPP; 10556 env->prog->call_get_func_ip = true; 10557 } 10558 10559 if (changes_data) 10560 clear_all_pkt_pointers(env); 10561 return 0; 10562 } 10563 10564 /* mark_btf_func_reg_size() is used when the reg size is determined by 10565 * the BTF func_proto's return value size and argument. 10566 */ 10567 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10568 size_t reg_size) 10569 { 10570 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 10571 10572 if (regno == BPF_REG_0) { 10573 /* Function return value */ 10574 reg->live |= REG_LIVE_WRITTEN; 10575 reg->subreg_def = reg_size == sizeof(u64) ? 10576 DEF_NOT_SUBREG : env->insn_idx + 1; 10577 } else { 10578 /* Function argument */ 10579 if (reg_size == sizeof(u64)) { 10580 mark_insn_zext(env, reg); 10581 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 10582 } else { 10583 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 10584 } 10585 } 10586 } 10587 10588 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10589 { 10590 return meta->kfunc_flags & KF_ACQUIRE; 10591 } 10592 10593 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10594 { 10595 return meta->kfunc_flags & KF_RELEASE; 10596 } 10597 10598 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 10599 { 10600 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 10601 } 10602 10603 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 10604 { 10605 return meta->kfunc_flags & KF_SLEEPABLE; 10606 } 10607 10608 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10609 { 10610 return meta->kfunc_flags & KF_DESTRUCTIVE; 10611 } 10612 10613 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10614 { 10615 return meta->kfunc_flags & KF_RCU; 10616 } 10617 10618 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 10619 { 10620 return meta->kfunc_flags & KF_RCU_PROTECTED; 10621 } 10622 10623 static bool __kfunc_param_match_suffix(const struct btf *btf, 10624 const struct btf_param *arg, 10625 const char *suffix) 10626 { 10627 int suffix_len = strlen(suffix), len; 10628 const char *param_name; 10629 10630 /* In the future, this can be ported to use BTF tagging */ 10631 param_name = btf_name_by_offset(btf, arg->name_off); 10632 if (str_is_empty(param_name)) 10633 return false; 10634 len = strlen(param_name); 10635 if (len < suffix_len) 10636 return false; 10637 param_name += len - suffix_len; 10638 return !strncmp(param_name, suffix, suffix_len); 10639 } 10640 10641 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10642 const struct btf_param *arg, 10643 const struct bpf_reg_state *reg) 10644 { 10645 const struct btf_type *t; 10646 10647 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10648 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10649 return false; 10650 10651 return __kfunc_param_match_suffix(btf, arg, "__sz"); 10652 } 10653 10654 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10655 const struct btf_param *arg, 10656 const struct bpf_reg_state *reg) 10657 { 10658 const struct btf_type *t; 10659 10660 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10661 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10662 return false; 10663 10664 return __kfunc_param_match_suffix(btf, arg, "__szk"); 10665 } 10666 10667 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 10668 { 10669 return __kfunc_param_match_suffix(btf, arg, "__opt"); 10670 } 10671 10672 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10673 { 10674 return __kfunc_param_match_suffix(btf, arg, "__k"); 10675 } 10676 10677 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10678 { 10679 return __kfunc_param_match_suffix(btf, arg, "__ign"); 10680 } 10681 10682 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10683 { 10684 return __kfunc_param_match_suffix(btf, arg, "__alloc"); 10685 } 10686 10687 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10688 { 10689 return __kfunc_param_match_suffix(btf, arg, "__uninit"); 10690 } 10691 10692 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10693 { 10694 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr"); 10695 } 10696 10697 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 10698 { 10699 return __kfunc_param_match_suffix(btf, arg, "__nullable"); 10700 } 10701 10702 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 10703 { 10704 return __kfunc_param_match_suffix(btf, arg, "__str"); 10705 } 10706 10707 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10708 const struct btf_param *arg, 10709 const char *name) 10710 { 10711 int len, target_len = strlen(name); 10712 const char *param_name; 10713 10714 param_name = btf_name_by_offset(btf, arg->name_off); 10715 if (str_is_empty(param_name)) 10716 return false; 10717 len = strlen(param_name); 10718 if (len != target_len) 10719 return false; 10720 if (strcmp(param_name, name)) 10721 return false; 10722 10723 return true; 10724 } 10725 10726 enum { 10727 KF_ARG_DYNPTR_ID, 10728 KF_ARG_LIST_HEAD_ID, 10729 KF_ARG_LIST_NODE_ID, 10730 KF_ARG_RB_ROOT_ID, 10731 KF_ARG_RB_NODE_ID, 10732 }; 10733 10734 BTF_ID_LIST(kf_arg_btf_ids) 10735 BTF_ID(struct, bpf_dynptr_kern) 10736 BTF_ID(struct, bpf_list_head) 10737 BTF_ID(struct, bpf_list_node) 10738 BTF_ID(struct, bpf_rb_root) 10739 BTF_ID(struct, bpf_rb_node) 10740 10741 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10742 const struct btf_param *arg, int type) 10743 { 10744 const struct btf_type *t; 10745 u32 res_id; 10746 10747 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10748 if (!t) 10749 return false; 10750 if (!btf_type_is_ptr(t)) 10751 return false; 10752 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10753 if (!t) 10754 return false; 10755 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10756 } 10757 10758 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10759 { 10760 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10761 } 10762 10763 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10764 { 10765 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10766 } 10767 10768 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10769 { 10770 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10771 } 10772 10773 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10774 { 10775 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10776 } 10777 10778 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10779 { 10780 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10781 } 10782 10783 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10784 const struct btf_param *arg) 10785 { 10786 const struct btf_type *t; 10787 10788 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10789 if (!t) 10790 return false; 10791 10792 return true; 10793 } 10794 10795 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10796 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10797 const struct btf *btf, 10798 const struct btf_type *t, int rec) 10799 { 10800 const struct btf_type *member_type; 10801 const struct btf_member *member; 10802 u32 i; 10803 10804 if (!btf_type_is_struct(t)) 10805 return false; 10806 10807 for_each_member(i, t, member) { 10808 const struct btf_array *array; 10809 10810 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 10811 if (btf_type_is_struct(member_type)) { 10812 if (rec >= 3) { 10813 verbose(env, "max struct nesting depth exceeded\n"); 10814 return false; 10815 } 10816 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 10817 return false; 10818 continue; 10819 } 10820 if (btf_type_is_array(member_type)) { 10821 array = btf_array(member_type); 10822 if (!array->nelems) 10823 return false; 10824 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 10825 if (!btf_type_is_scalar(member_type)) 10826 return false; 10827 continue; 10828 } 10829 if (!btf_type_is_scalar(member_type)) 10830 return false; 10831 } 10832 return true; 10833 } 10834 10835 enum kfunc_ptr_arg_type { 10836 KF_ARG_PTR_TO_CTX, 10837 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 10838 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 10839 KF_ARG_PTR_TO_DYNPTR, 10840 KF_ARG_PTR_TO_ITER, 10841 KF_ARG_PTR_TO_LIST_HEAD, 10842 KF_ARG_PTR_TO_LIST_NODE, 10843 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 10844 KF_ARG_PTR_TO_MEM, 10845 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 10846 KF_ARG_PTR_TO_CALLBACK, 10847 KF_ARG_PTR_TO_RB_ROOT, 10848 KF_ARG_PTR_TO_RB_NODE, 10849 KF_ARG_PTR_TO_NULL, 10850 KF_ARG_PTR_TO_CONST_STR, 10851 }; 10852 10853 enum special_kfunc_type { 10854 KF_bpf_obj_new_impl, 10855 KF_bpf_obj_drop_impl, 10856 KF_bpf_refcount_acquire_impl, 10857 KF_bpf_list_push_front_impl, 10858 KF_bpf_list_push_back_impl, 10859 KF_bpf_list_pop_front, 10860 KF_bpf_list_pop_back, 10861 KF_bpf_cast_to_kern_ctx, 10862 KF_bpf_rdonly_cast, 10863 KF_bpf_rcu_read_lock, 10864 KF_bpf_rcu_read_unlock, 10865 KF_bpf_rbtree_remove, 10866 KF_bpf_rbtree_add_impl, 10867 KF_bpf_rbtree_first, 10868 KF_bpf_dynptr_from_skb, 10869 KF_bpf_dynptr_from_xdp, 10870 KF_bpf_dynptr_slice, 10871 KF_bpf_dynptr_slice_rdwr, 10872 KF_bpf_dynptr_clone, 10873 KF_bpf_percpu_obj_new_impl, 10874 KF_bpf_percpu_obj_drop_impl, 10875 KF_bpf_throw, 10876 KF_bpf_iter_css_task_new, 10877 }; 10878 10879 BTF_SET_START(special_kfunc_set) 10880 BTF_ID(func, bpf_obj_new_impl) 10881 BTF_ID(func, bpf_obj_drop_impl) 10882 BTF_ID(func, bpf_refcount_acquire_impl) 10883 BTF_ID(func, bpf_list_push_front_impl) 10884 BTF_ID(func, bpf_list_push_back_impl) 10885 BTF_ID(func, bpf_list_pop_front) 10886 BTF_ID(func, bpf_list_pop_back) 10887 BTF_ID(func, bpf_cast_to_kern_ctx) 10888 BTF_ID(func, bpf_rdonly_cast) 10889 BTF_ID(func, bpf_rbtree_remove) 10890 BTF_ID(func, bpf_rbtree_add_impl) 10891 BTF_ID(func, bpf_rbtree_first) 10892 BTF_ID(func, bpf_dynptr_from_skb) 10893 BTF_ID(func, bpf_dynptr_from_xdp) 10894 BTF_ID(func, bpf_dynptr_slice) 10895 BTF_ID(func, bpf_dynptr_slice_rdwr) 10896 BTF_ID(func, bpf_dynptr_clone) 10897 BTF_ID(func, bpf_percpu_obj_new_impl) 10898 BTF_ID(func, bpf_percpu_obj_drop_impl) 10899 BTF_ID(func, bpf_throw) 10900 #ifdef CONFIG_CGROUPS 10901 BTF_ID(func, bpf_iter_css_task_new) 10902 #endif 10903 BTF_SET_END(special_kfunc_set) 10904 10905 BTF_ID_LIST(special_kfunc_list) 10906 BTF_ID(func, bpf_obj_new_impl) 10907 BTF_ID(func, bpf_obj_drop_impl) 10908 BTF_ID(func, bpf_refcount_acquire_impl) 10909 BTF_ID(func, bpf_list_push_front_impl) 10910 BTF_ID(func, bpf_list_push_back_impl) 10911 BTF_ID(func, bpf_list_pop_front) 10912 BTF_ID(func, bpf_list_pop_back) 10913 BTF_ID(func, bpf_cast_to_kern_ctx) 10914 BTF_ID(func, bpf_rdonly_cast) 10915 BTF_ID(func, bpf_rcu_read_lock) 10916 BTF_ID(func, bpf_rcu_read_unlock) 10917 BTF_ID(func, bpf_rbtree_remove) 10918 BTF_ID(func, bpf_rbtree_add_impl) 10919 BTF_ID(func, bpf_rbtree_first) 10920 BTF_ID(func, bpf_dynptr_from_skb) 10921 BTF_ID(func, bpf_dynptr_from_xdp) 10922 BTF_ID(func, bpf_dynptr_slice) 10923 BTF_ID(func, bpf_dynptr_slice_rdwr) 10924 BTF_ID(func, bpf_dynptr_clone) 10925 BTF_ID(func, bpf_percpu_obj_new_impl) 10926 BTF_ID(func, bpf_percpu_obj_drop_impl) 10927 BTF_ID(func, bpf_throw) 10928 #ifdef CONFIG_CGROUPS 10929 BTF_ID(func, bpf_iter_css_task_new) 10930 #else 10931 BTF_ID_UNUSED 10932 #endif 10933 10934 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 10935 { 10936 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 10937 meta->arg_owning_ref) { 10938 return false; 10939 } 10940 10941 return meta->kfunc_flags & KF_RET_NULL; 10942 } 10943 10944 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 10945 { 10946 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 10947 } 10948 10949 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 10950 { 10951 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 10952 } 10953 10954 static enum kfunc_ptr_arg_type 10955 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 10956 struct bpf_kfunc_call_arg_meta *meta, 10957 const struct btf_type *t, const struct btf_type *ref_t, 10958 const char *ref_tname, const struct btf_param *args, 10959 int argno, int nargs) 10960 { 10961 u32 regno = argno + 1; 10962 struct bpf_reg_state *regs = cur_regs(env); 10963 struct bpf_reg_state *reg = ®s[regno]; 10964 bool arg_mem_size = false; 10965 10966 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 10967 return KF_ARG_PTR_TO_CTX; 10968 10969 /* In this function, we verify the kfunc's BTF as per the argument type, 10970 * leaving the rest of the verification with respect to the register 10971 * type to our caller. When a set of conditions hold in the BTF type of 10972 * arguments, we resolve it to a known kfunc_ptr_arg_type. 10973 */ 10974 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 10975 return KF_ARG_PTR_TO_CTX; 10976 10977 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 10978 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 10979 10980 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 10981 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 10982 10983 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 10984 return KF_ARG_PTR_TO_DYNPTR; 10985 10986 if (is_kfunc_arg_iter(meta, argno)) 10987 return KF_ARG_PTR_TO_ITER; 10988 10989 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 10990 return KF_ARG_PTR_TO_LIST_HEAD; 10991 10992 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 10993 return KF_ARG_PTR_TO_LIST_NODE; 10994 10995 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 10996 return KF_ARG_PTR_TO_RB_ROOT; 10997 10998 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 10999 return KF_ARG_PTR_TO_RB_NODE; 11000 11001 if (is_kfunc_arg_const_str(meta->btf, &args[argno])) 11002 return KF_ARG_PTR_TO_CONST_STR; 11003 11004 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 11005 if (!btf_type_is_struct(ref_t)) { 11006 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 11007 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 11008 return -EINVAL; 11009 } 11010 return KF_ARG_PTR_TO_BTF_ID; 11011 } 11012 11013 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 11014 return KF_ARG_PTR_TO_CALLBACK; 11015 11016 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg)) 11017 return KF_ARG_PTR_TO_NULL; 11018 11019 if (argno + 1 < nargs && 11020 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 11021 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 11022 arg_mem_size = true; 11023 11024 /* This is the catch all argument type of register types supported by 11025 * check_helper_mem_access. However, we only allow when argument type is 11026 * pointer to scalar, or struct composed (recursively) of scalars. When 11027 * arg_mem_size is true, the pointer can be void *. 11028 */ 11029 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 11030 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 11031 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 11032 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 11033 return -EINVAL; 11034 } 11035 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 11036 } 11037 11038 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 11039 struct bpf_reg_state *reg, 11040 const struct btf_type *ref_t, 11041 const char *ref_tname, u32 ref_id, 11042 struct bpf_kfunc_call_arg_meta *meta, 11043 int argno) 11044 { 11045 const struct btf_type *reg_ref_t; 11046 bool strict_type_match = false; 11047 const struct btf *reg_btf; 11048 const char *reg_ref_tname; 11049 u32 reg_ref_id; 11050 11051 if (base_type(reg->type) == PTR_TO_BTF_ID) { 11052 reg_btf = reg->btf; 11053 reg_ref_id = reg->btf_id; 11054 } else { 11055 reg_btf = btf_vmlinux; 11056 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 11057 } 11058 11059 /* Enforce strict type matching for calls to kfuncs that are acquiring 11060 * or releasing a reference, or are no-cast aliases. We do _not_ 11061 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 11062 * as we want to enable BPF programs to pass types that are bitwise 11063 * equivalent without forcing them to explicitly cast with something 11064 * like bpf_cast_to_kern_ctx(). 11065 * 11066 * For example, say we had a type like the following: 11067 * 11068 * struct bpf_cpumask { 11069 * cpumask_t cpumask; 11070 * refcount_t usage; 11071 * }; 11072 * 11073 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 11074 * to a struct cpumask, so it would be safe to pass a struct 11075 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 11076 * 11077 * The philosophy here is similar to how we allow scalars of different 11078 * types to be passed to kfuncs as long as the size is the same. The 11079 * only difference here is that we're simply allowing 11080 * btf_struct_ids_match() to walk the struct at the 0th offset, and 11081 * resolve types. 11082 */ 11083 if (is_kfunc_acquire(meta) || 11084 (is_kfunc_release(meta) && reg->ref_obj_id) || 11085 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 11086 strict_type_match = true; 11087 11088 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 11089 11090 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 11091 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 11092 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 11093 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 11094 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 11095 btf_type_str(reg_ref_t), reg_ref_tname); 11096 return -EINVAL; 11097 } 11098 return 0; 11099 } 11100 11101 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11102 { 11103 struct bpf_verifier_state *state = env->cur_state; 11104 struct btf_record *rec = reg_btf_record(reg); 11105 11106 if (!state->active_lock.ptr) { 11107 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 11108 return -EFAULT; 11109 } 11110 11111 if (type_flag(reg->type) & NON_OWN_REF) { 11112 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 11113 return -EFAULT; 11114 } 11115 11116 reg->type |= NON_OWN_REF; 11117 if (rec->refcount_off >= 0) 11118 reg->type |= MEM_RCU; 11119 11120 return 0; 11121 } 11122 11123 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 11124 { 11125 struct bpf_func_state *state, *unused; 11126 struct bpf_reg_state *reg; 11127 int i; 11128 11129 state = cur_func(env); 11130 11131 if (!ref_obj_id) { 11132 verbose(env, "verifier internal error: ref_obj_id is zero for " 11133 "owning -> non-owning conversion\n"); 11134 return -EFAULT; 11135 } 11136 11137 for (i = 0; i < state->acquired_refs; i++) { 11138 if (state->refs[i].id != ref_obj_id) 11139 continue; 11140 11141 /* Clear ref_obj_id here so release_reference doesn't clobber 11142 * the whole reg 11143 */ 11144 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11145 if (reg->ref_obj_id == ref_obj_id) { 11146 reg->ref_obj_id = 0; 11147 ref_set_non_owning(env, reg); 11148 } 11149 })); 11150 return 0; 11151 } 11152 11153 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 11154 return -EFAULT; 11155 } 11156 11157 /* Implementation details: 11158 * 11159 * Each register points to some region of memory, which we define as an 11160 * allocation. Each allocation may embed a bpf_spin_lock which protects any 11161 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 11162 * allocation. The lock and the data it protects are colocated in the same 11163 * memory region. 11164 * 11165 * Hence, everytime a register holds a pointer value pointing to such 11166 * allocation, the verifier preserves a unique reg->id for it. 11167 * 11168 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 11169 * bpf_spin_lock is called. 11170 * 11171 * To enable this, lock state in the verifier captures two values: 11172 * active_lock.ptr = Register's type specific pointer 11173 * active_lock.id = A unique ID for each register pointer value 11174 * 11175 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11176 * supported register types. 11177 * 11178 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11179 * allocated objects is the reg->btf pointer. 11180 * 11181 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11182 * can establish the provenance of the map value statically for each distinct 11183 * lookup into such maps. They always contain a single map value hence unique 11184 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11185 * 11186 * So, in case of global variables, they use array maps with max_entries = 1, 11187 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11188 * into the same map value as max_entries is 1, as described above). 11189 * 11190 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11191 * outer map pointer (in verifier context), but each lookup into an inner map 11192 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11193 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11194 * will get different reg->id assigned to each lookup, hence different 11195 * active_lock.id. 11196 * 11197 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11198 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11199 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11200 */ 11201 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11202 { 11203 void *ptr; 11204 u32 id; 11205 11206 switch ((int)reg->type) { 11207 case PTR_TO_MAP_VALUE: 11208 ptr = reg->map_ptr; 11209 break; 11210 case PTR_TO_BTF_ID | MEM_ALLOC: 11211 ptr = reg->btf; 11212 break; 11213 default: 11214 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 11215 return -EFAULT; 11216 } 11217 id = reg->id; 11218 11219 if (!env->cur_state->active_lock.ptr) 11220 return -EINVAL; 11221 if (env->cur_state->active_lock.ptr != ptr || 11222 env->cur_state->active_lock.id != id) { 11223 verbose(env, "held lock and object are not in the same allocation\n"); 11224 return -EINVAL; 11225 } 11226 return 0; 11227 } 11228 11229 static bool is_bpf_list_api_kfunc(u32 btf_id) 11230 { 11231 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11232 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11233 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11234 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 11235 } 11236 11237 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11238 { 11239 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 11240 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11241 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 11242 } 11243 11244 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11245 { 11246 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 11247 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11248 } 11249 11250 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11251 { 11252 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11253 } 11254 11255 static bool is_bpf_throw_kfunc(struct bpf_insn *insn) 11256 { 11257 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 11258 insn->imm == special_kfunc_list[KF_bpf_throw]; 11259 } 11260 11261 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11262 { 11263 return is_bpf_rbtree_api_kfunc(btf_id); 11264 } 11265 11266 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11267 enum btf_field_type head_field_type, 11268 u32 kfunc_btf_id) 11269 { 11270 bool ret; 11271 11272 switch (head_field_type) { 11273 case BPF_LIST_HEAD: 11274 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11275 break; 11276 case BPF_RB_ROOT: 11277 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11278 break; 11279 default: 11280 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11281 btf_field_type_name(head_field_type)); 11282 return false; 11283 } 11284 11285 if (!ret) 11286 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11287 btf_field_type_name(head_field_type)); 11288 return ret; 11289 } 11290 11291 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11292 enum btf_field_type node_field_type, 11293 u32 kfunc_btf_id) 11294 { 11295 bool ret; 11296 11297 switch (node_field_type) { 11298 case BPF_LIST_NODE: 11299 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11300 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 11301 break; 11302 case BPF_RB_NODE: 11303 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11304 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 11305 break; 11306 default: 11307 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11308 btf_field_type_name(node_field_type)); 11309 return false; 11310 } 11311 11312 if (!ret) 11313 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11314 btf_field_type_name(node_field_type)); 11315 return ret; 11316 } 11317 11318 static int 11319 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11320 struct bpf_reg_state *reg, u32 regno, 11321 struct bpf_kfunc_call_arg_meta *meta, 11322 enum btf_field_type head_field_type, 11323 struct btf_field **head_field) 11324 { 11325 const char *head_type_name; 11326 struct btf_field *field; 11327 struct btf_record *rec; 11328 u32 head_off; 11329 11330 if (meta->btf != btf_vmlinux) { 11331 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11332 return -EFAULT; 11333 } 11334 11335 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11336 return -EFAULT; 11337 11338 head_type_name = btf_field_type_name(head_field_type); 11339 if (!tnum_is_const(reg->var_off)) { 11340 verbose(env, 11341 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11342 regno, head_type_name); 11343 return -EINVAL; 11344 } 11345 11346 rec = reg_btf_record(reg); 11347 head_off = reg->off + reg->var_off.value; 11348 field = btf_record_find(rec, head_off, head_field_type); 11349 if (!field) { 11350 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11351 return -EINVAL; 11352 } 11353 11354 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11355 if (check_reg_allocation_locked(env, reg)) { 11356 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11357 rec->spin_lock_off, head_type_name); 11358 return -EINVAL; 11359 } 11360 11361 if (*head_field) { 11362 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 11363 return -EFAULT; 11364 } 11365 *head_field = field; 11366 return 0; 11367 } 11368 11369 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11370 struct bpf_reg_state *reg, u32 regno, 11371 struct bpf_kfunc_call_arg_meta *meta) 11372 { 11373 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 11374 &meta->arg_list_head.field); 11375 } 11376 11377 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11378 struct bpf_reg_state *reg, u32 regno, 11379 struct bpf_kfunc_call_arg_meta *meta) 11380 { 11381 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 11382 &meta->arg_rbtree_root.field); 11383 } 11384 11385 static int 11386 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11387 struct bpf_reg_state *reg, u32 regno, 11388 struct bpf_kfunc_call_arg_meta *meta, 11389 enum btf_field_type head_field_type, 11390 enum btf_field_type node_field_type, 11391 struct btf_field **node_field) 11392 { 11393 const char *node_type_name; 11394 const struct btf_type *et, *t; 11395 struct btf_field *field; 11396 u32 node_off; 11397 11398 if (meta->btf != btf_vmlinux) { 11399 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11400 return -EFAULT; 11401 } 11402 11403 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11404 return -EFAULT; 11405 11406 node_type_name = btf_field_type_name(node_field_type); 11407 if (!tnum_is_const(reg->var_off)) { 11408 verbose(env, 11409 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11410 regno, node_type_name); 11411 return -EINVAL; 11412 } 11413 11414 node_off = reg->off + reg->var_off.value; 11415 field = reg_find_field_offset(reg, node_off, node_field_type); 11416 if (!field || field->offset != node_off) { 11417 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11418 return -EINVAL; 11419 } 11420 11421 field = *node_field; 11422 11423 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11424 t = btf_type_by_id(reg->btf, reg->btf_id); 11425 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11426 field->graph_root.value_btf_id, true)) { 11427 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11428 "in struct %s, but arg is at offset=%d in struct %s\n", 11429 btf_field_type_name(head_field_type), 11430 btf_field_type_name(node_field_type), 11431 field->graph_root.node_offset, 11432 btf_name_by_offset(field->graph_root.btf, et->name_off), 11433 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11434 return -EINVAL; 11435 } 11436 meta->arg_btf = reg->btf; 11437 meta->arg_btf_id = reg->btf_id; 11438 11439 if (node_off != field->graph_root.node_offset) { 11440 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11441 node_off, btf_field_type_name(node_field_type), 11442 field->graph_root.node_offset, 11443 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11444 return -EINVAL; 11445 } 11446 11447 return 0; 11448 } 11449 11450 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11451 struct bpf_reg_state *reg, u32 regno, 11452 struct bpf_kfunc_call_arg_meta *meta) 11453 { 11454 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11455 BPF_LIST_HEAD, BPF_LIST_NODE, 11456 &meta->arg_list_head.field); 11457 } 11458 11459 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11460 struct bpf_reg_state *reg, u32 regno, 11461 struct bpf_kfunc_call_arg_meta *meta) 11462 { 11463 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11464 BPF_RB_ROOT, BPF_RB_NODE, 11465 &meta->arg_rbtree_root.field); 11466 } 11467 11468 /* 11469 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 11470 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 11471 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 11472 * them can only be attached to some specific hook points. 11473 */ 11474 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 11475 { 11476 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11477 11478 switch (prog_type) { 11479 case BPF_PROG_TYPE_LSM: 11480 return true; 11481 case BPF_PROG_TYPE_TRACING: 11482 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 11483 return true; 11484 fallthrough; 11485 default: 11486 return env->prog->aux->sleepable; 11487 } 11488 } 11489 11490 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11491 int insn_idx) 11492 { 11493 const char *func_name = meta->func_name, *ref_tname; 11494 const struct btf *btf = meta->btf; 11495 const struct btf_param *args; 11496 struct btf_record *rec; 11497 u32 i, nargs; 11498 int ret; 11499 11500 args = (const struct btf_param *)(meta->func_proto + 1); 11501 nargs = btf_type_vlen(meta->func_proto); 11502 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 11503 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11504 MAX_BPF_FUNC_REG_ARGS); 11505 return -EINVAL; 11506 } 11507 11508 /* Check that BTF function arguments match actual types that the 11509 * verifier sees. 11510 */ 11511 for (i = 0; i < nargs; i++) { 11512 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 11513 const struct btf_type *t, *ref_t, *resolve_ret; 11514 enum bpf_arg_type arg_type = ARG_DONTCARE; 11515 u32 regno = i + 1, ref_id, type_size; 11516 bool is_ret_buf_sz = false; 11517 int kf_arg_type; 11518 11519 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11520 11521 if (is_kfunc_arg_ignore(btf, &args[i])) 11522 continue; 11523 11524 if (btf_type_is_scalar(t)) { 11525 if (reg->type != SCALAR_VALUE) { 11526 verbose(env, "R%d is not a scalar\n", regno); 11527 return -EINVAL; 11528 } 11529 11530 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11531 if (meta->arg_constant.found) { 11532 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11533 return -EFAULT; 11534 } 11535 if (!tnum_is_const(reg->var_off)) { 11536 verbose(env, "R%d must be a known constant\n", regno); 11537 return -EINVAL; 11538 } 11539 ret = mark_chain_precision(env, regno); 11540 if (ret < 0) 11541 return ret; 11542 meta->arg_constant.found = true; 11543 meta->arg_constant.value = reg->var_off.value; 11544 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 11545 meta->r0_rdonly = true; 11546 is_ret_buf_sz = true; 11547 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 11548 is_ret_buf_sz = true; 11549 } 11550 11551 if (is_ret_buf_sz) { 11552 if (meta->r0_size) { 11553 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 11554 return -EINVAL; 11555 } 11556 11557 if (!tnum_is_const(reg->var_off)) { 11558 verbose(env, "R%d is not a const\n", regno); 11559 return -EINVAL; 11560 } 11561 11562 meta->r0_size = reg->var_off.value; 11563 ret = mark_chain_precision(env, regno); 11564 if (ret) 11565 return ret; 11566 } 11567 continue; 11568 } 11569 11570 if (!btf_type_is_ptr(t)) { 11571 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 11572 return -EINVAL; 11573 } 11574 11575 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 11576 (register_is_null(reg) || type_may_be_null(reg->type)) && 11577 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 11578 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 11579 return -EACCES; 11580 } 11581 11582 if (reg->ref_obj_id) { 11583 if (is_kfunc_release(meta) && meta->ref_obj_id) { 11584 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 11585 regno, reg->ref_obj_id, 11586 meta->ref_obj_id); 11587 return -EFAULT; 11588 } 11589 meta->ref_obj_id = reg->ref_obj_id; 11590 if (is_kfunc_release(meta)) 11591 meta->release_regno = regno; 11592 } 11593 11594 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 11595 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 11596 11597 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 11598 if (kf_arg_type < 0) 11599 return kf_arg_type; 11600 11601 switch (kf_arg_type) { 11602 case KF_ARG_PTR_TO_NULL: 11603 continue; 11604 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11605 case KF_ARG_PTR_TO_BTF_ID: 11606 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 11607 break; 11608 11609 if (!is_trusted_reg(reg)) { 11610 if (!is_kfunc_rcu(meta)) { 11611 verbose(env, "R%d must be referenced or trusted\n", regno); 11612 return -EINVAL; 11613 } 11614 if (!is_rcu_reg(reg)) { 11615 verbose(env, "R%d must be a rcu pointer\n", regno); 11616 return -EINVAL; 11617 } 11618 } 11619 11620 fallthrough; 11621 case KF_ARG_PTR_TO_CTX: 11622 /* Trusted arguments have the same offset checks as release arguments */ 11623 arg_type |= OBJ_RELEASE; 11624 break; 11625 case KF_ARG_PTR_TO_DYNPTR: 11626 case KF_ARG_PTR_TO_ITER: 11627 case KF_ARG_PTR_TO_LIST_HEAD: 11628 case KF_ARG_PTR_TO_LIST_NODE: 11629 case KF_ARG_PTR_TO_RB_ROOT: 11630 case KF_ARG_PTR_TO_RB_NODE: 11631 case KF_ARG_PTR_TO_MEM: 11632 case KF_ARG_PTR_TO_MEM_SIZE: 11633 case KF_ARG_PTR_TO_CALLBACK: 11634 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11635 case KF_ARG_PTR_TO_CONST_STR: 11636 /* Trusted by default */ 11637 break; 11638 default: 11639 WARN_ON_ONCE(1); 11640 return -EFAULT; 11641 } 11642 11643 if (is_kfunc_release(meta) && reg->ref_obj_id) 11644 arg_type |= OBJ_RELEASE; 11645 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 11646 if (ret < 0) 11647 return ret; 11648 11649 switch (kf_arg_type) { 11650 case KF_ARG_PTR_TO_CTX: 11651 if (reg->type != PTR_TO_CTX) { 11652 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 11653 return -EINVAL; 11654 } 11655 11656 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11657 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 11658 if (ret < 0) 11659 return -EINVAL; 11660 meta->ret_btf_id = ret; 11661 } 11662 break; 11663 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11664 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 11665 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) { 11666 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i); 11667 return -EINVAL; 11668 } 11669 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 11670 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 11671 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i); 11672 return -EINVAL; 11673 } 11674 } else { 11675 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11676 return -EINVAL; 11677 } 11678 if (!reg->ref_obj_id) { 11679 verbose(env, "allocated object must be referenced\n"); 11680 return -EINVAL; 11681 } 11682 if (meta->btf == btf_vmlinux) { 11683 meta->arg_btf = reg->btf; 11684 meta->arg_btf_id = reg->btf_id; 11685 } 11686 break; 11687 case KF_ARG_PTR_TO_DYNPTR: 11688 { 11689 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 11690 int clone_ref_obj_id = 0; 11691 11692 if (reg->type != PTR_TO_STACK && 11693 reg->type != CONST_PTR_TO_DYNPTR) { 11694 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 11695 return -EINVAL; 11696 } 11697 11698 if (reg->type == CONST_PTR_TO_DYNPTR) 11699 dynptr_arg_type |= MEM_RDONLY; 11700 11701 if (is_kfunc_arg_uninit(btf, &args[i])) 11702 dynptr_arg_type |= MEM_UNINIT; 11703 11704 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 11705 dynptr_arg_type |= DYNPTR_TYPE_SKB; 11706 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 11707 dynptr_arg_type |= DYNPTR_TYPE_XDP; 11708 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 11709 (dynptr_arg_type & MEM_UNINIT)) { 11710 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 11711 11712 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 11713 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 11714 return -EFAULT; 11715 } 11716 11717 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 11718 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 11719 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 11720 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 11721 return -EFAULT; 11722 } 11723 } 11724 11725 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 11726 if (ret < 0) 11727 return ret; 11728 11729 if (!(dynptr_arg_type & MEM_UNINIT)) { 11730 int id = dynptr_id(env, reg); 11731 11732 if (id < 0) { 11733 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 11734 return id; 11735 } 11736 meta->initialized_dynptr.id = id; 11737 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 11738 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 11739 } 11740 11741 break; 11742 } 11743 case KF_ARG_PTR_TO_ITER: 11744 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 11745 if (!check_css_task_iter_allowlist(env)) { 11746 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 11747 return -EINVAL; 11748 } 11749 } 11750 ret = process_iter_arg(env, regno, insn_idx, meta); 11751 if (ret < 0) 11752 return ret; 11753 break; 11754 case KF_ARG_PTR_TO_LIST_HEAD: 11755 if (reg->type != PTR_TO_MAP_VALUE && 11756 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11757 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11758 return -EINVAL; 11759 } 11760 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11761 verbose(env, "allocated object must be referenced\n"); 11762 return -EINVAL; 11763 } 11764 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 11765 if (ret < 0) 11766 return ret; 11767 break; 11768 case KF_ARG_PTR_TO_RB_ROOT: 11769 if (reg->type != PTR_TO_MAP_VALUE && 11770 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11771 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11772 return -EINVAL; 11773 } 11774 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11775 verbose(env, "allocated object must be referenced\n"); 11776 return -EINVAL; 11777 } 11778 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 11779 if (ret < 0) 11780 return ret; 11781 break; 11782 case KF_ARG_PTR_TO_LIST_NODE: 11783 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11784 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11785 return -EINVAL; 11786 } 11787 if (!reg->ref_obj_id) { 11788 verbose(env, "allocated object must be referenced\n"); 11789 return -EINVAL; 11790 } 11791 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 11792 if (ret < 0) 11793 return ret; 11794 break; 11795 case KF_ARG_PTR_TO_RB_NODE: 11796 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 11797 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 11798 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 11799 return -EINVAL; 11800 } 11801 if (in_rbtree_lock_required_cb(env)) { 11802 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 11803 return -EINVAL; 11804 } 11805 } else { 11806 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11807 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11808 return -EINVAL; 11809 } 11810 if (!reg->ref_obj_id) { 11811 verbose(env, "allocated object must be referenced\n"); 11812 return -EINVAL; 11813 } 11814 } 11815 11816 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 11817 if (ret < 0) 11818 return ret; 11819 break; 11820 case KF_ARG_PTR_TO_BTF_ID: 11821 /* Only base_type is checked, further checks are done here */ 11822 if ((base_type(reg->type) != PTR_TO_BTF_ID || 11823 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 11824 !reg2btf_ids[base_type(reg->type)]) { 11825 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 11826 verbose(env, "expected %s or socket\n", 11827 reg_type_str(env, base_type(reg->type) | 11828 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 11829 return -EINVAL; 11830 } 11831 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 11832 if (ret < 0) 11833 return ret; 11834 break; 11835 case KF_ARG_PTR_TO_MEM: 11836 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 11837 if (IS_ERR(resolve_ret)) { 11838 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 11839 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 11840 return -EINVAL; 11841 } 11842 ret = check_mem_reg(env, reg, regno, type_size); 11843 if (ret < 0) 11844 return ret; 11845 break; 11846 case KF_ARG_PTR_TO_MEM_SIZE: 11847 { 11848 struct bpf_reg_state *buff_reg = ®s[regno]; 11849 const struct btf_param *buff_arg = &args[i]; 11850 struct bpf_reg_state *size_reg = ®s[regno + 1]; 11851 const struct btf_param *size_arg = &args[i + 1]; 11852 11853 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 11854 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 11855 if (ret < 0) { 11856 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 11857 return ret; 11858 } 11859 } 11860 11861 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 11862 if (meta->arg_constant.found) { 11863 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11864 return -EFAULT; 11865 } 11866 if (!tnum_is_const(size_reg->var_off)) { 11867 verbose(env, "R%d must be a known constant\n", regno + 1); 11868 return -EINVAL; 11869 } 11870 meta->arg_constant.found = true; 11871 meta->arg_constant.value = size_reg->var_off.value; 11872 } 11873 11874 /* Skip next '__sz' or '__szk' argument */ 11875 i++; 11876 break; 11877 } 11878 case KF_ARG_PTR_TO_CALLBACK: 11879 if (reg->type != PTR_TO_FUNC) { 11880 verbose(env, "arg%d expected pointer to func\n", i); 11881 return -EINVAL; 11882 } 11883 meta->subprogno = reg->subprogno; 11884 break; 11885 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11886 if (!type_is_ptr_alloc_obj(reg->type)) { 11887 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 11888 return -EINVAL; 11889 } 11890 if (!type_is_non_owning_ref(reg->type)) 11891 meta->arg_owning_ref = true; 11892 11893 rec = reg_btf_record(reg); 11894 if (!rec) { 11895 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 11896 return -EFAULT; 11897 } 11898 11899 if (rec->refcount_off < 0) { 11900 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 11901 return -EINVAL; 11902 } 11903 11904 meta->arg_btf = reg->btf; 11905 meta->arg_btf_id = reg->btf_id; 11906 break; 11907 case KF_ARG_PTR_TO_CONST_STR: 11908 if (reg->type != PTR_TO_MAP_VALUE) { 11909 verbose(env, "arg#%d doesn't point to a const string\n", i); 11910 return -EINVAL; 11911 } 11912 ret = check_reg_const_str(env, reg, regno); 11913 if (ret) 11914 return ret; 11915 break; 11916 } 11917 } 11918 11919 if (is_kfunc_release(meta) && !meta->release_regno) { 11920 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 11921 func_name); 11922 return -EINVAL; 11923 } 11924 11925 return 0; 11926 } 11927 11928 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 11929 struct bpf_insn *insn, 11930 struct bpf_kfunc_call_arg_meta *meta, 11931 const char **kfunc_name) 11932 { 11933 const struct btf_type *func, *func_proto; 11934 u32 func_id, *kfunc_flags; 11935 const char *func_name; 11936 struct btf *desc_btf; 11937 11938 if (kfunc_name) 11939 *kfunc_name = NULL; 11940 11941 if (!insn->imm) 11942 return -EINVAL; 11943 11944 desc_btf = find_kfunc_desc_btf(env, insn->off); 11945 if (IS_ERR(desc_btf)) 11946 return PTR_ERR(desc_btf); 11947 11948 func_id = insn->imm; 11949 func = btf_type_by_id(desc_btf, func_id); 11950 func_name = btf_name_by_offset(desc_btf, func->name_off); 11951 if (kfunc_name) 11952 *kfunc_name = func_name; 11953 func_proto = btf_type_by_id(desc_btf, func->type); 11954 11955 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 11956 if (!kfunc_flags) { 11957 return -EACCES; 11958 } 11959 11960 memset(meta, 0, sizeof(*meta)); 11961 meta->btf = desc_btf; 11962 meta->func_id = func_id; 11963 meta->kfunc_flags = *kfunc_flags; 11964 meta->func_proto = func_proto; 11965 meta->func_name = func_name; 11966 11967 return 0; 11968 } 11969 11970 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 11971 11972 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 11973 int *insn_idx_p) 11974 { 11975 const struct btf_type *t, *ptr_type; 11976 u32 i, nargs, ptr_type_id, release_ref_obj_id; 11977 struct bpf_reg_state *regs = cur_regs(env); 11978 const char *func_name, *ptr_type_name; 11979 bool sleepable, rcu_lock, rcu_unlock; 11980 struct bpf_kfunc_call_arg_meta meta; 11981 struct bpf_insn_aux_data *insn_aux; 11982 int err, insn_idx = *insn_idx_p; 11983 const struct btf_param *args; 11984 const struct btf_type *ret_t; 11985 struct btf *desc_btf; 11986 11987 /* skip for now, but return error when we find this in fixup_kfunc_call */ 11988 if (!insn->imm) 11989 return 0; 11990 11991 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 11992 if (err == -EACCES && func_name) 11993 verbose(env, "calling kernel function %s is not allowed\n", func_name); 11994 if (err) 11995 return err; 11996 desc_btf = meta.btf; 11997 insn_aux = &env->insn_aux_data[insn_idx]; 11998 11999 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 12000 12001 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 12002 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 12003 return -EACCES; 12004 } 12005 12006 sleepable = is_kfunc_sleepable(&meta); 12007 if (sleepable && !env->prog->aux->sleepable) { 12008 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 12009 return -EACCES; 12010 } 12011 12012 /* Check the arguments */ 12013 err = check_kfunc_args(env, &meta, insn_idx); 12014 if (err < 0) 12015 return err; 12016 12017 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12018 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12019 set_rbtree_add_callback_state); 12020 if (err) { 12021 verbose(env, "kfunc %s#%d failed callback verification\n", 12022 func_name, meta.func_id); 12023 return err; 12024 } 12025 } 12026 12027 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 12028 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 12029 12030 if (env->cur_state->active_rcu_lock) { 12031 struct bpf_func_state *state; 12032 struct bpf_reg_state *reg; 12033 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 12034 12035 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 12036 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 12037 return -EACCES; 12038 } 12039 12040 if (rcu_lock) { 12041 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 12042 return -EINVAL; 12043 } else if (rcu_unlock) { 12044 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({ 12045 if (reg->type & MEM_RCU) { 12046 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 12047 reg->type |= PTR_UNTRUSTED; 12048 } 12049 })); 12050 env->cur_state->active_rcu_lock = false; 12051 } else if (sleepable) { 12052 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 12053 return -EACCES; 12054 } 12055 } else if (rcu_lock) { 12056 env->cur_state->active_rcu_lock = true; 12057 } else if (rcu_unlock) { 12058 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 12059 return -EINVAL; 12060 } 12061 12062 /* In case of release function, we get register number of refcounted 12063 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 12064 */ 12065 if (meta.release_regno) { 12066 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 12067 if (err) { 12068 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12069 func_name, meta.func_id); 12070 return err; 12071 } 12072 } 12073 12074 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 12075 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 12076 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12077 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 12078 insn_aux->insert_off = regs[BPF_REG_2].off; 12079 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 12080 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 12081 if (err) { 12082 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 12083 func_name, meta.func_id); 12084 return err; 12085 } 12086 12087 err = release_reference(env, release_ref_obj_id); 12088 if (err) { 12089 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12090 func_name, meta.func_id); 12091 return err; 12092 } 12093 } 12094 12095 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 12096 if (!bpf_jit_supports_exceptions()) { 12097 verbose(env, "JIT does not support calling kfunc %s#%d\n", 12098 func_name, meta.func_id); 12099 return -ENOTSUPP; 12100 } 12101 env->seen_exception = true; 12102 12103 /* In the case of the default callback, the cookie value passed 12104 * to bpf_throw becomes the return value of the program. 12105 */ 12106 if (!env->exception_callback_subprog) { 12107 err = check_return_code(env, BPF_REG_1, "R1"); 12108 if (err < 0) 12109 return err; 12110 } 12111 } 12112 12113 for (i = 0; i < CALLER_SAVED_REGS; i++) 12114 mark_reg_not_init(env, regs, caller_saved[i]); 12115 12116 /* Check return type */ 12117 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 12118 12119 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 12120 /* Only exception is bpf_obj_new_impl */ 12121 if (meta.btf != btf_vmlinux || 12122 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 12123 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] && 12124 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 12125 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 12126 return -EINVAL; 12127 } 12128 } 12129 12130 if (btf_type_is_scalar(t)) { 12131 mark_reg_unknown(env, regs, BPF_REG_0); 12132 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 12133 } else if (btf_type_is_ptr(t)) { 12134 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 12135 12136 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12137 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 12138 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12139 struct btf_struct_meta *struct_meta; 12140 struct btf *ret_btf; 12141 u32 ret_btf_id; 12142 12143 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set) 12144 return -ENOMEM; 12145 12146 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 12147 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 12148 return -EINVAL; 12149 } 12150 12151 ret_btf = env->prog->aux->btf; 12152 ret_btf_id = meta.arg_constant.value; 12153 12154 /* This may be NULL due to user not supplying a BTF */ 12155 if (!ret_btf) { 12156 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 12157 return -EINVAL; 12158 } 12159 12160 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 12161 if (!ret_t || !__btf_type_is_struct(ret_t)) { 12162 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 12163 return -EINVAL; 12164 } 12165 12166 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12167 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 12168 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 12169 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 12170 return -EINVAL; 12171 } 12172 12173 if (!bpf_global_percpu_ma_set) { 12174 mutex_lock(&bpf_percpu_ma_lock); 12175 if (!bpf_global_percpu_ma_set) { 12176 /* Charge memory allocated with bpf_global_percpu_ma to 12177 * root memcg. The obj_cgroup for root memcg is NULL. 12178 */ 12179 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 12180 if (!err) 12181 bpf_global_percpu_ma_set = true; 12182 } 12183 mutex_unlock(&bpf_percpu_ma_lock); 12184 if (err) 12185 return err; 12186 } 12187 12188 mutex_lock(&bpf_percpu_ma_lock); 12189 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 12190 mutex_unlock(&bpf_percpu_ma_lock); 12191 if (err) 12192 return err; 12193 } 12194 12195 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 12196 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12197 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 12198 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 12199 return -EINVAL; 12200 } 12201 12202 if (struct_meta) { 12203 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 12204 return -EINVAL; 12205 } 12206 } 12207 12208 mark_reg_known_zero(env, regs, BPF_REG_0); 12209 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12210 regs[BPF_REG_0].btf = ret_btf; 12211 regs[BPF_REG_0].btf_id = ret_btf_id; 12212 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) 12213 regs[BPF_REG_0].type |= MEM_PERCPU; 12214 12215 insn_aux->obj_new_size = ret_t->size; 12216 insn_aux->kptr_struct_meta = struct_meta; 12217 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 12218 mark_reg_known_zero(env, regs, BPF_REG_0); 12219 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12220 regs[BPF_REG_0].btf = meta.arg_btf; 12221 regs[BPF_REG_0].btf_id = meta.arg_btf_id; 12222 12223 insn_aux->kptr_struct_meta = 12224 btf_find_struct_meta(meta.arg_btf, 12225 meta.arg_btf_id); 12226 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 12227 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 12228 struct btf_field *field = meta.arg_list_head.field; 12229 12230 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12231 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12232 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12233 struct btf_field *field = meta.arg_rbtree_root.field; 12234 12235 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12236 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12237 mark_reg_known_zero(env, regs, BPF_REG_0); 12238 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 12239 regs[BPF_REG_0].btf = desc_btf; 12240 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 12241 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 12242 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 12243 if (!ret_t || !btf_type_is_struct(ret_t)) { 12244 verbose(env, 12245 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 12246 return -EINVAL; 12247 } 12248 12249 mark_reg_known_zero(env, regs, BPF_REG_0); 12250 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 12251 regs[BPF_REG_0].btf = desc_btf; 12252 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 12253 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 12254 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 12255 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 12256 12257 mark_reg_known_zero(env, regs, BPF_REG_0); 12258 12259 if (!meta.arg_constant.found) { 12260 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 12261 return -EFAULT; 12262 } 12263 12264 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 12265 12266 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 12267 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 12268 12269 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 12270 regs[BPF_REG_0].type |= MEM_RDONLY; 12271 } else { 12272 /* this will set env->seen_direct_write to true */ 12273 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 12274 verbose(env, "the prog does not allow writes to packet data\n"); 12275 return -EINVAL; 12276 } 12277 } 12278 12279 if (!meta.initialized_dynptr.id) { 12280 verbose(env, "verifier internal error: no dynptr id\n"); 12281 return -EFAULT; 12282 } 12283 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 12284 12285 /* we don't need to set BPF_REG_0's ref obj id 12286 * because packet slices are not refcounted (see 12287 * dynptr_type_refcounted) 12288 */ 12289 } else { 12290 verbose(env, "kernel function %s unhandled dynamic return type\n", 12291 meta.func_name); 12292 return -EFAULT; 12293 } 12294 } else if (!__btf_type_is_struct(ptr_type)) { 12295 if (!meta.r0_size) { 12296 __u32 sz; 12297 12298 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 12299 meta.r0_size = sz; 12300 meta.r0_rdonly = true; 12301 } 12302 } 12303 if (!meta.r0_size) { 12304 ptr_type_name = btf_name_by_offset(desc_btf, 12305 ptr_type->name_off); 12306 verbose(env, 12307 "kernel function %s returns pointer type %s %s is not supported\n", 12308 func_name, 12309 btf_type_str(ptr_type), 12310 ptr_type_name); 12311 return -EINVAL; 12312 } 12313 12314 mark_reg_known_zero(env, regs, BPF_REG_0); 12315 regs[BPF_REG_0].type = PTR_TO_MEM; 12316 regs[BPF_REG_0].mem_size = meta.r0_size; 12317 12318 if (meta.r0_rdonly) 12319 regs[BPF_REG_0].type |= MEM_RDONLY; 12320 12321 /* Ensures we don't access the memory after a release_reference() */ 12322 if (meta.ref_obj_id) 12323 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 12324 } else { 12325 mark_reg_known_zero(env, regs, BPF_REG_0); 12326 regs[BPF_REG_0].btf = desc_btf; 12327 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 12328 regs[BPF_REG_0].btf_id = ptr_type_id; 12329 } 12330 12331 if (is_kfunc_ret_null(&meta)) { 12332 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 12333 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 12334 regs[BPF_REG_0].id = ++env->id_gen; 12335 } 12336 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 12337 if (is_kfunc_acquire(&meta)) { 12338 int id = acquire_reference_state(env, insn_idx); 12339 12340 if (id < 0) 12341 return id; 12342 if (is_kfunc_ret_null(&meta)) 12343 regs[BPF_REG_0].id = id; 12344 regs[BPF_REG_0].ref_obj_id = id; 12345 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12346 ref_set_non_owning(env, ®s[BPF_REG_0]); 12347 } 12348 12349 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 12350 regs[BPF_REG_0].id = ++env->id_gen; 12351 } else if (btf_type_is_void(t)) { 12352 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12353 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 12354 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 12355 insn_aux->kptr_struct_meta = 12356 btf_find_struct_meta(meta.arg_btf, 12357 meta.arg_btf_id); 12358 } 12359 } 12360 } 12361 12362 nargs = btf_type_vlen(meta.func_proto); 12363 args = (const struct btf_param *)(meta.func_proto + 1); 12364 for (i = 0; i < nargs; i++) { 12365 u32 regno = i + 1; 12366 12367 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 12368 if (btf_type_is_ptr(t)) 12369 mark_btf_func_reg_size(env, regno, sizeof(void *)); 12370 else 12371 /* scalar. ensured by btf_check_kfunc_arg_match() */ 12372 mark_btf_func_reg_size(env, regno, t->size); 12373 } 12374 12375 if (is_iter_next_kfunc(&meta)) { 12376 err = process_iter_next_call(env, insn_idx, &meta); 12377 if (err) 12378 return err; 12379 } 12380 12381 return 0; 12382 } 12383 12384 static bool signed_add_overflows(s64 a, s64 b) 12385 { 12386 /* Do the add in u64, where overflow is well-defined */ 12387 s64 res = (s64)((u64)a + (u64)b); 12388 12389 if (b < 0) 12390 return res > a; 12391 return res < a; 12392 } 12393 12394 static bool signed_add32_overflows(s32 a, s32 b) 12395 { 12396 /* Do the add in u32, where overflow is well-defined */ 12397 s32 res = (s32)((u32)a + (u32)b); 12398 12399 if (b < 0) 12400 return res > a; 12401 return res < a; 12402 } 12403 12404 static bool signed_sub_overflows(s64 a, s64 b) 12405 { 12406 /* Do the sub in u64, where overflow is well-defined */ 12407 s64 res = (s64)((u64)a - (u64)b); 12408 12409 if (b < 0) 12410 return res < a; 12411 return res > a; 12412 } 12413 12414 static bool signed_sub32_overflows(s32 a, s32 b) 12415 { 12416 /* Do the sub in u32, where overflow is well-defined */ 12417 s32 res = (s32)((u32)a - (u32)b); 12418 12419 if (b < 0) 12420 return res < a; 12421 return res > a; 12422 } 12423 12424 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 12425 const struct bpf_reg_state *reg, 12426 enum bpf_reg_type type) 12427 { 12428 bool known = tnum_is_const(reg->var_off); 12429 s64 val = reg->var_off.value; 12430 s64 smin = reg->smin_value; 12431 12432 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 12433 verbose(env, "math between %s pointer and %lld is not allowed\n", 12434 reg_type_str(env, type), val); 12435 return false; 12436 } 12437 12438 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 12439 verbose(env, "%s pointer offset %d is not allowed\n", 12440 reg_type_str(env, type), reg->off); 12441 return false; 12442 } 12443 12444 if (smin == S64_MIN) { 12445 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 12446 reg_type_str(env, type)); 12447 return false; 12448 } 12449 12450 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 12451 verbose(env, "value %lld makes %s pointer be out of bounds\n", 12452 smin, reg_type_str(env, type)); 12453 return false; 12454 } 12455 12456 return true; 12457 } 12458 12459 enum { 12460 REASON_BOUNDS = -1, 12461 REASON_TYPE = -2, 12462 REASON_PATHS = -3, 12463 REASON_LIMIT = -4, 12464 REASON_STACK = -5, 12465 }; 12466 12467 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 12468 u32 *alu_limit, bool mask_to_left) 12469 { 12470 u32 max = 0, ptr_limit = 0; 12471 12472 switch (ptr_reg->type) { 12473 case PTR_TO_STACK: 12474 /* Offset 0 is out-of-bounds, but acceptable start for the 12475 * left direction, see BPF_REG_FP. Also, unknown scalar 12476 * offset where we would need to deal with min/max bounds is 12477 * currently prohibited for unprivileged. 12478 */ 12479 max = MAX_BPF_STACK + mask_to_left; 12480 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 12481 break; 12482 case PTR_TO_MAP_VALUE: 12483 max = ptr_reg->map_ptr->value_size; 12484 ptr_limit = (mask_to_left ? 12485 ptr_reg->smin_value : 12486 ptr_reg->umax_value) + ptr_reg->off; 12487 break; 12488 default: 12489 return REASON_TYPE; 12490 } 12491 12492 if (ptr_limit >= max) 12493 return REASON_LIMIT; 12494 *alu_limit = ptr_limit; 12495 return 0; 12496 } 12497 12498 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 12499 const struct bpf_insn *insn) 12500 { 12501 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 12502 } 12503 12504 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 12505 u32 alu_state, u32 alu_limit) 12506 { 12507 /* If we arrived here from different branches with different 12508 * state or limits to sanitize, then this won't work. 12509 */ 12510 if (aux->alu_state && 12511 (aux->alu_state != alu_state || 12512 aux->alu_limit != alu_limit)) 12513 return REASON_PATHS; 12514 12515 /* Corresponding fixup done in do_misc_fixups(). */ 12516 aux->alu_state = alu_state; 12517 aux->alu_limit = alu_limit; 12518 return 0; 12519 } 12520 12521 static int sanitize_val_alu(struct bpf_verifier_env *env, 12522 struct bpf_insn *insn) 12523 { 12524 struct bpf_insn_aux_data *aux = cur_aux(env); 12525 12526 if (can_skip_alu_sanitation(env, insn)) 12527 return 0; 12528 12529 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 12530 } 12531 12532 static bool sanitize_needed(u8 opcode) 12533 { 12534 return opcode == BPF_ADD || opcode == BPF_SUB; 12535 } 12536 12537 struct bpf_sanitize_info { 12538 struct bpf_insn_aux_data aux; 12539 bool mask_to_left; 12540 }; 12541 12542 static struct bpf_verifier_state * 12543 sanitize_speculative_path(struct bpf_verifier_env *env, 12544 const struct bpf_insn *insn, 12545 u32 next_idx, u32 curr_idx) 12546 { 12547 struct bpf_verifier_state *branch; 12548 struct bpf_reg_state *regs; 12549 12550 branch = push_stack(env, next_idx, curr_idx, true); 12551 if (branch && insn) { 12552 regs = branch->frame[branch->curframe]->regs; 12553 if (BPF_SRC(insn->code) == BPF_K) { 12554 mark_reg_unknown(env, regs, insn->dst_reg); 12555 } else if (BPF_SRC(insn->code) == BPF_X) { 12556 mark_reg_unknown(env, regs, insn->dst_reg); 12557 mark_reg_unknown(env, regs, insn->src_reg); 12558 } 12559 } 12560 return branch; 12561 } 12562 12563 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 12564 struct bpf_insn *insn, 12565 const struct bpf_reg_state *ptr_reg, 12566 const struct bpf_reg_state *off_reg, 12567 struct bpf_reg_state *dst_reg, 12568 struct bpf_sanitize_info *info, 12569 const bool commit_window) 12570 { 12571 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 12572 struct bpf_verifier_state *vstate = env->cur_state; 12573 bool off_is_imm = tnum_is_const(off_reg->var_off); 12574 bool off_is_neg = off_reg->smin_value < 0; 12575 bool ptr_is_dst_reg = ptr_reg == dst_reg; 12576 u8 opcode = BPF_OP(insn->code); 12577 u32 alu_state, alu_limit; 12578 struct bpf_reg_state tmp; 12579 bool ret; 12580 int err; 12581 12582 if (can_skip_alu_sanitation(env, insn)) 12583 return 0; 12584 12585 /* We already marked aux for masking from non-speculative 12586 * paths, thus we got here in the first place. We only care 12587 * to explore bad access from here. 12588 */ 12589 if (vstate->speculative) 12590 goto do_sim; 12591 12592 if (!commit_window) { 12593 if (!tnum_is_const(off_reg->var_off) && 12594 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 12595 return REASON_BOUNDS; 12596 12597 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 12598 (opcode == BPF_SUB && !off_is_neg); 12599 } 12600 12601 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 12602 if (err < 0) 12603 return err; 12604 12605 if (commit_window) { 12606 /* In commit phase we narrow the masking window based on 12607 * the observed pointer move after the simulated operation. 12608 */ 12609 alu_state = info->aux.alu_state; 12610 alu_limit = abs(info->aux.alu_limit - alu_limit); 12611 } else { 12612 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 12613 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 12614 alu_state |= ptr_is_dst_reg ? 12615 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 12616 12617 /* Limit pruning on unknown scalars to enable deep search for 12618 * potential masking differences from other program paths. 12619 */ 12620 if (!off_is_imm) 12621 env->explore_alu_limits = true; 12622 } 12623 12624 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 12625 if (err < 0) 12626 return err; 12627 do_sim: 12628 /* If we're in commit phase, we're done here given we already 12629 * pushed the truncated dst_reg into the speculative verification 12630 * stack. 12631 * 12632 * Also, when register is a known constant, we rewrite register-based 12633 * operation to immediate-based, and thus do not need masking (and as 12634 * a consequence, do not need to simulate the zero-truncation either). 12635 */ 12636 if (commit_window || off_is_imm) 12637 return 0; 12638 12639 /* Simulate and find potential out-of-bounds access under 12640 * speculative execution from truncation as a result of 12641 * masking when off was not within expected range. If off 12642 * sits in dst, then we temporarily need to move ptr there 12643 * to simulate dst (== 0) +/-= ptr. Needed, for example, 12644 * for cases where we use K-based arithmetic in one direction 12645 * and truncated reg-based in the other in order to explore 12646 * bad access. 12647 */ 12648 if (!ptr_is_dst_reg) { 12649 tmp = *dst_reg; 12650 copy_register_state(dst_reg, ptr_reg); 12651 } 12652 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 12653 env->insn_idx); 12654 if (!ptr_is_dst_reg && ret) 12655 *dst_reg = tmp; 12656 return !ret ? REASON_STACK : 0; 12657 } 12658 12659 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 12660 { 12661 struct bpf_verifier_state *vstate = env->cur_state; 12662 12663 /* If we simulate paths under speculation, we don't update the 12664 * insn as 'seen' such that when we verify unreachable paths in 12665 * the non-speculative domain, sanitize_dead_code() can still 12666 * rewrite/sanitize them. 12667 */ 12668 if (!vstate->speculative) 12669 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 12670 } 12671 12672 static int sanitize_err(struct bpf_verifier_env *env, 12673 const struct bpf_insn *insn, int reason, 12674 const struct bpf_reg_state *off_reg, 12675 const struct bpf_reg_state *dst_reg) 12676 { 12677 static const char *err = "pointer arithmetic with it prohibited for !root"; 12678 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 12679 u32 dst = insn->dst_reg, src = insn->src_reg; 12680 12681 switch (reason) { 12682 case REASON_BOUNDS: 12683 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 12684 off_reg == dst_reg ? dst : src, err); 12685 break; 12686 case REASON_TYPE: 12687 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 12688 off_reg == dst_reg ? src : dst, err); 12689 break; 12690 case REASON_PATHS: 12691 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 12692 dst, op, err); 12693 break; 12694 case REASON_LIMIT: 12695 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 12696 dst, op, err); 12697 break; 12698 case REASON_STACK: 12699 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 12700 dst, err); 12701 break; 12702 default: 12703 verbose(env, "verifier internal error: unknown reason (%d)\n", 12704 reason); 12705 break; 12706 } 12707 12708 return -EACCES; 12709 } 12710 12711 /* check that stack access falls within stack limits and that 'reg' doesn't 12712 * have a variable offset. 12713 * 12714 * Variable offset is prohibited for unprivileged mode for simplicity since it 12715 * requires corresponding support in Spectre masking for stack ALU. See also 12716 * retrieve_ptr_limit(). 12717 * 12718 * 12719 * 'off' includes 'reg->off'. 12720 */ 12721 static int check_stack_access_for_ptr_arithmetic( 12722 struct bpf_verifier_env *env, 12723 int regno, 12724 const struct bpf_reg_state *reg, 12725 int off) 12726 { 12727 if (!tnum_is_const(reg->var_off)) { 12728 char tn_buf[48]; 12729 12730 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 12731 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 12732 regno, tn_buf, off); 12733 return -EACCES; 12734 } 12735 12736 if (off >= 0 || off < -MAX_BPF_STACK) { 12737 verbose(env, "R%d stack pointer arithmetic goes out of range, " 12738 "prohibited for !root; off=%d\n", regno, off); 12739 return -EACCES; 12740 } 12741 12742 return 0; 12743 } 12744 12745 static int sanitize_check_bounds(struct bpf_verifier_env *env, 12746 const struct bpf_insn *insn, 12747 const struct bpf_reg_state *dst_reg) 12748 { 12749 u32 dst = insn->dst_reg; 12750 12751 /* For unprivileged we require that resulting offset must be in bounds 12752 * in order to be able to sanitize access later on. 12753 */ 12754 if (env->bypass_spec_v1) 12755 return 0; 12756 12757 switch (dst_reg->type) { 12758 case PTR_TO_STACK: 12759 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 12760 dst_reg->off + dst_reg->var_off.value)) 12761 return -EACCES; 12762 break; 12763 case PTR_TO_MAP_VALUE: 12764 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 12765 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 12766 "prohibited for !root\n", dst); 12767 return -EACCES; 12768 } 12769 break; 12770 default: 12771 break; 12772 } 12773 12774 return 0; 12775 } 12776 12777 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 12778 * Caller should also handle BPF_MOV case separately. 12779 * If we return -EACCES, caller may want to try again treating pointer as a 12780 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 12781 */ 12782 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 12783 struct bpf_insn *insn, 12784 const struct bpf_reg_state *ptr_reg, 12785 const struct bpf_reg_state *off_reg) 12786 { 12787 struct bpf_verifier_state *vstate = env->cur_state; 12788 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 12789 struct bpf_reg_state *regs = state->regs, *dst_reg; 12790 bool known = tnum_is_const(off_reg->var_off); 12791 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 12792 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 12793 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 12794 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 12795 struct bpf_sanitize_info info = {}; 12796 u8 opcode = BPF_OP(insn->code); 12797 u32 dst = insn->dst_reg; 12798 int ret; 12799 12800 dst_reg = ®s[dst]; 12801 12802 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 12803 smin_val > smax_val || umin_val > umax_val) { 12804 /* Taint dst register if offset had invalid bounds derived from 12805 * e.g. dead branches. 12806 */ 12807 __mark_reg_unknown(env, dst_reg); 12808 return 0; 12809 } 12810 12811 if (BPF_CLASS(insn->code) != BPF_ALU64) { 12812 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 12813 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 12814 __mark_reg_unknown(env, dst_reg); 12815 return 0; 12816 } 12817 12818 verbose(env, 12819 "R%d 32-bit pointer arithmetic prohibited\n", 12820 dst); 12821 return -EACCES; 12822 } 12823 12824 if (ptr_reg->type & PTR_MAYBE_NULL) { 12825 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 12826 dst, reg_type_str(env, ptr_reg->type)); 12827 return -EACCES; 12828 } 12829 12830 switch (base_type(ptr_reg->type)) { 12831 case PTR_TO_FLOW_KEYS: 12832 if (known) 12833 break; 12834 fallthrough; 12835 case CONST_PTR_TO_MAP: 12836 /* smin_val represents the known value */ 12837 if (known && smin_val == 0 && opcode == BPF_ADD) 12838 break; 12839 fallthrough; 12840 case PTR_TO_PACKET_END: 12841 case PTR_TO_SOCKET: 12842 case PTR_TO_SOCK_COMMON: 12843 case PTR_TO_TCP_SOCK: 12844 case PTR_TO_XDP_SOCK: 12845 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 12846 dst, reg_type_str(env, ptr_reg->type)); 12847 return -EACCES; 12848 default: 12849 break; 12850 } 12851 12852 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 12853 * The id may be overwritten later if we create a new variable offset. 12854 */ 12855 dst_reg->type = ptr_reg->type; 12856 dst_reg->id = ptr_reg->id; 12857 12858 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 12859 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 12860 return -EINVAL; 12861 12862 /* pointer types do not carry 32-bit bounds at the moment. */ 12863 __mark_reg32_unbounded(dst_reg); 12864 12865 if (sanitize_needed(opcode)) { 12866 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 12867 &info, false); 12868 if (ret < 0) 12869 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12870 } 12871 12872 switch (opcode) { 12873 case BPF_ADD: 12874 /* We can take a fixed offset as long as it doesn't overflow 12875 * the s32 'off' field 12876 */ 12877 if (known && (ptr_reg->off + smin_val == 12878 (s64)(s32)(ptr_reg->off + smin_val))) { 12879 /* pointer += K. Accumulate it into fixed offset */ 12880 dst_reg->smin_value = smin_ptr; 12881 dst_reg->smax_value = smax_ptr; 12882 dst_reg->umin_value = umin_ptr; 12883 dst_reg->umax_value = umax_ptr; 12884 dst_reg->var_off = ptr_reg->var_off; 12885 dst_reg->off = ptr_reg->off + smin_val; 12886 dst_reg->raw = ptr_reg->raw; 12887 break; 12888 } 12889 /* A new variable offset is created. Note that off_reg->off 12890 * == 0, since it's a scalar. 12891 * dst_reg gets the pointer type and since some positive 12892 * integer value was added to the pointer, give it a new 'id' 12893 * if it's a PTR_TO_PACKET. 12894 * this creates a new 'base' pointer, off_reg (variable) gets 12895 * added into the variable offset, and we copy the fixed offset 12896 * from ptr_reg. 12897 */ 12898 if (signed_add_overflows(smin_ptr, smin_val) || 12899 signed_add_overflows(smax_ptr, smax_val)) { 12900 dst_reg->smin_value = S64_MIN; 12901 dst_reg->smax_value = S64_MAX; 12902 } else { 12903 dst_reg->smin_value = smin_ptr + smin_val; 12904 dst_reg->smax_value = smax_ptr + smax_val; 12905 } 12906 if (umin_ptr + umin_val < umin_ptr || 12907 umax_ptr + umax_val < umax_ptr) { 12908 dst_reg->umin_value = 0; 12909 dst_reg->umax_value = U64_MAX; 12910 } else { 12911 dst_reg->umin_value = umin_ptr + umin_val; 12912 dst_reg->umax_value = umax_ptr + umax_val; 12913 } 12914 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 12915 dst_reg->off = ptr_reg->off; 12916 dst_reg->raw = ptr_reg->raw; 12917 if (reg_is_pkt_pointer(ptr_reg)) { 12918 dst_reg->id = ++env->id_gen; 12919 /* something was added to pkt_ptr, set range to zero */ 12920 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12921 } 12922 break; 12923 case BPF_SUB: 12924 if (dst_reg == off_reg) { 12925 /* scalar -= pointer. Creates an unknown scalar */ 12926 verbose(env, "R%d tried to subtract pointer from scalar\n", 12927 dst); 12928 return -EACCES; 12929 } 12930 /* We don't allow subtraction from FP, because (according to 12931 * test_verifier.c test "invalid fp arithmetic", JITs might not 12932 * be able to deal with it. 12933 */ 12934 if (ptr_reg->type == PTR_TO_STACK) { 12935 verbose(env, "R%d subtraction from stack pointer prohibited\n", 12936 dst); 12937 return -EACCES; 12938 } 12939 if (known && (ptr_reg->off - smin_val == 12940 (s64)(s32)(ptr_reg->off - smin_val))) { 12941 /* pointer -= K. Subtract it from fixed offset */ 12942 dst_reg->smin_value = smin_ptr; 12943 dst_reg->smax_value = smax_ptr; 12944 dst_reg->umin_value = umin_ptr; 12945 dst_reg->umax_value = umax_ptr; 12946 dst_reg->var_off = ptr_reg->var_off; 12947 dst_reg->id = ptr_reg->id; 12948 dst_reg->off = ptr_reg->off - smin_val; 12949 dst_reg->raw = ptr_reg->raw; 12950 break; 12951 } 12952 /* A new variable offset is created. If the subtrahend is known 12953 * nonnegative, then any reg->range we had before is still good. 12954 */ 12955 if (signed_sub_overflows(smin_ptr, smax_val) || 12956 signed_sub_overflows(smax_ptr, smin_val)) { 12957 /* Overflow possible, we know nothing */ 12958 dst_reg->smin_value = S64_MIN; 12959 dst_reg->smax_value = S64_MAX; 12960 } else { 12961 dst_reg->smin_value = smin_ptr - smax_val; 12962 dst_reg->smax_value = smax_ptr - smin_val; 12963 } 12964 if (umin_ptr < umax_val) { 12965 /* Overflow possible, we know nothing */ 12966 dst_reg->umin_value = 0; 12967 dst_reg->umax_value = U64_MAX; 12968 } else { 12969 /* Cannot overflow (as long as bounds are consistent) */ 12970 dst_reg->umin_value = umin_ptr - umax_val; 12971 dst_reg->umax_value = umax_ptr - umin_val; 12972 } 12973 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 12974 dst_reg->off = ptr_reg->off; 12975 dst_reg->raw = ptr_reg->raw; 12976 if (reg_is_pkt_pointer(ptr_reg)) { 12977 dst_reg->id = ++env->id_gen; 12978 /* something was added to pkt_ptr, set range to zero */ 12979 if (smin_val < 0) 12980 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12981 } 12982 break; 12983 case BPF_AND: 12984 case BPF_OR: 12985 case BPF_XOR: 12986 /* bitwise ops on pointers are troublesome, prohibit. */ 12987 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 12988 dst, bpf_alu_string[opcode >> 4]); 12989 return -EACCES; 12990 default: 12991 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 12992 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 12993 dst, bpf_alu_string[opcode >> 4]); 12994 return -EACCES; 12995 } 12996 12997 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 12998 return -EINVAL; 12999 reg_bounds_sync(dst_reg); 13000 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 13001 return -EACCES; 13002 if (sanitize_needed(opcode)) { 13003 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 13004 &info, true); 13005 if (ret < 0) 13006 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13007 } 13008 13009 return 0; 13010 } 13011 13012 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 13013 struct bpf_reg_state *src_reg) 13014 { 13015 s32 smin_val = src_reg->s32_min_value; 13016 s32 smax_val = src_reg->s32_max_value; 13017 u32 umin_val = src_reg->u32_min_value; 13018 u32 umax_val = src_reg->u32_max_value; 13019 13020 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 13021 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 13022 dst_reg->s32_min_value = S32_MIN; 13023 dst_reg->s32_max_value = S32_MAX; 13024 } else { 13025 dst_reg->s32_min_value += smin_val; 13026 dst_reg->s32_max_value += smax_val; 13027 } 13028 if (dst_reg->u32_min_value + umin_val < umin_val || 13029 dst_reg->u32_max_value + umax_val < umax_val) { 13030 dst_reg->u32_min_value = 0; 13031 dst_reg->u32_max_value = U32_MAX; 13032 } else { 13033 dst_reg->u32_min_value += umin_val; 13034 dst_reg->u32_max_value += umax_val; 13035 } 13036 } 13037 13038 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 13039 struct bpf_reg_state *src_reg) 13040 { 13041 s64 smin_val = src_reg->smin_value; 13042 s64 smax_val = src_reg->smax_value; 13043 u64 umin_val = src_reg->umin_value; 13044 u64 umax_val = src_reg->umax_value; 13045 13046 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 13047 signed_add_overflows(dst_reg->smax_value, smax_val)) { 13048 dst_reg->smin_value = S64_MIN; 13049 dst_reg->smax_value = S64_MAX; 13050 } else { 13051 dst_reg->smin_value += smin_val; 13052 dst_reg->smax_value += smax_val; 13053 } 13054 if (dst_reg->umin_value + umin_val < umin_val || 13055 dst_reg->umax_value + umax_val < umax_val) { 13056 dst_reg->umin_value = 0; 13057 dst_reg->umax_value = U64_MAX; 13058 } else { 13059 dst_reg->umin_value += umin_val; 13060 dst_reg->umax_value += umax_val; 13061 } 13062 } 13063 13064 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 13065 struct bpf_reg_state *src_reg) 13066 { 13067 s32 smin_val = src_reg->s32_min_value; 13068 s32 smax_val = src_reg->s32_max_value; 13069 u32 umin_val = src_reg->u32_min_value; 13070 u32 umax_val = src_reg->u32_max_value; 13071 13072 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 13073 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 13074 /* Overflow possible, we know nothing */ 13075 dst_reg->s32_min_value = S32_MIN; 13076 dst_reg->s32_max_value = S32_MAX; 13077 } else { 13078 dst_reg->s32_min_value -= smax_val; 13079 dst_reg->s32_max_value -= smin_val; 13080 } 13081 if (dst_reg->u32_min_value < umax_val) { 13082 /* Overflow possible, we know nothing */ 13083 dst_reg->u32_min_value = 0; 13084 dst_reg->u32_max_value = U32_MAX; 13085 } else { 13086 /* Cannot overflow (as long as bounds are consistent) */ 13087 dst_reg->u32_min_value -= umax_val; 13088 dst_reg->u32_max_value -= umin_val; 13089 } 13090 } 13091 13092 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 13093 struct bpf_reg_state *src_reg) 13094 { 13095 s64 smin_val = src_reg->smin_value; 13096 s64 smax_val = src_reg->smax_value; 13097 u64 umin_val = src_reg->umin_value; 13098 u64 umax_val = src_reg->umax_value; 13099 13100 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 13101 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 13102 /* Overflow possible, we know nothing */ 13103 dst_reg->smin_value = S64_MIN; 13104 dst_reg->smax_value = S64_MAX; 13105 } else { 13106 dst_reg->smin_value -= smax_val; 13107 dst_reg->smax_value -= smin_val; 13108 } 13109 if (dst_reg->umin_value < umax_val) { 13110 /* Overflow possible, we know nothing */ 13111 dst_reg->umin_value = 0; 13112 dst_reg->umax_value = U64_MAX; 13113 } else { 13114 /* Cannot overflow (as long as bounds are consistent) */ 13115 dst_reg->umin_value -= umax_val; 13116 dst_reg->umax_value -= umin_val; 13117 } 13118 } 13119 13120 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 13121 struct bpf_reg_state *src_reg) 13122 { 13123 s32 smin_val = src_reg->s32_min_value; 13124 u32 umin_val = src_reg->u32_min_value; 13125 u32 umax_val = src_reg->u32_max_value; 13126 13127 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 13128 /* Ain't nobody got time to multiply that sign */ 13129 __mark_reg32_unbounded(dst_reg); 13130 return; 13131 } 13132 /* Both values are positive, so we can work with unsigned and 13133 * copy the result to signed (unless it exceeds S32_MAX). 13134 */ 13135 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 13136 /* Potential overflow, we know nothing */ 13137 __mark_reg32_unbounded(dst_reg); 13138 return; 13139 } 13140 dst_reg->u32_min_value *= umin_val; 13141 dst_reg->u32_max_value *= umax_val; 13142 if (dst_reg->u32_max_value > S32_MAX) { 13143 /* Overflow possible, we know nothing */ 13144 dst_reg->s32_min_value = S32_MIN; 13145 dst_reg->s32_max_value = S32_MAX; 13146 } else { 13147 dst_reg->s32_min_value = dst_reg->u32_min_value; 13148 dst_reg->s32_max_value = dst_reg->u32_max_value; 13149 } 13150 } 13151 13152 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 13153 struct bpf_reg_state *src_reg) 13154 { 13155 s64 smin_val = src_reg->smin_value; 13156 u64 umin_val = src_reg->umin_value; 13157 u64 umax_val = src_reg->umax_value; 13158 13159 if (smin_val < 0 || dst_reg->smin_value < 0) { 13160 /* Ain't nobody got time to multiply that sign */ 13161 __mark_reg64_unbounded(dst_reg); 13162 return; 13163 } 13164 /* Both values are positive, so we can work with unsigned and 13165 * copy the result to signed (unless it exceeds S64_MAX). 13166 */ 13167 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 13168 /* Potential overflow, we know nothing */ 13169 __mark_reg64_unbounded(dst_reg); 13170 return; 13171 } 13172 dst_reg->umin_value *= umin_val; 13173 dst_reg->umax_value *= umax_val; 13174 if (dst_reg->umax_value > S64_MAX) { 13175 /* Overflow possible, we know nothing */ 13176 dst_reg->smin_value = S64_MIN; 13177 dst_reg->smax_value = S64_MAX; 13178 } else { 13179 dst_reg->smin_value = dst_reg->umin_value; 13180 dst_reg->smax_value = dst_reg->umax_value; 13181 } 13182 } 13183 13184 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 13185 struct bpf_reg_state *src_reg) 13186 { 13187 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13188 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13189 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13190 s32 smin_val = src_reg->s32_min_value; 13191 u32 umax_val = src_reg->u32_max_value; 13192 13193 if (src_known && dst_known) { 13194 __mark_reg32_known(dst_reg, var32_off.value); 13195 return; 13196 } 13197 13198 /* We get our minimum from the var_off, since that's inherently 13199 * bitwise. Our maximum is the minimum of the operands' maxima. 13200 */ 13201 dst_reg->u32_min_value = var32_off.value; 13202 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 13203 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 13204 /* Lose signed bounds when ANDing negative numbers, 13205 * ain't nobody got time for that. 13206 */ 13207 dst_reg->s32_min_value = S32_MIN; 13208 dst_reg->s32_max_value = S32_MAX; 13209 } else { 13210 /* ANDing two positives gives a positive, so safe to 13211 * cast result into s64. 13212 */ 13213 dst_reg->s32_min_value = dst_reg->u32_min_value; 13214 dst_reg->s32_max_value = dst_reg->u32_max_value; 13215 } 13216 } 13217 13218 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 13219 struct bpf_reg_state *src_reg) 13220 { 13221 bool src_known = tnum_is_const(src_reg->var_off); 13222 bool dst_known = tnum_is_const(dst_reg->var_off); 13223 s64 smin_val = src_reg->smin_value; 13224 u64 umax_val = src_reg->umax_value; 13225 13226 if (src_known && dst_known) { 13227 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13228 return; 13229 } 13230 13231 /* We get our minimum from the var_off, since that's inherently 13232 * bitwise. Our maximum is the minimum of the operands' maxima. 13233 */ 13234 dst_reg->umin_value = dst_reg->var_off.value; 13235 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 13236 if (dst_reg->smin_value < 0 || smin_val < 0) { 13237 /* Lose signed bounds when ANDing negative numbers, 13238 * ain't nobody got time for that. 13239 */ 13240 dst_reg->smin_value = S64_MIN; 13241 dst_reg->smax_value = S64_MAX; 13242 } else { 13243 /* ANDing two positives gives a positive, so safe to 13244 * cast result into s64. 13245 */ 13246 dst_reg->smin_value = dst_reg->umin_value; 13247 dst_reg->smax_value = dst_reg->umax_value; 13248 } 13249 /* We may learn something more from the var_off */ 13250 __update_reg_bounds(dst_reg); 13251 } 13252 13253 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 13254 struct bpf_reg_state *src_reg) 13255 { 13256 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13257 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13258 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13259 s32 smin_val = src_reg->s32_min_value; 13260 u32 umin_val = src_reg->u32_min_value; 13261 13262 if (src_known && dst_known) { 13263 __mark_reg32_known(dst_reg, var32_off.value); 13264 return; 13265 } 13266 13267 /* We get our maximum from the var_off, and our minimum is the 13268 * maximum of the operands' minima 13269 */ 13270 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 13271 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13272 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 13273 /* Lose signed bounds when ORing negative numbers, 13274 * ain't nobody got time for that. 13275 */ 13276 dst_reg->s32_min_value = S32_MIN; 13277 dst_reg->s32_max_value = S32_MAX; 13278 } else { 13279 /* ORing two positives gives a positive, so safe to 13280 * cast result into s64. 13281 */ 13282 dst_reg->s32_min_value = dst_reg->u32_min_value; 13283 dst_reg->s32_max_value = dst_reg->u32_max_value; 13284 } 13285 } 13286 13287 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 13288 struct bpf_reg_state *src_reg) 13289 { 13290 bool src_known = tnum_is_const(src_reg->var_off); 13291 bool dst_known = tnum_is_const(dst_reg->var_off); 13292 s64 smin_val = src_reg->smin_value; 13293 u64 umin_val = src_reg->umin_value; 13294 13295 if (src_known && dst_known) { 13296 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13297 return; 13298 } 13299 13300 /* We get our maximum from the var_off, and our minimum is the 13301 * maximum of the operands' minima 13302 */ 13303 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 13304 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13305 if (dst_reg->smin_value < 0 || smin_val < 0) { 13306 /* Lose signed bounds when ORing negative numbers, 13307 * ain't nobody got time for that. 13308 */ 13309 dst_reg->smin_value = S64_MIN; 13310 dst_reg->smax_value = S64_MAX; 13311 } else { 13312 /* ORing two positives gives a positive, so safe to 13313 * cast result into s64. 13314 */ 13315 dst_reg->smin_value = dst_reg->umin_value; 13316 dst_reg->smax_value = dst_reg->umax_value; 13317 } 13318 /* We may learn something more from the var_off */ 13319 __update_reg_bounds(dst_reg); 13320 } 13321 13322 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 13323 struct bpf_reg_state *src_reg) 13324 { 13325 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13326 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13327 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13328 s32 smin_val = src_reg->s32_min_value; 13329 13330 if (src_known && dst_known) { 13331 __mark_reg32_known(dst_reg, var32_off.value); 13332 return; 13333 } 13334 13335 /* We get both minimum and maximum from the var32_off. */ 13336 dst_reg->u32_min_value = var32_off.value; 13337 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13338 13339 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 13340 /* XORing two positive sign numbers gives a positive, 13341 * so safe to cast u32 result into s32. 13342 */ 13343 dst_reg->s32_min_value = dst_reg->u32_min_value; 13344 dst_reg->s32_max_value = dst_reg->u32_max_value; 13345 } else { 13346 dst_reg->s32_min_value = S32_MIN; 13347 dst_reg->s32_max_value = S32_MAX; 13348 } 13349 } 13350 13351 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 13352 struct bpf_reg_state *src_reg) 13353 { 13354 bool src_known = tnum_is_const(src_reg->var_off); 13355 bool dst_known = tnum_is_const(dst_reg->var_off); 13356 s64 smin_val = src_reg->smin_value; 13357 13358 if (src_known && dst_known) { 13359 /* dst_reg->var_off.value has been updated earlier */ 13360 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13361 return; 13362 } 13363 13364 /* We get both minimum and maximum from the var_off. */ 13365 dst_reg->umin_value = dst_reg->var_off.value; 13366 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13367 13368 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 13369 /* XORing two positive sign numbers gives a positive, 13370 * so safe to cast u64 result into s64. 13371 */ 13372 dst_reg->smin_value = dst_reg->umin_value; 13373 dst_reg->smax_value = dst_reg->umax_value; 13374 } else { 13375 dst_reg->smin_value = S64_MIN; 13376 dst_reg->smax_value = S64_MAX; 13377 } 13378 13379 __update_reg_bounds(dst_reg); 13380 } 13381 13382 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13383 u64 umin_val, u64 umax_val) 13384 { 13385 /* We lose all sign bit information (except what we can pick 13386 * up from var_off) 13387 */ 13388 dst_reg->s32_min_value = S32_MIN; 13389 dst_reg->s32_max_value = S32_MAX; 13390 /* If we might shift our top bit out, then we know nothing */ 13391 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 13392 dst_reg->u32_min_value = 0; 13393 dst_reg->u32_max_value = U32_MAX; 13394 } else { 13395 dst_reg->u32_min_value <<= umin_val; 13396 dst_reg->u32_max_value <<= umax_val; 13397 } 13398 } 13399 13400 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13401 struct bpf_reg_state *src_reg) 13402 { 13403 u32 umax_val = src_reg->u32_max_value; 13404 u32 umin_val = src_reg->u32_min_value; 13405 /* u32 alu operation will zext upper bits */ 13406 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13407 13408 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13409 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 13410 /* Not required but being careful mark reg64 bounds as unknown so 13411 * that we are forced to pick them up from tnum and zext later and 13412 * if some path skips this step we are still safe. 13413 */ 13414 __mark_reg64_unbounded(dst_reg); 13415 __update_reg32_bounds(dst_reg); 13416 } 13417 13418 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 13419 u64 umin_val, u64 umax_val) 13420 { 13421 /* Special case <<32 because it is a common compiler pattern to sign 13422 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 13423 * positive we know this shift will also be positive so we can track 13424 * bounds correctly. Otherwise we lose all sign bit information except 13425 * what we can pick up from var_off. Perhaps we can generalize this 13426 * later to shifts of any length. 13427 */ 13428 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 13429 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 13430 else 13431 dst_reg->smax_value = S64_MAX; 13432 13433 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 13434 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 13435 else 13436 dst_reg->smin_value = S64_MIN; 13437 13438 /* If we might shift our top bit out, then we know nothing */ 13439 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 13440 dst_reg->umin_value = 0; 13441 dst_reg->umax_value = U64_MAX; 13442 } else { 13443 dst_reg->umin_value <<= umin_val; 13444 dst_reg->umax_value <<= umax_val; 13445 } 13446 } 13447 13448 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 13449 struct bpf_reg_state *src_reg) 13450 { 13451 u64 umax_val = src_reg->umax_value; 13452 u64 umin_val = src_reg->umin_value; 13453 13454 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 13455 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 13456 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13457 13458 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 13459 /* We may learn something more from the var_off */ 13460 __update_reg_bounds(dst_reg); 13461 } 13462 13463 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 13464 struct bpf_reg_state *src_reg) 13465 { 13466 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13467 u32 umax_val = src_reg->u32_max_value; 13468 u32 umin_val = src_reg->u32_min_value; 13469 13470 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13471 * be negative, then either: 13472 * 1) src_reg might be zero, so the sign bit of the result is 13473 * unknown, so we lose our signed bounds 13474 * 2) it's known negative, thus the unsigned bounds capture the 13475 * signed bounds 13476 * 3) the signed bounds cross zero, so they tell us nothing 13477 * about the result 13478 * If the value in dst_reg is known nonnegative, then again the 13479 * unsigned bounds capture the signed bounds. 13480 * Thus, in all cases it suffices to blow away our signed bounds 13481 * and rely on inferring new ones from the unsigned bounds and 13482 * var_off of the result. 13483 */ 13484 dst_reg->s32_min_value = S32_MIN; 13485 dst_reg->s32_max_value = S32_MAX; 13486 13487 dst_reg->var_off = tnum_rshift(subreg, umin_val); 13488 dst_reg->u32_min_value >>= umax_val; 13489 dst_reg->u32_max_value >>= umin_val; 13490 13491 __mark_reg64_unbounded(dst_reg); 13492 __update_reg32_bounds(dst_reg); 13493 } 13494 13495 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 13496 struct bpf_reg_state *src_reg) 13497 { 13498 u64 umax_val = src_reg->umax_value; 13499 u64 umin_val = src_reg->umin_value; 13500 13501 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13502 * be negative, then either: 13503 * 1) src_reg might be zero, so the sign bit of the result is 13504 * unknown, so we lose our signed bounds 13505 * 2) it's known negative, thus the unsigned bounds capture the 13506 * signed bounds 13507 * 3) the signed bounds cross zero, so they tell us nothing 13508 * about the result 13509 * If the value in dst_reg is known nonnegative, then again the 13510 * unsigned bounds capture the signed bounds. 13511 * Thus, in all cases it suffices to blow away our signed bounds 13512 * and rely on inferring new ones from the unsigned bounds and 13513 * var_off of the result. 13514 */ 13515 dst_reg->smin_value = S64_MIN; 13516 dst_reg->smax_value = S64_MAX; 13517 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 13518 dst_reg->umin_value >>= umax_val; 13519 dst_reg->umax_value >>= umin_val; 13520 13521 /* Its not easy to operate on alu32 bounds here because it depends 13522 * on bits being shifted in. Take easy way out and mark unbounded 13523 * so we can recalculate later from tnum. 13524 */ 13525 __mark_reg32_unbounded(dst_reg); 13526 __update_reg_bounds(dst_reg); 13527 } 13528 13529 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 13530 struct bpf_reg_state *src_reg) 13531 { 13532 u64 umin_val = src_reg->u32_min_value; 13533 13534 /* Upon reaching here, src_known is true and 13535 * umax_val is equal to umin_val. 13536 */ 13537 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 13538 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 13539 13540 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 13541 13542 /* blow away the dst_reg umin_value/umax_value and rely on 13543 * dst_reg var_off to refine the result. 13544 */ 13545 dst_reg->u32_min_value = 0; 13546 dst_reg->u32_max_value = U32_MAX; 13547 13548 __mark_reg64_unbounded(dst_reg); 13549 __update_reg32_bounds(dst_reg); 13550 } 13551 13552 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 13553 struct bpf_reg_state *src_reg) 13554 { 13555 u64 umin_val = src_reg->umin_value; 13556 13557 /* Upon reaching here, src_known is true and umax_val is equal 13558 * to umin_val. 13559 */ 13560 dst_reg->smin_value >>= umin_val; 13561 dst_reg->smax_value >>= umin_val; 13562 13563 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 13564 13565 /* blow away the dst_reg umin_value/umax_value and rely on 13566 * dst_reg var_off to refine the result. 13567 */ 13568 dst_reg->umin_value = 0; 13569 dst_reg->umax_value = U64_MAX; 13570 13571 /* Its not easy to operate on alu32 bounds here because it depends 13572 * on bits being shifted in from upper 32-bits. Take easy way out 13573 * and mark unbounded so we can recalculate later from tnum. 13574 */ 13575 __mark_reg32_unbounded(dst_reg); 13576 __update_reg_bounds(dst_reg); 13577 } 13578 13579 /* WARNING: This function does calculations on 64-bit values, but the actual 13580 * execution may occur on 32-bit values. Therefore, things like bitshifts 13581 * need extra checks in the 32-bit case. 13582 */ 13583 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 13584 struct bpf_insn *insn, 13585 struct bpf_reg_state *dst_reg, 13586 struct bpf_reg_state src_reg) 13587 { 13588 struct bpf_reg_state *regs = cur_regs(env); 13589 u8 opcode = BPF_OP(insn->code); 13590 bool src_known; 13591 s64 smin_val, smax_val; 13592 u64 umin_val, umax_val; 13593 s32 s32_min_val, s32_max_val; 13594 u32 u32_min_val, u32_max_val; 13595 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 13596 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 13597 int ret; 13598 13599 smin_val = src_reg.smin_value; 13600 smax_val = src_reg.smax_value; 13601 umin_val = src_reg.umin_value; 13602 umax_val = src_reg.umax_value; 13603 13604 s32_min_val = src_reg.s32_min_value; 13605 s32_max_val = src_reg.s32_max_value; 13606 u32_min_val = src_reg.u32_min_value; 13607 u32_max_val = src_reg.u32_max_value; 13608 13609 if (alu32) { 13610 src_known = tnum_subreg_is_const(src_reg.var_off); 13611 if ((src_known && 13612 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 13613 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 13614 /* Taint dst register if offset had invalid bounds 13615 * derived from e.g. dead branches. 13616 */ 13617 __mark_reg_unknown(env, dst_reg); 13618 return 0; 13619 } 13620 } else { 13621 src_known = tnum_is_const(src_reg.var_off); 13622 if ((src_known && 13623 (smin_val != smax_val || umin_val != umax_val)) || 13624 smin_val > smax_val || umin_val > umax_val) { 13625 /* Taint dst register if offset had invalid bounds 13626 * derived from e.g. dead branches. 13627 */ 13628 __mark_reg_unknown(env, dst_reg); 13629 return 0; 13630 } 13631 } 13632 13633 if (!src_known && 13634 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 13635 __mark_reg_unknown(env, dst_reg); 13636 return 0; 13637 } 13638 13639 if (sanitize_needed(opcode)) { 13640 ret = sanitize_val_alu(env, insn); 13641 if (ret < 0) 13642 return sanitize_err(env, insn, ret, NULL, NULL); 13643 } 13644 13645 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 13646 * There are two classes of instructions: The first class we track both 13647 * alu32 and alu64 sign/unsigned bounds independently this provides the 13648 * greatest amount of precision when alu operations are mixed with jmp32 13649 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 13650 * and BPF_OR. This is possible because these ops have fairly easy to 13651 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 13652 * See alu32 verifier tests for examples. The second class of 13653 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 13654 * with regards to tracking sign/unsigned bounds because the bits may 13655 * cross subreg boundaries in the alu64 case. When this happens we mark 13656 * the reg unbounded in the subreg bound space and use the resulting 13657 * tnum to calculate an approximation of the sign/unsigned bounds. 13658 */ 13659 switch (opcode) { 13660 case BPF_ADD: 13661 scalar32_min_max_add(dst_reg, &src_reg); 13662 scalar_min_max_add(dst_reg, &src_reg); 13663 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 13664 break; 13665 case BPF_SUB: 13666 scalar32_min_max_sub(dst_reg, &src_reg); 13667 scalar_min_max_sub(dst_reg, &src_reg); 13668 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 13669 break; 13670 case BPF_MUL: 13671 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 13672 scalar32_min_max_mul(dst_reg, &src_reg); 13673 scalar_min_max_mul(dst_reg, &src_reg); 13674 break; 13675 case BPF_AND: 13676 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 13677 scalar32_min_max_and(dst_reg, &src_reg); 13678 scalar_min_max_and(dst_reg, &src_reg); 13679 break; 13680 case BPF_OR: 13681 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 13682 scalar32_min_max_or(dst_reg, &src_reg); 13683 scalar_min_max_or(dst_reg, &src_reg); 13684 break; 13685 case BPF_XOR: 13686 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 13687 scalar32_min_max_xor(dst_reg, &src_reg); 13688 scalar_min_max_xor(dst_reg, &src_reg); 13689 break; 13690 case BPF_LSH: 13691 if (umax_val >= insn_bitness) { 13692 /* Shifts greater than 31 or 63 are undefined. 13693 * This includes shifts by a negative number. 13694 */ 13695 mark_reg_unknown(env, regs, insn->dst_reg); 13696 break; 13697 } 13698 if (alu32) 13699 scalar32_min_max_lsh(dst_reg, &src_reg); 13700 else 13701 scalar_min_max_lsh(dst_reg, &src_reg); 13702 break; 13703 case BPF_RSH: 13704 if (umax_val >= insn_bitness) { 13705 /* Shifts greater than 31 or 63 are undefined. 13706 * This includes shifts by a negative number. 13707 */ 13708 mark_reg_unknown(env, regs, insn->dst_reg); 13709 break; 13710 } 13711 if (alu32) 13712 scalar32_min_max_rsh(dst_reg, &src_reg); 13713 else 13714 scalar_min_max_rsh(dst_reg, &src_reg); 13715 break; 13716 case BPF_ARSH: 13717 if (umax_val >= insn_bitness) { 13718 /* Shifts greater than 31 or 63 are undefined. 13719 * This includes shifts by a negative number. 13720 */ 13721 mark_reg_unknown(env, regs, insn->dst_reg); 13722 break; 13723 } 13724 if (alu32) 13725 scalar32_min_max_arsh(dst_reg, &src_reg); 13726 else 13727 scalar_min_max_arsh(dst_reg, &src_reg); 13728 break; 13729 default: 13730 mark_reg_unknown(env, regs, insn->dst_reg); 13731 break; 13732 } 13733 13734 /* ALU32 ops are zero extended into 64bit register */ 13735 if (alu32) 13736 zext_32_to_64(dst_reg); 13737 reg_bounds_sync(dst_reg); 13738 return 0; 13739 } 13740 13741 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 13742 * and var_off. 13743 */ 13744 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 13745 struct bpf_insn *insn) 13746 { 13747 struct bpf_verifier_state *vstate = env->cur_state; 13748 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13749 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 13750 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 13751 u8 opcode = BPF_OP(insn->code); 13752 int err; 13753 13754 dst_reg = ®s[insn->dst_reg]; 13755 src_reg = NULL; 13756 if (dst_reg->type != SCALAR_VALUE) 13757 ptr_reg = dst_reg; 13758 else 13759 /* Make sure ID is cleared otherwise dst_reg min/max could be 13760 * incorrectly propagated into other registers by find_equal_scalars() 13761 */ 13762 dst_reg->id = 0; 13763 if (BPF_SRC(insn->code) == BPF_X) { 13764 src_reg = ®s[insn->src_reg]; 13765 if (src_reg->type != SCALAR_VALUE) { 13766 if (dst_reg->type != SCALAR_VALUE) { 13767 /* Combining two pointers by any ALU op yields 13768 * an arbitrary scalar. Disallow all math except 13769 * pointer subtraction 13770 */ 13771 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13772 mark_reg_unknown(env, regs, insn->dst_reg); 13773 return 0; 13774 } 13775 verbose(env, "R%d pointer %s pointer prohibited\n", 13776 insn->dst_reg, 13777 bpf_alu_string[opcode >> 4]); 13778 return -EACCES; 13779 } else { 13780 /* scalar += pointer 13781 * This is legal, but we have to reverse our 13782 * src/dest handling in computing the range 13783 */ 13784 err = mark_chain_precision(env, insn->dst_reg); 13785 if (err) 13786 return err; 13787 return adjust_ptr_min_max_vals(env, insn, 13788 src_reg, dst_reg); 13789 } 13790 } else if (ptr_reg) { 13791 /* pointer += scalar */ 13792 err = mark_chain_precision(env, insn->src_reg); 13793 if (err) 13794 return err; 13795 return adjust_ptr_min_max_vals(env, insn, 13796 dst_reg, src_reg); 13797 } else if (dst_reg->precise) { 13798 /* if dst_reg is precise, src_reg should be precise as well */ 13799 err = mark_chain_precision(env, insn->src_reg); 13800 if (err) 13801 return err; 13802 } 13803 } else { 13804 /* Pretend the src is a reg with a known value, since we only 13805 * need to be able to read from this state. 13806 */ 13807 off_reg.type = SCALAR_VALUE; 13808 __mark_reg_known(&off_reg, insn->imm); 13809 src_reg = &off_reg; 13810 if (ptr_reg) /* pointer += K */ 13811 return adjust_ptr_min_max_vals(env, insn, 13812 ptr_reg, src_reg); 13813 } 13814 13815 /* Got here implies adding two SCALAR_VALUEs */ 13816 if (WARN_ON_ONCE(ptr_reg)) { 13817 print_verifier_state(env, state, true); 13818 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 13819 return -EINVAL; 13820 } 13821 if (WARN_ON(!src_reg)) { 13822 print_verifier_state(env, state, true); 13823 verbose(env, "verifier internal error: no src_reg\n"); 13824 return -EINVAL; 13825 } 13826 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 13827 } 13828 13829 /* check validity of 32-bit and 64-bit arithmetic operations */ 13830 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 13831 { 13832 struct bpf_reg_state *regs = cur_regs(env); 13833 u8 opcode = BPF_OP(insn->code); 13834 int err; 13835 13836 if (opcode == BPF_END || opcode == BPF_NEG) { 13837 if (opcode == BPF_NEG) { 13838 if (BPF_SRC(insn->code) != BPF_K || 13839 insn->src_reg != BPF_REG_0 || 13840 insn->off != 0 || insn->imm != 0) { 13841 verbose(env, "BPF_NEG uses reserved fields\n"); 13842 return -EINVAL; 13843 } 13844 } else { 13845 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 13846 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 13847 (BPF_CLASS(insn->code) == BPF_ALU64 && 13848 BPF_SRC(insn->code) != BPF_TO_LE)) { 13849 verbose(env, "BPF_END uses reserved fields\n"); 13850 return -EINVAL; 13851 } 13852 } 13853 13854 /* check src operand */ 13855 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13856 if (err) 13857 return err; 13858 13859 if (is_pointer_value(env, insn->dst_reg)) { 13860 verbose(env, "R%d pointer arithmetic prohibited\n", 13861 insn->dst_reg); 13862 return -EACCES; 13863 } 13864 13865 /* check dest operand */ 13866 err = check_reg_arg(env, insn->dst_reg, DST_OP); 13867 if (err) 13868 return err; 13869 13870 } else if (opcode == BPF_MOV) { 13871 13872 if (BPF_SRC(insn->code) == BPF_X) { 13873 if (insn->imm != 0) { 13874 verbose(env, "BPF_MOV uses reserved fields\n"); 13875 return -EINVAL; 13876 } 13877 13878 if (BPF_CLASS(insn->code) == BPF_ALU) { 13879 if (insn->off != 0 && insn->off != 8 && insn->off != 16) { 13880 verbose(env, "BPF_MOV uses reserved fields\n"); 13881 return -EINVAL; 13882 } 13883 } else { 13884 if (insn->off != 0 && insn->off != 8 && insn->off != 16 && 13885 insn->off != 32) { 13886 verbose(env, "BPF_MOV uses reserved fields\n"); 13887 return -EINVAL; 13888 } 13889 } 13890 13891 /* check src operand */ 13892 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13893 if (err) 13894 return err; 13895 } else { 13896 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 13897 verbose(env, "BPF_MOV uses reserved fields\n"); 13898 return -EINVAL; 13899 } 13900 } 13901 13902 /* check dest operand, mark as required later */ 13903 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13904 if (err) 13905 return err; 13906 13907 if (BPF_SRC(insn->code) == BPF_X) { 13908 struct bpf_reg_state *src_reg = regs + insn->src_reg; 13909 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 13910 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id && 13911 !tnum_is_const(src_reg->var_off); 13912 13913 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13914 if (insn->off == 0) { 13915 /* case: R1 = R2 13916 * copy register state to dest reg 13917 */ 13918 if (need_id) 13919 /* Assign src and dst registers the same ID 13920 * that will be used by find_equal_scalars() 13921 * to propagate min/max range. 13922 */ 13923 src_reg->id = ++env->id_gen; 13924 copy_register_state(dst_reg, src_reg); 13925 dst_reg->live |= REG_LIVE_WRITTEN; 13926 dst_reg->subreg_def = DEF_NOT_SUBREG; 13927 } else { 13928 /* case: R1 = (s8, s16 s32)R2 */ 13929 if (is_pointer_value(env, insn->src_reg)) { 13930 verbose(env, 13931 "R%d sign-extension part of pointer\n", 13932 insn->src_reg); 13933 return -EACCES; 13934 } else if (src_reg->type == SCALAR_VALUE) { 13935 bool no_sext; 13936 13937 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13938 if (no_sext && need_id) 13939 src_reg->id = ++env->id_gen; 13940 copy_register_state(dst_reg, src_reg); 13941 if (!no_sext) 13942 dst_reg->id = 0; 13943 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 13944 dst_reg->live |= REG_LIVE_WRITTEN; 13945 dst_reg->subreg_def = DEF_NOT_SUBREG; 13946 } else { 13947 mark_reg_unknown(env, regs, insn->dst_reg); 13948 } 13949 } 13950 } else { 13951 /* R1 = (u32) R2 */ 13952 if (is_pointer_value(env, insn->src_reg)) { 13953 verbose(env, 13954 "R%d partial copy of pointer\n", 13955 insn->src_reg); 13956 return -EACCES; 13957 } else if (src_reg->type == SCALAR_VALUE) { 13958 if (insn->off == 0) { 13959 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX; 13960 13961 if (is_src_reg_u32 && need_id) 13962 src_reg->id = ++env->id_gen; 13963 copy_register_state(dst_reg, src_reg); 13964 /* Make sure ID is cleared if src_reg is not in u32 13965 * range otherwise dst_reg min/max could be incorrectly 13966 * propagated into src_reg by find_equal_scalars() 13967 */ 13968 if (!is_src_reg_u32) 13969 dst_reg->id = 0; 13970 dst_reg->live |= REG_LIVE_WRITTEN; 13971 dst_reg->subreg_def = env->insn_idx + 1; 13972 } else { 13973 /* case: W1 = (s8, s16)W2 */ 13974 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13975 13976 if (no_sext && need_id) 13977 src_reg->id = ++env->id_gen; 13978 copy_register_state(dst_reg, src_reg); 13979 if (!no_sext) 13980 dst_reg->id = 0; 13981 dst_reg->live |= REG_LIVE_WRITTEN; 13982 dst_reg->subreg_def = env->insn_idx + 1; 13983 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 13984 } 13985 } else { 13986 mark_reg_unknown(env, regs, 13987 insn->dst_reg); 13988 } 13989 zext_32_to_64(dst_reg); 13990 reg_bounds_sync(dst_reg); 13991 } 13992 } else { 13993 /* case: R = imm 13994 * remember the value we stored into this reg 13995 */ 13996 /* clear any state __mark_reg_known doesn't set */ 13997 mark_reg_unknown(env, regs, insn->dst_reg); 13998 regs[insn->dst_reg].type = SCALAR_VALUE; 13999 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14000 __mark_reg_known(regs + insn->dst_reg, 14001 insn->imm); 14002 } else { 14003 __mark_reg_known(regs + insn->dst_reg, 14004 (u32)insn->imm); 14005 } 14006 } 14007 14008 } else if (opcode > BPF_END) { 14009 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 14010 return -EINVAL; 14011 14012 } else { /* all other ALU ops: and, sub, xor, add, ... */ 14013 14014 if (BPF_SRC(insn->code) == BPF_X) { 14015 if (insn->imm != 0 || insn->off > 1 || 14016 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14017 verbose(env, "BPF_ALU uses reserved fields\n"); 14018 return -EINVAL; 14019 } 14020 /* check src1 operand */ 14021 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14022 if (err) 14023 return err; 14024 } else { 14025 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 14026 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14027 verbose(env, "BPF_ALU uses reserved fields\n"); 14028 return -EINVAL; 14029 } 14030 } 14031 14032 /* check src2 operand */ 14033 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14034 if (err) 14035 return err; 14036 14037 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 14038 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 14039 verbose(env, "div by zero\n"); 14040 return -EINVAL; 14041 } 14042 14043 if ((opcode == BPF_LSH || opcode == BPF_RSH || 14044 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 14045 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 14046 14047 if (insn->imm < 0 || insn->imm >= size) { 14048 verbose(env, "invalid shift %d\n", insn->imm); 14049 return -EINVAL; 14050 } 14051 } 14052 14053 /* check dest operand */ 14054 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14055 err = err ?: adjust_reg_min_max_vals(env, insn); 14056 if (err) 14057 return err; 14058 } 14059 14060 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 14061 } 14062 14063 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 14064 struct bpf_reg_state *dst_reg, 14065 enum bpf_reg_type type, 14066 bool range_right_open) 14067 { 14068 struct bpf_func_state *state; 14069 struct bpf_reg_state *reg; 14070 int new_range; 14071 14072 if (dst_reg->off < 0 || 14073 (dst_reg->off == 0 && range_right_open)) 14074 /* This doesn't give us any range */ 14075 return; 14076 14077 if (dst_reg->umax_value > MAX_PACKET_OFF || 14078 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 14079 /* Risk of overflow. For instance, ptr + (1<<63) may be less 14080 * than pkt_end, but that's because it's also less than pkt. 14081 */ 14082 return; 14083 14084 new_range = dst_reg->off; 14085 if (range_right_open) 14086 new_range++; 14087 14088 /* Examples for register markings: 14089 * 14090 * pkt_data in dst register: 14091 * 14092 * r2 = r3; 14093 * r2 += 8; 14094 * if (r2 > pkt_end) goto <handle exception> 14095 * <access okay> 14096 * 14097 * r2 = r3; 14098 * r2 += 8; 14099 * if (r2 < pkt_end) goto <access okay> 14100 * <handle exception> 14101 * 14102 * Where: 14103 * r2 == dst_reg, pkt_end == src_reg 14104 * r2=pkt(id=n,off=8,r=0) 14105 * r3=pkt(id=n,off=0,r=0) 14106 * 14107 * pkt_data in src register: 14108 * 14109 * r2 = r3; 14110 * r2 += 8; 14111 * if (pkt_end >= r2) goto <access okay> 14112 * <handle exception> 14113 * 14114 * r2 = r3; 14115 * r2 += 8; 14116 * if (pkt_end <= r2) goto <handle exception> 14117 * <access okay> 14118 * 14119 * Where: 14120 * pkt_end == dst_reg, r2 == src_reg 14121 * r2=pkt(id=n,off=8,r=0) 14122 * r3=pkt(id=n,off=0,r=0) 14123 * 14124 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 14125 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 14126 * and [r3, r3 + 8-1) respectively is safe to access depending on 14127 * the check. 14128 */ 14129 14130 /* If our ids match, then we must have the same max_value. And we 14131 * don't care about the other reg's fixed offset, since if it's too big 14132 * the range won't allow anything. 14133 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 14134 */ 14135 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14136 if (reg->type == type && reg->id == dst_reg->id) 14137 /* keep the maximum range already checked */ 14138 reg->range = max(reg->range, new_range); 14139 })); 14140 } 14141 14142 /* 14143 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 14144 */ 14145 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14146 u8 opcode, bool is_jmp32) 14147 { 14148 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 14149 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 14150 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value; 14151 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value; 14152 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value; 14153 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value; 14154 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value; 14155 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value; 14156 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value; 14157 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value; 14158 14159 switch (opcode) { 14160 case BPF_JEQ: 14161 /* constants, umin/umax and smin/smax checks would be 14162 * redundant in this case because they all should match 14163 */ 14164 if (tnum_is_const(t1) && tnum_is_const(t2)) 14165 return t1.value == t2.value; 14166 /* non-overlapping ranges */ 14167 if (umin1 > umax2 || umax1 < umin2) 14168 return 0; 14169 if (smin1 > smax2 || smax1 < smin2) 14170 return 0; 14171 if (!is_jmp32) { 14172 /* if 64-bit ranges are inconclusive, see if we can 14173 * utilize 32-bit subrange knowledge to eliminate 14174 * branches that can't be taken a priori 14175 */ 14176 if (reg1->u32_min_value > reg2->u32_max_value || 14177 reg1->u32_max_value < reg2->u32_min_value) 14178 return 0; 14179 if (reg1->s32_min_value > reg2->s32_max_value || 14180 reg1->s32_max_value < reg2->s32_min_value) 14181 return 0; 14182 } 14183 break; 14184 case BPF_JNE: 14185 /* constants, umin/umax and smin/smax checks would be 14186 * redundant in this case because they all should match 14187 */ 14188 if (tnum_is_const(t1) && tnum_is_const(t2)) 14189 return t1.value != t2.value; 14190 /* non-overlapping ranges */ 14191 if (umin1 > umax2 || umax1 < umin2) 14192 return 1; 14193 if (smin1 > smax2 || smax1 < smin2) 14194 return 1; 14195 if (!is_jmp32) { 14196 /* if 64-bit ranges are inconclusive, see if we can 14197 * utilize 32-bit subrange knowledge to eliminate 14198 * branches that can't be taken a priori 14199 */ 14200 if (reg1->u32_min_value > reg2->u32_max_value || 14201 reg1->u32_max_value < reg2->u32_min_value) 14202 return 1; 14203 if (reg1->s32_min_value > reg2->s32_max_value || 14204 reg1->s32_max_value < reg2->s32_min_value) 14205 return 1; 14206 } 14207 break; 14208 case BPF_JSET: 14209 if (!is_reg_const(reg2, is_jmp32)) { 14210 swap(reg1, reg2); 14211 swap(t1, t2); 14212 } 14213 if (!is_reg_const(reg2, is_jmp32)) 14214 return -1; 14215 if ((~t1.mask & t1.value) & t2.value) 14216 return 1; 14217 if (!((t1.mask | t1.value) & t2.value)) 14218 return 0; 14219 break; 14220 case BPF_JGT: 14221 if (umin1 > umax2) 14222 return 1; 14223 else if (umax1 <= umin2) 14224 return 0; 14225 break; 14226 case BPF_JSGT: 14227 if (smin1 > smax2) 14228 return 1; 14229 else if (smax1 <= smin2) 14230 return 0; 14231 break; 14232 case BPF_JLT: 14233 if (umax1 < umin2) 14234 return 1; 14235 else if (umin1 >= umax2) 14236 return 0; 14237 break; 14238 case BPF_JSLT: 14239 if (smax1 < smin2) 14240 return 1; 14241 else if (smin1 >= smax2) 14242 return 0; 14243 break; 14244 case BPF_JGE: 14245 if (umin1 >= umax2) 14246 return 1; 14247 else if (umax1 < umin2) 14248 return 0; 14249 break; 14250 case BPF_JSGE: 14251 if (smin1 >= smax2) 14252 return 1; 14253 else if (smax1 < smin2) 14254 return 0; 14255 break; 14256 case BPF_JLE: 14257 if (umax1 <= umin2) 14258 return 1; 14259 else if (umin1 > umax2) 14260 return 0; 14261 break; 14262 case BPF_JSLE: 14263 if (smax1 <= smin2) 14264 return 1; 14265 else if (smin1 > smax2) 14266 return 0; 14267 break; 14268 } 14269 14270 return -1; 14271 } 14272 14273 static int flip_opcode(u32 opcode) 14274 { 14275 /* How can we transform "a <op> b" into "b <op> a"? */ 14276 static const u8 opcode_flip[16] = { 14277 /* these stay the same */ 14278 [BPF_JEQ >> 4] = BPF_JEQ, 14279 [BPF_JNE >> 4] = BPF_JNE, 14280 [BPF_JSET >> 4] = BPF_JSET, 14281 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 14282 [BPF_JGE >> 4] = BPF_JLE, 14283 [BPF_JGT >> 4] = BPF_JLT, 14284 [BPF_JLE >> 4] = BPF_JGE, 14285 [BPF_JLT >> 4] = BPF_JGT, 14286 [BPF_JSGE >> 4] = BPF_JSLE, 14287 [BPF_JSGT >> 4] = BPF_JSLT, 14288 [BPF_JSLE >> 4] = BPF_JSGE, 14289 [BPF_JSLT >> 4] = BPF_JSGT 14290 }; 14291 return opcode_flip[opcode >> 4]; 14292 } 14293 14294 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 14295 struct bpf_reg_state *src_reg, 14296 u8 opcode) 14297 { 14298 struct bpf_reg_state *pkt; 14299 14300 if (src_reg->type == PTR_TO_PACKET_END) { 14301 pkt = dst_reg; 14302 } else if (dst_reg->type == PTR_TO_PACKET_END) { 14303 pkt = src_reg; 14304 opcode = flip_opcode(opcode); 14305 } else { 14306 return -1; 14307 } 14308 14309 if (pkt->range >= 0) 14310 return -1; 14311 14312 switch (opcode) { 14313 case BPF_JLE: 14314 /* pkt <= pkt_end */ 14315 fallthrough; 14316 case BPF_JGT: 14317 /* pkt > pkt_end */ 14318 if (pkt->range == BEYOND_PKT_END) 14319 /* pkt has at last one extra byte beyond pkt_end */ 14320 return opcode == BPF_JGT; 14321 break; 14322 case BPF_JLT: 14323 /* pkt < pkt_end */ 14324 fallthrough; 14325 case BPF_JGE: 14326 /* pkt >= pkt_end */ 14327 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 14328 return opcode == BPF_JGE; 14329 break; 14330 } 14331 return -1; 14332 } 14333 14334 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 14335 * and return: 14336 * 1 - branch will be taken and "goto target" will be executed 14337 * 0 - branch will not be taken and fall-through to next insn 14338 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 14339 * range [0,10] 14340 */ 14341 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14342 u8 opcode, bool is_jmp32) 14343 { 14344 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 14345 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 14346 14347 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 14348 u64 val; 14349 14350 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 14351 if (!is_reg_const(reg2, is_jmp32)) { 14352 opcode = flip_opcode(opcode); 14353 swap(reg1, reg2); 14354 } 14355 /* and ensure that reg2 is a constant */ 14356 if (!is_reg_const(reg2, is_jmp32)) 14357 return -1; 14358 14359 if (!reg_not_null(reg1)) 14360 return -1; 14361 14362 /* If pointer is valid tests against zero will fail so we can 14363 * use this to direct branch taken. 14364 */ 14365 val = reg_const_value(reg2, is_jmp32); 14366 if (val != 0) 14367 return -1; 14368 14369 switch (opcode) { 14370 case BPF_JEQ: 14371 return 0; 14372 case BPF_JNE: 14373 return 1; 14374 default: 14375 return -1; 14376 } 14377 } 14378 14379 /* now deal with two scalars, but not necessarily constants */ 14380 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32); 14381 } 14382 14383 /* Opcode that corresponds to a *false* branch condition. 14384 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 14385 */ 14386 static u8 rev_opcode(u8 opcode) 14387 { 14388 switch (opcode) { 14389 case BPF_JEQ: return BPF_JNE; 14390 case BPF_JNE: return BPF_JEQ; 14391 /* JSET doesn't have it's reverse opcode in BPF, so add 14392 * BPF_X flag to denote the reverse of that operation 14393 */ 14394 case BPF_JSET: return BPF_JSET | BPF_X; 14395 case BPF_JSET | BPF_X: return BPF_JSET; 14396 case BPF_JGE: return BPF_JLT; 14397 case BPF_JGT: return BPF_JLE; 14398 case BPF_JLE: return BPF_JGT; 14399 case BPF_JLT: return BPF_JGE; 14400 case BPF_JSGE: return BPF_JSLT; 14401 case BPF_JSGT: return BPF_JSLE; 14402 case BPF_JSLE: return BPF_JSGT; 14403 case BPF_JSLT: return BPF_JSGE; 14404 default: return 0; 14405 } 14406 } 14407 14408 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 14409 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14410 u8 opcode, bool is_jmp32) 14411 { 14412 struct tnum t; 14413 u64 val; 14414 14415 again: 14416 switch (opcode) { 14417 case BPF_JEQ: 14418 if (is_jmp32) { 14419 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14420 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14421 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14422 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14423 reg2->u32_min_value = reg1->u32_min_value; 14424 reg2->u32_max_value = reg1->u32_max_value; 14425 reg2->s32_min_value = reg1->s32_min_value; 14426 reg2->s32_max_value = reg1->s32_max_value; 14427 14428 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 14429 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14430 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 14431 } else { 14432 reg1->umin_value = max(reg1->umin_value, reg2->umin_value); 14433 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14434 reg1->smin_value = max(reg1->smin_value, reg2->smin_value); 14435 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14436 reg2->umin_value = reg1->umin_value; 14437 reg2->umax_value = reg1->umax_value; 14438 reg2->smin_value = reg1->smin_value; 14439 reg2->smax_value = reg1->smax_value; 14440 14441 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 14442 reg2->var_off = reg1->var_off; 14443 } 14444 break; 14445 case BPF_JNE: 14446 if (!is_reg_const(reg2, is_jmp32)) 14447 swap(reg1, reg2); 14448 if (!is_reg_const(reg2, is_jmp32)) 14449 break; 14450 14451 /* try to recompute the bound of reg1 if reg2 is a const and 14452 * is exactly the edge of reg1. 14453 */ 14454 val = reg_const_value(reg2, is_jmp32); 14455 if (is_jmp32) { 14456 /* u32_min_value is not equal to 0xffffffff at this point, 14457 * because otherwise u32_max_value is 0xffffffff as well, 14458 * in such a case both reg1 and reg2 would be constants, 14459 * jump would be predicted and reg_set_min_max() won't 14460 * be called. 14461 * 14462 * Same reasoning works for all {u,s}{min,max}{32,64} cases 14463 * below. 14464 */ 14465 if (reg1->u32_min_value == (u32)val) 14466 reg1->u32_min_value++; 14467 if (reg1->u32_max_value == (u32)val) 14468 reg1->u32_max_value--; 14469 if (reg1->s32_min_value == (s32)val) 14470 reg1->s32_min_value++; 14471 if (reg1->s32_max_value == (s32)val) 14472 reg1->s32_max_value--; 14473 } else { 14474 if (reg1->umin_value == (u64)val) 14475 reg1->umin_value++; 14476 if (reg1->umax_value == (u64)val) 14477 reg1->umax_value--; 14478 if (reg1->smin_value == (s64)val) 14479 reg1->smin_value++; 14480 if (reg1->smax_value == (s64)val) 14481 reg1->smax_value--; 14482 } 14483 break; 14484 case BPF_JSET: 14485 if (!is_reg_const(reg2, is_jmp32)) 14486 swap(reg1, reg2); 14487 if (!is_reg_const(reg2, is_jmp32)) 14488 break; 14489 val = reg_const_value(reg2, is_jmp32); 14490 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 14491 * requires single bit to learn something useful. E.g., if we 14492 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 14493 * are actually set? We can learn something definite only if 14494 * it's a single-bit value to begin with. 14495 * 14496 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 14497 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 14498 * bit 1 is set, which we can readily use in adjustments. 14499 */ 14500 if (!is_power_of_2(val)) 14501 break; 14502 if (is_jmp32) { 14503 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 14504 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14505 } else { 14506 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 14507 } 14508 break; 14509 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 14510 if (!is_reg_const(reg2, is_jmp32)) 14511 swap(reg1, reg2); 14512 if (!is_reg_const(reg2, is_jmp32)) 14513 break; 14514 val = reg_const_value(reg2, is_jmp32); 14515 if (is_jmp32) { 14516 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 14517 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14518 } else { 14519 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 14520 } 14521 break; 14522 case BPF_JLE: 14523 if (is_jmp32) { 14524 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14525 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14526 } else { 14527 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14528 reg2->umin_value = max(reg1->umin_value, reg2->umin_value); 14529 } 14530 break; 14531 case BPF_JLT: 14532 if (is_jmp32) { 14533 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1); 14534 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value); 14535 } else { 14536 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1); 14537 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value); 14538 } 14539 break; 14540 case BPF_JSLE: 14541 if (is_jmp32) { 14542 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14543 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14544 } else { 14545 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14546 reg2->smin_value = max(reg1->smin_value, reg2->smin_value); 14547 } 14548 break; 14549 case BPF_JSLT: 14550 if (is_jmp32) { 14551 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1); 14552 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value); 14553 } else { 14554 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1); 14555 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value); 14556 } 14557 break; 14558 case BPF_JGE: 14559 case BPF_JGT: 14560 case BPF_JSGE: 14561 case BPF_JSGT: 14562 /* just reuse LE/LT logic above */ 14563 opcode = flip_opcode(opcode); 14564 swap(reg1, reg2); 14565 goto again; 14566 default: 14567 return; 14568 } 14569 } 14570 14571 /* Adjusts the register min/max values in the case that the dst_reg and 14572 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K 14573 * check, in which case we havea fake SCALAR_VALUE representing insn->imm). 14574 * Technically we can do similar adjustments for pointers to the same object, 14575 * but we don't support that right now. 14576 */ 14577 static int reg_set_min_max(struct bpf_verifier_env *env, 14578 struct bpf_reg_state *true_reg1, 14579 struct bpf_reg_state *true_reg2, 14580 struct bpf_reg_state *false_reg1, 14581 struct bpf_reg_state *false_reg2, 14582 u8 opcode, bool is_jmp32) 14583 { 14584 int err; 14585 14586 /* If either register is a pointer, we can't learn anything about its 14587 * variable offset from the compare (unless they were a pointer into 14588 * the same object, but we don't bother with that). 14589 */ 14590 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE) 14591 return 0; 14592 14593 /* fallthrough (FALSE) branch */ 14594 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32); 14595 reg_bounds_sync(false_reg1); 14596 reg_bounds_sync(false_reg2); 14597 14598 /* jump (TRUE) branch */ 14599 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32); 14600 reg_bounds_sync(true_reg1); 14601 reg_bounds_sync(true_reg2); 14602 14603 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1"); 14604 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2"); 14605 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1"); 14606 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2"); 14607 return err; 14608 } 14609 14610 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 14611 struct bpf_reg_state *reg, u32 id, 14612 bool is_null) 14613 { 14614 if (type_may_be_null(reg->type) && reg->id == id && 14615 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 14616 /* Old offset (both fixed and variable parts) should have been 14617 * known-zero, because we don't allow pointer arithmetic on 14618 * pointers that might be NULL. If we see this happening, don't 14619 * convert the register. 14620 * 14621 * But in some cases, some helpers that return local kptrs 14622 * advance offset for the returned pointer. In those cases, it 14623 * is fine to expect to see reg->off. 14624 */ 14625 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 14626 return; 14627 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 14628 WARN_ON_ONCE(reg->off)) 14629 return; 14630 14631 if (is_null) { 14632 reg->type = SCALAR_VALUE; 14633 /* We don't need id and ref_obj_id from this point 14634 * onwards anymore, thus we should better reset it, 14635 * so that state pruning has chances to take effect. 14636 */ 14637 reg->id = 0; 14638 reg->ref_obj_id = 0; 14639 14640 return; 14641 } 14642 14643 mark_ptr_not_null_reg(reg); 14644 14645 if (!reg_may_point_to_spin_lock(reg)) { 14646 /* For not-NULL ptr, reg->ref_obj_id will be reset 14647 * in release_reference(). 14648 * 14649 * reg->id is still used by spin_lock ptr. Other 14650 * than spin_lock ptr type, reg->id can be reset. 14651 */ 14652 reg->id = 0; 14653 } 14654 } 14655 } 14656 14657 /* The logic is similar to find_good_pkt_pointers(), both could eventually 14658 * be folded together at some point. 14659 */ 14660 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 14661 bool is_null) 14662 { 14663 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14664 struct bpf_reg_state *regs = state->regs, *reg; 14665 u32 ref_obj_id = regs[regno].ref_obj_id; 14666 u32 id = regs[regno].id; 14667 14668 if (ref_obj_id && ref_obj_id == id && is_null) 14669 /* regs[regno] is in the " == NULL" branch. 14670 * No one could have freed the reference state before 14671 * doing the NULL check. 14672 */ 14673 WARN_ON_ONCE(release_reference_state(state, id)); 14674 14675 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14676 mark_ptr_or_null_reg(state, reg, id, is_null); 14677 })); 14678 } 14679 14680 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 14681 struct bpf_reg_state *dst_reg, 14682 struct bpf_reg_state *src_reg, 14683 struct bpf_verifier_state *this_branch, 14684 struct bpf_verifier_state *other_branch) 14685 { 14686 if (BPF_SRC(insn->code) != BPF_X) 14687 return false; 14688 14689 /* Pointers are always 64-bit. */ 14690 if (BPF_CLASS(insn->code) == BPF_JMP32) 14691 return false; 14692 14693 switch (BPF_OP(insn->code)) { 14694 case BPF_JGT: 14695 if ((dst_reg->type == PTR_TO_PACKET && 14696 src_reg->type == PTR_TO_PACKET_END) || 14697 (dst_reg->type == PTR_TO_PACKET_META && 14698 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14699 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 14700 find_good_pkt_pointers(this_branch, dst_reg, 14701 dst_reg->type, false); 14702 mark_pkt_end(other_branch, insn->dst_reg, true); 14703 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14704 src_reg->type == PTR_TO_PACKET) || 14705 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14706 src_reg->type == PTR_TO_PACKET_META)) { 14707 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 14708 find_good_pkt_pointers(other_branch, src_reg, 14709 src_reg->type, true); 14710 mark_pkt_end(this_branch, insn->src_reg, false); 14711 } else { 14712 return false; 14713 } 14714 break; 14715 case BPF_JLT: 14716 if ((dst_reg->type == PTR_TO_PACKET && 14717 src_reg->type == PTR_TO_PACKET_END) || 14718 (dst_reg->type == PTR_TO_PACKET_META && 14719 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14720 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 14721 find_good_pkt_pointers(other_branch, dst_reg, 14722 dst_reg->type, true); 14723 mark_pkt_end(this_branch, insn->dst_reg, false); 14724 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14725 src_reg->type == PTR_TO_PACKET) || 14726 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14727 src_reg->type == PTR_TO_PACKET_META)) { 14728 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 14729 find_good_pkt_pointers(this_branch, src_reg, 14730 src_reg->type, false); 14731 mark_pkt_end(other_branch, insn->src_reg, true); 14732 } else { 14733 return false; 14734 } 14735 break; 14736 case BPF_JGE: 14737 if ((dst_reg->type == PTR_TO_PACKET && 14738 src_reg->type == PTR_TO_PACKET_END) || 14739 (dst_reg->type == PTR_TO_PACKET_META && 14740 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14741 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 14742 find_good_pkt_pointers(this_branch, dst_reg, 14743 dst_reg->type, true); 14744 mark_pkt_end(other_branch, insn->dst_reg, false); 14745 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14746 src_reg->type == PTR_TO_PACKET) || 14747 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14748 src_reg->type == PTR_TO_PACKET_META)) { 14749 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 14750 find_good_pkt_pointers(other_branch, src_reg, 14751 src_reg->type, false); 14752 mark_pkt_end(this_branch, insn->src_reg, true); 14753 } else { 14754 return false; 14755 } 14756 break; 14757 case BPF_JLE: 14758 if ((dst_reg->type == PTR_TO_PACKET && 14759 src_reg->type == PTR_TO_PACKET_END) || 14760 (dst_reg->type == PTR_TO_PACKET_META && 14761 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14762 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 14763 find_good_pkt_pointers(other_branch, dst_reg, 14764 dst_reg->type, false); 14765 mark_pkt_end(this_branch, insn->dst_reg, true); 14766 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14767 src_reg->type == PTR_TO_PACKET) || 14768 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14769 src_reg->type == PTR_TO_PACKET_META)) { 14770 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 14771 find_good_pkt_pointers(this_branch, src_reg, 14772 src_reg->type, true); 14773 mark_pkt_end(other_branch, insn->src_reg, false); 14774 } else { 14775 return false; 14776 } 14777 break; 14778 default: 14779 return false; 14780 } 14781 14782 return true; 14783 } 14784 14785 static void find_equal_scalars(struct bpf_verifier_state *vstate, 14786 struct bpf_reg_state *known_reg) 14787 { 14788 struct bpf_func_state *state; 14789 struct bpf_reg_state *reg; 14790 14791 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14792 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 14793 copy_register_state(reg, known_reg); 14794 })); 14795 } 14796 14797 static int check_cond_jmp_op(struct bpf_verifier_env *env, 14798 struct bpf_insn *insn, int *insn_idx) 14799 { 14800 struct bpf_verifier_state *this_branch = env->cur_state; 14801 struct bpf_verifier_state *other_branch; 14802 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 14803 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 14804 struct bpf_reg_state *eq_branch_regs; 14805 struct bpf_reg_state fake_reg = {}; 14806 u8 opcode = BPF_OP(insn->code); 14807 bool is_jmp32; 14808 int pred = -1; 14809 int err; 14810 14811 /* Only conditional jumps are expected to reach here. */ 14812 if (opcode == BPF_JA || opcode > BPF_JSLE) { 14813 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 14814 return -EINVAL; 14815 } 14816 14817 /* check src2 operand */ 14818 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14819 if (err) 14820 return err; 14821 14822 dst_reg = ®s[insn->dst_reg]; 14823 if (BPF_SRC(insn->code) == BPF_X) { 14824 if (insn->imm != 0) { 14825 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14826 return -EINVAL; 14827 } 14828 14829 /* check src1 operand */ 14830 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14831 if (err) 14832 return err; 14833 14834 src_reg = ®s[insn->src_reg]; 14835 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 14836 is_pointer_value(env, insn->src_reg)) { 14837 verbose(env, "R%d pointer comparison prohibited\n", 14838 insn->src_reg); 14839 return -EACCES; 14840 } 14841 } else { 14842 if (insn->src_reg != BPF_REG_0) { 14843 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14844 return -EINVAL; 14845 } 14846 src_reg = &fake_reg; 14847 src_reg->type = SCALAR_VALUE; 14848 __mark_reg_known(src_reg, insn->imm); 14849 } 14850 14851 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 14852 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32); 14853 if (pred >= 0) { 14854 /* If we get here with a dst_reg pointer type it is because 14855 * above is_branch_taken() special cased the 0 comparison. 14856 */ 14857 if (!__is_pointer_value(false, dst_reg)) 14858 err = mark_chain_precision(env, insn->dst_reg); 14859 if (BPF_SRC(insn->code) == BPF_X && !err && 14860 !__is_pointer_value(false, src_reg)) 14861 err = mark_chain_precision(env, insn->src_reg); 14862 if (err) 14863 return err; 14864 } 14865 14866 if (pred == 1) { 14867 /* Only follow the goto, ignore fall-through. If needed, push 14868 * the fall-through branch for simulation under speculative 14869 * execution. 14870 */ 14871 if (!env->bypass_spec_v1 && 14872 !sanitize_speculative_path(env, insn, *insn_idx + 1, 14873 *insn_idx)) 14874 return -EFAULT; 14875 if (env->log.level & BPF_LOG_LEVEL) 14876 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14877 *insn_idx += insn->off; 14878 return 0; 14879 } else if (pred == 0) { 14880 /* Only follow the fall-through branch, since that's where the 14881 * program will go. If needed, push the goto branch for 14882 * simulation under speculative execution. 14883 */ 14884 if (!env->bypass_spec_v1 && 14885 !sanitize_speculative_path(env, insn, 14886 *insn_idx + insn->off + 1, 14887 *insn_idx)) 14888 return -EFAULT; 14889 if (env->log.level & BPF_LOG_LEVEL) 14890 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14891 return 0; 14892 } 14893 14894 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 14895 false); 14896 if (!other_branch) 14897 return -EFAULT; 14898 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 14899 14900 if (BPF_SRC(insn->code) == BPF_X) { 14901 err = reg_set_min_max(env, 14902 &other_branch_regs[insn->dst_reg], 14903 &other_branch_regs[insn->src_reg], 14904 dst_reg, src_reg, opcode, is_jmp32); 14905 } else /* BPF_SRC(insn->code) == BPF_K */ { 14906 err = reg_set_min_max(env, 14907 &other_branch_regs[insn->dst_reg], 14908 src_reg /* fake one */, 14909 dst_reg, src_reg /* same fake one */, 14910 opcode, is_jmp32); 14911 } 14912 if (err) 14913 return err; 14914 14915 if (BPF_SRC(insn->code) == BPF_X && 14916 src_reg->type == SCALAR_VALUE && src_reg->id && 14917 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 14918 find_equal_scalars(this_branch, src_reg); 14919 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 14920 } 14921 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 14922 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 14923 find_equal_scalars(this_branch, dst_reg); 14924 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 14925 } 14926 14927 /* if one pointer register is compared to another pointer 14928 * register check if PTR_MAYBE_NULL could be lifted. 14929 * E.g. register A - maybe null 14930 * register B - not null 14931 * for JNE A, B, ... - A is not null in the false branch; 14932 * for JEQ A, B, ... - A is not null in the true branch. 14933 * 14934 * Since PTR_TO_BTF_ID points to a kernel struct that does 14935 * not need to be null checked by the BPF program, i.e., 14936 * could be null even without PTR_MAYBE_NULL marking, so 14937 * only propagate nullness when neither reg is that type. 14938 */ 14939 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 14940 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 14941 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 14942 base_type(src_reg->type) != PTR_TO_BTF_ID && 14943 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 14944 eq_branch_regs = NULL; 14945 switch (opcode) { 14946 case BPF_JEQ: 14947 eq_branch_regs = other_branch_regs; 14948 break; 14949 case BPF_JNE: 14950 eq_branch_regs = regs; 14951 break; 14952 default: 14953 /* do nothing */ 14954 break; 14955 } 14956 if (eq_branch_regs) { 14957 if (type_may_be_null(src_reg->type)) 14958 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 14959 else 14960 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 14961 } 14962 } 14963 14964 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 14965 * NOTE: these optimizations below are related with pointer comparison 14966 * which will never be JMP32. 14967 */ 14968 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 14969 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 14970 type_may_be_null(dst_reg->type)) { 14971 /* Mark all identical registers in each branch as either 14972 * safe or unknown depending R == 0 or R != 0 conditional. 14973 */ 14974 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 14975 opcode == BPF_JNE); 14976 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 14977 opcode == BPF_JEQ); 14978 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 14979 this_branch, other_branch) && 14980 is_pointer_value(env, insn->dst_reg)) { 14981 verbose(env, "R%d pointer comparison prohibited\n", 14982 insn->dst_reg); 14983 return -EACCES; 14984 } 14985 if (env->log.level & BPF_LOG_LEVEL) 14986 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14987 return 0; 14988 } 14989 14990 /* verify BPF_LD_IMM64 instruction */ 14991 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 14992 { 14993 struct bpf_insn_aux_data *aux = cur_aux(env); 14994 struct bpf_reg_state *regs = cur_regs(env); 14995 struct bpf_reg_state *dst_reg; 14996 struct bpf_map *map; 14997 int err; 14998 14999 if (BPF_SIZE(insn->code) != BPF_DW) { 15000 verbose(env, "invalid BPF_LD_IMM insn\n"); 15001 return -EINVAL; 15002 } 15003 if (insn->off != 0) { 15004 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 15005 return -EINVAL; 15006 } 15007 15008 err = check_reg_arg(env, insn->dst_reg, DST_OP); 15009 if (err) 15010 return err; 15011 15012 dst_reg = ®s[insn->dst_reg]; 15013 if (insn->src_reg == 0) { 15014 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 15015 15016 dst_reg->type = SCALAR_VALUE; 15017 __mark_reg_known(®s[insn->dst_reg], imm); 15018 return 0; 15019 } 15020 15021 /* All special src_reg cases are listed below. From this point onwards 15022 * we either succeed and assign a corresponding dst_reg->type after 15023 * zeroing the offset, or fail and reject the program. 15024 */ 15025 mark_reg_known_zero(env, regs, insn->dst_reg); 15026 15027 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 15028 dst_reg->type = aux->btf_var.reg_type; 15029 switch (base_type(dst_reg->type)) { 15030 case PTR_TO_MEM: 15031 dst_reg->mem_size = aux->btf_var.mem_size; 15032 break; 15033 case PTR_TO_BTF_ID: 15034 dst_reg->btf = aux->btf_var.btf; 15035 dst_reg->btf_id = aux->btf_var.btf_id; 15036 break; 15037 default: 15038 verbose(env, "bpf verifier is misconfigured\n"); 15039 return -EFAULT; 15040 } 15041 return 0; 15042 } 15043 15044 if (insn->src_reg == BPF_PSEUDO_FUNC) { 15045 struct bpf_prog_aux *aux = env->prog->aux; 15046 u32 subprogno = find_subprog(env, 15047 env->insn_idx + insn->imm + 1); 15048 15049 if (!aux->func_info) { 15050 verbose(env, "missing btf func_info\n"); 15051 return -EINVAL; 15052 } 15053 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 15054 verbose(env, "callback function not static\n"); 15055 return -EINVAL; 15056 } 15057 15058 dst_reg->type = PTR_TO_FUNC; 15059 dst_reg->subprogno = subprogno; 15060 return 0; 15061 } 15062 15063 map = env->used_maps[aux->map_index]; 15064 dst_reg->map_ptr = map; 15065 15066 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 15067 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 15068 dst_reg->type = PTR_TO_MAP_VALUE; 15069 dst_reg->off = aux->map_off; 15070 WARN_ON_ONCE(map->max_entries != 1); 15071 /* We want reg->id to be same (0) as map_value is not distinct */ 15072 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 15073 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 15074 dst_reg->type = CONST_PTR_TO_MAP; 15075 } else { 15076 verbose(env, "bpf verifier is misconfigured\n"); 15077 return -EINVAL; 15078 } 15079 15080 return 0; 15081 } 15082 15083 static bool may_access_skb(enum bpf_prog_type type) 15084 { 15085 switch (type) { 15086 case BPF_PROG_TYPE_SOCKET_FILTER: 15087 case BPF_PROG_TYPE_SCHED_CLS: 15088 case BPF_PROG_TYPE_SCHED_ACT: 15089 return true; 15090 default: 15091 return false; 15092 } 15093 } 15094 15095 /* verify safety of LD_ABS|LD_IND instructions: 15096 * - they can only appear in the programs where ctx == skb 15097 * - since they are wrappers of function calls, they scratch R1-R5 registers, 15098 * preserve R6-R9, and store return value into R0 15099 * 15100 * Implicit input: 15101 * ctx == skb == R6 == CTX 15102 * 15103 * Explicit input: 15104 * SRC == any register 15105 * IMM == 32-bit immediate 15106 * 15107 * Output: 15108 * R0 - 8/16/32-bit skb data converted to cpu endianness 15109 */ 15110 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 15111 { 15112 struct bpf_reg_state *regs = cur_regs(env); 15113 static const int ctx_reg = BPF_REG_6; 15114 u8 mode = BPF_MODE(insn->code); 15115 int i, err; 15116 15117 if (!may_access_skb(resolve_prog_type(env->prog))) { 15118 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 15119 return -EINVAL; 15120 } 15121 15122 if (!env->ops->gen_ld_abs) { 15123 verbose(env, "bpf verifier is misconfigured\n"); 15124 return -EINVAL; 15125 } 15126 15127 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 15128 BPF_SIZE(insn->code) == BPF_DW || 15129 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 15130 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 15131 return -EINVAL; 15132 } 15133 15134 /* check whether implicit source operand (register R6) is readable */ 15135 err = check_reg_arg(env, ctx_reg, SRC_OP); 15136 if (err) 15137 return err; 15138 15139 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 15140 * gen_ld_abs() may terminate the program at runtime, leading to 15141 * reference leak. 15142 */ 15143 err = check_reference_leak(env, false); 15144 if (err) { 15145 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 15146 return err; 15147 } 15148 15149 if (env->cur_state->active_lock.ptr) { 15150 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 15151 return -EINVAL; 15152 } 15153 15154 if (env->cur_state->active_rcu_lock) { 15155 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 15156 return -EINVAL; 15157 } 15158 15159 if (regs[ctx_reg].type != PTR_TO_CTX) { 15160 verbose(env, 15161 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 15162 return -EINVAL; 15163 } 15164 15165 if (mode == BPF_IND) { 15166 /* check explicit source operand */ 15167 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15168 if (err) 15169 return err; 15170 } 15171 15172 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 15173 if (err < 0) 15174 return err; 15175 15176 /* reset caller saved regs to unreadable */ 15177 for (i = 0; i < CALLER_SAVED_REGS; i++) { 15178 mark_reg_not_init(env, regs, caller_saved[i]); 15179 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 15180 } 15181 15182 /* mark destination R0 register as readable, since it contains 15183 * the value fetched from the packet. 15184 * Already marked as written above. 15185 */ 15186 mark_reg_unknown(env, regs, BPF_REG_0); 15187 /* ld_abs load up to 32-bit skb data. */ 15188 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 15189 return 0; 15190 } 15191 15192 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 15193 { 15194 const char *exit_ctx = "At program exit"; 15195 struct tnum enforce_attach_type_range = tnum_unknown; 15196 const struct bpf_prog *prog = env->prog; 15197 struct bpf_reg_state *reg; 15198 struct bpf_retval_range range = retval_range(0, 1); 15199 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 15200 int err; 15201 struct bpf_func_state *frame = env->cur_state->frame[0]; 15202 const bool is_subprog = frame->subprogno; 15203 15204 /* LSM and struct_ops func-ptr's return type could be "void" */ 15205 if (!is_subprog || frame->in_exception_callback_fn) { 15206 switch (prog_type) { 15207 case BPF_PROG_TYPE_LSM: 15208 if (prog->expected_attach_type == BPF_LSM_CGROUP) 15209 /* See below, can be 0 or 0-1 depending on hook. */ 15210 break; 15211 fallthrough; 15212 case BPF_PROG_TYPE_STRUCT_OPS: 15213 if (!prog->aux->attach_func_proto->type) 15214 return 0; 15215 break; 15216 default: 15217 break; 15218 } 15219 } 15220 15221 /* eBPF calling convention is such that R0 is used 15222 * to return the value from eBPF program. 15223 * Make sure that it's readable at this time 15224 * of bpf_exit, which means that program wrote 15225 * something into it earlier 15226 */ 15227 err = check_reg_arg(env, regno, SRC_OP); 15228 if (err) 15229 return err; 15230 15231 if (is_pointer_value(env, regno)) { 15232 verbose(env, "R%d leaks addr as return value\n", regno); 15233 return -EACCES; 15234 } 15235 15236 reg = cur_regs(env) + regno; 15237 15238 if (frame->in_async_callback_fn) { 15239 /* enforce return zero from async callbacks like timer */ 15240 exit_ctx = "At async callback return"; 15241 range = retval_range(0, 0); 15242 goto enforce_retval; 15243 } 15244 15245 if (is_subprog && !frame->in_exception_callback_fn) { 15246 if (reg->type != SCALAR_VALUE) { 15247 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 15248 regno, reg_type_str(env, reg->type)); 15249 return -EINVAL; 15250 } 15251 return 0; 15252 } 15253 15254 switch (prog_type) { 15255 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 15256 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 15257 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 15258 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG || 15259 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 15260 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 15261 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME || 15262 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 15263 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME || 15264 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME) 15265 range = retval_range(1, 1); 15266 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 15267 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 15268 range = retval_range(0, 3); 15269 break; 15270 case BPF_PROG_TYPE_CGROUP_SKB: 15271 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 15272 range = retval_range(0, 3); 15273 enforce_attach_type_range = tnum_range(2, 3); 15274 } 15275 break; 15276 case BPF_PROG_TYPE_CGROUP_SOCK: 15277 case BPF_PROG_TYPE_SOCK_OPS: 15278 case BPF_PROG_TYPE_CGROUP_DEVICE: 15279 case BPF_PROG_TYPE_CGROUP_SYSCTL: 15280 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 15281 break; 15282 case BPF_PROG_TYPE_RAW_TRACEPOINT: 15283 if (!env->prog->aux->attach_btf_id) 15284 return 0; 15285 range = retval_range(0, 0); 15286 break; 15287 case BPF_PROG_TYPE_TRACING: 15288 switch (env->prog->expected_attach_type) { 15289 case BPF_TRACE_FENTRY: 15290 case BPF_TRACE_FEXIT: 15291 range = retval_range(0, 0); 15292 break; 15293 case BPF_TRACE_RAW_TP: 15294 case BPF_MODIFY_RETURN: 15295 return 0; 15296 case BPF_TRACE_ITER: 15297 break; 15298 default: 15299 return -ENOTSUPP; 15300 } 15301 break; 15302 case BPF_PROG_TYPE_SK_LOOKUP: 15303 range = retval_range(SK_DROP, SK_PASS); 15304 break; 15305 15306 case BPF_PROG_TYPE_LSM: 15307 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 15308 /* Regular BPF_PROG_TYPE_LSM programs can return 15309 * any value. 15310 */ 15311 return 0; 15312 } 15313 if (!env->prog->aux->attach_func_proto->type) { 15314 /* Make sure programs that attach to void 15315 * hooks don't try to modify return value. 15316 */ 15317 range = retval_range(1, 1); 15318 } 15319 break; 15320 15321 case BPF_PROG_TYPE_NETFILTER: 15322 range = retval_range(NF_DROP, NF_ACCEPT); 15323 break; 15324 case BPF_PROG_TYPE_EXT: 15325 /* freplace program can return anything as its return value 15326 * depends on the to-be-replaced kernel func or bpf program. 15327 */ 15328 default: 15329 return 0; 15330 } 15331 15332 enforce_retval: 15333 if (reg->type != SCALAR_VALUE) { 15334 verbose(env, "%s the register R%d is not a known value (%s)\n", 15335 exit_ctx, regno, reg_type_str(env, reg->type)); 15336 return -EINVAL; 15337 } 15338 15339 err = mark_chain_precision(env, regno); 15340 if (err) 15341 return err; 15342 15343 if (!retval_range_within(range, reg)) { 15344 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 15345 if (!is_subprog && 15346 prog->expected_attach_type == BPF_LSM_CGROUP && 15347 prog_type == BPF_PROG_TYPE_LSM && 15348 !prog->aux->attach_func_proto->type) 15349 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 15350 return -EINVAL; 15351 } 15352 15353 if (!tnum_is_unknown(enforce_attach_type_range) && 15354 tnum_in(enforce_attach_type_range, reg->var_off)) 15355 env->prog->enforce_expected_attach_type = 1; 15356 return 0; 15357 } 15358 15359 /* non-recursive DFS pseudo code 15360 * 1 procedure DFS-iterative(G,v): 15361 * 2 label v as discovered 15362 * 3 let S be a stack 15363 * 4 S.push(v) 15364 * 5 while S is not empty 15365 * 6 t <- S.peek() 15366 * 7 if t is what we're looking for: 15367 * 8 return t 15368 * 9 for all edges e in G.adjacentEdges(t) do 15369 * 10 if edge e is already labelled 15370 * 11 continue with the next edge 15371 * 12 w <- G.adjacentVertex(t,e) 15372 * 13 if vertex w is not discovered and not explored 15373 * 14 label e as tree-edge 15374 * 15 label w as discovered 15375 * 16 S.push(w) 15376 * 17 continue at 5 15377 * 18 else if vertex w is discovered 15378 * 19 label e as back-edge 15379 * 20 else 15380 * 21 // vertex w is explored 15381 * 22 label e as forward- or cross-edge 15382 * 23 label t as explored 15383 * 24 S.pop() 15384 * 15385 * convention: 15386 * 0x10 - discovered 15387 * 0x11 - discovered and fall-through edge labelled 15388 * 0x12 - discovered and fall-through and branch edges labelled 15389 * 0x20 - explored 15390 */ 15391 15392 enum { 15393 DISCOVERED = 0x10, 15394 EXPLORED = 0x20, 15395 FALLTHROUGH = 1, 15396 BRANCH = 2, 15397 }; 15398 15399 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 15400 { 15401 env->insn_aux_data[idx].prune_point = true; 15402 } 15403 15404 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 15405 { 15406 return env->insn_aux_data[insn_idx].prune_point; 15407 } 15408 15409 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 15410 { 15411 env->insn_aux_data[idx].force_checkpoint = true; 15412 } 15413 15414 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 15415 { 15416 return env->insn_aux_data[insn_idx].force_checkpoint; 15417 } 15418 15419 static void mark_calls_callback(struct bpf_verifier_env *env, int idx) 15420 { 15421 env->insn_aux_data[idx].calls_callback = true; 15422 } 15423 15424 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx) 15425 { 15426 return env->insn_aux_data[insn_idx].calls_callback; 15427 } 15428 15429 enum { 15430 DONE_EXPLORING = 0, 15431 KEEP_EXPLORING = 1, 15432 }; 15433 15434 /* t, w, e - match pseudo-code above: 15435 * t - index of current instruction 15436 * w - next instruction 15437 * e - edge 15438 */ 15439 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 15440 { 15441 int *insn_stack = env->cfg.insn_stack; 15442 int *insn_state = env->cfg.insn_state; 15443 15444 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 15445 return DONE_EXPLORING; 15446 15447 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 15448 return DONE_EXPLORING; 15449 15450 if (w < 0 || w >= env->prog->len) { 15451 verbose_linfo(env, t, "%d: ", t); 15452 verbose(env, "jump out of range from insn %d to %d\n", t, w); 15453 return -EINVAL; 15454 } 15455 15456 if (e == BRANCH) { 15457 /* mark branch target for state pruning */ 15458 mark_prune_point(env, w); 15459 mark_jmp_point(env, w); 15460 } 15461 15462 if (insn_state[w] == 0) { 15463 /* tree-edge */ 15464 insn_state[t] = DISCOVERED | e; 15465 insn_state[w] = DISCOVERED; 15466 if (env->cfg.cur_stack >= env->prog->len) 15467 return -E2BIG; 15468 insn_stack[env->cfg.cur_stack++] = w; 15469 return KEEP_EXPLORING; 15470 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 15471 if (env->bpf_capable) 15472 return DONE_EXPLORING; 15473 verbose_linfo(env, t, "%d: ", t); 15474 verbose_linfo(env, w, "%d: ", w); 15475 verbose(env, "back-edge from insn %d to %d\n", t, w); 15476 return -EINVAL; 15477 } else if (insn_state[w] == EXPLORED) { 15478 /* forward- or cross-edge */ 15479 insn_state[t] = DISCOVERED | e; 15480 } else { 15481 verbose(env, "insn state internal bug\n"); 15482 return -EFAULT; 15483 } 15484 return DONE_EXPLORING; 15485 } 15486 15487 static int visit_func_call_insn(int t, struct bpf_insn *insns, 15488 struct bpf_verifier_env *env, 15489 bool visit_callee) 15490 { 15491 int ret, insn_sz; 15492 15493 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 15494 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 15495 if (ret) 15496 return ret; 15497 15498 mark_prune_point(env, t + insn_sz); 15499 /* when we exit from subprog, we need to record non-linear history */ 15500 mark_jmp_point(env, t + insn_sz); 15501 15502 if (visit_callee) { 15503 mark_prune_point(env, t); 15504 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env); 15505 } 15506 return ret; 15507 } 15508 15509 /* Visits the instruction at index t and returns one of the following: 15510 * < 0 - an error occurred 15511 * DONE_EXPLORING - the instruction was fully explored 15512 * KEEP_EXPLORING - there is still work to be done before it is fully explored 15513 */ 15514 static int visit_insn(int t, struct bpf_verifier_env *env) 15515 { 15516 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 15517 int ret, off, insn_sz; 15518 15519 if (bpf_pseudo_func(insn)) 15520 return visit_func_call_insn(t, insns, env, true); 15521 15522 /* All non-branch instructions have a single fall-through edge. */ 15523 if (BPF_CLASS(insn->code) != BPF_JMP && 15524 BPF_CLASS(insn->code) != BPF_JMP32) { 15525 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 15526 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 15527 } 15528 15529 switch (BPF_OP(insn->code)) { 15530 case BPF_EXIT: 15531 return DONE_EXPLORING; 15532 15533 case BPF_CALL: 15534 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback) 15535 /* Mark this call insn as a prune point to trigger 15536 * is_state_visited() check before call itself is 15537 * processed by __check_func_call(). Otherwise new 15538 * async state will be pushed for further exploration. 15539 */ 15540 mark_prune_point(env, t); 15541 /* For functions that invoke callbacks it is not known how many times 15542 * callback would be called. Verifier models callback calling functions 15543 * by repeatedly visiting callback bodies and returning to origin call 15544 * instruction. 15545 * In order to stop such iteration verifier needs to identify when a 15546 * state identical some state from a previous iteration is reached. 15547 * Check below forces creation of checkpoint before callback calling 15548 * instruction to allow search for such identical states. 15549 */ 15550 if (is_sync_callback_calling_insn(insn)) { 15551 mark_calls_callback(env, t); 15552 mark_force_checkpoint(env, t); 15553 mark_prune_point(env, t); 15554 mark_jmp_point(env, t); 15555 } 15556 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 15557 struct bpf_kfunc_call_arg_meta meta; 15558 15559 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 15560 if (ret == 0 && is_iter_next_kfunc(&meta)) { 15561 mark_prune_point(env, t); 15562 /* Checking and saving state checkpoints at iter_next() call 15563 * is crucial for fast convergence of open-coded iterator loop 15564 * logic, so we need to force it. If we don't do that, 15565 * is_state_visited() might skip saving a checkpoint, causing 15566 * unnecessarily long sequence of not checkpointed 15567 * instructions and jumps, leading to exhaustion of jump 15568 * history buffer, and potentially other undesired outcomes. 15569 * It is expected that with correct open-coded iterators 15570 * convergence will happen quickly, so we don't run a risk of 15571 * exhausting memory. 15572 */ 15573 mark_force_checkpoint(env, t); 15574 } 15575 } 15576 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 15577 15578 case BPF_JA: 15579 if (BPF_SRC(insn->code) != BPF_K) 15580 return -EINVAL; 15581 15582 if (BPF_CLASS(insn->code) == BPF_JMP) 15583 off = insn->off; 15584 else 15585 off = insn->imm; 15586 15587 /* unconditional jump with single edge */ 15588 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 15589 if (ret) 15590 return ret; 15591 15592 mark_prune_point(env, t + off + 1); 15593 mark_jmp_point(env, t + off + 1); 15594 15595 return ret; 15596 15597 default: 15598 /* conditional jump with two edges */ 15599 mark_prune_point(env, t); 15600 15601 ret = push_insn(t, t + 1, FALLTHROUGH, env); 15602 if (ret) 15603 return ret; 15604 15605 return push_insn(t, t + insn->off + 1, BRANCH, env); 15606 } 15607 } 15608 15609 /* non-recursive depth-first-search to detect loops in BPF program 15610 * loop == back-edge in directed graph 15611 */ 15612 static int check_cfg(struct bpf_verifier_env *env) 15613 { 15614 int insn_cnt = env->prog->len; 15615 int *insn_stack, *insn_state; 15616 int ex_insn_beg, i, ret = 0; 15617 bool ex_done = false; 15618 15619 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15620 if (!insn_state) 15621 return -ENOMEM; 15622 15623 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15624 if (!insn_stack) { 15625 kvfree(insn_state); 15626 return -ENOMEM; 15627 } 15628 15629 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 15630 insn_stack[0] = 0; /* 0 is the first instruction */ 15631 env->cfg.cur_stack = 1; 15632 15633 walk_cfg: 15634 while (env->cfg.cur_stack > 0) { 15635 int t = insn_stack[env->cfg.cur_stack - 1]; 15636 15637 ret = visit_insn(t, env); 15638 switch (ret) { 15639 case DONE_EXPLORING: 15640 insn_state[t] = EXPLORED; 15641 env->cfg.cur_stack--; 15642 break; 15643 case KEEP_EXPLORING: 15644 break; 15645 default: 15646 if (ret > 0) { 15647 verbose(env, "visit_insn internal bug\n"); 15648 ret = -EFAULT; 15649 } 15650 goto err_free; 15651 } 15652 } 15653 15654 if (env->cfg.cur_stack < 0) { 15655 verbose(env, "pop stack internal bug\n"); 15656 ret = -EFAULT; 15657 goto err_free; 15658 } 15659 15660 if (env->exception_callback_subprog && !ex_done) { 15661 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start; 15662 15663 insn_state[ex_insn_beg] = DISCOVERED; 15664 insn_stack[0] = ex_insn_beg; 15665 env->cfg.cur_stack = 1; 15666 ex_done = true; 15667 goto walk_cfg; 15668 } 15669 15670 for (i = 0; i < insn_cnt; i++) { 15671 struct bpf_insn *insn = &env->prog->insnsi[i]; 15672 15673 if (insn_state[i] != EXPLORED) { 15674 verbose(env, "unreachable insn %d\n", i); 15675 ret = -EINVAL; 15676 goto err_free; 15677 } 15678 if (bpf_is_ldimm64(insn)) { 15679 if (insn_state[i + 1] != 0) { 15680 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 15681 ret = -EINVAL; 15682 goto err_free; 15683 } 15684 i++; /* skip second half of ldimm64 */ 15685 } 15686 } 15687 ret = 0; /* cfg looks good */ 15688 15689 err_free: 15690 kvfree(insn_state); 15691 kvfree(insn_stack); 15692 env->cfg.insn_state = env->cfg.insn_stack = NULL; 15693 return ret; 15694 } 15695 15696 static int check_abnormal_return(struct bpf_verifier_env *env) 15697 { 15698 int i; 15699 15700 for (i = 1; i < env->subprog_cnt; i++) { 15701 if (env->subprog_info[i].has_ld_abs) { 15702 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 15703 return -EINVAL; 15704 } 15705 if (env->subprog_info[i].has_tail_call) { 15706 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 15707 return -EINVAL; 15708 } 15709 } 15710 return 0; 15711 } 15712 15713 /* The minimum supported BTF func info size */ 15714 #define MIN_BPF_FUNCINFO_SIZE 8 15715 #define MAX_FUNCINFO_REC_SIZE 252 15716 15717 static int check_btf_func_early(struct bpf_verifier_env *env, 15718 const union bpf_attr *attr, 15719 bpfptr_t uattr) 15720 { 15721 u32 krec_size = sizeof(struct bpf_func_info); 15722 const struct btf_type *type, *func_proto; 15723 u32 i, nfuncs, urec_size, min_size; 15724 struct bpf_func_info *krecord; 15725 struct bpf_prog *prog; 15726 const struct btf *btf; 15727 u32 prev_offset = 0; 15728 bpfptr_t urecord; 15729 int ret = -ENOMEM; 15730 15731 nfuncs = attr->func_info_cnt; 15732 if (!nfuncs) { 15733 if (check_abnormal_return(env)) 15734 return -EINVAL; 15735 return 0; 15736 } 15737 15738 urec_size = attr->func_info_rec_size; 15739 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 15740 urec_size > MAX_FUNCINFO_REC_SIZE || 15741 urec_size % sizeof(u32)) { 15742 verbose(env, "invalid func info rec size %u\n", urec_size); 15743 return -EINVAL; 15744 } 15745 15746 prog = env->prog; 15747 btf = prog->aux->btf; 15748 15749 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15750 min_size = min_t(u32, krec_size, urec_size); 15751 15752 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 15753 if (!krecord) 15754 return -ENOMEM; 15755 15756 for (i = 0; i < nfuncs; i++) { 15757 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 15758 if (ret) { 15759 if (ret == -E2BIG) { 15760 verbose(env, "nonzero tailing record in func info"); 15761 /* set the size kernel expects so loader can zero 15762 * out the rest of the record. 15763 */ 15764 if (copy_to_bpfptr_offset(uattr, 15765 offsetof(union bpf_attr, func_info_rec_size), 15766 &min_size, sizeof(min_size))) 15767 ret = -EFAULT; 15768 } 15769 goto err_free; 15770 } 15771 15772 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 15773 ret = -EFAULT; 15774 goto err_free; 15775 } 15776 15777 /* check insn_off */ 15778 ret = -EINVAL; 15779 if (i == 0) { 15780 if (krecord[i].insn_off) { 15781 verbose(env, 15782 "nonzero insn_off %u for the first func info record", 15783 krecord[i].insn_off); 15784 goto err_free; 15785 } 15786 } else if (krecord[i].insn_off <= prev_offset) { 15787 verbose(env, 15788 "same or smaller insn offset (%u) than previous func info record (%u)", 15789 krecord[i].insn_off, prev_offset); 15790 goto err_free; 15791 } 15792 15793 /* check type_id */ 15794 type = btf_type_by_id(btf, krecord[i].type_id); 15795 if (!type || !btf_type_is_func(type)) { 15796 verbose(env, "invalid type id %d in func info", 15797 krecord[i].type_id); 15798 goto err_free; 15799 } 15800 15801 func_proto = btf_type_by_id(btf, type->type); 15802 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 15803 /* btf_func_check() already verified it during BTF load */ 15804 goto err_free; 15805 15806 prev_offset = krecord[i].insn_off; 15807 bpfptr_add(&urecord, urec_size); 15808 } 15809 15810 prog->aux->func_info = krecord; 15811 prog->aux->func_info_cnt = nfuncs; 15812 return 0; 15813 15814 err_free: 15815 kvfree(krecord); 15816 return ret; 15817 } 15818 15819 static int check_btf_func(struct bpf_verifier_env *env, 15820 const union bpf_attr *attr, 15821 bpfptr_t uattr) 15822 { 15823 const struct btf_type *type, *func_proto, *ret_type; 15824 u32 i, nfuncs, urec_size; 15825 struct bpf_func_info *krecord; 15826 struct bpf_func_info_aux *info_aux = NULL; 15827 struct bpf_prog *prog; 15828 const struct btf *btf; 15829 bpfptr_t urecord; 15830 bool scalar_return; 15831 int ret = -ENOMEM; 15832 15833 nfuncs = attr->func_info_cnt; 15834 if (!nfuncs) { 15835 if (check_abnormal_return(env)) 15836 return -EINVAL; 15837 return 0; 15838 } 15839 if (nfuncs != env->subprog_cnt) { 15840 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 15841 return -EINVAL; 15842 } 15843 15844 urec_size = attr->func_info_rec_size; 15845 15846 prog = env->prog; 15847 btf = prog->aux->btf; 15848 15849 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15850 15851 krecord = prog->aux->func_info; 15852 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 15853 if (!info_aux) 15854 return -ENOMEM; 15855 15856 for (i = 0; i < nfuncs; i++) { 15857 /* check insn_off */ 15858 ret = -EINVAL; 15859 15860 if (env->subprog_info[i].start != krecord[i].insn_off) { 15861 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 15862 goto err_free; 15863 } 15864 15865 /* Already checked type_id */ 15866 type = btf_type_by_id(btf, krecord[i].type_id); 15867 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 15868 /* Already checked func_proto */ 15869 func_proto = btf_type_by_id(btf, type->type); 15870 15871 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 15872 scalar_return = 15873 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 15874 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 15875 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 15876 goto err_free; 15877 } 15878 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 15879 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 15880 goto err_free; 15881 } 15882 15883 bpfptr_add(&urecord, urec_size); 15884 } 15885 15886 prog->aux->func_info_aux = info_aux; 15887 return 0; 15888 15889 err_free: 15890 kfree(info_aux); 15891 return ret; 15892 } 15893 15894 static void adjust_btf_func(struct bpf_verifier_env *env) 15895 { 15896 struct bpf_prog_aux *aux = env->prog->aux; 15897 int i; 15898 15899 if (!aux->func_info) 15900 return; 15901 15902 /* func_info is not available for hidden subprogs */ 15903 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 15904 aux->func_info[i].insn_off = env->subprog_info[i].start; 15905 } 15906 15907 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 15908 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 15909 15910 static int check_btf_line(struct bpf_verifier_env *env, 15911 const union bpf_attr *attr, 15912 bpfptr_t uattr) 15913 { 15914 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 15915 struct bpf_subprog_info *sub; 15916 struct bpf_line_info *linfo; 15917 struct bpf_prog *prog; 15918 const struct btf *btf; 15919 bpfptr_t ulinfo; 15920 int err; 15921 15922 nr_linfo = attr->line_info_cnt; 15923 if (!nr_linfo) 15924 return 0; 15925 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 15926 return -EINVAL; 15927 15928 rec_size = attr->line_info_rec_size; 15929 if (rec_size < MIN_BPF_LINEINFO_SIZE || 15930 rec_size > MAX_LINEINFO_REC_SIZE || 15931 rec_size & (sizeof(u32) - 1)) 15932 return -EINVAL; 15933 15934 /* Need to zero it in case the userspace may 15935 * pass in a smaller bpf_line_info object. 15936 */ 15937 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 15938 GFP_KERNEL | __GFP_NOWARN); 15939 if (!linfo) 15940 return -ENOMEM; 15941 15942 prog = env->prog; 15943 btf = prog->aux->btf; 15944 15945 s = 0; 15946 sub = env->subprog_info; 15947 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 15948 expected_size = sizeof(struct bpf_line_info); 15949 ncopy = min_t(u32, expected_size, rec_size); 15950 for (i = 0; i < nr_linfo; i++) { 15951 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 15952 if (err) { 15953 if (err == -E2BIG) { 15954 verbose(env, "nonzero tailing record in line_info"); 15955 if (copy_to_bpfptr_offset(uattr, 15956 offsetof(union bpf_attr, line_info_rec_size), 15957 &expected_size, sizeof(expected_size))) 15958 err = -EFAULT; 15959 } 15960 goto err_free; 15961 } 15962 15963 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 15964 err = -EFAULT; 15965 goto err_free; 15966 } 15967 15968 /* 15969 * Check insn_off to ensure 15970 * 1) strictly increasing AND 15971 * 2) bounded by prog->len 15972 * 15973 * The linfo[0].insn_off == 0 check logically falls into 15974 * the later "missing bpf_line_info for func..." case 15975 * because the first linfo[0].insn_off must be the 15976 * first sub also and the first sub must have 15977 * subprog_info[0].start == 0. 15978 */ 15979 if ((i && linfo[i].insn_off <= prev_offset) || 15980 linfo[i].insn_off >= prog->len) { 15981 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 15982 i, linfo[i].insn_off, prev_offset, 15983 prog->len); 15984 err = -EINVAL; 15985 goto err_free; 15986 } 15987 15988 if (!prog->insnsi[linfo[i].insn_off].code) { 15989 verbose(env, 15990 "Invalid insn code at line_info[%u].insn_off\n", 15991 i); 15992 err = -EINVAL; 15993 goto err_free; 15994 } 15995 15996 if (!btf_name_by_offset(btf, linfo[i].line_off) || 15997 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 15998 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 15999 err = -EINVAL; 16000 goto err_free; 16001 } 16002 16003 if (s != env->subprog_cnt) { 16004 if (linfo[i].insn_off == sub[s].start) { 16005 sub[s].linfo_idx = i; 16006 s++; 16007 } else if (sub[s].start < linfo[i].insn_off) { 16008 verbose(env, "missing bpf_line_info for func#%u\n", s); 16009 err = -EINVAL; 16010 goto err_free; 16011 } 16012 } 16013 16014 prev_offset = linfo[i].insn_off; 16015 bpfptr_add(&ulinfo, rec_size); 16016 } 16017 16018 if (s != env->subprog_cnt) { 16019 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 16020 env->subprog_cnt - s, s); 16021 err = -EINVAL; 16022 goto err_free; 16023 } 16024 16025 prog->aux->linfo = linfo; 16026 prog->aux->nr_linfo = nr_linfo; 16027 16028 return 0; 16029 16030 err_free: 16031 kvfree(linfo); 16032 return err; 16033 } 16034 16035 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 16036 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 16037 16038 static int check_core_relo(struct bpf_verifier_env *env, 16039 const union bpf_attr *attr, 16040 bpfptr_t uattr) 16041 { 16042 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 16043 struct bpf_core_relo core_relo = {}; 16044 struct bpf_prog *prog = env->prog; 16045 const struct btf *btf = prog->aux->btf; 16046 struct bpf_core_ctx ctx = { 16047 .log = &env->log, 16048 .btf = btf, 16049 }; 16050 bpfptr_t u_core_relo; 16051 int err; 16052 16053 nr_core_relo = attr->core_relo_cnt; 16054 if (!nr_core_relo) 16055 return 0; 16056 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 16057 return -EINVAL; 16058 16059 rec_size = attr->core_relo_rec_size; 16060 if (rec_size < MIN_CORE_RELO_SIZE || 16061 rec_size > MAX_CORE_RELO_SIZE || 16062 rec_size % sizeof(u32)) 16063 return -EINVAL; 16064 16065 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 16066 expected_size = sizeof(struct bpf_core_relo); 16067 ncopy = min_t(u32, expected_size, rec_size); 16068 16069 /* Unlike func_info and line_info, copy and apply each CO-RE 16070 * relocation record one at a time. 16071 */ 16072 for (i = 0; i < nr_core_relo; i++) { 16073 /* future proofing when sizeof(bpf_core_relo) changes */ 16074 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 16075 if (err) { 16076 if (err == -E2BIG) { 16077 verbose(env, "nonzero tailing record in core_relo"); 16078 if (copy_to_bpfptr_offset(uattr, 16079 offsetof(union bpf_attr, core_relo_rec_size), 16080 &expected_size, sizeof(expected_size))) 16081 err = -EFAULT; 16082 } 16083 break; 16084 } 16085 16086 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 16087 err = -EFAULT; 16088 break; 16089 } 16090 16091 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 16092 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 16093 i, core_relo.insn_off, prog->len); 16094 err = -EINVAL; 16095 break; 16096 } 16097 16098 err = bpf_core_apply(&ctx, &core_relo, i, 16099 &prog->insnsi[core_relo.insn_off / 8]); 16100 if (err) 16101 break; 16102 bpfptr_add(&u_core_relo, rec_size); 16103 } 16104 return err; 16105 } 16106 16107 static int check_btf_info_early(struct bpf_verifier_env *env, 16108 const union bpf_attr *attr, 16109 bpfptr_t uattr) 16110 { 16111 struct btf *btf; 16112 int err; 16113 16114 if (!attr->func_info_cnt && !attr->line_info_cnt) { 16115 if (check_abnormal_return(env)) 16116 return -EINVAL; 16117 return 0; 16118 } 16119 16120 btf = btf_get_by_fd(attr->prog_btf_fd); 16121 if (IS_ERR(btf)) 16122 return PTR_ERR(btf); 16123 if (btf_is_kernel(btf)) { 16124 btf_put(btf); 16125 return -EACCES; 16126 } 16127 env->prog->aux->btf = btf; 16128 16129 err = check_btf_func_early(env, attr, uattr); 16130 if (err) 16131 return err; 16132 return 0; 16133 } 16134 16135 static int check_btf_info(struct bpf_verifier_env *env, 16136 const union bpf_attr *attr, 16137 bpfptr_t uattr) 16138 { 16139 int err; 16140 16141 if (!attr->func_info_cnt && !attr->line_info_cnt) { 16142 if (check_abnormal_return(env)) 16143 return -EINVAL; 16144 return 0; 16145 } 16146 16147 err = check_btf_func(env, attr, uattr); 16148 if (err) 16149 return err; 16150 16151 err = check_btf_line(env, attr, uattr); 16152 if (err) 16153 return err; 16154 16155 err = check_core_relo(env, attr, uattr); 16156 if (err) 16157 return err; 16158 16159 return 0; 16160 } 16161 16162 /* check %cur's range satisfies %old's */ 16163 static bool range_within(struct bpf_reg_state *old, 16164 struct bpf_reg_state *cur) 16165 { 16166 return old->umin_value <= cur->umin_value && 16167 old->umax_value >= cur->umax_value && 16168 old->smin_value <= cur->smin_value && 16169 old->smax_value >= cur->smax_value && 16170 old->u32_min_value <= cur->u32_min_value && 16171 old->u32_max_value >= cur->u32_max_value && 16172 old->s32_min_value <= cur->s32_min_value && 16173 old->s32_max_value >= cur->s32_max_value; 16174 } 16175 16176 /* If in the old state two registers had the same id, then they need to have 16177 * the same id in the new state as well. But that id could be different from 16178 * the old state, so we need to track the mapping from old to new ids. 16179 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 16180 * regs with old id 5 must also have new id 9 for the new state to be safe. But 16181 * regs with a different old id could still have new id 9, we don't care about 16182 * that. 16183 * So we look through our idmap to see if this old id has been seen before. If 16184 * so, we require the new id to match; otherwise, we add the id pair to the map. 16185 */ 16186 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 16187 { 16188 struct bpf_id_pair *map = idmap->map; 16189 unsigned int i; 16190 16191 /* either both IDs should be set or both should be zero */ 16192 if (!!old_id != !!cur_id) 16193 return false; 16194 16195 if (old_id == 0) /* cur_id == 0 as well */ 16196 return true; 16197 16198 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 16199 if (!map[i].old) { 16200 /* Reached an empty slot; haven't seen this id before */ 16201 map[i].old = old_id; 16202 map[i].cur = cur_id; 16203 return true; 16204 } 16205 if (map[i].old == old_id) 16206 return map[i].cur == cur_id; 16207 if (map[i].cur == cur_id) 16208 return false; 16209 } 16210 /* We ran out of idmap slots, which should be impossible */ 16211 WARN_ON_ONCE(1); 16212 return false; 16213 } 16214 16215 /* Similar to check_ids(), but allocate a unique temporary ID 16216 * for 'old_id' or 'cur_id' of zero. 16217 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 16218 */ 16219 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 16220 { 16221 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 16222 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 16223 16224 return check_ids(old_id, cur_id, idmap); 16225 } 16226 16227 static void clean_func_state(struct bpf_verifier_env *env, 16228 struct bpf_func_state *st) 16229 { 16230 enum bpf_reg_liveness live; 16231 int i, j; 16232 16233 for (i = 0; i < BPF_REG_FP; i++) { 16234 live = st->regs[i].live; 16235 /* liveness must not touch this register anymore */ 16236 st->regs[i].live |= REG_LIVE_DONE; 16237 if (!(live & REG_LIVE_READ)) 16238 /* since the register is unused, clear its state 16239 * to make further comparison simpler 16240 */ 16241 __mark_reg_not_init(env, &st->regs[i]); 16242 } 16243 16244 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 16245 live = st->stack[i].spilled_ptr.live; 16246 /* liveness must not touch this stack slot anymore */ 16247 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 16248 if (!(live & REG_LIVE_READ)) { 16249 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 16250 for (j = 0; j < BPF_REG_SIZE; j++) 16251 st->stack[i].slot_type[j] = STACK_INVALID; 16252 } 16253 } 16254 } 16255 16256 static void clean_verifier_state(struct bpf_verifier_env *env, 16257 struct bpf_verifier_state *st) 16258 { 16259 int i; 16260 16261 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 16262 /* all regs in this state in all frames were already marked */ 16263 return; 16264 16265 for (i = 0; i <= st->curframe; i++) 16266 clean_func_state(env, st->frame[i]); 16267 } 16268 16269 /* the parentage chains form a tree. 16270 * the verifier states are added to state lists at given insn and 16271 * pushed into state stack for future exploration. 16272 * when the verifier reaches bpf_exit insn some of the verifer states 16273 * stored in the state lists have their final liveness state already, 16274 * but a lot of states will get revised from liveness point of view when 16275 * the verifier explores other branches. 16276 * Example: 16277 * 1: r0 = 1 16278 * 2: if r1 == 100 goto pc+1 16279 * 3: r0 = 2 16280 * 4: exit 16281 * when the verifier reaches exit insn the register r0 in the state list of 16282 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 16283 * of insn 2 and goes exploring further. At the insn 4 it will walk the 16284 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 16285 * 16286 * Since the verifier pushes the branch states as it sees them while exploring 16287 * the program the condition of walking the branch instruction for the second 16288 * time means that all states below this branch were already explored and 16289 * their final liveness marks are already propagated. 16290 * Hence when the verifier completes the search of state list in is_state_visited() 16291 * we can call this clean_live_states() function to mark all liveness states 16292 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 16293 * will not be used. 16294 * This function also clears the registers and stack for states that !READ 16295 * to simplify state merging. 16296 * 16297 * Important note here that walking the same branch instruction in the callee 16298 * doesn't meant that the states are DONE. The verifier has to compare 16299 * the callsites 16300 */ 16301 static void clean_live_states(struct bpf_verifier_env *env, int insn, 16302 struct bpf_verifier_state *cur) 16303 { 16304 struct bpf_verifier_state_list *sl; 16305 16306 sl = *explored_state(env, insn); 16307 while (sl) { 16308 if (sl->state.branches) 16309 goto next; 16310 if (sl->state.insn_idx != insn || 16311 !same_callsites(&sl->state, cur)) 16312 goto next; 16313 clean_verifier_state(env, &sl->state); 16314 next: 16315 sl = sl->next; 16316 } 16317 } 16318 16319 static bool regs_exact(const struct bpf_reg_state *rold, 16320 const struct bpf_reg_state *rcur, 16321 struct bpf_idmap *idmap) 16322 { 16323 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16324 check_ids(rold->id, rcur->id, idmap) && 16325 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16326 } 16327 16328 /* Returns true if (rold safe implies rcur safe) */ 16329 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 16330 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact) 16331 { 16332 if (exact) 16333 return regs_exact(rold, rcur, idmap); 16334 16335 if (!(rold->live & REG_LIVE_READ)) 16336 /* explored state didn't use this */ 16337 return true; 16338 if (rold->type == NOT_INIT) 16339 /* explored state can't have used this */ 16340 return true; 16341 if (rcur->type == NOT_INIT) 16342 return false; 16343 16344 /* Enforce that register types have to match exactly, including their 16345 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 16346 * rule. 16347 * 16348 * One can make a point that using a pointer register as unbounded 16349 * SCALAR would be technically acceptable, but this could lead to 16350 * pointer leaks because scalars are allowed to leak while pointers 16351 * are not. We could make this safe in special cases if root is 16352 * calling us, but it's probably not worth the hassle. 16353 * 16354 * Also, register types that are *not* MAYBE_NULL could technically be 16355 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 16356 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 16357 * to the same map). 16358 * However, if the old MAYBE_NULL register then got NULL checked, 16359 * doing so could have affected others with the same id, and we can't 16360 * check for that because we lost the id when we converted to 16361 * a non-MAYBE_NULL variant. 16362 * So, as a general rule we don't allow mixing MAYBE_NULL and 16363 * non-MAYBE_NULL registers as well. 16364 */ 16365 if (rold->type != rcur->type) 16366 return false; 16367 16368 switch (base_type(rold->type)) { 16369 case SCALAR_VALUE: 16370 if (env->explore_alu_limits) { 16371 /* explore_alu_limits disables tnum_in() and range_within() 16372 * logic and requires everything to be strict 16373 */ 16374 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16375 check_scalar_ids(rold->id, rcur->id, idmap); 16376 } 16377 if (!rold->precise) 16378 return true; 16379 /* Why check_ids() for scalar registers? 16380 * 16381 * Consider the following BPF code: 16382 * 1: r6 = ... unbound scalar, ID=a ... 16383 * 2: r7 = ... unbound scalar, ID=b ... 16384 * 3: if (r6 > r7) goto +1 16385 * 4: r6 = r7 16386 * 5: if (r6 > X) goto ... 16387 * 6: ... memory operation using r7 ... 16388 * 16389 * First verification path is [1-6]: 16390 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 16391 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark 16392 * r7 <= X, because r6 and r7 share same id. 16393 * Next verification path is [1-4, 6]. 16394 * 16395 * Instruction (6) would be reached in two states: 16396 * I. r6{.id=b}, r7{.id=b} via path 1-6; 16397 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 16398 * 16399 * Use check_ids() to distinguish these states. 16400 * --- 16401 * Also verify that new value satisfies old value range knowledge. 16402 */ 16403 return range_within(rold, rcur) && 16404 tnum_in(rold->var_off, rcur->var_off) && 16405 check_scalar_ids(rold->id, rcur->id, idmap); 16406 case PTR_TO_MAP_KEY: 16407 case PTR_TO_MAP_VALUE: 16408 case PTR_TO_MEM: 16409 case PTR_TO_BUF: 16410 case PTR_TO_TP_BUFFER: 16411 /* If the new min/max/var_off satisfy the old ones and 16412 * everything else matches, we are OK. 16413 */ 16414 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 16415 range_within(rold, rcur) && 16416 tnum_in(rold->var_off, rcur->var_off) && 16417 check_ids(rold->id, rcur->id, idmap) && 16418 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16419 case PTR_TO_PACKET_META: 16420 case PTR_TO_PACKET: 16421 /* We must have at least as much range as the old ptr 16422 * did, so that any accesses which were safe before are 16423 * still safe. This is true even if old range < old off, 16424 * since someone could have accessed through (ptr - k), or 16425 * even done ptr -= k in a register, to get a safe access. 16426 */ 16427 if (rold->range > rcur->range) 16428 return false; 16429 /* If the offsets don't match, we can't trust our alignment; 16430 * nor can we be sure that we won't fall out of range. 16431 */ 16432 if (rold->off != rcur->off) 16433 return false; 16434 /* id relations must be preserved */ 16435 if (!check_ids(rold->id, rcur->id, idmap)) 16436 return false; 16437 /* new val must satisfy old val knowledge */ 16438 return range_within(rold, rcur) && 16439 tnum_in(rold->var_off, rcur->var_off); 16440 case PTR_TO_STACK: 16441 /* two stack pointers are equal only if they're pointing to 16442 * the same stack frame, since fp-8 in foo != fp-8 in bar 16443 */ 16444 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 16445 default: 16446 return regs_exact(rold, rcur, idmap); 16447 } 16448 } 16449 16450 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 16451 struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact) 16452 { 16453 int i, spi; 16454 16455 /* walk slots of the explored stack and ignore any additional 16456 * slots in the current stack, since explored(safe) state 16457 * didn't use them 16458 */ 16459 for (i = 0; i < old->allocated_stack; i++) { 16460 struct bpf_reg_state *old_reg, *cur_reg; 16461 16462 spi = i / BPF_REG_SIZE; 16463 16464 if (exact && 16465 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16466 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16467 return false; 16468 16469 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) { 16470 i += BPF_REG_SIZE - 1; 16471 /* explored state didn't use this */ 16472 continue; 16473 } 16474 16475 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 16476 continue; 16477 16478 if (env->allow_uninit_stack && 16479 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 16480 continue; 16481 16482 /* explored stack has more populated slots than current stack 16483 * and these slots were used 16484 */ 16485 if (i >= cur->allocated_stack) 16486 return false; 16487 16488 /* if old state was safe with misc data in the stack 16489 * it will be safe with zero-initialized stack. 16490 * The opposite is not true 16491 */ 16492 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 16493 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 16494 continue; 16495 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16496 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16497 /* Ex: old explored (safe) state has STACK_SPILL in 16498 * this stack slot, but current has STACK_MISC -> 16499 * this verifier states are not equivalent, 16500 * return false to continue verification of this path 16501 */ 16502 return false; 16503 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 16504 continue; 16505 /* Both old and cur are having same slot_type */ 16506 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 16507 case STACK_SPILL: 16508 /* when explored and current stack slot are both storing 16509 * spilled registers, check that stored pointers types 16510 * are the same as well. 16511 * Ex: explored safe path could have stored 16512 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 16513 * but current path has stored: 16514 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 16515 * such verifier states are not equivalent. 16516 * return false to continue verification of this path 16517 */ 16518 if (!regsafe(env, &old->stack[spi].spilled_ptr, 16519 &cur->stack[spi].spilled_ptr, idmap, exact)) 16520 return false; 16521 break; 16522 case STACK_DYNPTR: 16523 old_reg = &old->stack[spi].spilled_ptr; 16524 cur_reg = &cur->stack[spi].spilled_ptr; 16525 if (old_reg->dynptr.type != cur_reg->dynptr.type || 16526 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 16527 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16528 return false; 16529 break; 16530 case STACK_ITER: 16531 old_reg = &old->stack[spi].spilled_ptr; 16532 cur_reg = &cur->stack[spi].spilled_ptr; 16533 /* iter.depth is not compared between states as it 16534 * doesn't matter for correctness and would otherwise 16535 * prevent convergence; we maintain it only to prevent 16536 * infinite loop check triggering, see 16537 * iter_active_depths_differ() 16538 */ 16539 if (old_reg->iter.btf != cur_reg->iter.btf || 16540 old_reg->iter.btf_id != cur_reg->iter.btf_id || 16541 old_reg->iter.state != cur_reg->iter.state || 16542 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 16543 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16544 return false; 16545 break; 16546 case STACK_MISC: 16547 case STACK_ZERO: 16548 case STACK_INVALID: 16549 continue; 16550 /* Ensure that new unhandled slot types return false by default */ 16551 default: 16552 return false; 16553 } 16554 } 16555 return true; 16556 } 16557 16558 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 16559 struct bpf_idmap *idmap) 16560 { 16561 int i; 16562 16563 if (old->acquired_refs != cur->acquired_refs) 16564 return false; 16565 16566 for (i = 0; i < old->acquired_refs; i++) { 16567 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 16568 return false; 16569 } 16570 16571 return true; 16572 } 16573 16574 /* compare two verifier states 16575 * 16576 * all states stored in state_list are known to be valid, since 16577 * verifier reached 'bpf_exit' instruction through them 16578 * 16579 * this function is called when verifier exploring different branches of 16580 * execution popped from the state stack. If it sees an old state that has 16581 * more strict register state and more strict stack state then this execution 16582 * branch doesn't need to be explored further, since verifier already 16583 * concluded that more strict state leads to valid finish. 16584 * 16585 * Therefore two states are equivalent if register state is more conservative 16586 * and explored stack state is more conservative than the current one. 16587 * Example: 16588 * explored current 16589 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 16590 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 16591 * 16592 * In other words if current stack state (one being explored) has more 16593 * valid slots than old one that already passed validation, it means 16594 * the verifier can stop exploring and conclude that current state is valid too 16595 * 16596 * Similarly with registers. If explored state has register type as invalid 16597 * whereas register type in current state is meaningful, it means that 16598 * the current state will reach 'bpf_exit' instruction safely 16599 */ 16600 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 16601 struct bpf_func_state *cur, bool exact) 16602 { 16603 int i; 16604 16605 for (i = 0; i < MAX_BPF_REG; i++) 16606 if (!regsafe(env, &old->regs[i], &cur->regs[i], 16607 &env->idmap_scratch, exact)) 16608 return false; 16609 16610 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 16611 return false; 16612 16613 if (!refsafe(old, cur, &env->idmap_scratch)) 16614 return false; 16615 16616 return true; 16617 } 16618 16619 static void reset_idmap_scratch(struct bpf_verifier_env *env) 16620 { 16621 env->idmap_scratch.tmp_id_gen = env->id_gen; 16622 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 16623 } 16624 16625 static bool states_equal(struct bpf_verifier_env *env, 16626 struct bpf_verifier_state *old, 16627 struct bpf_verifier_state *cur, 16628 bool exact) 16629 { 16630 int i; 16631 16632 if (old->curframe != cur->curframe) 16633 return false; 16634 16635 reset_idmap_scratch(env); 16636 16637 /* Verification state from speculative execution simulation 16638 * must never prune a non-speculative execution one. 16639 */ 16640 if (old->speculative && !cur->speculative) 16641 return false; 16642 16643 if (old->active_lock.ptr != cur->active_lock.ptr) 16644 return false; 16645 16646 /* Old and cur active_lock's have to be either both present 16647 * or both absent. 16648 */ 16649 if (!!old->active_lock.id != !!cur->active_lock.id) 16650 return false; 16651 16652 if (old->active_lock.id && 16653 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch)) 16654 return false; 16655 16656 if (old->active_rcu_lock != cur->active_rcu_lock) 16657 return false; 16658 16659 /* for states to be equal callsites have to be the same 16660 * and all frame states need to be equivalent 16661 */ 16662 for (i = 0; i <= old->curframe; i++) { 16663 if (old->frame[i]->callsite != cur->frame[i]->callsite) 16664 return false; 16665 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact)) 16666 return false; 16667 } 16668 return true; 16669 } 16670 16671 /* Return 0 if no propagation happened. Return negative error code if error 16672 * happened. Otherwise, return the propagated bit. 16673 */ 16674 static int propagate_liveness_reg(struct bpf_verifier_env *env, 16675 struct bpf_reg_state *reg, 16676 struct bpf_reg_state *parent_reg) 16677 { 16678 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 16679 u8 flag = reg->live & REG_LIVE_READ; 16680 int err; 16681 16682 /* When comes here, read flags of PARENT_REG or REG could be any of 16683 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 16684 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 16685 */ 16686 if (parent_flag == REG_LIVE_READ64 || 16687 /* Or if there is no read flag from REG. */ 16688 !flag || 16689 /* Or if the read flag from REG is the same as PARENT_REG. */ 16690 parent_flag == flag) 16691 return 0; 16692 16693 err = mark_reg_read(env, reg, parent_reg, flag); 16694 if (err) 16695 return err; 16696 16697 return flag; 16698 } 16699 16700 /* A write screens off any subsequent reads; but write marks come from the 16701 * straight-line code between a state and its parent. When we arrive at an 16702 * equivalent state (jump target or such) we didn't arrive by the straight-line 16703 * code, so read marks in the state must propagate to the parent regardless 16704 * of the state's write marks. That's what 'parent == state->parent' comparison 16705 * in mark_reg_read() is for. 16706 */ 16707 static int propagate_liveness(struct bpf_verifier_env *env, 16708 const struct bpf_verifier_state *vstate, 16709 struct bpf_verifier_state *vparent) 16710 { 16711 struct bpf_reg_state *state_reg, *parent_reg; 16712 struct bpf_func_state *state, *parent; 16713 int i, frame, err = 0; 16714 16715 if (vparent->curframe != vstate->curframe) { 16716 WARN(1, "propagate_live: parent frame %d current frame %d\n", 16717 vparent->curframe, vstate->curframe); 16718 return -EFAULT; 16719 } 16720 /* Propagate read liveness of registers... */ 16721 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 16722 for (frame = 0; frame <= vstate->curframe; frame++) { 16723 parent = vparent->frame[frame]; 16724 state = vstate->frame[frame]; 16725 parent_reg = parent->regs; 16726 state_reg = state->regs; 16727 /* We don't need to worry about FP liveness, it's read-only */ 16728 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 16729 err = propagate_liveness_reg(env, &state_reg[i], 16730 &parent_reg[i]); 16731 if (err < 0) 16732 return err; 16733 if (err == REG_LIVE_READ64) 16734 mark_insn_zext(env, &parent_reg[i]); 16735 } 16736 16737 /* Propagate stack slots. */ 16738 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 16739 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 16740 parent_reg = &parent->stack[i].spilled_ptr; 16741 state_reg = &state->stack[i].spilled_ptr; 16742 err = propagate_liveness_reg(env, state_reg, 16743 parent_reg); 16744 if (err < 0) 16745 return err; 16746 } 16747 } 16748 return 0; 16749 } 16750 16751 /* find precise scalars in the previous equivalent state and 16752 * propagate them into the current state 16753 */ 16754 static int propagate_precision(struct bpf_verifier_env *env, 16755 const struct bpf_verifier_state *old) 16756 { 16757 struct bpf_reg_state *state_reg; 16758 struct bpf_func_state *state; 16759 int i, err = 0, fr; 16760 bool first; 16761 16762 for (fr = old->curframe; fr >= 0; fr--) { 16763 state = old->frame[fr]; 16764 state_reg = state->regs; 16765 first = true; 16766 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 16767 if (state_reg->type != SCALAR_VALUE || 16768 !state_reg->precise || 16769 !(state_reg->live & REG_LIVE_READ)) 16770 continue; 16771 if (env->log.level & BPF_LOG_LEVEL2) { 16772 if (first) 16773 verbose(env, "frame %d: propagating r%d", fr, i); 16774 else 16775 verbose(env, ",r%d", i); 16776 } 16777 bt_set_frame_reg(&env->bt, fr, i); 16778 first = false; 16779 } 16780 16781 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16782 if (!is_spilled_reg(&state->stack[i])) 16783 continue; 16784 state_reg = &state->stack[i].spilled_ptr; 16785 if (state_reg->type != SCALAR_VALUE || 16786 !state_reg->precise || 16787 !(state_reg->live & REG_LIVE_READ)) 16788 continue; 16789 if (env->log.level & BPF_LOG_LEVEL2) { 16790 if (first) 16791 verbose(env, "frame %d: propagating fp%d", 16792 fr, (-i - 1) * BPF_REG_SIZE); 16793 else 16794 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 16795 } 16796 bt_set_frame_slot(&env->bt, fr, i); 16797 first = false; 16798 } 16799 if (!first) 16800 verbose(env, "\n"); 16801 } 16802 16803 err = mark_chain_precision_batch(env); 16804 if (err < 0) 16805 return err; 16806 16807 return 0; 16808 } 16809 16810 static bool states_maybe_looping(struct bpf_verifier_state *old, 16811 struct bpf_verifier_state *cur) 16812 { 16813 struct bpf_func_state *fold, *fcur; 16814 int i, fr = cur->curframe; 16815 16816 if (old->curframe != fr) 16817 return false; 16818 16819 fold = old->frame[fr]; 16820 fcur = cur->frame[fr]; 16821 for (i = 0; i < MAX_BPF_REG; i++) 16822 if (memcmp(&fold->regs[i], &fcur->regs[i], 16823 offsetof(struct bpf_reg_state, parent))) 16824 return false; 16825 return true; 16826 } 16827 16828 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 16829 { 16830 return env->insn_aux_data[insn_idx].is_iter_next; 16831 } 16832 16833 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 16834 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 16835 * states to match, which otherwise would look like an infinite loop. So while 16836 * iter_next() calls are taken care of, we still need to be careful and 16837 * prevent erroneous and too eager declaration of "ininite loop", when 16838 * iterators are involved. 16839 * 16840 * Here's a situation in pseudo-BPF assembly form: 16841 * 16842 * 0: again: ; set up iter_next() call args 16843 * 1: r1 = &it ; <CHECKPOINT HERE> 16844 * 2: call bpf_iter_num_next ; this is iter_next() call 16845 * 3: if r0 == 0 goto done 16846 * 4: ... something useful here ... 16847 * 5: goto again ; another iteration 16848 * 6: done: 16849 * 7: r1 = &it 16850 * 8: call bpf_iter_num_destroy ; clean up iter state 16851 * 9: exit 16852 * 16853 * This is a typical loop. Let's assume that we have a prune point at 1:, 16854 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 16855 * again`, assuming other heuristics don't get in a way). 16856 * 16857 * When we first time come to 1:, let's say we have some state X. We proceed 16858 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 16859 * Now we come back to validate that forked ACTIVE state. We proceed through 16860 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 16861 * are converging. But the problem is that we don't know that yet, as this 16862 * convergence has to happen at iter_next() call site only. So if nothing is 16863 * done, at 1: verifier will use bounded loop logic and declare infinite 16864 * looping (and would be *technically* correct, if not for iterator's 16865 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 16866 * don't want that. So what we do in process_iter_next_call() when we go on 16867 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 16868 * a different iteration. So when we suspect an infinite loop, we additionally 16869 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 16870 * pretend we are not looping and wait for next iter_next() call. 16871 * 16872 * This only applies to ACTIVE state. In DRAINED state we don't expect to 16873 * loop, because that would actually mean infinite loop, as DRAINED state is 16874 * "sticky", and so we'll keep returning into the same instruction with the 16875 * same state (at least in one of possible code paths). 16876 * 16877 * This approach allows to keep infinite loop heuristic even in the face of 16878 * active iterator. E.g., C snippet below is and will be detected as 16879 * inifintely looping: 16880 * 16881 * struct bpf_iter_num it; 16882 * int *p, x; 16883 * 16884 * bpf_iter_num_new(&it, 0, 10); 16885 * while ((p = bpf_iter_num_next(&t))) { 16886 * x = p; 16887 * while (x--) {} // <<-- infinite loop here 16888 * } 16889 * 16890 */ 16891 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 16892 { 16893 struct bpf_reg_state *slot, *cur_slot; 16894 struct bpf_func_state *state; 16895 int i, fr; 16896 16897 for (fr = old->curframe; fr >= 0; fr--) { 16898 state = old->frame[fr]; 16899 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16900 if (state->stack[i].slot_type[0] != STACK_ITER) 16901 continue; 16902 16903 slot = &state->stack[i].spilled_ptr; 16904 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 16905 continue; 16906 16907 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 16908 if (cur_slot->iter.depth != slot->iter.depth) 16909 return true; 16910 } 16911 } 16912 return false; 16913 } 16914 16915 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 16916 { 16917 struct bpf_verifier_state_list *new_sl; 16918 struct bpf_verifier_state_list *sl, **pprev; 16919 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry; 16920 int i, j, n, err, states_cnt = 0; 16921 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx); 16922 bool add_new_state = force_new_state; 16923 bool force_exact; 16924 16925 /* bpf progs typically have pruning point every 4 instructions 16926 * http://vger.kernel.org/bpfconf2019.html#session-1 16927 * Do not add new state for future pruning if the verifier hasn't seen 16928 * at least 2 jumps and at least 8 instructions. 16929 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 16930 * In tests that amounts to up to 50% reduction into total verifier 16931 * memory consumption and 20% verifier time speedup. 16932 */ 16933 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 16934 env->insn_processed - env->prev_insn_processed >= 8) 16935 add_new_state = true; 16936 16937 pprev = explored_state(env, insn_idx); 16938 sl = *pprev; 16939 16940 clean_live_states(env, insn_idx, cur); 16941 16942 while (sl) { 16943 states_cnt++; 16944 if (sl->state.insn_idx != insn_idx) 16945 goto next; 16946 16947 if (sl->state.branches) { 16948 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 16949 16950 if (frame->in_async_callback_fn && 16951 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 16952 /* Different async_entry_cnt means that the verifier is 16953 * processing another entry into async callback. 16954 * Seeing the same state is not an indication of infinite 16955 * loop or infinite recursion. 16956 * But finding the same state doesn't mean that it's safe 16957 * to stop processing the current state. The previous state 16958 * hasn't yet reached bpf_exit, since state.branches > 0. 16959 * Checking in_async_callback_fn alone is not enough either. 16960 * Since the verifier still needs to catch infinite loops 16961 * inside async callbacks. 16962 */ 16963 goto skip_inf_loop_check; 16964 } 16965 /* BPF open-coded iterators loop detection is special. 16966 * states_maybe_looping() logic is too simplistic in detecting 16967 * states that *might* be equivalent, because it doesn't know 16968 * about ID remapping, so don't even perform it. 16969 * See process_iter_next_call() and iter_active_depths_differ() 16970 * for overview of the logic. When current and one of parent 16971 * states are detected as equivalent, it's a good thing: we prove 16972 * convergence and can stop simulating further iterations. 16973 * It's safe to assume that iterator loop will finish, taking into 16974 * account iter_next() contract of eventually returning 16975 * sticky NULL result. 16976 * 16977 * Note, that states have to be compared exactly in this case because 16978 * read and precision marks might not be finalized inside the loop. 16979 * E.g. as in the program below: 16980 * 16981 * 1. r7 = -16 16982 * 2. r6 = bpf_get_prandom_u32() 16983 * 3. while (bpf_iter_num_next(&fp[-8])) { 16984 * 4. if (r6 != 42) { 16985 * 5. r7 = -32 16986 * 6. r6 = bpf_get_prandom_u32() 16987 * 7. continue 16988 * 8. } 16989 * 9. r0 = r10 16990 * 10. r0 += r7 16991 * 11. r8 = *(u64 *)(r0 + 0) 16992 * 12. r6 = bpf_get_prandom_u32() 16993 * 13. } 16994 * 16995 * Here verifier would first visit path 1-3, create a checkpoint at 3 16996 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 16997 * not have read or precision mark for r7 yet, thus inexact states 16998 * comparison would discard current state with r7=-32 16999 * => unsafe memory access at 11 would not be caught. 17000 */ 17001 if (is_iter_next_insn(env, insn_idx)) { 17002 if (states_equal(env, &sl->state, cur, true)) { 17003 struct bpf_func_state *cur_frame; 17004 struct bpf_reg_state *iter_state, *iter_reg; 17005 int spi; 17006 17007 cur_frame = cur->frame[cur->curframe]; 17008 /* btf_check_iter_kfuncs() enforces that 17009 * iter state pointer is always the first arg 17010 */ 17011 iter_reg = &cur_frame->regs[BPF_REG_1]; 17012 /* current state is valid due to states_equal(), 17013 * so we can assume valid iter and reg state, 17014 * no need for extra (re-)validations 17015 */ 17016 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 17017 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 17018 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 17019 update_loop_entry(cur, &sl->state); 17020 goto hit; 17021 } 17022 } 17023 goto skip_inf_loop_check; 17024 } 17025 if (calls_callback(env, insn_idx)) { 17026 if (states_equal(env, &sl->state, cur, true)) 17027 goto hit; 17028 goto skip_inf_loop_check; 17029 } 17030 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 17031 if (states_maybe_looping(&sl->state, cur) && 17032 states_equal(env, &sl->state, cur, false) && 17033 !iter_active_depths_differ(&sl->state, cur) && 17034 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 17035 verbose_linfo(env, insn_idx, "; "); 17036 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 17037 verbose(env, "cur state:"); 17038 print_verifier_state(env, cur->frame[cur->curframe], true); 17039 verbose(env, "old state:"); 17040 print_verifier_state(env, sl->state.frame[cur->curframe], true); 17041 return -EINVAL; 17042 } 17043 /* if the verifier is processing a loop, avoid adding new state 17044 * too often, since different loop iterations have distinct 17045 * states and may not help future pruning. 17046 * This threshold shouldn't be too low to make sure that 17047 * a loop with large bound will be rejected quickly. 17048 * The most abusive loop will be: 17049 * r1 += 1 17050 * if r1 < 1000000 goto pc-2 17051 * 1M insn_procssed limit / 100 == 10k peak states. 17052 * This threshold shouldn't be too high either, since states 17053 * at the end of the loop are likely to be useful in pruning. 17054 */ 17055 skip_inf_loop_check: 17056 if (!force_new_state && 17057 env->jmps_processed - env->prev_jmps_processed < 20 && 17058 env->insn_processed - env->prev_insn_processed < 100) 17059 add_new_state = false; 17060 goto miss; 17061 } 17062 /* If sl->state is a part of a loop and this loop's entry is a part of 17063 * current verification path then states have to be compared exactly. 17064 * 'force_exact' is needed to catch the following case: 17065 * 17066 * initial Here state 'succ' was processed first, 17067 * | it was eventually tracked to produce a 17068 * V state identical to 'hdr'. 17069 * .---------> hdr All branches from 'succ' had been explored 17070 * | | and thus 'succ' has its .branches == 0. 17071 * | V 17072 * | .------... Suppose states 'cur' and 'succ' correspond 17073 * | | | to the same instruction + callsites. 17074 * | V V In such case it is necessary to check 17075 * | ... ... if 'succ' and 'cur' are states_equal(). 17076 * | | | If 'succ' and 'cur' are a part of the 17077 * | V V same loop exact flag has to be set. 17078 * | succ <- cur To check if that is the case, verify 17079 * | | if loop entry of 'succ' is in current 17080 * | V DFS path. 17081 * | ... 17082 * | | 17083 * '----' 17084 * 17085 * Additional details are in the comment before get_loop_entry(). 17086 */ 17087 loop_entry = get_loop_entry(&sl->state); 17088 force_exact = loop_entry && loop_entry->branches > 0; 17089 if (states_equal(env, &sl->state, cur, force_exact)) { 17090 if (force_exact) 17091 update_loop_entry(cur, loop_entry); 17092 hit: 17093 sl->hit_cnt++; 17094 /* reached equivalent register/stack state, 17095 * prune the search. 17096 * Registers read by the continuation are read by us. 17097 * If we have any write marks in env->cur_state, they 17098 * will prevent corresponding reads in the continuation 17099 * from reaching our parent (an explored_state). Our 17100 * own state will get the read marks recorded, but 17101 * they'll be immediately forgotten as we're pruning 17102 * this state and will pop a new one. 17103 */ 17104 err = propagate_liveness(env, &sl->state, cur); 17105 17106 /* if previous state reached the exit with precision and 17107 * current state is equivalent to it (except precsion marks) 17108 * the precision needs to be propagated back in 17109 * the current state. 17110 */ 17111 if (is_jmp_point(env, env->insn_idx)) 17112 err = err ? : push_jmp_history(env, cur, 0); 17113 err = err ? : propagate_precision(env, &sl->state); 17114 if (err) 17115 return err; 17116 return 1; 17117 } 17118 miss: 17119 /* when new state is not going to be added do not increase miss count. 17120 * Otherwise several loop iterations will remove the state 17121 * recorded earlier. The goal of these heuristics is to have 17122 * states from some iterations of the loop (some in the beginning 17123 * and some at the end) to help pruning. 17124 */ 17125 if (add_new_state) 17126 sl->miss_cnt++; 17127 /* heuristic to determine whether this state is beneficial 17128 * to keep checking from state equivalence point of view. 17129 * Higher numbers increase max_states_per_insn and verification time, 17130 * but do not meaningfully decrease insn_processed. 17131 * 'n' controls how many times state could miss before eviction. 17132 * Use bigger 'n' for checkpoints because evicting checkpoint states 17133 * too early would hinder iterator convergence. 17134 */ 17135 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 17136 if (sl->miss_cnt > sl->hit_cnt * n + n) { 17137 /* the state is unlikely to be useful. Remove it to 17138 * speed up verification 17139 */ 17140 *pprev = sl->next; 17141 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE && 17142 !sl->state.used_as_loop_entry) { 17143 u32 br = sl->state.branches; 17144 17145 WARN_ONCE(br, 17146 "BUG live_done but branches_to_explore %d\n", 17147 br); 17148 free_verifier_state(&sl->state, false); 17149 kfree(sl); 17150 env->peak_states--; 17151 } else { 17152 /* cannot free this state, since parentage chain may 17153 * walk it later. Add it for free_list instead to 17154 * be freed at the end of verification 17155 */ 17156 sl->next = env->free_list; 17157 env->free_list = sl; 17158 } 17159 sl = *pprev; 17160 continue; 17161 } 17162 next: 17163 pprev = &sl->next; 17164 sl = *pprev; 17165 } 17166 17167 if (env->max_states_per_insn < states_cnt) 17168 env->max_states_per_insn = states_cnt; 17169 17170 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 17171 return 0; 17172 17173 if (!add_new_state) 17174 return 0; 17175 17176 /* There were no equivalent states, remember the current one. 17177 * Technically the current state is not proven to be safe yet, 17178 * but it will either reach outer most bpf_exit (which means it's safe) 17179 * or it will be rejected. When there are no loops the verifier won't be 17180 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 17181 * again on the way to bpf_exit. 17182 * When looping the sl->state.branches will be > 0 and this state 17183 * will not be considered for equivalence until branches == 0. 17184 */ 17185 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 17186 if (!new_sl) 17187 return -ENOMEM; 17188 env->total_states++; 17189 env->peak_states++; 17190 env->prev_jmps_processed = env->jmps_processed; 17191 env->prev_insn_processed = env->insn_processed; 17192 17193 /* forget precise markings we inherited, see __mark_chain_precision */ 17194 if (env->bpf_capable) 17195 mark_all_scalars_imprecise(env, cur); 17196 17197 /* add new state to the head of linked list */ 17198 new = &new_sl->state; 17199 err = copy_verifier_state(new, cur); 17200 if (err) { 17201 free_verifier_state(new, false); 17202 kfree(new_sl); 17203 return err; 17204 } 17205 new->insn_idx = insn_idx; 17206 WARN_ONCE(new->branches != 1, 17207 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 17208 17209 cur->parent = new; 17210 cur->first_insn_idx = insn_idx; 17211 cur->dfs_depth = new->dfs_depth + 1; 17212 clear_jmp_history(cur); 17213 new_sl->next = *explored_state(env, insn_idx); 17214 *explored_state(env, insn_idx) = new_sl; 17215 /* connect new state to parentage chain. Current frame needs all 17216 * registers connected. Only r6 - r9 of the callers are alive (pushed 17217 * to the stack implicitly by JITs) so in callers' frames connect just 17218 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 17219 * the state of the call instruction (with WRITTEN set), and r0 comes 17220 * from callee with its full parentage chain, anyway. 17221 */ 17222 /* clear write marks in current state: the writes we did are not writes 17223 * our child did, so they don't screen off its reads from us. 17224 * (There are no read marks in current state, because reads always mark 17225 * their parent and current state never has children yet. Only 17226 * explored_states can get read marks.) 17227 */ 17228 for (j = 0; j <= cur->curframe; j++) { 17229 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 17230 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 17231 for (i = 0; i < BPF_REG_FP; i++) 17232 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 17233 } 17234 17235 /* all stack frames are accessible from callee, clear them all */ 17236 for (j = 0; j <= cur->curframe; j++) { 17237 struct bpf_func_state *frame = cur->frame[j]; 17238 struct bpf_func_state *newframe = new->frame[j]; 17239 17240 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 17241 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 17242 frame->stack[i].spilled_ptr.parent = 17243 &newframe->stack[i].spilled_ptr; 17244 } 17245 } 17246 return 0; 17247 } 17248 17249 /* Return true if it's OK to have the same insn return a different type. */ 17250 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 17251 { 17252 switch (base_type(type)) { 17253 case PTR_TO_CTX: 17254 case PTR_TO_SOCKET: 17255 case PTR_TO_SOCK_COMMON: 17256 case PTR_TO_TCP_SOCK: 17257 case PTR_TO_XDP_SOCK: 17258 case PTR_TO_BTF_ID: 17259 return false; 17260 default: 17261 return true; 17262 } 17263 } 17264 17265 /* If an instruction was previously used with particular pointer types, then we 17266 * need to be careful to avoid cases such as the below, where it may be ok 17267 * for one branch accessing the pointer, but not ok for the other branch: 17268 * 17269 * R1 = sock_ptr 17270 * goto X; 17271 * ... 17272 * R1 = some_other_valid_ptr; 17273 * goto X; 17274 * ... 17275 * R2 = *(u32 *)(R1 + 0); 17276 */ 17277 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 17278 { 17279 return src != prev && (!reg_type_mismatch_ok(src) || 17280 !reg_type_mismatch_ok(prev)); 17281 } 17282 17283 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 17284 bool allow_trust_missmatch) 17285 { 17286 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 17287 17288 if (*prev_type == NOT_INIT) { 17289 /* Saw a valid insn 17290 * dst_reg = *(u32 *)(src_reg + off) 17291 * save type to validate intersecting paths 17292 */ 17293 *prev_type = type; 17294 } else if (reg_type_mismatch(type, *prev_type)) { 17295 /* Abuser program is trying to use the same insn 17296 * dst_reg = *(u32*) (src_reg + off) 17297 * with different pointer types: 17298 * src_reg == ctx in one branch and 17299 * src_reg == stack|map in some other branch. 17300 * Reject it. 17301 */ 17302 if (allow_trust_missmatch && 17303 base_type(type) == PTR_TO_BTF_ID && 17304 base_type(*prev_type) == PTR_TO_BTF_ID) { 17305 /* 17306 * Have to support a use case when one path through 17307 * the program yields TRUSTED pointer while another 17308 * is UNTRUSTED. Fallback to UNTRUSTED to generate 17309 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 17310 */ 17311 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 17312 } else { 17313 verbose(env, "same insn cannot be used with different pointers\n"); 17314 return -EINVAL; 17315 } 17316 } 17317 17318 return 0; 17319 } 17320 17321 static int do_check(struct bpf_verifier_env *env) 17322 { 17323 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17324 struct bpf_verifier_state *state = env->cur_state; 17325 struct bpf_insn *insns = env->prog->insnsi; 17326 struct bpf_reg_state *regs; 17327 int insn_cnt = env->prog->len; 17328 bool do_print_state = false; 17329 int prev_insn_idx = -1; 17330 17331 for (;;) { 17332 bool exception_exit = false; 17333 struct bpf_insn *insn; 17334 u8 class; 17335 int err; 17336 17337 /* reset current history entry on each new instruction */ 17338 env->cur_hist_ent = NULL; 17339 17340 env->prev_insn_idx = prev_insn_idx; 17341 if (env->insn_idx >= insn_cnt) { 17342 verbose(env, "invalid insn idx %d insn_cnt %d\n", 17343 env->insn_idx, insn_cnt); 17344 return -EFAULT; 17345 } 17346 17347 insn = &insns[env->insn_idx]; 17348 class = BPF_CLASS(insn->code); 17349 17350 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 17351 verbose(env, 17352 "BPF program is too large. Processed %d insn\n", 17353 env->insn_processed); 17354 return -E2BIG; 17355 } 17356 17357 state->last_insn_idx = env->prev_insn_idx; 17358 17359 if (is_prune_point(env, env->insn_idx)) { 17360 err = is_state_visited(env, env->insn_idx); 17361 if (err < 0) 17362 return err; 17363 if (err == 1) { 17364 /* found equivalent state, can prune the search */ 17365 if (env->log.level & BPF_LOG_LEVEL) { 17366 if (do_print_state) 17367 verbose(env, "\nfrom %d to %d%s: safe\n", 17368 env->prev_insn_idx, env->insn_idx, 17369 env->cur_state->speculative ? 17370 " (speculative execution)" : ""); 17371 else 17372 verbose(env, "%d: safe\n", env->insn_idx); 17373 } 17374 goto process_bpf_exit; 17375 } 17376 } 17377 17378 if (is_jmp_point(env, env->insn_idx)) { 17379 err = push_jmp_history(env, state, 0); 17380 if (err) 17381 return err; 17382 } 17383 17384 if (signal_pending(current)) 17385 return -EAGAIN; 17386 17387 if (need_resched()) 17388 cond_resched(); 17389 17390 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17391 verbose(env, "\nfrom %d to %d%s:", 17392 env->prev_insn_idx, env->insn_idx, 17393 env->cur_state->speculative ? 17394 " (speculative execution)" : ""); 17395 print_verifier_state(env, state->frame[state->curframe], true); 17396 do_print_state = false; 17397 } 17398 17399 if (env->log.level & BPF_LOG_LEVEL) { 17400 const struct bpf_insn_cbs cbs = { 17401 .cb_call = disasm_kfunc_name, 17402 .cb_print = verbose, 17403 .private_data = env, 17404 }; 17405 17406 if (verifier_state_scratched(env)) 17407 print_insn_state(env, state->frame[state->curframe]); 17408 17409 verbose_linfo(env, env->insn_idx, "; "); 17410 env->prev_log_pos = env->log.end_pos; 17411 verbose(env, "%d: ", env->insn_idx); 17412 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 17413 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17414 env->prev_log_pos = env->log.end_pos; 17415 } 17416 17417 if (bpf_prog_is_offloaded(env->prog->aux)) { 17418 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17419 env->prev_insn_idx); 17420 if (err) 17421 return err; 17422 } 17423 17424 regs = cur_regs(env); 17425 sanitize_mark_insn_seen(env); 17426 prev_insn_idx = env->insn_idx; 17427 17428 if (class == BPF_ALU || class == BPF_ALU64) { 17429 err = check_alu_op(env, insn); 17430 if (err) 17431 return err; 17432 17433 } else if (class == BPF_LDX) { 17434 enum bpf_reg_type src_reg_type; 17435 17436 /* check for reserved fields is already done */ 17437 17438 /* check src operand */ 17439 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17440 if (err) 17441 return err; 17442 17443 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 17444 if (err) 17445 return err; 17446 17447 src_reg_type = regs[insn->src_reg].type; 17448 17449 /* check that memory (src_reg + off) is readable, 17450 * the state of dst_reg will be updated by this func 17451 */ 17452 err = check_mem_access(env, env->insn_idx, insn->src_reg, 17453 insn->off, BPF_SIZE(insn->code), 17454 BPF_READ, insn->dst_reg, false, 17455 BPF_MODE(insn->code) == BPF_MEMSX); 17456 err = err ?: save_aux_ptr_type(env, src_reg_type, true); 17457 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], "ldx"); 17458 if (err) 17459 return err; 17460 } else if (class == BPF_STX) { 17461 enum bpf_reg_type dst_reg_type; 17462 17463 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 17464 err = check_atomic(env, env->insn_idx, insn); 17465 if (err) 17466 return err; 17467 env->insn_idx++; 17468 continue; 17469 } 17470 17471 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 17472 verbose(env, "BPF_STX uses reserved fields\n"); 17473 return -EINVAL; 17474 } 17475 17476 /* check src1 operand */ 17477 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17478 if (err) 17479 return err; 17480 /* check src2 operand */ 17481 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17482 if (err) 17483 return err; 17484 17485 dst_reg_type = regs[insn->dst_reg].type; 17486 17487 /* check that memory (dst_reg + off) is writeable */ 17488 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17489 insn->off, BPF_SIZE(insn->code), 17490 BPF_WRITE, insn->src_reg, false, false); 17491 if (err) 17492 return err; 17493 17494 err = save_aux_ptr_type(env, dst_reg_type, false); 17495 if (err) 17496 return err; 17497 } else if (class == BPF_ST) { 17498 enum bpf_reg_type dst_reg_type; 17499 17500 if (BPF_MODE(insn->code) != BPF_MEM || 17501 insn->src_reg != BPF_REG_0) { 17502 verbose(env, "BPF_ST uses reserved fields\n"); 17503 return -EINVAL; 17504 } 17505 /* check src operand */ 17506 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17507 if (err) 17508 return err; 17509 17510 dst_reg_type = regs[insn->dst_reg].type; 17511 17512 /* check that memory (dst_reg + off) is writeable */ 17513 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17514 insn->off, BPF_SIZE(insn->code), 17515 BPF_WRITE, -1, false, false); 17516 if (err) 17517 return err; 17518 17519 err = save_aux_ptr_type(env, dst_reg_type, false); 17520 if (err) 17521 return err; 17522 } else if (class == BPF_JMP || class == BPF_JMP32) { 17523 u8 opcode = BPF_OP(insn->code); 17524 17525 env->jmps_processed++; 17526 if (opcode == BPF_CALL) { 17527 if (BPF_SRC(insn->code) != BPF_K || 17528 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 17529 && insn->off != 0) || 17530 (insn->src_reg != BPF_REG_0 && 17531 insn->src_reg != BPF_PSEUDO_CALL && 17532 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 17533 insn->dst_reg != BPF_REG_0 || 17534 class == BPF_JMP32) { 17535 verbose(env, "BPF_CALL uses reserved fields\n"); 17536 return -EINVAL; 17537 } 17538 17539 if (env->cur_state->active_lock.ptr) { 17540 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 17541 (insn->src_reg == BPF_PSEUDO_CALL) || 17542 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17543 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 17544 verbose(env, "function calls are not allowed while holding a lock\n"); 17545 return -EINVAL; 17546 } 17547 } 17548 if (insn->src_reg == BPF_PSEUDO_CALL) { 17549 err = check_func_call(env, insn, &env->insn_idx); 17550 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 17551 err = check_kfunc_call(env, insn, &env->insn_idx); 17552 if (!err && is_bpf_throw_kfunc(insn)) { 17553 exception_exit = true; 17554 goto process_bpf_exit_full; 17555 } 17556 } else { 17557 err = check_helper_call(env, insn, &env->insn_idx); 17558 } 17559 if (err) 17560 return err; 17561 17562 mark_reg_scratched(env, BPF_REG_0); 17563 } else if (opcode == BPF_JA) { 17564 if (BPF_SRC(insn->code) != BPF_K || 17565 insn->src_reg != BPF_REG_0 || 17566 insn->dst_reg != BPF_REG_0 || 17567 (class == BPF_JMP && insn->imm != 0) || 17568 (class == BPF_JMP32 && insn->off != 0)) { 17569 verbose(env, "BPF_JA uses reserved fields\n"); 17570 return -EINVAL; 17571 } 17572 17573 if (class == BPF_JMP) 17574 env->insn_idx += insn->off + 1; 17575 else 17576 env->insn_idx += insn->imm + 1; 17577 continue; 17578 17579 } else if (opcode == BPF_EXIT) { 17580 if (BPF_SRC(insn->code) != BPF_K || 17581 insn->imm != 0 || 17582 insn->src_reg != BPF_REG_0 || 17583 insn->dst_reg != BPF_REG_0 || 17584 class == BPF_JMP32) { 17585 verbose(env, "BPF_EXIT uses reserved fields\n"); 17586 return -EINVAL; 17587 } 17588 process_bpf_exit_full: 17589 if (env->cur_state->active_lock.ptr && 17590 !in_rbtree_lock_required_cb(env)) { 17591 verbose(env, "bpf_spin_unlock is missing\n"); 17592 return -EINVAL; 17593 } 17594 17595 if (env->cur_state->active_rcu_lock && 17596 !in_rbtree_lock_required_cb(env)) { 17597 verbose(env, "bpf_rcu_read_unlock is missing\n"); 17598 return -EINVAL; 17599 } 17600 17601 /* We must do check_reference_leak here before 17602 * prepare_func_exit to handle the case when 17603 * state->curframe > 0, it may be a callback 17604 * function, for which reference_state must 17605 * match caller reference state when it exits. 17606 */ 17607 err = check_reference_leak(env, exception_exit); 17608 if (err) 17609 return err; 17610 17611 /* The side effect of the prepare_func_exit 17612 * which is being skipped is that it frees 17613 * bpf_func_state. Typically, process_bpf_exit 17614 * will only be hit with outermost exit. 17615 * copy_verifier_state in pop_stack will handle 17616 * freeing of any extra bpf_func_state left over 17617 * from not processing all nested function 17618 * exits. We also skip return code checks as 17619 * they are not needed for exceptional exits. 17620 */ 17621 if (exception_exit) 17622 goto process_bpf_exit; 17623 17624 if (state->curframe) { 17625 /* exit from nested function */ 17626 err = prepare_func_exit(env, &env->insn_idx); 17627 if (err) 17628 return err; 17629 do_print_state = true; 17630 continue; 17631 } 17632 17633 err = check_return_code(env, BPF_REG_0, "R0"); 17634 if (err) 17635 return err; 17636 process_bpf_exit: 17637 mark_verifier_state_scratched(env); 17638 update_branch_counts(env, env->cur_state); 17639 err = pop_stack(env, &prev_insn_idx, 17640 &env->insn_idx, pop_log); 17641 if (err < 0) { 17642 if (err != -ENOENT) 17643 return err; 17644 break; 17645 } else { 17646 do_print_state = true; 17647 continue; 17648 } 17649 } else { 17650 err = check_cond_jmp_op(env, insn, &env->insn_idx); 17651 if (err) 17652 return err; 17653 } 17654 } else if (class == BPF_LD) { 17655 u8 mode = BPF_MODE(insn->code); 17656 17657 if (mode == BPF_ABS || mode == BPF_IND) { 17658 err = check_ld_abs(env, insn); 17659 if (err) 17660 return err; 17661 17662 } else if (mode == BPF_IMM) { 17663 err = check_ld_imm(env, insn); 17664 if (err) 17665 return err; 17666 17667 env->insn_idx++; 17668 sanitize_mark_insn_seen(env); 17669 } else { 17670 verbose(env, "invalid BPF_LD mode\n"); 17671 return -EINVAL; 17672 } 17673 } else { 17674 verbose(env, "unknown insn class %d\n", class); 17675 return -EINVAL; 17676 } 17677 17678 env->insn_idx++; 17679 } 17680 17681 return 0; 17682 } 17683 17684 static int find_btf_percpu_datasec(struct btf *btf) 17685 { 17686 const struct btf_type *t; 17687 const char *tname; 17688 int i, n; 17689 17690 /* 17691 * Both vmlinux and module each have their own ".data..percpu" 17692 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17693 * types to look at only module's own BTF types. 17694 */ 17695 n = btf_nr_types(btf); 17696 if (btf_is_module(btf)) 17697 i = btf_nr_types(btf_vmlinux); 17698 else 17699 i = 1; 17700 17701 for(; i < n; i++) { 17702 t = btf_type_by_id(btf, i); 17703 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17704 continue; 17705 17706 tname = btf_name_by_offset(btf, t->name_off); 17707 if (!strcmp(tname, ".data..percpu")) 17708 return i; 17709 } 17710 17711 return -ENOENT; 17712 } 17713 17714 /* replace pseudo btf_id with kernel symbol address */ 17715 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 17716 struct bpf_insn *insn, 17717 struct bpf_insn_aux_data *aux) 17718 { 17719 const struct btf_var_secinfo *vsi; 17720 const struct btf_type *datasec; 17721 struct btf_mod_pair *btf_mod; 17722 const struct btf_type *t; 17723 const char *sym_name; 17724 bool percpu = false; 17725 u32 type, id = insn->imm; 17726 struct btf *btf; 17727 s32 datasec_id; 17728 u64 addr; 17729 int i, btf_fd, err; 17730 17731 btf_fd = insn[1].imm; 17732 if (btf_fd) { 17733 btf = btf_get_by_fd(btf_fd); 17734 if (IS_ERR(btf)) { 17735 verbose(env, "invalid module BTF object FD specified.\n"); 17736 return -EINVAL; 17737 } 17738 } else { 17739 if (!btf_vmlinux) { 17740 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 17741 return -EINVAL; 17742 } 17743 btf = btf_vmlinux; 17744 btf_get(btf); 17745 } 17746 17747 t = btf_type_by_id(btf, id); 17748 if (!t) { 17749 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17750 err = -ENOENT; 17751 goto err_put; 17752 } 17753 17754 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 17755 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 17756 err = -EINVAL; 17757 goto err_put; 17758 } 17759 17760 sym_name = btf_name_by_offset(btf, t->name_off); 17761 addr = kallsyms_lookup_name(sym_name); 17762 if (!addr) { 17763 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 17764 sym_name); 17765 err = -ENOENT; 17766 goto err_put; 17767 } 17768 insn[0].imm = (u32)addr; 17769 insn[1].imm = addr >> 32; 17770 17771 if (btf_type_is_func(t)) { 17772 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17773 aux->btf_var.mem_size = 0; 17774 goto check_btf; 17775 } 17776 17777 datasec_id = find_btf_percpu_datasec(btf); 17778 if (datasec_id > 0) { 17779 datasec = btf_type_by_id(btf, datasec_id); 17780 for_each_vsi(i, datasec, vsi) { 17781 if (vsi->type == id) { 17782 percpu = true; 17783 break; 17784 } 17785 } 17786 } 17787 17788 type = t->type; 17789 t = btf_type_skip_modifiers(btf, type, NULL); 17790 if (percpu) { 17791 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 17792 aux->btf_var.btf = btf; 17793 aux->btf_var.btf_id = type; 17794 } else if (!btf_type_is_struct(t)) { 17795 const struct btf_type *ret; 17796 const char *tname; 17797 u32 tsize; 17798 17799 /* resolve the type size of ksym. */ 17800 ret = btf_resolve_size(btf, t, &tsize); 17801 if (IS_ERR(ret)) { 17802 tname = btf_name_by_offset(btf, t->name_off); 17803 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 17804 tname, PTR_ERR(ret)); 17805 err = -EINVAL; 17806 goto err_put; 17807 } 17808 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17809 aux->btf_var.mem_size = tsize; 17810 } else { 17811 aux->btf_var.reg_type = PTR_TO_BTF_ID; 17812 aux->btf_var.btf = btf; 17813 aux->btf_var.btf_id = type; 17814 } 17815 check_btf: 17816 /* check whether we recorded this BTF (and maybe module) already */ 17817 for (i = 0; i < env->used_btf_cnt; i++) { 17818 if (env->used_btfs[i].btf == btf) { 17819 btf_put(btf); 17820 return 0; 17821 } 17822 } 17823 17824 if (env->used_btf_cnt >= MAX_USED_BTFS) { 17825 err = -E2BIG; 17826 goto err_put; 17827 } 17828 17829 btf_mod = &env->used_btfs[env->used_btf_cnt]; 17830 btf_mod->btf = btf; 17831 btf_mod->module = NULL; 17832 17833 /* if we reference variables from kernel module, bump its refcount */ 17834 if (btf_is_module(btf)) { 17835 btf_mod->module = btf_try_get_module(btf); 17836 if (!btf_mod->module) { 17837 err = -ENXIO; 17838 goto err_put; 17839 } 17840 } 17841 17842 env->used_btf_cnt++; 17843 17844 return 0; 17845 err_put: 17846 btf_put(btf); 17847 return err; 17848 } 17849 17850 static bool is_tracing_prog_type(enum bpf_prog_type type) 17851 { 17852 switch (type) { 17853 case BPF_PROG_TYPE_KPROBE: 17854 case BPF_PROG_TYPE_TRACEPOINT: 17855 case BPF_PROG_TYPE_PERF_EVENT: 17856 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17857 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 17858 return true; 17859 default: 17860 return false; 17861 } 17862 } 17863 17864 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 17865 struct bpf_map *map, 17866 struct bpf_prog *prog) 17867 17868 { 17869 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17870 17871 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 17872 btf_record_has_field(map->record, BPF_RB_ROOT)) { 17873 if (is_tracing_prog_type(prog_type)) { 17874 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 17875 return -EINVAL; 17876 } 17877 } 17878 17879 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 17880 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 17881 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 17882 return -EINVAL; 17883 } 17884 17885 if (is_tracing_prog_type(prog_type)) { 17886 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 17887 return -EINVAL; 17888 } 17889 } 17890 17891 if (btf_record_has_field(map->record, BPF_TIMER)) { 17892 if (is_tracing_prog_type(prog_type)) { 17893 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 17894 return -EINVAL; 17895 } 17896 } 17897 17898 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 17899 !bpf_offload_prog_map_match(prog, map)) { 17900 verbose(env, "offload device mismatch between prog and map\n"); 17901 return -EINVAL; 17902 } 17903 17904 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 17905 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 17906 return -EINVAL; 17907 } 17908 17909 if (prog->aux->sleepable) 17910 switch (map->map_type) { 17911 case BPF_MAP_TYPE_HASH: 17912 case BPF_MAP_TYPE_LRU_HASH: 17913 case BPF_MAP_TYPE_ARRAY: 17914 case BPF_MAP_TYPE_PERCPU_HASH: 17915 case BPF_MAP_TYPE_PERCPU_ARRAY: 17916 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 17917 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 17918 case BPF_MAP_TYPE_HASH_OF_MAPS: 17919 case BPF_MAP_TYPE_RINGBUF: 17920 case BPF_MAP_TYPE_USER_RINGBUF: 17921 case BPF_MAP_TYPE_INODE_STORAGE: 17922 case BPF_MAP_TYPE_SK_STORAGE: 17923 case BPF_MAP_TYPE_TASK_STORAGE: 17924 case BPF_MAP_TYPE_CGRP_STORAGE: 17925 break; 17926 default: 17927 verbose(env, 17928 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 17929 return -EINVAL; 17930 } 17931 17932 return 0; 17933 } 17934 17935 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 17936 { 17937 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 17938 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 17939 } 17940 17941 /* find and rewrite pseudo imm in ld_imm64 instructions: 17942 * 17943 * 1. if it accesses map FD, replace it with actual map pointer. 17944 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 17945 * 17946 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 17947 */ 17948 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 17949 { 17950 struct bpf_insn *insn = env->prog->insnsi; 17951 int insn_cnt = env->prog->len; 17952 int i, j, err; 17953 17954 err = bpf_prog_calc_tag(env->prog); 17955 if (err) 17956 return err; 17957 17958 for (i = 0; i < insn_cnt; i++, insn++) { 17959 if (BPF_CLASS(insn->code) == BPF_LDX && 17960 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 17961 insn->imm != 0)) { 17962 verbose(env, "BPF_LDX uses reserved fields\n"); 17963 return -EINVAL; 17964 } 17965 17966 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 17967 struct bpf_insn_aux_data *aux; 17968 struct bpf_map *map; 17969 struct fd f; 17970 u64 addr; 17971 u32 fd; 17972 17973 if (i == insn_cnt - 1 || insn[1].code != 0 || 17974 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 17975 insn[1].off != 0) { 17976 verbose(env, "invalid bpf_ld_imm64 insn\n"); 17977 return -EINVAL; 17978 } 17979 17980 if (insn[0].src_reg == 0) 17981 /* valid generic load 64-bit imm */ 17982 goto next_insn; 17983 17984 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 17985 aux = &env->insn_aux_data[i]; 17986 err = check_pseudo_btf_id(env, insn, aux); 17987 if (err) 17988 return err; 17989 goto next_insn; 17990 } 17991 17992 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 17993 aux = &env->insn_aux_data[i]; 17994 aux->ptr_type = PTR_TO_FUNC; 17995 goto next_insn; 17996 } 17997 17998 /* In final convert_pseudo_ld_imm64() step, this is 17999 * converted into regular 64-bit imm load insn. 18000 */ 18001 switch (insn[0].src_reg) { 18002 case BPF_PSEUDO_MAP_VALUE: 18003 case BPF_PSEUDO_MAP_IDX_VALUE: 18004 break; 18005 case BPF_PSEUDO_MAP_FD: 18006 case BPF_PSEUDO_MAP_IDX: 18007 if (insn[1].imm == 0) 18008 break; 18009 fallthrough; 18010 default: 18011 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 18012 return -EINVAL; 18013 } 18014 18015 switch (insn[0].src_reg) { 18016 case BPF_PSEUDO_MAP_IDX_VALUE: 18017 case BPF_PSEUDO_MAP_IDX: 18018 if (bpfptr_is_null(env->fd_array)) { 18019 verbose(env, "fd_idx without fd_array is invalid\n"); 18020 return -EPROTO; 18021 } 18022 if (copy_from_bpfptr_offset(&fd, env->fd_array, 18023 insn[0].imm * sizeof(fd), 18024 sizeof(fd))) 18025 return -EFAULT; 18026 break; 18027 default: 18028 fd = insn[0].imm; 18029 break; 18030 } 18031 18032 f = fdget(fd); 18033 map = __bpf_map_get(f); 18034 if (IS_ERR(map)) { 18035 verbose(env, "fd %d is not pointing to valid bpf_map\n", 18036 insn[0].imm); 18037 return PTR_ERR(map); 18038 } 18039 18040 err = check_map_prog_compatibility(env, map, env->prog); 18041 if (err) { 18042 fdput(f); 18043 return err; 18044 } 18045 18046 aux = &env->insn_aux_data[i]; 18047 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 18048 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 18049 addr = (unsigned long)map; 18050 } else { 18051 u32 off = insn[1].imm; 18052 18053 if (off >= BPF_MAX_VAR_OFF) { 18054 verbose(env, "direct value offset of %u is not allowed\n", off); 18055 fdput(f); 18056 return -EINVAL; 18057 } 18058 18059 if (!map->ops->map_direct_value_addr) { 18060 verbose(env, "no direct value access support for this map type\n"); 18061 fdput(f); 18062 return -EINVAL; 18063 } 18064 18065 err = map->ops->map_direct_value_addr(map, &addr, off); 18066 if (err) { 18067 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 18068 map->value_size, off); 18069 fdput(f); 18070 return err; 18071 } 18072 18073 aux->map_off = off; 18074 addr += off; 18075 } 18076 18077 insn[0].imm = (u32)addr; 18078 insn[1].imm = addr >> 32; 18079 18080 /* check whether we recorded this map already */ 18081 for (j = 0; j < env->used_map_cnt; j++) { 18082 if (env->used_maps[j] == map) { 18083 aux->map_index = j; 18084 fdput(f); 18085 goto next_insn; 18086 } 18087 } 18088 18089 if (env->used_map_cnt >= MAX_USED_MAPS) { 18090 fdput(f); 18091 return -E2BIG; 18092 } 18093 18094 if (env->prog->aux->sleepable) 18095 atomic64_inc(&map->sleepable_refcnt); 18096 /* hold the map. If the program is rejected by verifier, 18097 * the map will be released by release_maps() or it 18098 * will be used by the valid program until it's unloaded 18099 * and all maps are released in bpf_free_used_maps() 18100 */ 18101 bpf_map_inc(map); 18102 18103 aux->map_index = env->used_map_cnt; 18104 env->used_maps[env->used_map_cnt++] = map; 18105 18106 if (bpf_map_is_cgroup_storage(map) && 18107 bpf_cgroup_storage_assign(env->prog->aux, map)) { 18108 verbose(env, "only one cgroup storage of each type is allowed\n"); 18109 fdput(f); 18110 return -EBUSY; 18111 } 18112 18113 fdput(f); 18114 next_insn: 18115 insn++; 18116 i++; 18117 continue; 18118 } 18119 18120 /* Basic sanity check before we invest more work here. */ 18121 if (!bpf_opcode_in_insntable(insn->code)) { 18122 verbose(env, "unknown opcode %02x\n", insn->code); 18123 return -EINVAL; 18124 } 18125 } 18126 18127 /* now all pseudo BPF_LD_IMM64 instructions load valid 18128 * 'struct bpf_map *' into a register instead of user map_fd. 18129 * These pointers will be used later by verifier to validate map access. 18130 */ 18131 return 0; 18132 } 18133 18134 /* drop refcnt of maps used by the rejected program */ 18135 static void release_maps(struct bpf_verifier_env *env) 18136 { 18137 __bpf_free_used_maps(env->prog->aux, env->used_maps, 18138 env->used_map_cnt); 18139 } 18140 18141 /* drop refcnt of maps used by the rejected program */ 18142 static void release_btfs(struct bpf_verifier_env *env) 18143 { 18144 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 18145 env->used_btf_cnt); 18146 } 18147 18148 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 18149 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 18150 { 18151 struct bpf_insn *insn = env->prog->insnsi; 18152 int insn_cnt = env->prog->len; 18153 int i; 18154 18155 for (i = 0; i < insn_cnt; i++, insn++) { 18156 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 18157 continue; 18158 if (insn->src_reg == BPF_PSEUDO_FUNC) 18159 continue; 18160 insn->src_reg = 0; 18161 } 18162 } 18163 18164 /* single env->prog->insni[off] instruction was replaced with the range 18165 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 18166 * [0, off) and [off, end) to new locations, so the patched range stays zero 18167 */ 18168 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 18169 struct bpf_insn_aux_data *new_data, 18170 struct bpf_prog *new_prog, u32 off, u32 cnt) 18171 { 18172 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 18173 struct bpf_insn *insn = new_prog->insnsi; 18174 u32 old_seen = old_data[off].seen; 18175 u32 prog_len; 18176 int i; 18177 18178 /* aux info at OFF always needs adjustment, no matter fast path 18179 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 18180 * original insn at old prog. 18181 */ 18182 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 18183 18184 if (cnt == 1) 18185 return; 18186 prog_len = new_prog->len; 18187 18188 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 18189 memcpy(new_data + off + cnt - 1, old_data + off, 18190 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 18191 for (i = off; i < off + cnt - 1; i++) { 18192 /* Expand insni[off]'s seen count to the patched range. */ 18193 new_data[i].seen = old_seen; 18194 new_data[i].zext_dst = insn_has_def32(env, insn + i); 18195 } 18196 env->insn_aux_data = new_data; 18197 vfree(old_data); 18198 } 18199 18200 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 18201 { 18202 int i; 18203 18204 if (len == 1) 18205 return; 18206 /* NOTE: fake 'exit' subprog should be updated as well. */ 18207 for (i = 0; i <= env->subprog_cnt; i++) { 18208 if (env->subprog_info[i].start <= off) 18209 continue; 18210 env->subprog_info[i].start += len - 1; 18211 } 18212 } 18213 18214 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 18215 { 18216 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 18217 int i, sz = prog->aux->size_poke_tab; 18218 struct bpf_jit_poke_descriptor *desc; 18219 18220 for (i = 0; i < sz; i++) { 18221 desc = &tab[i]; 18222 if (desc->insn_idx <= off) 18223 continue; 18224 desc->insn_idx += len - 1; 18225 } 18226 } 18227 18228 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 18229 const struct bpf_insn *patch, u32 len) 18230 { 18231 struct bpf_prog *new_prog; 18232 struct bpf_insn_aux_data *new_data = NULL; 18233 18234 if (len > 1) { 18235 new_data = vzalloc(array_size(env->prog->len + len - 1, 18236 sizeof(struct bpf_insn_aux_data))); 18237 if (!new_data) 18238 return NULL; 18239 } 18240 18241 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 18242 if (IS_ERR(new_prog)) { 18243 if (PTR_ERR(new_prog) == -ERANGE) 18244 verbose(env, 18245 "insn %d cannot be patched due to 16-bit range\n", 18246 env->insn_aux_data[off].orig_idx); 18247 vfree(new_data); 18248 return NULL; 18249 } 18250 adjust_insn_aux_data(env, new_data, new_prog, off, len); 18251 adjust_subprog_starts(env, off, len); 18252 adjust_poke_descs(new_prog, off, len); 18253 return new_prog; 18254 } 18255 18256 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 18257 u32 off, u32 cnt) 18258 { 18259 int i, j; 18260 18261 /* find first prog starting at or after off (first to remove) */ 18262 for (i = 0; i < env->subprog_cnt; i++) 18263 if (env->subprog_info[i].start >= off) 18264 break; 18265 /* find first prog starting at or after off + cnt (first to stay) */ 18266 for (j = i; j < env->subprog_cnt; j++) 18267 if (env->subprog_info[j].start >= off + cnt) 18268 break; 18269 /* if j doesn't start exactly at off + cnt, we are just removing 18270 * the front of previous prog 18271 */ 18272 if (env->subprog_info[j].start != off + cnt) 18273 j--; 18274 18275 if (j > i) { 18276 struct bpf_prog_aux *aux = env->prog->aux; 18277 int move; 18278 18279 /* move fake 'exit' subprog as well */ 18280 move = env->subprog_cnt + 1 - j; 18281 18282 memmove(env->subprog_info + i, 18283 env->subprog_info + j, 18284 sizeof(*env->subprog_info) * move); 18285 env->subprog_cnt -= j - i; 18286 18287 /* remove func_info */ 18288 if (aux->func_info) { 18289 move = aux->func_info_cnt - j; 18290 18291 memmove(aux->func_info + i, 18292 aux->func_info + j, 18293 sizeof(*aux->func_info) * move); 18294 aux->func_info_cnt -= j - i; 18295 /* func_info->insn_off is set after all code rewrites, 18296 * in adjust_btf_func() - no need to adjust 18297 */ 18298 } 18299 } else { 18300 /* convert i from "first prog to remove" to "first to adjust" */ 18301 if (env->subprog_info[i].start == off) 18302 i++; 18303 } 18304 18305 /* update fake 'exit' subprog as well */ 18306 for (; i <= env->subprog_cnt; i++) 18307 env->subprog_info[i].start -= cnt; 18308 18309 return 0; 18310 } 18311 18312 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 18313 u32 cnt) 18314 { 18315 struct bpf_prog *prog = env->prog; 18316 u32 i, l_off, l_cnt, nr_linfo; 18317 struct bpf_line_info *linfo; 18318 18319 nr_linfo = prog->aux->nr_linfo; 18320 if (!nr_linfo) 18321 return 0; 18322 18323 linfo = prog->aux->linfo; 18324 18325 /* find first line info to remove, count lines to be removed */ 18326 for (i = 0; i < nr_linfo; i++) 18327 if (linfo[i].insn_off >= off) 18328 break; 18329 18330 l_off = i; 18331 l_cnt = 0; 18332 for (; i < nr_linfo; i++) 18333 if (linfo[i].insn_off < off + cnt) 18334 l_cnt++; 18335 else 18336 break; 18337 18338 /* First live insn doesn't match first live linfo, it needs to "inherit" 18339 * last removed linfo. prog is already modified, so prog->len == off 18340 * means no live instructions after (tail of the program was removed). 18341 */ 18342 if (prog->len != off && l_cnt && 18343 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 18344 l_cnt--; 18345 linfo[--i].insn_off = off + cnt; 18346 } 18347 18348 /* remove the line info which refer to the removed instructions */ 18349 if (l_cnt) { 18350 memmove(linfo + l_off, linfo + i, 18351 sizeof(*linfo) * (nr_linfo - i)); 18352 18353 prog->aux->nr_linfo -= l_cnt; 18354 nr_linfo = prog->aux->nr_linfo; 18355 } 18356 18357 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 18358 for (i = l_off; i < nr_linfo; i++) 18359 linfo[i].insn_off -= cnt; 18360 18361 /* fix up all subprogs (incl. 'exit') which start >= off */ 18362 for (i = 0; i <= env->subprog_cnt; i++) 18363 if (env->subprog_info[i].linfo_idx > l_off) { 18364 /* program may have started in the removed region but 18365 * may not be fully removed 18366 */ 18367 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 18368 env->subprog_info[i].linfo_idx -= l_cnt; 18369 else 18370 env->subprog_info[i].linfo_idx = l_off; 18371 } 18372 18373 return 0; 18374 } 18375 18376 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 18377 { 18378 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18379 unsigned int orig_prog_len = env->prog->len; 18380 int err; 18381 18382 if (bpf_prog_is_offloaded(env->prog->aux)) 18383 bpf_prog_offload_remove_insns(env, off, cnt); 18384 18385 err = bpf_remove_insns(env->prog, off, cnt); 18386 if (err) 18387 return err; 18388 18389 err = adjust_subprog_starts_after_remove(env, off, cnt); 18390 if (err) 18391 return err; 18392 18393 err = bpf_adj_linfo_after_remove(env, off, cnt); 18394 if (err) 18395 return err; 18396 18397 memmove(aux_data + off, aux_data + off + cnt, 18398 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 18399 18400 return 0; 18401 } 18402 18403 /* The verifier does more data flow analysis than llvm and will not 18404 * explore branches that are dead at run time. Malicious programs can 18405 * have dead code too. Therefore replace all dead at-run-time code 18406 * with 'ja -1'. 18407 * 18408 * Just nops are not optimal, e.g. if they would sit at the end of the 18409 * program and through another bug we would manage to jump there, then 18410 * we'd execute beyond program memory otherwise. Returning exception 18411 * code also wouldn't work since we can have subprogs where the dead 18412 * code could be located. 18413 */ 18414 static void sanitize_dead_code(struct bpf_verifier_env *env) 18415 { 18416 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18417 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18418 struct bpf_insn *insn = env->prog->insnsi; 18419 const int insn_cnt = env->prog->len; 18420 int i; 18421 18422 for (i = 0; i < insn_cnt; i++) { 18423 if (aux_data[i].seen) 18424 continue; 18425 memcpy(insn + i, &trap, sizeof(trap)); 18426 aux_data[i].zext_dst = false; 18427 } 18428 } 18429 18430 static bool insn_is_cond_jump(u8 code) 18431 { 18432 u8 op; 18433 18434 op = BPF_OP(code); 18435 if (BPF_CLASS(code) == BPF_JMP32) 18436 return op != BPF_JA; 18437 18438 if (BPF_CLASS(code) != BPF_JMP) 18439 return false; 18440 18441 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 18442 } 18443 18444 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 18445 { 18446 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18447 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18448 struct bpf_insn *insn = env->prog->insnsi; 18449 const int insn_cnt = env->prog->len; 18450 int i; 18451 18452 for (i = 0; i < insn_cnt; i++, insn++) { 18453 if (!insn_is_cond_jump(insn->code)) 18454 continue; 18455 18456 if (!aux_data[i + 1].seen) 18457 ja.off = insn->off; 18458 else if (!aux_data[i + 1 + insn->off].seen) 18459 ja.off = 0; 18460 else 18461 continue; 18462 18463 if (bpf_prog_is_offloaded(env->prog->aux)) 18464 bpf_prog_offload_replace_insn(env, i, &ja); 18465 18466 memcpy(insn, &ja, sizeof(ja)); 18467 } 18468 } 18469 18470 static int opt_remove_dead_code(struct bpf_verifier_env *env) 18471 { 18472 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18473 int insn_cnt = env->prog->len; 18474 int i, err; 18475 18476 for (i = 0; i < insn_cnt; i++) { 18477 int j; 18478 18479 j = 0; 18480 while (i + j < insn_cnt && !aux_data[i + j].seen) 18481 j++; 18482 if (!j) 18483 continue; 18484 18485 err = verifier_remove_insns(env, i, j); 18486 if (err) 18487 return err; 18488 insn_cnt = env->prog->len; 18489 } 18490 18491 return 0; 18492 } 18493 18494 static int opt_remove_nops(struct bpf_verifier_env *env) 18495 { 18496 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18497 struct bpf_insn *insn = env->prog->insnsi; 18498 int insn_cnt = env->prog->len; 18499 int i, err; 18500 18501 for (i = 0; i < insn_cnt; i++) { 18502 if (memcmp(&insn[i], &ja, sizeof(ja))) 18503 continue; 18504 18505 err = verifier_remove_insns(env, i, 1); 18506 if (err) 18507 return err; 18508 insn_cnt--; 18509 i--; 18510 } 18511 18512 return 0; 18513 } 18514 18515 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 18516 const union bpf_attr *attr) 18517 { 18518 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 18519 struct bpf_insn_aux_data *aux = env->insn_aux_data; 18520 int i, patch_len, delta = 0, len = env->prog->len; 18521 struct bpf_insn *insns = env->prog->insnsi; 18522 struct bpf_prog *new_prog; 18523 bool rnd_hi32; 18524 18525 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 18526 zext_patch[1] = BPF_ZEXT_REG(0); 18527 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 18528 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 18529 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 18530 for (i = 0; i < len; i++) { 18531 int adj_idx = i + delta; 18532 struct bpf_insn insn; 18533 int load_reg; 18534 18535 insn = insns[adj_idx]; 18536 load_reg = insn_def_regno(&insn); 18537 if (!aux[adj_idx].zext_dst) { 18538 u8 code, class; 18539 u32 imm_rnd; 18540 18541 if (!rnd_hi32) 18542 continue; 18543 18544 code = insn.code; 18545 class = BPF_CLASS(code); 18546 if (load_reg == -1) 18547 continue; 18548 18549 /* NOTE: arg "reg" (the fourth one) is only used for 18550 * BPF_STX + SRC_OP, so it is safe to pass NULL 18551 * here. 18552 */ 18553 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 18554 if (class == BPF_LD && 18555 BPF_MODE(code) == BPF_IMM) 18556 i++; 18557 continue; 18558 } 18559 18560 /* ctx load could be transformed into wider load. */ 18561 if (class == BPF_LDX && 18562 aux[adj_idx].ptr_type == PTR_TO_CTX) 18563 continue; 18564 18565 imm_rnd = get_random_u32(); 18566 rnd_hi32_patch[0] = insn; 18567 rnd_hi32_patch[1].imm = imm_rnd; 18568 rnd_hi32_patch[3].dst_reg = load_reg; 18569 patch = rnd_hi32_patch; 18570 patch_len = 4; 18571 goto apply_patch_buffer; 18572 } 18573 18574 /* Add in an zero-extend instruction if a) the JIT has requested 18575 * it or b) it's a CMPXCHG. 18576 * 18577 * The latter is because: BPF_CMPXCHG always loads a value into 18578 * R0, therefore always zero-extends. However some archs' 18579 * equivalent instruction only does this load when the 18580 * comparison is successful. This detail of CMPXCHG is 18581 * orthogonal to the general zero-extension behaviour of the 18582 * CPU, so it's treated independently of bpf_jit_needs_zext. 18583 */ 18584 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 18585 continue; 18586 18587 /* Zero-extension is done by the caller. */ 18588 if (bpf_pseudo_kfunc_call(&insn)) 18589 continue; 18590 18591 if (WARN_ON(load_reg == -1)) { 18592 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 18593 return -EFAULT; 18594 } 18595 18596 zext_patch[0] = insn; 18597 zext_patch[1].dst_reg = load_reg; 18598 zext_patch[1].src_reg = load_reg; 18599 patch = zext_patch; 18600 patch_len = 2; 18601 apply_patch_buffer: 18602 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 18603 if (!new_prog) 18604 return -ENOMEM; 18605 env->prog = new_prog; 18606 insns = new_prog->insnsi; 18607 aux = env->insn_aux_data; 18608 delta += patch_len - 1; 18609 } 18610 18611 return 0; 18612 } 18613 18614 /* convert load instructions that access fields of a context type into a 18615 * sequence of instructions that access fields of the underlying structure: 18616 * struct __sk_buff -> struct sk_buff 18617 * struct bpf_sock_ops -> struct sock 18618 */ 18619 static int convert_ctx_accesses(struct bpf_verifier_env *env) 18620 { 18621 const struct bpf_verifier_ops *ops = env->ops; 18622 int i, cnt, size, ctx_field_size, delta = 0; 18623 const int insn_cnt = env->prog->len; 18624 struct bpf_insn insn_buf[16], *insn; 18625 u32 target_size, size_default, off; 18626 struct bpf_prog *new_prog; 18627 enum bpf_access_type type; 18628 bool is_narrower_load; 18629 18630 if (ops->gen_prologue || env->seen_direct_write) { 18631 if (!ops->gen_prologue) { 18632 verbose(env, "bpf verifier is misconfigured\n"); 18633 return -EINVAL; 18634 } 18635 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 18636 env->prog); 18637 if (cnt >= ARRAY_SIZE(insn_buf)) { 18638 verbose(env, "bpf verifier is misconfigured\n"); 18639 return -EINVAL; 18640 } else if (cnt) { 18641 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 18642 if (!new_prog) 18643 return -ENOMEM; 18644 18645 env->prog = new_prog; 18646 delta += cnt - 1; 18647 } 18648 } 18649 18650 if (bpf_prog_is_offloaded(env->prog->aux)) 18651 return 0; 18652 18653 insn = env->prog->insnsi + delta; 18654 18655 for (i = 0; i < insn_cnt; i++, insn++) { 18656 bpf_convert_ctx_access_t convert_ctx_access; 18657 u8 mode; 18658 18659 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 18660 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 18661 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 18662 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 18663 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 18664 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 18665 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 18666 type = BPF_READ; 18667 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 18668 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 18669 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 18670 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 18671 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 18672 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 18673 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 18674 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 18675 type = BPF_WRITE; 18676 } else { 18677 continue; 18678 } 18679 18680 if (type == BPF_WRITE && 18681 env->insn_aux_data[i + delta].sanitize_stack_spill) { 18682 struct bpf_insn patch[] = { 18683 *insn, 18684 BPF_ST_NOSPEC(), 18685 }; 18686 18687 cnt = ARRAY_SIZE(patch); 18688 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 18689 if (!new_prog) 18690 return -ENOMEM; 18691 18692 delta += cnt - 1; 18693 env->prog = new_prog; 18694 insn = new_prog->insnsi + i + delta; 18695 continue; 18696 } 18697 18698 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 18699 case PTR_TO_CTX: 18700 if (!ops->convert_ctx_access) 18701 continue; 18702 convert_ctx_access = ops->convert_ctx_access; 18703 break; 18704 case PTR_TO_SOCKET: 18705 case PTR_TO_SOCK_COMMON: 18706 convert_ctx_access = bpf_sock_convert_ctx_access; 18707 break; 18708 case PTR_TO_TCP_SOCK: 18709 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 18710 break; 18711 case PTR_TO_XDP_SOCK: 18712 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 18713 break; 18714 case PTR_TO_BTF_ID: 18715 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 18716 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 18717 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 18718 * be said once it is marked PTR_UNTRUSTED, hence we must handle 18719 * any faults for loads into such types. BPF_WRITE is disallowed 18720 * for this case. 18721 */ 18722 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 18723 if (type == BPF_READ) { 18724 if (BPF_MODE(insn->code) == BPF_MEM) 18725 insn->code = BPF_LDX | BPF_PROBE_MEM | 18726 BPF_SIZE((insn)->code); 18727 else 18728 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 18729 BPF_SIZE((insn)->code); 18730 env->prog->aux->num_exentries++; 18731 } 18732 continue; 18733 default: 18734 continue; 18735 } 18736 18737 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 18738 size = BPF_LDST_BYTES(insn); 18739 mode = BPF_MODE(insn->code); 18740 18741 /* If the read access is a narrower load of the field, 18742 * convert to a 4/8-byte load, to minimum program type specific 18743 * convert_ctx_access changes. If conversion is successful, 18744 * we will apply proper mask to the result. 18745 */ 18746 is_narrower_load = size < ctx_field_size; 18747 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 18748 off = insn->off; 18749 if (is_narrower_load) { 18750 u8 size_code; 18751 18752 if (type == BPF_WRITE) { 18753 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 18754 return -EINVAL; 18755 } 18756 18757 size_code = BPF_H; 18758 if (ctx_field_size == 4) 18759 size_code = BPF_W; 18760 else if (ctx_field_size == 8) 18761 size_code = BPF_DW; 18762 18763 insn->off = off & ~(size_default - 1); 18764 insn->code = BPF_LDX | BPF_MEM | size_code; 18765 } 18766 18767 target_size = 0; 18768 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 18769 &target_size); 18770 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 18771 (ctx_field_size && !target_size)) { 18772 verbose(env, "bpf verifier is misconfigured\n"); 18773 return -EINVAL; 18774 } 18775 18776 if (is_narrower_load && size < target_size) { 18777 u8 shift = bpf_ctx_narrow_access_offset( 18778 off, size, size_default) * 8; 18779 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 18780 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 18781 return -EINVAL; 18782 } 18783 if (ctx_field_size <= 4) { 18784 if (shift) 18785 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 18786 insn->dst_reg, 18787 shift); 18788 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18789 (1 << size * 8) - 1); 18790 } else { 18791 if (shift) 18792 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 18793 insn->dst_reg, 18794 shift); 18795 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18796 (1ULL << size * 8) - 1); 18797 } 18798 } 18799 if (mode == BPF_MEMSX) 18800 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 18801 insn->dst_reg, insn->dst_reg, 18802 size * 8, 0); 18803 18804 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18805 if (!new_prog) 18806 return -ENOMEM; 18807 18808 delta += cnt - 1; 18809 18810 /* keep walking new program and skip insns we just inserted */ 18811 env->prog = new_prog; 18812 insn = new_prog->insnsi + i + delta; 18813 } 18814 18815 return 0; 18816 } 18817 18818 static int jit_subprogs(struct bpf_verifier_env *env) 18819 { 18820 struct bpf_prog *prog = env->prog, **func, *tmp; 18821 int i, j, subprog_start, subprog_end = 0, len, subprog; 18822 struct bpf_map *map_ptr; 18823 struct bpf_insn *insn; 18824 void *old_bpf_func; 18825 int err, num_exentries; 18826 18827 if (env->subprog_cnt <= 1) 18828 return 0; 18829 18830 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18831 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 18832 continue; 18833 18834 /* Upon error here we cannot fall back to interpreter but 18835 * need a hard reject of the program. Thus -EFAULT is 18836 * propagated in any case. 18837 */ 18838 subprog = find_subprog(env, i + insn->imm + 1); 18839 if (subprog < 0) { 18840 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 18841 i + insn->imm + 1); 18842 return -EFAULT; 18843 } 18844 /* temporarily remember subprog id inside insn instead of 18845 * aux_data, since next loop will split up all insns into funcs 18846 */ 18847 insn->off = subprog; 18848 /* remember original imm in case JIT fails and fallback 18849 * to interpreter will be needed 18850 */ 18851 env->insn_aux_data[i].call_imm = insn->imm; 18852 /* point imm to __bpf_call_base+1 from JITs point of view */ 18853 insn->imm = 1; 18854 if (bpf_pseudo_func(insn)) 18855 /* jit (e.g. x86_64) may emit fewer instructions 18856 * if it learns a u32 imm is the same as a u64 imm. 18857 * Force a non zero here. 18858 */ 18859 insn[1].imm = 1; 18860 } 18861 18862 err = bpf_prog_alloc_jited_linfo(prog); 18863 if (err) 18864 goto out_undo_insn; 18865 18866 err = -ENOMEM; 18867 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 18868 if (!func) 18869 goto out_undo_insn; 18870 18871 for (i = 0; i < env->subprog_cnt; i++) { 18872 subprog_start = subprog_end; 18873 subprog_end = env->subprog_info[i + 1].start; 18874 18875 len = subprog_end - subprog_start; 18876 /* bpf_prog_run() doesn't call subprogs directly, 18877 * hence main prog stats include the runtime of subprogs. 18878 * subprogs don't have IDs and not reachable via prog_get_next_id 18879 * func[i]->stats will never be accessed and stays NULL 18880 */ 18881 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 18882 if (!func[i]) 18883 goto out_free; 18884 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 18885 len * sizeof(struct bpf_insn)); 18886 func[i]->type = prog->type; 18887 func[i]->len = len; 18888 if (bpf_prog_calc_tag(func[i])) 18889 goto out_free; 18890 func[i]->is_func = 1; 18891 func[i]->aux->func_idx = i; 18892 /* Below members will be freed only at prog->aux */ 18893 func[i]->aux->btf = prog->aux->btf; 18894 func[i]->aux->func_info = prog->aux->func_info; 18895 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 18896 func[i]->aux->poke_tab = prog->aux->poke_tab; 18897 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 18898 18899 for (j = 0; j < prog->aux->size_poke_tab; j++) { 18900 struct bpf_jit_poke_descriptor *poke; 18901 18902 poke = &prog->aux->poke_tab[j]; 18903 if (poke->insn_idx < subprog_end && 18904 poke->insn_idx >= subprog_start) 18905 poke->aux = func[i]->aux; 18906 } 18907 18908 func[i]->aux->name[0] = 'F'; 18909 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 18910 func[i]->jit_requested = 1; 18911 func[i]->blinding_requested = prog->blinding_requested; 18912 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 18913 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 18914 func[i]->aux->linfo = prog->aux->linfo; 18915 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 18916 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 18917 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 18918 num_exentries = 0; 18919 insn = func[i]->insnsi; 18920 for (j = 0; j < func[i]->len; j++, insn++) { 18921 if (BPF_CLASS(insn->code) == BPF_LDX && 18922 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 18923 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 18924 num_exentries++; 18925 } 18926 func[i]->aux->num_exentries = num_exentries; 18927 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 18928 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb; 18929 if (!i) 18930 func[i]->aux->exception_boundary = env->seen_exception; 18931 func[i] = bpf_int_jit_compile(func[i]); 18932 if (!func[i]->jited) { 18933 err = -ENOTSUPP; 18934 goto out_free; 18935 } 18936 cond_resched(); 18937 } 18938 18939 /* at this point all bpf functions were successfully JITed 18940 * now populate all bpf_calls with correct addresses and 18941 * run last pass of JIT 18942 */ 18943 for (i = 0; i < env->subprog_cnt; i++) { 18944 insn = func[i]->insnsi; 18945 for (j = 0; j < func[i]->len; j++, insn++) { 18946 if (bpf_pseudo_func(insn)) { 18947 subprog = insn->off; 18948 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 18949 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 18950 continue; 18951 } 18952 if (!bpf_pseudo_call(insn)) 18953 continue; 18954 subprog = insn->off; 18955 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 18956 } 18957 18958 /* we use the aux data to keep a list of the start addresses 18959 * of the JITed images for each function in the program 18960 * 18961 * for some architectures, such as powerpc64, the imm field 18962 * might not be large enough to hold the offset of the start 18963 * address of the callee's JITed image from __bpf_call_base 18964 * 18965 * in such cases, we can lookup the start address of a callee 18966 * by using its subprog id, available from the off field of 18967 * the call instruction, as an index for this list 18968 */ 18969 func[i]->aux->func = func; 18970 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 18971 func[i]->aux->real_func_cnt = env->subprog_cnt; 18972 } 18973 for (i = 0; i < env->subprog_cnt; i++) { 18974 old_bpf_func = func[i]->bpf_func; 18975 tmp = bpf_int_jit_compile(func[i]); 18976 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 18977 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 18978 err = -ENOTSUPP; 18979 goto out_free; 18980 } 18981 cond_resched(); 18982 } 18983 18984 /* finally lock prog and jit images for all functions and 18985 * populate kallsysm. Begin at the first subprogram, since 18986 * bpf_prog_load will add the kallsyms for the main program. 18987 */ 18988 for (i = 1; i < env->subprog_cnt; i++) { 18989 bpf_prog_lock_ro(func[i]); 18990 bpf_prog_kallsyms_add(func[i]); 18991 } 18992 18993 /* Last step: make now unused interpreter insns from main 18994 * prog consistent for later dump requests, so they can 18995 * later look the same as if they were interpreted only. 18996 */ 18997 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18998 if (bpf_pseudo_func(insn)) { 18999 insn[0].imm = env->insn_aux_data[i].call_imm; 19000 insn[1].imm = insn->off; 19001 insn->off = 0; 19002 continue; 19003 } 19004 if (!bpf_pseudo_call(insn)) 19005 continue; 19006 insn->off = env->insn_aux_data[i].call_imm; 19007 subprog = find_subprog(env, i + insn->off + 1); 19008 insn->imm = subprog; 19009 } 19010 19011 prog->jited = 1; 19012 prog->bpf_func = func[0]->bpf_func; 19013 prog->jited_len = func[0]->jited_len; 19014 prog->aux->extable = func[0]->aux->extable; 19015 prog->aux->num_exentries = func[0]->aux->num_exentries; 19016 prog->aux->func = func; 19017 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 19018 prog->aux->real_func_cnt = env->subprog_cnt; 19019 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func; 19020 prog->aux->exception_boundary = func[0]->aux->exception_boundary; 19021 bpf_prog_jit_attempt_done(prog); 19022 return 0; 19023 out_free: 19024 /* We failed JIT'ing, so at this point we need to unregister poke 19025 * descriptors from subprogs, so that kernel is not attempting to 19026 * patch it anymore as we're freeing the subprog JIT memory. 19027 */ 19028 for (i = 0; i < prog->aux->size_poke_tab; i++) { 19029 map_ptr = prog->aux->poke_tab[i].tail_call.map; 19030 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 19031 } 19032 /* At this point we're guaranteed that poke descriptors are not 19033 * live anymore. We can just unlink its descriptor table as it's 19034 * released with the main prog. 19035 */ 19036 for (i = 0; i < env->subprog_cnt; i++) { 19037 if (!func[i]) 19038 continue; 19039 func[i]->aux->poke_tab = NULL; 19040 bpf_jit_free(func[i]); 19041 } 19042 kfree(func); 19043 out_undo_insn: 19044 /* cleanup main prog to be interpreted */ 19045 prog->jit_requested = 0; 19046 prog->blinding_requested = 0; 19047 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 19048 if (!bpf_pseudo_call(insn)) 19049 continue; 19050 insn->off = 0; 19051 insn->imm = env->insn_aux_data[i].call_imm; 19052 } 19053 bpf_prog_jit_attempt_done(prog); 19054 return err; 19055 } 19056 19057 static int fixup_call_args(struct bpf_verifier_env *env) 19058 { 19059 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 19060 struct bpf_prog *prog = env->prog; 19061 struct bpf_insn *insn = prog->insnsi; 19062 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 19063 int i, depth; 19064 #endif 19065 int err = 0; 19066 19067 if (env->prog->jit_requested && 19068 !bpf_prog_is_offloaded(env->prog->aux)) { 19069 err = jit_subprogs(env); 19070 if (err == 0) 19071 return 0; 19072 if (err == -EFAULT) 19073 return err; 19074 } 19075 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 19076 if (has_kfunc_call) { 19077 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 19078 return -EINVAL; 19079 } 19080 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 19081 /* When JIT fails the progs with bpf2bpf calls and tail_calls 19082 * have to be rejected, since interpreter doesn't support them yet. 19083 */ 19084 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 19085 return -EINVAL; 19086 } 19087 for (i = 0; i < prog->len; i++, insn++) { 19088 if (bpf_pseudo_func(insn)) { 19089 /* When JIT fails the progs with callback calls 19090 * have to be rejected, since interpreter doesn't support them yet. 19091 */ 19092 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 19093 return -EINVAL; 19094 } 19095 19096 if (!bpf_pseudo_call(insn)) 19097 continue; 19098 depth = get_callee_stack_depth(env, insn, i); 19099 if (depth < 0) 19100 return depth; 19101 bpf_patch_call_args(insn, depth); 19102 } 19103 err = 0; 19104 #endif 19105 return err; 19106 } 19107 19108 /* replace a generic kfunc with a specialized version if necessary */ 19109 static void specialize_kfunc(struct bpf_verifier_env *env, 19110 u32 func_id, u16 offset, unsigned long *addr) 19111 { 19112 struct bpf_prog *prog = env->prog; 19113 bool seen_direct_write; 19114 void *xdp_kfunc; 19115 bool is_rdonly; 19116 19117 if (bpf_dev_bound_kfunc_id(func_id)) { 19118 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 19119 if (xdp_kfunc) { 19120 *addr = (unsigned long)xdp_kfunc; 19121 return; 19122 } 19123 /* fallback to default kfunc when not supported by netdev */ 19124 } 19125 19126 if (offset) 19127 return; 19128 19129 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 19130 seen_direct_write = env->seen_direct_write; 19131 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 19132 19133 if (is_rdonly) 19134 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 19135 19136 /* restore env->seen_direct_write to its original value, since 19137 * may_access_direct_pkt_data mutates it 19138 */ 19139 env->seen_direct_write = seen_direct_write; 19140 } 19141 } 19142 19143 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 19144 u16 struct_meta_reg, 19145 u16 node_offset_reg, 19146 struct bpf_insn *insn, 19147 struct bpf_insn *insn_buf, 19148 int *cnt) 19149 { 19150 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 19151 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 19152 19153 insn_buf[0] = addr[0]; 19154 insn_buf[1] = addr[1]; 19155 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 19156 insn_buf[3] = *insn; 19157 *cnt = 4; 19158 } 19159 19160 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 19161 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 19162 { 19163 const struct bpf_kfunc_desc *desc; 19164 19165 if (!insn->imm) { 19166 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 19167 return -EINVAL; 19168 } 19169 19170 *cnt = 0; 19171 19172 /* insn->imm has the btf func_id. Replace it with an offset relative to 19173 * __bpf_call_base, unless the JIT needs to call functions that are 19174 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 19175 */ 19176 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 19177 if (!desc) { 19178 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 19179 insn->imm); 19180 return -EFAULT; 19181 } 19182 19183 if (!bpf_jit_supports_far_kfunc_call()) 19184 insn->imm = BPF_CALL_IMM(desc->addr); 19185 if (insn->off) 19186 return 0; 19187 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 19188 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 19189 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19190 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19191 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 19192 19193 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) { 19194 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 19195 insn_idx); 19196 return -EFAULT; 19197 } 19198 19199 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 19200 insn_buf[1] = addr[0]; 19201 insn_buf[2] = addr[1]; 19202 insn_buf[3] = *insn; 19203 *cnt = 4; 19204 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 19205 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] || 19206 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 19207 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19208 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19209 19210 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) { 19211 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 19212 insn_idx); 19213 return -EFAULT; 19214 } 19215 19216 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 19217 !kptr_struct_meta) { 19218 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 19219 insn_idx); 19220 return -EFAULT; 19221 } 19222 19223 insn_buf[0] = addr[0]; 19224 insn_buf[1] = addr[1]; 19225 insn_buf[2] = *insn; 19226 *cnt = 3; 19227 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 19228 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 19229 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 19230 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19231 int struct_meta_reg = BPF_REG_3; 19232 int node_offset_reg = BPF_REG_4; 19233 19234 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 19235 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 19236 struct_meta_reg = BPF_REG_4; 19237 node_offset_reg = BPF_REG_5; 19238 } 19239 19240 if (!kptr_struct_meta) { 19241 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 19242 insn_idx); 19243 return -EFAULT; 19244 } 19245 19246 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 19247 node_offset_reg, insn, insn_buf, cnt); 19248 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 19249 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 19250 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 19251 *cnt = 1; 19252 } 19253 return 0; 19254 } 19255 19256 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */ 19257 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len) 19258 { 19259 struct bpf_subprog_info *info = env->subprog_info; 19260 int cnt = env->subprog_cnt; 19261 struct bpf_prog *prog; 19262 19263 /* We only reserve one slot for hidden subprogs in subprog_info. */ 19264 if (env->hidden_subprog_cnt) { 19265 verbose(env, "verifier internal error: only one hidden subprog supported\n"); 19266 return -EFAULT; 19267 } 19268 /* We're not patching any existing instruction, just appending the new 19269 * ones for the hidden subprog. Hence all of the adjustment operations 19270 * in bpf_patch_insn_data are no-ops. 19271 */ 19272 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len); 19273 if (!prog) 19274 return -ENOMEM; 19275 env->prog = prog; 19276 info[cnt + 1].start = info[cnt].start; 19277 info[cnt].start = prog->len - len + 1; 19278 env->subprog_cnt++; 19279 env->hidden_subprog_cnt++; 19280 return 0; 19281 } 19282 19283 /* Do various post-verification rewrites in a single program pass. 19284 * These rewrites simplify JIT and interpreter implementations. 19285 */ 19286 static int do_misc_fixups(struct bpf_verifier_env *env) 19287 { 19288 struct bpf_prog *prog = env->prog; 19289 enum bpf_attach_type eatype = prog->expected_attach_type; 19290 enum bpf_prog_type prog_type = resolve_prog_type(prog); 19291 struct bpf_insn *insn = prog->insnsi; 19292 const struct bpf_func_proto *fn; 19293 const int insn_cnt = prog->len; 19294 const struct bpf_map_ops *ops; 19295 struct bpf_insn_aux_data *aux; 19296 struct bpf_insn insn_buf[16]; 19297 struct bpf_prog *new_prog; 19298 struct bpf_map *map_ptr; 19299 int i, ret, cnt, delta = 0; 19300 19301 if (env->seen_exception && !env->exception_callback_subprog) { 19302 struct bpf_insn patch[] = { 19303 env->prog->insnsi[insn_cnt - 1], 19304 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1), 19305 BPF_EXIT_INSN(), 19306 }; 19307 19308 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch)); 19309 if (ret < 0) 19310 return ret; 19311 prog = env->prog; 19312 insn = prog->insnsi; 19313 19314 env->exception_callback_subprog = env->subprog_cnt - 1; 19315 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */ 19316 mark_subprog_exc_cb(env, env->exception_callback_subprog); 19317 } 19318 19319 for (i = 0; i < insn_cnt; i++, insn++) { 19320 /* Make divide-by-zero exceptions impossible. */ 19321 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 19322 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 19323 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 19324 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 19325 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 19326 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 19327 struct bpf_insn *patchlet; 19328 struct bpf_insn chk_and_div[] = { 19329 /* [R,W]x div 0 -> 0 */ 19330 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 19331 BPF_JNE | BPF_K, insn->src_reg, 19332 0, 2, 0), 19333 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 19334 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 19335 *insn, 19336 }; 19337 struct bpf_insn chk_and_mod[] = { 19338 /* [R,W]x mod 0 -> [R,W]x */ 19339 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 19340 BPF_JEQ | BPF_K, insn->src_reg, 19341 0, 1 + (is64 ? 0 : 1), 0), 19342 *insn, 19343 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 19344 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 19345 }; 19346 19347 patchlet = isdiv ? chk_and_div : chk_and_mod; 19348 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 19349 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 19350 19351 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 19352 if (!new_prog) 19353 return -ENOMEM; 19354 19355 delta += cnt - 1; 19356 env->prog = prog = new_prog; 19357 insn = new_prog->insnsi + i + delta; 19358 continue; 19359 } 19360 19361 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 19362 if (BPF_CLASS(insn->code) == BPF_LD && 19363 (BPF_MODE(insn->code) == BPF_ABS || 19364 BPF_MODE(insn->code) == BPF_IND)) { 19365 cnt = env->ops->gen_ld_abs(insn, insn_buf); 19366 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19367 verbose(env, "bpf verifier is misconfigured\n"); 19368 return -EINVAL; 19369 } 19370 19371 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19372 if (!new_prog) 19373 return -ENOMEM; 19374 19375 delta += cnt - 1; 19376 env->prog = prog = new_prog; 19377 insn = new_prog->insnsi + i + delta; 19378 continue; 19379 } 19380 19381 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 19382 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 19383 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 19384 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 19385 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 19386 struct bpf_insn *patch = &insn_buf[0]; 19387 bool issrc, isneg, isimm; 19388 u32 off_reg; 19389 19390 aux = &env->insn_aux_data[i + delta]; 19391 if (!aux->alu_state || 19392 aux->alu_state == BPF_ALU_NON_POINTER) 19393 continue; 19394 19395 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 19396 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 19397 BPF_ALU_SANITIZE_SRC; 19398 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 19399 19400 off_reg = issrc ? insn->src_reg : insn->dst_reg; 19401 if (isimm) { 19402 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19403 } else { 19404 if (isneg) 19405 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19406 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19407 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 19408 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 19409 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 19410 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 19411 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 19412 } 19413 if (!issrc) 19414 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 19415 insn->src_reg = BPF_REG_AX; 19416 if (isneg) 19417 insn->code = insn->code == code_add ? 19418 code_sub : code_add; 19419 *patch++ = *insn; 19420 if (issrc && isneg && !isimm) 19421 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19422 cnt = patch - insn_buf; 19423 19424 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19425 if (!new_prog) 19426 return -ENOMEM; 19427 19428 delta += cnt - 1; 19429 env->prog = prog = new_prog; 19430 insn = new_prog->insnsi + i + delta; 19431 continue; 19432 } 19433 19434 if (insn->code != (BPF_JMP | BPF_CALL)) 19435 continue; 19436 if (insn->src_reg == BPF_PSEUDO_CALL) 19437 continue; 19438 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 19439 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 19440 if (ret) 19441 return ret; 19442 if (cnt == 0) 19443 continue; 19444 19445 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19446 if (!new_prog) 19447 return -ENOMEM; 19448 19449 delta += cnt - 1; 19450 env->prog = prog = new_prog; 19451 insn = new_prog->insnsi + i + delta; 19452 continue; 19453 } 19454 19455 if (insn->imm == BPF_FUNC_get_route_realm) 19456 prog->dst_needed = 1; 19457 if (insn->imm == BPF_FUNC_get_prandom_u32) 19458 bpf_user_rnd_init_once(); 19459 if (insn->imm == BPF_FUNC_override_return) 19460 prog->kprobe_override = 1; 19461 if (insn->imm == BPF_FUNC_tail_call) { 19462 /* If we tail call into other programs, we 19463 * cannot make any assumptions since they can 19464 * be replaced dynamically during runtime in 19465 * the program array. 19466 */ 19467 prog->cb_access = 1; 19468 if (!allow_tail_call_in_subprogs(env)) 19469 prog->aux->stack_depth = MAX_BPF_STACK; 19470 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 19471 19472 /* mark bpf_tail_call as different opcode to avoid 19473 * conditional branch in the interpreter for every normal 19474 * call and to prevent accidental JITing by JIT compiler 19475 * that doesn't support bpf_tail_call yet 19476 */ 19477 insn->imm = 0; 19478 insn->code = BPF_JMP | BPF_TAIL_CALL; 19479 19480 aux = &env->insn_aux_data[i + delta]; 19481 if (env->bpf_capable && !prog->blinding_requested && 19482 prog->jit_requested && 19483 !bpf_map_key_poisoned(aux) && 19484 !bpf_map_ptr_poisoned(aux) && 19485 !bpf_map_ptr_unpriv(aux)) { 19486 struct bpf_jit_poke_descriptor desc = { 19487 .reason = BPF_POKE_REASON_TAIL_CALL, 19488 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 19489 .tail_call.key = bpf_map_key_immediate(aux), 19490 .insn_idx = i + delta, 19491 }; 19492 19493 ret = bpf_jit_add_poke_descriptor(prog, &desc); 19494 if (ret < 0) { 19495 verbose(env, "adding tail call poke descriptor failed\n"); 19496 return ret; 19497 } 19498 19499 insn->imm = ret + 1; 19500 continue; 19501 } 19502 19503 if (!bpf_map_ptr_unpriv(aux)) 19504 continue; 19505 19506 /* instead of changing every JIT dealing with tail_call 19507 * emit two extra insns: 19508 * if (index >= max_entries) goto out; 19509 * index &= array->index_mask; 19510 * to avoid out-of-bounds cpu speculation 19511 */ 19512 if (bpf_map_ptr_poisoned(aux)) { 19513 verbose(env, "tail_call abusing map_ptr\n"); 19514 return -EINVAL; 19515 } 19516 19517 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19518 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 19519 map_ptr->max_entries, 2); 19520 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 19521 container_of(map_ptr, 19522 struct bpf_array, 19523 map)->index_mask); 19524 insn_buf[2] = *insn; 19525 cnt = 3; 19526 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19527 if (!new_prog) 19528 return -ENOMEM; 19529 19530 delta += cnt - 1; 19531 env->prog = prog = new_prog; 19532 insn = new_prog->insnsi + i + delta; 19533 continue; 19534 } 19535 19536 if (insn->imm == BPF_FUNC_timer_set_callback) { 19537 /* The verifier will process callback_fn as many times as necessary 19538 * with different maps and the register states prepared by 19539 * set_timer_callback_state will be accurate. 19540 * 19541 * The following use case is valid: 19542 * map1 is shared by prog1, prog2, prog3. 19543 * prog1 calls bpf_timer_init for some map1 elements 19544 * prog2 calls bpf_timer_set_callback for some map1 elements. 19545 * Those that were not bpf_timer_init-ed will return -EINVAL. 19546 * prog3 calls bpf_timer_start for some map1 elements. 19547 * Those that were not both bpf_timer_init-ed and 19548 * bpf_timer_set_callback-ed will return -EINVAL. 19549 */ 19550 struct bpf_insn ld_addrs[2] = { 19551 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 19552 }; 19553 19554 insn_buf[0] = ld_addrs[0]; 19555 insn_buf[1] = ld_addrs[1]; 19556 insn_buf[2] = *insn; 19557 cnt = 3; 19558 19559 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19560 if (!new_prog) 19561 return -ENOMEM; 19562 19563 delta += cnt - 1; 19564 env->prog = prog = new_prog; 19565 insn = new_prog->insnsi + i + delta; 19566 goto patch_call_imm; 19567 } 19568 19569 if (is_storage_get_function(insn->imm)) { 19570 if (!env->prog->aux->sleepable || 19571 env->insn_aux_data[i + delta].storage_get_func_atomic) 19572 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 19573 else 19574 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 19575 insn_buf[1] = *insn; 19576 cnt = 2; 19577 19578 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19579 if (!new_prog) 19580 return -ENOMEM; 19581 19582 delta += cnt - 1; 19583 env->prog = prog = new_prog; 19584 insn = new_prog->insnsi + i + delta; 19585 goto patch_call_imm; 19586 } 19587 19588 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */ 19589 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) { 19590 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data, 19591 * bpf_mem_alloc() returns a ptr to the percpu data ptr. 19592 */ 19593 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0); 19594 insn_buf[1] = *insn; 19595 cnt = 2; 19596 19597 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19598 if (!new_prog) 19599 return -ENOMEM; 19600 19601 delta += cnt - 1; 19602 env->prog = prog = new_prog; 19603 insn = new_prog->insnsi + i + delta; 19604 goto patch_call_imm; 19605 } 19606 19607 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 19608 * and other inlining handlers are currently limited to 64 bit 19609 * only. 19610 */ 19611 if (prog->jit_requested && BITS_PER_LONG == 64 && 19612 (insn->imm == BPF_FUNC_map_lookup_elem || 19613 insn->imm == BPF_FUNC_map_update_elem || 19614 insn->imm == BPF_FUNC_map_delete_elem || 19615 insn->imm == BPF_FUNC_map_push_elem || 19616 insn->imm == BPF_FUNC_map_pop_elem || 19617 insn->imm == BPF_FUNC_map_peek_elem || 19618 insn->imm == BPF_FUNC_redirect_map || 19619 insn->imm == BPF_FUNC_for_each_map_elem || 19620 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 19621 aux = &env->insn_aux_data[i + delta]; 19622 if (bpf_map_ptr_poisoned(aux)) 19623 goto patch_call_imm; 19624 19625 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19626 ops = map_ptr->ops; 19627 if (insn->imm == BPF_FUNC_map_lookup_elem && 19628 ops->map_gen_lookup) { 19629 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 19630 if (cnt == -EOPNOTSUPP) 19631 goto patch_map_ops_generic; 19632 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19633 verbose(env, "bpf verifier is misconfigured\n"); 19634 return -EINVAL; 19635 } 19636 19637 new_prog = bpf_patch_insn_data(env, i + delta, 19638 insn_buf, cnt); 19639 if (!new_prog) 19640 return -ENOMEM; 19641 19642 delta += cnt - 1; 19643 env->prog = prog = new_prog; 19644 insn = new_prog->insnsi + i + delta; 19645 continue; 19646 } 19647 19648 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 19649 (void *(*)(struct bpf_map *map, void *key))NULL)); 19650 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 19651 (long (*)(struct bpf_map *map, void *key))NULL)); 19652 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 19653 (long (*)(struct bpf_map *map, void *key, void *value, 19654 u64 flags))NULL)); 19655 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 19656 (long (*)(struct bpf_map *map, void *value, 19657 u64 flags))NULL)); 19658 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 19659 (long (*)(struct bpf_map *map, void *value))NULL)); 19660 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 19661 (long (*)(struct bpf_map *map, void *value))NULL)); 19662 BUILD_BUG_ON(!__same_type(ops->map_redirect, 19663 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 19664 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 19665 (long (*)(struct bpf_map *map, 19666 bpf_callback_t callback_fn, 19667 void *callback_ctx, 19668 u64 flags))NULL)); 19669 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 19670 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 19671 19672 patch_map_ops_generic: 19673 switch (insn->imm) { 19674 case BPF_FUNC_map_lookup_elem: 19675 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 19676 continue; 19677 case BPF_FUNC_map_update_elem: 19678 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 19679 continue; 19680 case BPF_FUNC_map_delete_elem: 19681 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 19682 continue; 19683 case BPF_FUNC_map_push_elem: 19684 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 19685 continue; 19686 case BPF_FUNC_map_pop_elem: 19687 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 19688 continue; 19689 case BPF_FUNC_map_peek_elem: 19690 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 19691 continue; 19692 case BPF_FUNC_redirect_map: 19693 insn->imm = BPF_CALL_IMM(ops->map_redirect); 19694 continue; 19695 case BPF_FUNC_for_each_map_elem: 19696 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 19697 continue; 19698 case BPF_FUNC_map_lookup_percpu_elem: 19699 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 19700 continue; 19701 } 19702 19703 goto patch_call_imm; 19704 } 19705 19706 /* Implement bpf_jiffies64 inline. */ 19707 if (prog->jit_requested && BITS_PER_LONG == 64 && 19708 insn->imm == BPF_FUNC_jiffies64) { 19709 struct bpf_insn ld_jiffies_addr[2] = { 19710 BPF_LD_IMM64(BPF_REG_0, 19711 (unsigned long)&jiffies), 19712 }; 19713 19714 insn_buf[0] = ld_jiffies_addr[0]; 19715 insn_buf[1] = ld_jiffies_addr[1]; 19716 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 19717 BPF_REG_0, 0); 19718 cnt = 3; 19719 19720 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 19721 cnt); 19722 if (!new_prog) 19723 return -ENOMEM; 19724 19725 delta += cnt - 1; 19726 env->prog = prog = new_prog; 19727 insn = new_prog->insnsi + i + delta; 19728 continue; 19729 } 19730 19731 /* Implement bpf_get_func_arg inline. */ 19732 if (prog_type == BPF_PROG_TYPE_TRACING && 19733 insn->imm == BPF_FUNC_get_func_arg) { 19734 /* Load nr_args from ctx - 8 */ 19735 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19736 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 19737 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 19738 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 19739 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 19740 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19741 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 19742 insn_buf[7] = BPF_JMP_A(1); 19743 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 19744 cnt = 9; 19745 19746 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19747 if (!new_prog) 19748 return -ENOMEM; 19749 19750 delta += cnt - 1; 19751 env->prog = prog = new_prog; 19752 insn = new_prog->insnsi + i + delta; 19753 continue; 19754 } 19755 19756 /* Implement bpf_get_func_ret inline. */ 19757 if (prog_type == BPF_PROG_TYPE_TRACING && 19758 insn->imm == BPF_FUNC_get_func_ret) { 19759 if (eatype == BPF_TRACE_FEXIT || 19760 eatype == BPF_MODIFY_RETURN) { 19761 /* Load nr_args from ctx - 8 */ 19762 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19763 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 19764 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 19765 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19766 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 19767 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 19768 cnt = 6; 19769 } else { 19770 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 19771 cnt = 1; 19772 } 19773 19774 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19775 if (!new_prog) 19776 return -ENOMEM; 19777 19778 delta += cnt - 1; 19779 env->prog = prog = new_prog; 19780 insn = new_prog->insnsi + i + delta; 19781 continue; 19782 } 19783 19784 /* Implement get_func_arg_cnt inline. */ 19785 if (prog_type == BPF_PROG_TYPE_TRACING && 19786 insn->imm == BPF_FUNC_get_func_arg_cnt) { 19787 /* Load nr_args from ctx - 8 */ 19788 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19789 19790 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19791 if (!new_prog) 19792 return -ENOMEM; 19793 19794 env->prog = prog = new_prog; 19795 insn = new_prog->insnsi + i + delta; 19796 continue; 19797 } 19798 19799 /* Implement bpf_get_func_ip inline. */ 19800 if (prog_type == BPF_PROG_TYPE_TRACING && 19801 insn->imm == BPF_FUNC_get_func_ip) { 19802 /* Load IP address from ctx - 16 */ 19803 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 19804 19805 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19806 if (!new_prog) 19807 return -ENOMEM; 19808 19809 env->prog = prog = new_prog; 19810 insn = new_prog->insnsi + i + delta; 19811 continue; 19812 } 19813 19814 patch_call_imm: 19815 fn = env->ops->get_func_proto(insn->imm, env->prog); 19816 /* all functions that have prototype and verifier allowed 19817 * programs to call them, must be real in-kernel functions 19818 */ 19819 if (!fn->func) { 19820 verbose(env, 19821 "kernel subsystem misconfigured func %s#%d\n", 19822 func_id_name(insn->imm), insn->imm); 19823 return -EFAULT; 19824 } 19825 insn->imm = fn->func - __bpf_call_base; 19826 } 19827 19828 /* Since poke tab is now finalized, publish aux to tracker. */ 19829 for (i = 0; i < prog->aux->size_poke_tab; i++) { 19830 map_ptr = prog->aux->poke_tab[i].tail_call.map; 19831 if (!map_ptr->ops->map_poke_track || 19832 !map_ptr->ops->map_poke_untrack || 19833 !map_ptr->ops->map_poke_run) { 19834 verbose(env, "bpf verifier is misconfigured\n"); 19835 return -EINVAL; 19836 } 19837 19838 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 19839 if (ret < 0) { 19840 verbose(env, "tracking tail call prog failed\n"); 19841 return ret; 19842 } 19843 } 19844 19845 sort_kfunc_descs_by_imm_off(env->prog); 19846 19847 return 0; 19848 } 19849 19850 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 19851 int position, 19852 s32 stack_base, 19853 u32 callback_subprogno, 19854 u32 *cnt) 19855 { 19856 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 19857 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 19858 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 19859 int reg_loop_max = BPF_REG_6; 19860 int reg_loop_cnt = BPF_REG_7; 19861 int reg_loop_ctx = BPF_REG_8; 19862 19863 struct bpf_prog *new_prog; 19864 u32 callback_start; 19865 u32 call_insn_offset; 19866 s32 callback_offset; 19867 19868 /* This represents an inlined version of bpf_iter.c:bpf_loop, 19869 * be careful to modify this code in sync. 19870 */ 19871 struct bpf_insn insn_buf[] = { 19872 /* Return error and jump to the end of the patch if 19873 * expected number of iterations is too big. 19874 */ 19875 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 19876 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 19877 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 19878 /* spill R6, R7, R8 to use these as loop vars */ 19879 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 19880 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 19881 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 19882 /* initialize loop vars */ 19883 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 19884 BPF_MOV32_IMM(reg_loop_cnt, 0), 19885 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 19886 /* loop header, 19887 * if reg_loop_cnt >= reg_loop_max skip the loop body 19888 */ 19889 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 19890 /* callback call, 19891 * correct callback offset would be set after patching 19892 */ 19893 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 19894 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 19895 BPF_CALL_REL(0), 19896 /* increment loop counter */ 19897 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 19898 /* jump to loop header if callback returned 0 */ 19899 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 19900 /* return value of bpf_loop, 19901 * set R0 to the number of iterations 19902 */ 19903 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 19904 /* restore original values of R6, R7, R8 */ 19905 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 19906 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 19907 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 19908 }; 19909 19910 *cnt = ARRAY_SIZE(insn_buf); 19911 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 19912 if (!new_prog) 19913 return new_prog; 19914 19915 /* callback start is known only after patching */ 19916 callback_start = env->subprog_info[callback_subprogno].start; 19917 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 19918 call_insn_offset = position + 12; 19919 callback_offset = callback_start - call_insn_offset - 1; 19920 new_prog->insnsi[call_insn_offset].imm = callback_offset; 19921 19922 return new_prog; 19923 } 19924 19925 static bool is_bpf_loop_call(struct bpf_insn *insn) 19926 { 19927 return insn->code == (BPF_JMP | BPF_CALL) && 19928 insn->src_reg == 0 && 19929 insn->imm == BPF_FUNC_loop; 19930 } 19931 19932 /* For all sub-programs in the program (including main) check 19933 * insn_aux_data to see if there are bpf_loop calls that require 19934 * inlining. If such calls are found the calls are replaced with a 19935 * sequence of instructions produced by `inline_bpf_loop` function and 19936 * subprog stack_depth is increased by the size of 3 registers. 19937 * This stack space is used to spill values of the R6, R7, R8. These 19938 * registers are used to store the loop bound, counter and context 19939 * variables. 19940 */ 19941 static int optimize_bpf_loop(struct bpf_verifier_env *env) 19942 { 19943 struct bpf_subprog_info *subprogs = env->subprog_info; 19944 int i, cur_subprog = 0, cnt, delta = 0; 19945 struct bpf_insn *insn = env->prog->insnsi; 19946 int insn_cnt = env->prog->len; 19947 u16 stack_depth = subprogs[cur_subprog].stack_depth; 19948 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19949 u16 stack_depth_extra = 0; 19950 19951 for (i = 0; i < insn_cnt; i++, insn++) { 19952 struct bpf_loop_inline_state *inline_state = 19953 &env->insn_aux_data[i + delta].loop_inline_state; 19954 19955 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 19956 struct bpf_prog *new_prog; 19957 19958 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 19959 new_prog = inline_bpf_loop(env, 19960 i + delta, 19961 -(stack_depth + stack_depth_extra), 19962 inline_state->callback_subprogno, 19963 &cnt); 19964 if (!new_prog) 19965 return -ENOMEM; 19966 19967 delta += cnt - 1; 19968 env->prog = new_prog; 19969 insn = new_prog->insnsi + i + delta; 19970 } 19971 19972 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 19973 subprogs[cur_subprog].stack_depth += stack_depth_extra; 19974 cur_subprog++; 19975 stack_depth = subprogs[cur_subprog].stack_depth; 19976 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19977 stack_depth_extra = 0; 19978 } 19979 } 19980 19981 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 19982 19983 return 0; 19984 } 19985 19986 static void free_states(struct bpf_verifier_env *env) 19987 { 19988 struct bpf_verifier_state_list *sl, *sln; 19989 int i; 19990 19991 sl = env->free_list; 19992 while (sl) { 19993 sln = sl->next; 19994 free_verifier_state(&sl->state, false); 19995 kfree(sl); 19996 sl = sln; 19997 } 19998 env->free_list = NULL; 19999 20000 if (!env->explored_states) 20001 return; 20002 20003 for (i = 0; i < state_htab_size(env); i++) { 20004 sl = env->explored_states[i]; 20005 20006 while (sl) { 20007 sln = sl->next; 20008 free_verifier_state(&sl->state, false); 20009 kfree(sl); 20010 sl = sln; 20011 } 20012 env->explored_states[i] = NULL; 20013 } 20014 } 20015 20016 static int do_check_common(struct bpf_verifier_env *env, int subprog) 20017 { 20018 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 20019 struct bpf_subprog_info *sub = subprog_info(env, subprog); 20020 struct bpf_verifier_state *state; 20021 struct bpf_reg_state *regs; 20022 int ret, i; 20023 20024 env->prev_linfo = NULL; 20025 env->pass_cnt++; 20026 20027 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 20028 if (!state) 20029 return -ENOMEM; 20030 state->curframe = 0; 20031 state->speculative = false; 20032 state->branches = 1; 20033 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 20034 if (!state->frame[0]) { 20035 kfree(state); 20036 return -ENOMEM; 20037 } 20038 env->cur_state = state; 20039 init_func_state(env, state->frame[0], 20040 BPF_MAIN_FUNC /* callsite */, 20041 0 /* frameno */, 20042 subprog); 20043 state->first_insn_idx = env->subprog_info[subprog].start; 20044 state->last_insn_idx = -1; 20045 20046 20047 regs = state->frame[state->curframe]->regs; 20048 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 20049 const char *sub_name = subprog_name(env, subprog); 20050 struct bpf_subprog_arg_info *arg; 20051 struct bpf_reg_state *reg; 20052 20053 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 20054 ret = btf_prepare_func_args(env, subprog); 20055 if (ret) 20056 goto out; 20057 20058 if (subprog_is_exc_cb(env, subprog)) { 20059 state->frame[0]->in_exception_callback_fn = true; 20060 /* We have already ensured that the callback returns an integer, just 20061 * like all global subprogs. We need to determine it only has a single 20062 * scalar argument. 20063 */ 20064 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 20065 verbose(env, "exception cb only supports single integer argument\n"); 20066 ret = -EINVAL; 20067 goto out; 20068 } 20069 } 20070 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) { 20071 arg = &sub->args[i - BPF_REG_1]; 20072 reg = ®s[i]; 20073 20074 if (arg->arg_type == ARG_PTR_TO_CTX) { 20075 reg->type = PTR_TO_CTX; 20076 mark_reg_known_zero(env, regs, i); 20077 } else if (arg->arg_type == ARG_ANYTHING) { 20078 reg->type = SCALAR_VALUE; 20079 mark_reg_unknown(env, regs, i); 20080 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 20081 /* assume unspecial LOCAL dynptr type */ 20082 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen); 20083 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 20084 reg->type = PTR_TO_MEM; 20085 if (arg->arg_type & PTR_MAYBE_NULL) 20086 reg->type |= PTR_MAYBE_NULL; 20087 mark_reg_known_zero(env, regs, i); 20088 reg->mem_size = arg->mem_size; 20089 reg->id = ++env->id_gen; 20090 } else { 20091 WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n", 20092 i - BPF_REG_1, arg->arg_type); 20093 ret = -EFAULT; 20094 goto out; 20095 } 20096 } 20097 } else { 20098 /* if main BPF program has associated BTF info, validate that 20099 * it's matching expected signature, and otherwise mark BTF 20100 * info for main program as unreliable 20101 */ 20102 if (env->prog->aux->func_info_aux) { 20103 ret = btf_prepare_func_args(env, 0); 20104 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) 20105 env->prog->aux->func_info_aux[0].unreliable = true; 20106 } 20107 20108 /* 1st arg to a function */ 20109 regs[BPF_REG_1].type = PTR_TO_CTX; 20110 mark_reg_known_zero(env, regs, BPF_REG_1); 20111 } 20112 20113 ret = do_check(env); 20114 out: 20115 /* check for NULL is necessary, since cur_state can be freed inside 20116 * do_check() under memory pressure. 20117 */ 20118 if (env->cur_state) { 20119 free_verifier_state(env->cur_state, true); 20120 env->cur_state = NULL; 20121 } 20122 while (!pop_stack(env, NULL, NULL, false)); 20123 if (!ret && pop_log) 20124 bpf_vlog_reset(&env->log, 0); 20125 free_states(env); 20126 return ret; 20127 } 20128 20129 /* Lazily verify all global functions based on their BTF, if they are called 20130 * from main BPF program or any of subprograms transitively. 20131 * BPF global subprogs called from dead code are not validated. 20132 * All callable global functions must pass verification. 20133 * Otherwise the whole program is rejected. 20134 * Consider: 20135 * int bar(int); 20136 * int foo(int f) 20137 * { 20138 * return bar(f); 20139 * } 20140 * int bar(int b) 20141 * { 20142 * ... 20143 * } 20144 * foo() will be verified first for R1=any_scalar_value. During verification it 20145 * will be assumed that bar() already verified successfully and call to bar() 20146 * from foo() will be checked for type match only. Later bar() will be verified 20147 * independently to check that it's safe for R1=any_scalar_value. 20148 */ 20149 static int do_check_subprogs(struct bpf_verifier_env *env) 20150 { 20151 struct bpf_prog_aux *aux = env->prog->aux; 20152 struct bpf_func_info_aux *sub_aux; 20153 int i, ret, new_cnt; 20154 20155 if (!aux->func_info) 20156 return 0; 20157 20158 /* exception callback is presumed to be always called */ 20159 if (env->exception_callback_subprog) 20160 subprog_aux(env, env->exception_callback_subprog)->called = true; 20161 20162 again: 20163 new_cnt = 0; 20164 for (i = 1; i < env->subprog_cnt; i++) { 20165 if (!subprog_is_global(env, i)) 20166 continue; 20167 20168 sub_aux = subprog_aux(env, i); 20169 if (!sub_aux->called || sub_aux->verified) 20170 continue; 20171 20172 env->insn_idx = env->subprog_info[i].start; 20173 WARN_ON_ONCE(env->insn_idx == 0); 20174 ret = do_check_common(env, i); 20175 if (ret) { 20176 return ret; 20177 } else if (env->log.level & BPF_LOG_LEVEL) { 20178 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 20179 i, subprog_name(env, i)); 20180 } 20181 20182 /* We verified new global subprog, it might have called some 20183 * more global subprogs that we haven't verified yet, so we 20184 * need to do another pass over subprogs to verify those. 20185 */ 20186 sub_aux->verified = true; 20187 new_cnt++; 20188 } 20189 20190 /* We can't loop forever as we verify at least one global subprog on 20191 * each pass. 20192 */ 20193 if (new_cnt) 20194 goto again; 20195 20196 return 0; 20197 } 20198 20199 static int do_check_main(struct bpf_verifier_env *env) 20200 { 20201 int ret; 20202 20203 env->insn_idx = 0; 20204 ret = do_check_common(env, 0); 20205 if (!ret) 20206 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 20207 return ret; 20208 } 20209 20210 20211 static void print_verification_stats(struct bpf_verifier_env *env) 20212 { 20213 int i; 20214 20215 if (env->log.level & BPF_LOG_STATS) { 20216 verbose(env, "verification time %lld usec\n", 20217 div_u64(env->verification_time, 1000)); 20218 verbose(env, "stack depth "); 20219 for (i = 0; i < env->subprog_cnt; i++) { 20220 u32 depth = env->subprog_info[i].stack_depth; 20221 20222 verbose(env, "%d", depth); 20223 if (i + 1 < env->subprog_cnt) 20224 verbose(env, "+"); 20225 } 20226 verbose(env, "\n"); 20227 } 20228 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 20229 "total_states %d peak_states %d mark_read %d\n", 20230 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 20231 env->max_states_per_insn, env->total_states, 20232 env->peak_states, env->longest_mark_read_walk); 20233 } 20234 20235 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 20236 { 20237 const struct btf_type *t, *func_proto; 20238 const struct bpf_struct_ops *st_ops; 20239 const struct btf_member *member; 20240 struct bpf_prog *prog = env->prog; 20241 u32 btf_id, member_idx; 20242 const char *mname; 20243 20244 if (!prog->gpl_compatible) { 20245 verbose(env, "struct ops programs must have a GPL compatible license\n"); 20246 return -EINVAL; 20247 } 20248 20249 btf_id = prog->aux->attach_btf_id; 20250 st_ops = bpf_struct_ops_find(btf_id); 20251 if (!st_ops) { 20252 verbose(env, "attach_btf_id %u is not a supported struct\n", 20253 btf_id); 20254 return -ENOTSUPP; 20255 } 20256 20257 t = st_ops->type; 20258 member_idx = prog->expected_attach_type; 20259 if (member_idx >= btf_type_vlen(t)) { 20260 verbose(env, "attach to invalid member idx %u of struct %s\n", 20261 member_idx, st_ops->name); 20262 return -EINVAL; 20263 } 20264 20265 member = &btf_type_member(t)[member_idx]; 20266 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 20267 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 20268 NULL); 20269 if (!func_proto) { 20270 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 20271 mname, member_idx, st_ops->name); 20272 return -EINVAL; 20273 } 20274 20275 if (st_ops->check_member) { 20276 int err = st_ops->check_member(t, member, prog); 20277 20278 if (err) { 20279 verbose(env, "attach to unsupported member %s of struct %s\n", 20280 mname, st_ops->name); 20281 return err; 20282 } 20283 } 20284 20285 prog->aux->attach_func_proto = func_proto; 20286 prog->aux->attach_func_name = mname; 20287 env->ops = st_ops->verifier_ops; 20288 20289 return 0; 20290 } 20291 #define SECURITY_PREFIX "security_" 20292 20293 static int check_attach_modify_return(unsigned long addr, const char *func_name) 20294 { 20295 if (within_error_injection_list(addr) || 20296 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 20297 return 0; 20298 20299 return -EINVAL; 20300 } 20301 20302 /* list of non-sleepable functions that are otherwise on 20303 * ALLOW_ERROR_INJECTION list 20304 */ 20305 BTF_SET_START(btf_non_sleepable_error_inject) 20306 /* Three functions below can be called from sleepable and non-sleepable context. 20307 * Assume non-sleepable from bpf safety point of view. 20308 */ 20309 BTF_ID(func, __filemap_add_folio) 20310 BTF_ID(func, should_fail_alloc_page) 20311 BTF_ID(func, should_failslab) 20312 BTF_SET_END(btf_non_sleepable_error_inject) 20313 20314 static int check_non_sleepable_error_inject(u32 btf_id) 20315 { 20316 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 20317 } 20318 20319 int bpf_check_attach_target(struct bpf_verifier_log *log, 20320 const struct bpf_prog *prog, 20321 const struct bpf_prog *tgt_prog, 20322 u32 btf_id, 20323 struct bpf_attach_target_info *tgt_info) 20324 { 20325 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 20326 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 20327 const char prefix[] = "btf_trace_"; 20328 int ret = 0, subprog = -1, i; 20329 const struct btf_type *t; 20330 bool conservative = true; 20331 const char *tname; 20332 struct btf *btf; 20333 long addr = 0; 20334 struct module *mod = NULL; 20335 20336 if (!btf_id) { 20337 bpf_log(log, "Tracing programs must provide btf_id\n"); 20338 return -EINVAL; 20339 } 20340 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 20341 if (!btf) { 20342 bpf_log(log, 20343 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 20344 return -EINVAL; 20345 } 20346 t = btf_type_by_id(btf, btf_id); 20347 if (!t) { 20348 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 20349 return -EINVAL; 20350 } 20351 tname = btf_name_by_offset(btf, t->name_off); 20352 if (!tname) { 20353 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 20354 return -EINVAL; 20355 } 20356 if (tgt_prog) { 20357 struct bpf_prog_aux *aux = tgt_prog->aux; 20358 20359 if (bpf_prog_is_dev_bound(prog->aux) && 20360 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 20361 bpf_log(log, "Target program bound device mismatch"); 20362 return -EINVAL; 20363 } 20364 20365 for (i = 0; i < aux->func_info_cnt; i++) 20366 if (aux->func_info[i].type_id == btf_id) { 20367 subprog = i; 20368 break; 20369 } 20370 if (subprog == -1) { 20371 bpf_log(log, "Subprog %s doesn't exist\n", tname); 20372 return -EINVAL; 20373 } 20374 if (aux->func && aux->func[subprog]->aux->exception_cb) { 20375 bpf_log(log, 20376 "%s programs cannot attach to exception callback\n", 20377 prog_extension ? "Extension" : "FENTRY/FEXIT"); 20378 return -EINVAL; 20379 } 20380 conservative = aux->func_info_aux[subprog].unreliable; 20381 if (prog_extension) { 20382 if (conservative) { 20383 bpf_log(log, 20384 "Cannot replace static functions\n"); 20385 return -EINVAL; 20386 } 20387 if (!prog->jit_requested) { 20388 bpf_log(log, 20389 "Extension programs should be JITed\n"); 20390 return -EINVAL; 20391 } 20392 } 20393 if (!tgt_prog->jited) { 20394 bpf_log(log, "Can attach to only JITed progs\n"); 20395 return -EINVAL; 20396 } 20397 if (prog_tracing) { 20398 if (aux->attach_tracing_prog) { 20399 /* 20400 * Target program is an fentry/fexit which is already attached 20401 * to another tracing program. More levels of nesting 20402 * attachment are not allowed. 20403 */ 20404 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 20405 return -EINVAL; 20406 } 20407 } else if (tgt_prog->type == prog->type) { 20408 /* 20409 * To avoid potential call chain cycles, prevent attaching of a 20410 * program extension to another extension. It's ok to attach 20411 * fentry/fexit to extension program. 20412 */ 20413 bpf_log(log, "Cannot recursively attach\n"); 20414 return -EINVAL; 20415 } 20416 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 20417 prog_extension && 20418 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 20419 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 20420 /* Program extensions can extend all program types 20421 * except fentry/fexit. The reason is the following. 20422 * The fentry/fexit programs are used for performance 20423 * analysis, stats and can be attached to any program 20424 * type. When extension program is replacing XDP function 20425 * it is necessary to allow performance analysis of all 20426 * functions. Both original XDP program and its program 20427 * extension. Hence attaching fentry/fexit to 20428 * BPF_PROG_TYPE_EXT is allowed. If extending of 20429 * fentry/fexit was allowed it would be possible to create 20430 * long call chain fentry->extension->fentry->extension 20431 * beyond reasonable stack size. Hence extending fentry 20432 * is not allowed. 20433 */ 20434 bpf_log(log, "Cannot extend fentry/fexit\n"); 20435 return -EINVAL; 20436 } 20437 } else { 20438 if (prog_extension) { 20439 bpf_log(log, "Cannot replace kernel functions\n"); 20440 return -EINVAL; 20441 } 20442 } 20443 20444 switch (prog->expected_attach_type) { 20445 case BPF_TRACE_RAW_TP: 20446 if (tgt_prog) { 20447 bpf_log(log, 20448 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 20449 return -EINVAL; 20450 } 20451 if (!btf_type_is_typedef(t)) { 20452 bpf_log(log, "attach_btf_id %u is not a typedef\n", 20453 btf_id); 20454 return -EINVAL; 20455 } 20456 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 20457 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 20458 btf_id, tname); 20459 return -EINVAL; 20460 } 20461 tname += sizeof(prefix) - 1; 20462 t = btf_type_by_id(btf, t->type); 20463 if (!btf_type_is_ptr(t)) 20464 /* should never happen in valid vmlinux build */ 20465 return -EINVAL; 20466 t = btf_type_by_id(btf, t->type); 20467 if (!btf_type_is_func_proto(t)) 20468 /* should never happen in valid vmlinux build */ 20469 return -EINVAL; 20470 20471 break; 20472 case BPF_TRACE_ITER: 20473 if (!btf_type_is_func(t)) { 20474 bpf_log(log, "attach_btf_id %u is not a function\n", 20475 btf_id); 20476 return -EINVAL; 20477 } 20478 t = btf_type_by_id(btf, t->type); 20479 if (!btf_type_is_func_proto(t)) 20480 return -EINVAL; 20481 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 20482 if (ret) 20483 return ret; 20484 break; 20485 default: 20486 if (!prog_extension) 20487 return -EINVAL; 20488 fallthrough; 20489 case BPF_MODIFY_RETURN: 20490 case BPF_LSM_MAC: 20491 case BPF_LSM_CGROUP: 20492 case BPF_TRACE_FENTRY: 20493 case BPF_TRACE_FEXIT: 20494 if (!btf_type_is_func(t)) { 20495 bpf_log(log, "attach_btf_id %u is not a function\n", 20496 btf_id); 20497 return -EINVAL; 20498 } 20499 if (prog_extension && 20500 btf_check_type_match(log, prog, btf, t)) 20501 return -EINVAL; 20502 t = btf_type_by_id(btf, t->type); 20503 if (!btf_type_is_func_proto(t)) 20504 return -EINVAL; 20505 20506 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 20507 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 20508 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 20509 return -EINVAL; 20510 20511 if (tgt_prog && conservative) 20512 t = NULL; 20513 20514 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 20515 if (ret < 0) 20516 return ret; 20517 20518 if (tgt_prog) { 20519 if (subprog == 0) 20520 addr = (long) tgt_prog->bpf_func; 20521 else 20522 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 20523 } else { 20524 if (btf_is_module(btf)) { 20525 mod = btf_try_get_module(btf); 20526 if (mod) 20527 addr = find_kallsyms_symbol_value(mod, tname); 20528 else 20529 addr = 0; 20530 } else { 20531 addr = kallsyms_lookup_name(tname); 20532 } 20533 if (!addr) { 20534 module_put(mod); 20535 bpf_log(log, 20536 "The address of function %s cannot be found\n", 20537 tname); 20538 return -ENOENT; 20539 } 20540 } 20541 20542 if (prog->aux->sleepable) { 20543 ret = -EINVAL; 20544 switch (prog->type) { 20545 case BPF_PROG_TYPE_TRACING: 20546 20547 /* fentry/fexit/fmod_ret progs can be sleepable if they are 20548 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 20549 */ 20550 if (!check_non_sleepable_error_inject(btf_id) && 20551 within_error_injection_list(addr)) 20552 ret = 0; 20553 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 20554 * in the fmodret id set with the KF_SLEEPABLE flag. 20555 */ 20556 else { 20557 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 20558 prog); 20559 20560 if (flags && (*flags & KF_SLEEPABLE)) 20561 ret = 0; 20562 } 20563 break; 20564 case BPF_PROG_TYPE_LSM: 20565 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 20566 * Only some of them are sleepable. 20567 */ 20568 if (bpf_lsm_is_sleepable_hook(btf_id)) 20569 ret = 0; 20570 break; 20571 default: 20572 break; 20573 } 20574 if (ret) { 20575 module_put(mod); 20576 bpf_log(log, "%s is not sleepable\n", tname); 20577 return ret; 20578 } 20579 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 20580 if (tgt_prog) { 20581 module_put(mod); 20582 bpf_log(log, "can't modify return codes of BPF programs\n"); 20583 return -EINVAL; 20584 } 20585 ret = -EINVAL; 20586 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 20587 !check_attach_modify_return(addr, tname)) 20588 ret = 0; 20589 if (ret) { 20590 module_put(mod); 20591 bpf_log(log, "%s() is not modifiable\n", tname); 20592 return ret; 20593 } 20594 } 20595 20596 break; 20597 } 20598 tgt_info->tgt_addr = addr; 20599 tgt_info->tgt_name = tname; 20600 tgt_info->tgt_type = t; 20601 tgt_info->tgt_mod = mod; 20602 return 0; 20603 } 20604 20605 BTF_SET_START(btf_id_deny) 20606 BTF_ID_UNUSED 20607 #ifdef CONFIG_SMP 20608 BTF_ID(func, migrate_disable) 20609 BTF_ID(func, migrate_enable) 20610 #endif 20611 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 20612 BTF_ID(func, rcu_read_unlock_strict) 20613 #endif 20614 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 20615 BTF_ID(func, preempt_count_add) 20616 BTF_ID(func, preempt_count_sub) 20617 #endif 20618 #ifdef CONFIG_PREEMPT_RCU 20619 BTF_ID(func, __rcu_read_lock) 20620 BTF_ID(func, __rcu_read_unlock) 20621 #endif 20622 BTF_SET_END(btf_id_deny) 20623 20624 static bool can_be_sleepable(struct bpf_prog *prog) 20625 { 20626 if (prog->type == BPF_PROG_TYPE_TRACING) { 20627 switch (prog->expected_attach_type) { 20628 case BPF_TRACE_FENTRY: 20629 case BPF_TRACE_FEXIT: 20630 case BPF_MODIFY_RETURN: 20631 case BPF_TRACE_ITER: 20632 return true; 20633 default: 20634 return false; 20635 } 20636 } 20637 return prog->type == BPF_PROG_TYPE_LSM || 20638 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 20639 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 20640 } 20641 20642 static int check_attach_btf_id(struct bpf_verifier_env *env) 20643 { 20644 struct bpf_prog *prog = env->prog; 20645 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 20646 struct bpf_attach_target_info tgt_info = {}; 20647 u32 btf_id = prog->aux->attach_btf_id; 20648 struct bpf_trampoline *tr; 20649 int ret; 20650 u64 key; 20651 20652 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 20653 if (prog->aux->sleepable) 20654 /* attach_btf_id checked to be zero already */ 20655 return 0; 20656 verbose(env, "Syscall programs can only be sleepable\n"); 20657 return -EINVAL; 20658 } 20659 20660 if (prog->aux->sleepable && !can_be_sleepable(prog)) { 20661 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 20662 return -EINVAL; 20663 } 20664 20665 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 20666 return check_struct_ops_btf_id(env); 20667 20668 if (prog->type != BPF_PROG_TYPE_TRACING && 20669 prog->type != BPF_PROG_TYPE_LSM && 20670 prog->type != BPF_PROG_TYPE_EXT) 20671 return 0; 20672 20673 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 20674 if (ret) 20675 return ret; 20676 20677 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 20678 /* to make freplace equivalent to their targets, they need to 20679 * inherit env->ops and expected_attach_type for the rest of the 20680 * verification 20681 */ 20682 env->ops = bpf_verifier_ops[tgt_prog->type]; 20683 prog->expected_attach_type = tgt_prog->expected_attach_type; 20684 } 20685 20686 /* store info about the attachment target that will be used later */ 20687 prog->aux->attach_func_proto = tgt_info.tgt_type; 20688 prog->aux->attach_func_name = tgt_info.tgt_name; 20689 prog->aux->mod = tgt_info.tgt_mod; 20690 20691 if (tgt_prog) { 20692 prog->aux->saved_dst_prog_type = tgt_prog->type; 20693 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 20694 } 20695 20696 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 20697 prog->aux->attach_btf_trace = true; 20698 return 0; 20699 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 20700 if (!bpf_iter_prog_supported(prog)) 20701 return -EINVAL; 20702 return 0; 20703 } 20704 20705 if (prog->type == BPF_PROG_TYPE_LSM) { 20706 ret = bpf_lsm_verify_prog(&env->log, prog); 20707 if (ret < 0) 20708 return ret; 20709 } else if (prog->type == BPF_PROG_TYPE_TRACING && 20710 btf_id_set_contains(&btf_id_deny, btf_id)) { 20711 return -EINVAL; 20712 } 20713 20714 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 20715 tr = bpf_trampoline_get(key, &tgt_info); 20716 if (!tr) 20717 return -ENOMEM; 20718 20719 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 20720 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 20721 20722 prog->aux->dst_trampoline = tr; 20723 return 0; 20724 } 20725 20726 struct btf *bpf_get_btf_vmlinux(void) 20727 { 20728 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 20729 mutex_lock(&bpf_verifier_lock); 20730 if (!btf_vmlinux) 20731 btf_vmlinux = btf_parse_vmlinux(); 20732 mutex_unlock(&bpf_verifier_lock); 20733 } 20734 return btf_vmlinux; 20735 } 20736 20737 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 20738 { 20739 u64 start_time = ktime_get_ns(); 20740 struct bpf_verifier_env *env; 20741 int i, len, ret = -EINVAL, err; 20742 u32 log_true_size; 20743 bool is_priv; 20744 20745 /* no program is valid */ 20746 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 20747 return -EINVAL; 20748 20749 /* 'struct bpf_verifier_env' can be global, but since it's not small, 20750 * allocate/free it every time bpf_check() is called 20751 */ 20752 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 20753 if (!env) 20754 return -ENOMEM; 20755 20756 env->bt.env = env; 20757 20758 len = (*prog)->len; 20759 env->insn_aux_data = 20760 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 20761 ret = -ENOMEM; 20762 if (!env->insn_aux_data) 20763 goto err_free_env; 20764 for (i = 0; i < len; i++) 20765 env->insn_aux_data[i].orig_idx = i; 20766 env->prog = *prog; 20767 env->ops = bpf_verifier_ops[env->prog->type]; 20768 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 20769 is_priv = bpf_capable(); 20770 20771 bpf_get_btf_vmlinux(); 20772 20773 /* grab the mutex to protect few globals used by verifier */ 20774 if (!is_priv) 20775 mutex_lock(&bpf_verifier_lock); 20776 20777 /* user could have requested verbose verifier output 20778 * and supplied buffer to store the verification trace 20779 */ 20780 ret = bpf_vlog_init(&env->log, attr->log_level, 20781 (char __user *) (unsigned long) attr->log_buf, 20782 attr->log_size); 20783 if (ret) 20784 goto err_unlock; 20785 20786 mark_verifier_state_clean(env); 20787 20788 if (IS_ERR(btf_vmlinux)) { 20789 /* Either gcc or pahole or kernel are broken. */ 20790 verbose(env, "in-kernel BTF is malformed\n"); 20791 ret = PTR_ERR(btf_vmlinux); 20792 goto skip_full_check; 20793 } 20794 20795 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 20796 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 20797 env->strict_alignment = true; 20798 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 20799 env->strict_alignment = false; 20800 20801 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 20802 env->allow_uninit_stack = bpf_allow_uninit_stack(); 20803 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 20804 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 20805 env->bpf_capable = bpf_capable(); 20806 20807 if (is_priv) 20808 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 20809 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 20810 20811 env->explored_states = kvcalloc(state_htab_size(env), 20812 sizeof(struct bpf_verifier_state_list *), 20813 GFP_USER); 20814 ret = -ENOMEM; 20815 if (!env->explored_states) 20816 goto skip_full_check; 20817 20818 ret = check_btf_info_early(env, attr, uattr); 20819 if (ret < 0) 20820 goto skip_full_check; 20821 20822 ret = add_subprog_and_kfunc(env); 20823 if (ret < 0) 20824 goto skip_full_check; 20825 20826 ret = check_subprogs(env); 20827 if (ret < 0) 20828 goto skip_full_check; 20829 20830 ret = check_btf_info(env, attr, uattr); 20831 if (ret < 0) 20832 goto skip_full_check; 20833 20834 ret = check_attach_btf_id(env); 20835 if (ret) 20836 goto skip_full_check; 20837 20838 ret = resolve_pseudo_ldimm64(env); 20839 if (ret < 0) 20840 goto skip_full_check; 20841 20842 if (bpf_prog_is_offloaded(env->prog->aux)) { 20843 ret = bpf_prog_offload_verifier_prep(env->prog); 20844 if (ret) 20845 goto skip_full_check; 20846 } 20847 20848 ret = check_cfg(env); 20849 if (ret < 0) 20850 goto skip_full_check; 20851 20852 ret = do_check_main(env); 20853 ret = ret ?: do_check_subprogs(env); 20854 20855 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 20856 ret = bpf_prog_offload_finalize(env); 20857 20858 skip_full_check: 20859 kvfree(env->explored_states); 20860 20861 if (ret == 0) 20862 ret = check_max_stack_depth(env); 20863 20864 /* instruction rewrites happen after this point */ 20865 if (ret == 0) 20866 ret = optimize_bpf_loop(env); 20867 20868 if (is_priv) { 20869 if (ret == 0) 20870 opt_hard_wire_dead_code_branches(env); 20871 if (ret == 0) 20872 ret = opt_remove_dead_code(env); 20873 if (ret == 0) 20874 ret = opt_remove_nops(env); 20875 } else { 20876 if (ret == 0) 20877 sanitize_dead_code(env); 20878 } 20879 20880 if (ret == 0) 20881 /* program is valid, convert *(u32*)(ctx + off) accesses */ 20882 ret = convert_ctx_accesses(env); 20883 20884 if (ret == 0) 20885 ret = do_misc_fixups(env); 20886 20887 /* do 32-bit optimization after insn patching has done so those patched 20888 * insns could be handled correctly. 20889 */ 20890 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 20891 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 20892 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 20893 : false; 20894 } 20895 20896 if (ret == 0) 20897 ret = fixup_call_args(env); 20898 20899 env->verification_time = ktime_get_ns() - start_time; 20900 print_verification_stats(env); 20901 env->prog->aux->verified_insns = env->insn_processed; 20902 20903 /* preserve original error even if log finalization is successful */ 20904 err = bpf_vlog_finalize(&env->log, &log_true_size); 20905 if (err) 20906 ret = err; 20907 20908 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 20909 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 20910 &log_true_size, sizeof(log_true_size))) { 20911 ret = -EFAULT; 20912 goto err_release_maps; 20913 } 20914 20915 if (ret) 20916 goto err_release_maps; 20917 20918 if (env->used_map_cnt) { 20919 /* if program passed verifier, update used_maps in bpf_prog_info */ 20920 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 20921 sizeof(env->used_maps[0]), 20922 GFP_KERNEL); 20923 20924 if (!env->prog->aux->used_maps) { 20925 ret = -ENOMEM; 20926 goto err_release_maps; 20927 } 20928 20929 memcpy(env->prog->aux->used_maps, env->used_maps, 20930 sizeof(env->used_maps[0]) * env->used_map_cnt); 20931 env->prog->aux->used_map_cnt = env->used_map_cnt; 20932 } 20933 if (env->used_btf_cnt) { 20934 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 20935 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 20936 sizeof(env->used_btfs[0]), 20937 GFP_KERNEL); 20938 if (!env->prog->aux->used_btfs) { 20939 ret = -ENOMEM; 20940 goto err_release_maps; 20941 } 20942 20943 memcpy(env->prog->aux->used_btfs, env->used_btfs, 20944 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 20945 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 20946 } 20947 if (env->used_map_cnt || env->used_btf_cnt) { 20948 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 20949 * bpf_ld_imm64 instructions 20950 */ 20951 convert_pseudo_ld_imm64(env); 20952 } 20953 20954 adjust_btf_func(env); 20955 20956 err_release_maps: 20957 if (!env->prog->aux->used_maps) 20958 /* if we didn't copy map pointers into bpf_prog_info, release 20959 * them now. Otherwise free_used_maps() will release them. 20960 */ 20961 release_maps(env); 20962 if (!env->prog->aux->used_btfs) 20963 release_btfs(env); 20964 20965 /* extension progs temporarily inherit the attach_type of their targets 20966 for verification purposes, so set it back to zero before returning 20967 */ 20968 if (env->prog->type == BPF_PROG_TYPE_EXT) 20969 env->prog->expected_attach_type = 0; 20970 20971 *prog = env->prog; 20972 err_unlock: 20973 if (!is_priv) 20974 mutex_unlock(&bpf_verifier_lock); 20975 vfree(env->insn_aux_data); 20976 err_free_env: 20977 kfree(env); 20978 return ret; 20979 } 20980