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 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx); 199 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id); 200 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 201 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 202 static int ref_set_non_owning(struct bpf_verifier_env *env, 203 struct bpf_reg_state *reg); 204 static void specialize_kfunc(struct bpf_verifier_env *env, 205 u32 func_id, u16 offset, unsigned long *addr); 206 static bool is_trusted_reg(const struct bpf_reg_state *reg); 207 208 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 209 { 210 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON; 211 } 212 213 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 214 { 215 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV; 216 } 217 218 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 219 const struct bpf_map *map, bool unpriv) 220 { 221 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV); 222 unpriv |= bpf_map_ptr_unpriv(aux); 223 aux->map_ptr_state = (unsigned long)map | 224 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL); 225 } 226 227 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 228 { 229 return aux->map_key_state & BPF_MAP_KEY_POISON; 230 } 231 232 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 233 { 234 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 235 } 236 237 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 238 { 239 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 240 } 241 242 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 243 { 244 bool poisoned = bpf_map_key_poisoned(aux); 245 246 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 247 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 248 } 249 250 static bool bpf_helper_call(const struct bpf_insn *insn) 251 { 252 return insn->code == (BPF_JMP | BPF_CALL) && 253 insn->src_reg == 0; 254 } 255 256 static bool bpf_pseudo_call(const struct bpf_insn *insn) 257 { 258 return insn->code == (BPF_JMP | BPF_CALL) && 259 insn->src_reg == BPF_PSEUDO_CALL; 260 } 261 262 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 263 { 264 return insn->code == (BPF_JMP | BPF_CALL) && 265 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 266 } 267 268 struct bpf_call_arg_meta { 269 struct bpf_map *map_ptr; 270 bool raw_mode; 271 bool pkt_access; 272 u8 release_regno; 273 int regno; 274 int access_size; 275 int mem_size; 276 u64 msize_max_value; 277 int ref_obj_id; 278 int dynptr_id; 279 int map_uid; 280 int func_id; 281 struct btf *btf; 282 u32 btf_id; 283 struct btf *ret_btf; 284 u32 ret_btf_id; 285 u32 subprogno; 286 struct btf_field *kptr_field; 287 }; 288 289 struct bpf_kfunc_call_arg_meta { 290 /* In parameters */ 291 struct btf *btf; 292 u32 func_id; 293 u32 kfunc_flags; 294 const struct btf_type *func_proto; 295 const char *func_name; 296 /* Out parameters */ 297 u32 ref_obj_id; 298 u8 release_regno; 299 bool r0_rdonly; 300 u32 ret_btf_id; 301 u64 r0_size; 302 u32 subprogno; 303 struct { 304 u64 value; 305 bool found; 306 } arg_constant; 307 308 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling, 309 * generally to pass info about user-defined local kptr types to later 310 * verification logic 311 * bpf_obj_drop/bpf_percpu_obj_drop 312 * Record the local kptr type to be drop'd 313 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type) 314 * Record the local kptr type to be refcount_incr'd and use 315 * arg_owning_ref to determine whether refcount_acquire should be 316 * fallible 317 */ 318 struct btf *arg_btf; 319 u32 arg_btf_id; 320 bool arg_owning_ref; 321 322 struct { 323 struct btf_field *field; 324 } arg_list_head; 325 struct { 326 struct btf_field *field; 327 } arg_rbtree_root; 328 struct { 329 enum bpf_dynptr_type type; 330 u32 id; 331 u32 ref_obj_id; 332 } initialized_dynptr; 333 struct { 334 u8 spi; 335 u8 frameno; 336 } iter; 337 u64 mem_size; 338 }; 339 340 struct btf *btf_vmlinux; 341 342 static const char *btf_type_name(const struct btf *btf, u32 id) 343 { 344 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 345 } 346 347 static DEFINE_MUTEX(bpf_verifier_lock); 348 static DEFINE_MUTEX(bpf_percpu_ma_lock); 349 350 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 351 { 352 struct bpf_verifier_env *env = private_data; 353 va_list args; 354 355 if (!bpf_verifier_log_needed(&env->log)) 356 return; 357 358 va_start(args, fmt); 359 bpf_verifier_vlog(&env->log, fmt, args); 360 va_end(args); 361 } 362 363 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 364 struct bpf_reg_state *reg, 365 struct bpf_retval_range range, const char *ctx, 366 const char *reg_name) 367 { 368 bool unknown = true; 369 370 verbose(env, "%s the register %s has", ctx, reg_name); 371 if (reg->smin_value > S64_MIN) { 372 verbose(env, " smin=%lld", reg->smin_value); 373 unknown = false; 374 } 375 if (reg->smax_value < S64_MAX) { 376 verbose(env, " smax=%lld", reg->smax_value); 377 unknown = false; 378 } 379 if (unknown) 380 verbose(env, " unknown scalar value"); 381 verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval); 382 } 383 384 static bool type_may_be_null(u32 type) 385 { 386 return type & PTR_MAYBE_NULL; 387 } 388 389 static bool reg_not_null(const struct bpf_reg_state *reg) 390 { 391 enum bpf_reg_type type; 392 393 type = reg->type; 394 if (type_may_be_null(type)) 395 return false; 396 397 type = base_type(type); 398 return type == PTR_TO_SOCKET || 399 type == PTR_TO_TCP_SOCK || 400 type == PTR_TO_MAP_VALUE || 401 type == PTR_TO_MAP_KEY || 402 type == PTR_TO_SOCK_COMMON || 403 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) || 404 type == PTR_TO_MEM; 405 } 406 407 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 408 { 409 struct btf_record *rec = NULL; 410 struct btf_struct_meta *meta; 411 412 if (reg->type == PTR_TO_MAP_VALUE) { 413 rec = reg->map_ptr->record; 414 } else if (type_is_ptr_alloc_obj(reg->type)) { 415 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 416 if (meta) 417 rec = meta->record; 418 } 419 return rec; 420 } 421 422 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog) 423 { 424 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 425 426 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 427 } 428 429 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog) 430 { 431 struct bpf_func_info *info; 432 433 if (!env->prog->aux->func_info) 434 return ""; 435 436 info = &env->prog->aux->func_info[subprog]; 437 return btf_type_name(env->prog->aux->btf, info->type_id); 438 } 439 440 static struct bpf_func_info_aux *subprog_aux(const struct bpf_verifier_env *env, int subprog) 441 { 442 return &env->prog->aux->func_info_aux[subprog]; 443 } 444 445 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 446 { 447 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK); 448 } 449 450 static bool type_is_rdonly_mem(u32 type) 451 { 452 return type & MEM_RDONLY; 453 } 454 455 static bool is_acquire_function(enum bpf_func_id func_id, 456 const struct bpf_map *map) 457 { 458 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 459 460 if (func_id == BPF_FUNC_sk_lookup_tcp || 461 func_id == BPF_FUNC_sk_lookup_udp || 462 func_id == BPF_FUNC_skc_lookup_tcp || 463 func_id == BPF_FUNC_ringbuf_reserve || 464 func_id == BPF_FUNC_kptr_xchg) 465 return true; 466 467 if (func_id == BPF_FUNC_map_lookup_elem && 468 (map_type == BPF_MAP_TYPE_SOCKMAP || 469 map_type == BPF_MAP_TYPE_SOCKHASH)) 470 return true; 471 472 return false; 473 } 474 475 static bool is_ptr_cast_function(enum bpf_func_id func_id) 476 { 477 return func_id == BPF_FUNC_tcp_sock || 478 func_id == BPF_FUNC_sk_fullsock || 479 func_id == BPF_FUNC_skc_to_tcp_sock || 480 func_id == BPF_FUNC_skc_to_tcp6_sock || 481 func_id == BPF_FUNC_skc_to_udp6_sock || 482 func_id == BPF_FUNC_skc_to_mptcp_sock || 483 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 484 func_id == BPF_FUNC_skc_to_tcp_request_sock; 485 } 486 487 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 488 { 489 return func_id == BPF_FUNC_dynptr_data; 490 } 491 492 static bool is_sync_callback_calling_kfunc(u32 btf_id); 493 static bool is_bpf_throw_kfunc(struct bpf_insn *insn); 494 495 static bool is_sync_callback_calling_function(enum bpf_func_id func_id) 496 { 497 return func_id == BPF_FUNC_for_each_map_elem || 498 func_id == BPF_FUNC_find_vma || 499 func_id == BPF_FUNC_loop || 500 func_id == BPF_FUNC_user_ringbuf_drain; 501 } 502 503 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 504 { 505 return func_id == BPF_FUNC_timer_set_callback; 506 } 507 508 static bool is_callback_calling_function(enum bpf_func_id func_id) 509 { 510 return is_sync_callback_calling_function(func_id) || 511 is_async_callback_calling_function(func_id); 512 } 513 514 static bool is_sync_callback_calling_insn(struct bpf_insn *insn) 515 { 516 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) || 517 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm)); 518 } 519 520 static bool is_storage_get_function(enum bpf_func_id func_id) 521 { 522 return func_id == BPF_FUNC_sk_storage_get || 523 func_id == BPF_FUNC_inode_storage_get || 524 func_id == BPF_FUNC_task_storage_get || 525 func_id == BPF_FUNC_cgrp_storage_get; 526 } 527 528 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 529 const struct bpf_map *map) 530 { 531 int ref_obj_uses = 0; 532 533 if (is_ptr_cast_function(func_id)) 534 ref_obj_uses++; 535 if (is_acquire_function(func_id, map)) 536 ref_obj_uses++; 537 if (is_dynptr_ref_function(func_id)) 538 ref_obj_uses++; 539 540 return ref_obj_uses > 1; 541 } 542 543 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 544 { 545 return BPF_CLASS(insn->code) == BPF_STX && 546 BPF_MODE(insn->code) == BPF_ATOMIC && 547 insn->imm == BPF_CMPXCHG; 548 } 549 550 static int __get_spi(s32 off) 551 { 552 return (-off - 1) / BPF_REG_SIZE; 553 } 554 555 static struct bpf_func_state *func(struct bpf_verifier_env *env, 556 const struct bpf_reg_state *reg) 557 { 558 struct bpf_verifier_state *cur = env->cur_state; 559 560 return cur->frame[reg->frameno]; 561 } 562 563 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 564 { 565 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 566 567 /* We need to check that slots between [spi - nr_slots + 1, spi] are 568 * within [0, allocated_stack). 569 * 570 * Please note that the spi grows downwards. For example, a dynptr 571 * takes the size of two stack slots; the first slot will be at 572 * spi and the second slot will be at spi - 1. 573 */ 574 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 575 } 576 577 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 578 const char *obj_kind, int nr_slots) 579 { 580 int off, spi; 581 582 if (!tnum_is_const(reg->var_off)) { 583 verbose(env, "%s has to be at a constant offset\n", obj_kind); 584 return -EINVAL; 585 } 586 587 off = reg->off + reg->var_off.value; 588 if (off % BPF_REG_SIZE) { 589 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 590 return -EINVAL; 591 } 592 593 spi = __get_spi(off); 594 if (spi + 1 < nr_slots) { 595 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 596 return -EINVAL; 597 } 598 599 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots)) 600 return -ERANGE; 601 return spi; 602 } 603 604 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 605 { 606 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 607 } 608 609 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 610 { 611 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 612 } 613 614 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 615 { 616 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 617 case DYNPTR_TYPE_LOCAL: 618 return BPF_DYNPTR_TYPE_LOCAL; 619 case DYNPTR_TYPE_RINGBUF: 620 return BPF_DYNPTR_TYPE_RINGBUF; 621 case DYNPTR_TYPE_SKB: 622 return BPF_DYNPTR_TYPE_SKB; 623 case DYNPTR_TYPE_XDP: 624 return BPF_DYNPTR_TYPE_XDP; 625 default: 626 return BPF_DYNPTR_TYPE_INVALID; 627 } 628 } 629 630 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 631 { 632 switch (type) { 633 case BPF_DYNPTR_TYPE_LOCAL: 634 return DYNPTR_TYPE_LOCAL; 635 case BPF_DYNPTR_TYPE_RINGBUF: 636 return DYNPTR_TYPE_RINGBUF; 637 case BPF_DYNPTR_TYPE_SKB: 638 return DYNPTR_TYPE_SKB; 639 case BPF_DYNPTR_TYPE_XDP: 640 return DYNPTR_TYPE_XDP; 641 default: 642 return 0; 643 } 644 } 645 646 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 647 { 648 return type == BPF_DYNPTR_TYPE_RINGBUF; 649 } 650 651 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 652 enum bpf_dynptr_type type, 653 bool first_slot, int dynptr_id); 654 655 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 656 struct bpf_reg_state *reg); 657 658 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 659 struct bpf_reg_state *sreg1, 660 struct bpf_reg_state *sreg2, 661 enum bpf_dynptr_type type) 662 { 663 int id = ++env->id_gen; 664 665 __mark_dynptr_reg(sreg1, type, true, id); 666 __mark_dynptr_reg(sreg2, type, false, id); 667 } 668 669 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 670 struct bpf_reg_state *reg, 671 enum bpf_dynptr_type type) 672 { 673 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 674 } 675 676 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 677 struct bpf_func_state *state, int spi); 678 679 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 680 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id) 681 { 682 struct bpf_func_state *state = func(env, reg); 683 enum bpf_dynptr_type type; 684 int spi, i, err; 685 686 spi = dynptr_get_spi(env, reg); 687 if (spi < 0) 688 return spi; 689 690 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 691 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 692 * to ensure that for the following example: 693 * [d1][d1][d2][d2] 694 * spi 3 2 1 0 695 * So marking spi = 2 should lead to destruction of both d1 and d2. In 696 * case they do belong to same dynptr, second call won't see slot_type 697 * as STACK_DYNPTR and will simply skip destruction. 698 */ 699 err = destroy_if_dynptr_stack_slot(env, state, spi); 700 if (err) 701 return err; 702 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 703 if (err) 704 return err; 705 706 for (i = 0; i < BPF_REG_SIZE; i++) { 707 state->stack[spi].slot_type[i] = STACK_DYNPTR; 708 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 709 } 710 711 type = arg_to_dynptr_type(arg_type); 712 if (type == BPF_DYNPTR_TYPE_INVALID) 713 return -EINVAL; 714 715 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 716 &state->stack[spi - 1].spilled_ptr, type); 717 718 if (dynptr_type_refcounted(type)) { 719 /* The id is used to track proper releasing */ 720 int id; 721 722 if (clone_ref_obj_id) 723 id = clone_ref_obj_id; 724 else 725 id = acquire_reference_state(env, insn_idx); 726 727 if (id < 0) 728 return id; 729 730 state->stack[spi].spilled_ptr.ref_obj_id = id; 731 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 732 } 733 734 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 735 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 736 737 return 0; 738 } 739 740 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi) 741 { 742 int i; 743 744 for (i = 0; i < BPF_REG_SIZE; i++) { 745 state->stack[spi].slot_type[i] = STACK_INVALID; 746 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 747 } 748 749 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 750 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 751 752 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot? 753 * 754 * While we don't allow reading STACK_INVALID, it is still possible to 755 * do <8 byte writes marking some but not all slots as STACK_MISC. Then, 756 * helpers or insns can do partial read of that part without failing, 757 * but check_stack_range_initialized, check_stack_read_var_off, and 758 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of 759 * the slot conservatively. Hence we need to prevent those liveness 760 * marking walks. 761 * 762 * This was not a problem before because STACK_INVALID is only set by 763 * default (where the default reg state has its reg->parent as NULL), or 764 * in clean_live_states after REG_LIVE_DONE (at which point 765 * mark_reg_read won't walk reg->parent chain), but not randomly during 766 * verifier state exploration (like we did above). Hence, for our case 767 * parentage chain will still be live (i.e. reg->parent may be 768 * non-NULL), while earlier reg->parent was NULL, so we need 769 * REG_LIVE_WRITTEN to screen off read marker propagation when it is 770 * done later on reads or by mark_dynptr_read as well to unnecessary 771 * mark registers in verifier state. 772 */ 773 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 774 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 775 } 776 777 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 778 { 779 struct bpf_func_state *state = func(env, reg); 780 int spi, ref_obj_id, i; 781 782 spi = dynptr_get_spi(env, reg); 783 if (spi < 0) 784 return spi; 785 786 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 787 invalidate_dynptr(env, state, spi); 788 return 0; 789 } 790 791 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 792 793 /* If the dynptr has a ref_obj_id, then we need to invalidate 794 * two things: 795 * 796 * 1) Any dynptrs with a matching ref_obj_id (clones) 797 * 2) Any slices derived from this dynptr. 798 */ 799 800 /* Invalidate any slices associated with this dynptr */ 801 WARN_ON_ONCE(release_reference(env, ref_obj_id)); 802 803 /* Invalidate any dynptr clones */ 804 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) { 805 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id) 806 continue; 807 808 /* it should always be the case that if the ref obj id 809 * matches then the stack slot also belongs to a 810 * dynptr 811 */ 812 if (state->stack[i].slot_type[0] != STACK_DYNPTR) { 813 verbose(env, "verifier internal error: misconfigured ref_obj_id\n"); 814 return -EFAULT; 815 } 816 if (state->stack[i].spilled_ptr.dynptr.first_slot) 817 invalidate_dynptr(env, state, i); 818 } 819 820 return 0; 821 } 822 823 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 824 struct bpf_reg_state *reg); 825 826 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 827 { 828 if (!env->allow_ptr_leaks) 829 __mark_reg_not_init(env, reg); 830 else 831 __mark_reg_unknown(env, reg); 832 } 833 834 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 835 struct bpf_func_state *state, int spi) 836 { 837 struct bpf_func_state *fstate; 838 struct bpf_reg_state *dreg; 839 int i, dynptr_id; 840 841 /* We always ensure that STACK_DYNPTR is never set partially, 842 * hence just checking for slot_type[0] is enough. This is 843 * different for STACK_SPILL, where it may be only set for 844 * 1 byte, so code has to use is_spilled_reg. 845 */ 846 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 847 return 0; 848 849 /* Reposition spi to first slot */ 850 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 851 spi = spi + 1; 852 853 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 854 verbose(env, "cannot overwrite referenced dynptr\n"); 855 return -EINVAL; 856 } 857 858 mark_stack_slot_scratched(env, spi); 859 mark_stack_slot_scratched(env, spi - 1); 860 861 /* Writing partially to one dynptr stack slot destroys both. */ 862 for (i = 0; i < BPF_REG_SIZE; i++) { 863 state->stack[spi].slot_type[i] = STACK_INVALID; 864 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 865 } 866 867 dynptr_id = state->stack[spi].spilled_ptr.id; 868 /* Invalidate any slices associated with this dynptr */ 869 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 870 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 871 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 872 continue; 873 if (dreg->dynptr_id == dynptr_id) 874 mark_reg_invalid(env, dreg); 875 })); 876 877 /* Do not release reference state, we are destroying dynptr on stack, 878 * not using some helper to release it. Just reset register. 879 */ 880 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 881 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 882 883 /* Same reason as unmark_stack_slots_dynptr above */ 884 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 885 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 886 887 return 0; 888 } 889 890 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 891 { 892 int spi; 893 894 if (reg->type == CONST_PTR_TO_DYNPTR) 895 return false; 896 897 spi = dynptr_get_spi(env, reg); 898 899 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 900 * error because this just means the stack state hasn't been updated yet. 901 * We will do check_mem_access to check and update stack bounds later. 902 */ 903 if (spi < 0 && spi != -ERANGE) 904 return false; 905 906 /* We don't need to check if the stack slots are marked by previous 907 * dynptr initializations because we allow overwriting existing unreferenced 908 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 909 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 910 * touching are completely destructed before we reinitialize them for a new 911 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 912 * instead of delaying it until the end where the user will get "Unreleased 913 * reference" error. 914 */ 915 return true; 916 } 917 918 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 919 { 920 struct bpf_func_state *state = func(env, reg); 921 int i, spi; 922 923 /* This already represents first slot of initialized bpf_dynptr. 924 * 925 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 926 * check_func_arg_reg_off's logic, so we don't need to check its 927 * offset and alignment. 928 */ 929 if (reg->type == CONST_PTR_TO_DYNPTR) 930 return true; 931 932 spi = dynptr_get_spi(env, reg); 933 if (spi < 0) 934 return false; 935 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 936 return false; 937 938 for (i = 0; i < BPF_REG_SIZE; i++) { 939 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 940 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 941 return false; 942 } 943 944 return true; 945 } 946 947 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 948 enum bpf_arg_type arg_type) 949 { 950 struct bpf_func_state *state = func(env, reg); 951 enum bpf_dynptr_type dynptr_type; 952 int spi; 953 954 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 955 if (arg_type == ARG_PTR_TO_DYNPTR) 956 return true; 957 958 dynptr_type = arg_to_dynptr_type(arg_type); 959 if (reg->type == CONST_PTR_TO_DYNPTR) { 960 return reg->dynptr.type == dynptr_type; 961 } else { 962 spi = dynptr_get_spi(env, reg); 963 if (spi < 0) 964 return false; 965 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 966 } 967 } 968 969 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 970 971 static bool in_rcu_cs(struct bpf_verifier_env *env); 972 973 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta); 974 975 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 976 struct bpf_kfunc_call_arg_meta *meta, 977 struct bpf_reg_state *reg, int insn_idx, 978 struct btf *btf, u32 btf_id, int nr_slots) 979 { 980 struct bpf_func_state *state = func(env, reg); 981 int spi, i, j, id; 982 983 spi = iter_get_spi(env, reg, nr_slots); 984 if (spi < 0) 985 return spi; 986 987 id = acquire_reference_state(env, insn_idx); 988 if (id < 0) 989 return id; 990 991 for (i = 0; i < nr_slots; i++) { 992 struct bpf_stack_state *slot = &state->stack[spi - i]; 993 struct bpf_reg_state *st = &slot->spilled_ptr; 994 995 __mark_reg_known_zero(st); 996 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 997 if (is_kfunc_rcu_protected(meta)) { 998 if (in_rcu_cs(env)) 999 st->type |= MEM_RCU; 1000 else 1001 st->type |= PTR_UNTRUSTED; 1002 } 1003 st->live |= REG_LIVE_WRITTEN; 1004 st->ref_obj_id = i == 0 ? id : 0; 1005 st->iter.btf = btf; 1006 st->iter.btf_id = btf_id; 1007 st->iter.state = BPF_ITER_STATE_ACTIVE; 1008 st->iter.depth = 0; 1009 1010 for (j = 0; j < BPF_REG_SIZE; j++) 1011 slot->slot_type[j] = STACK_ITER; 1012 1013 mark_stack_slot_scratched(env, spi - i); 1014 } 1015 1016 return 0; 1017 } 1018 1019 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 1020 struct bpf_reg_state *reg, int nr_slots) 1021 { 1022 struct bpf_func_state *state = func(env, reg); 1023 int spi, i, j; 1024 1025 spi = iter_get_spi(env, reg, nr_slots); 1026 if (spi < 0) 1027 return spi; 1028 1029 for (i = 0; i < nr_slots; i++) { 1030 struct bpf_stack_state *slot = &state->stack[spi - i]; 1031 struct bpf_reg_state *st = &slot->spilled_ptr; 1032 1033 if (i == 0) 1034 WARN_ON_ONCE(release_reference(env, st->ref_obj_id)); 1035 1036 __mark_reg_not_init(env, st); 1037 1038 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1039 st->live |= REG_LIVE_WRITTEN; 1040 1041 for (j = 0; j < BPF_REG_SIZE; j++) 1042 slot->slot_type[j] = STACK_INVALID; 1043 1044 mark_stack_slot_scratched(env, spi - i); 1045 } 1046 1047 return 0; 1048 } 1049 1050 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1051 struct bpf_reg_state *reg, int nr_slots) 1052 { 1053 struct bpf_func_state *state = func(env, reg); 1054 int spi, i, j; 1055 1056 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1057 * will do check_mem_access to check and update stack bounds later, so 1058 * return true for that case. 1059 */ 1060 spi = iter_get_spi(env, reg, nr_slots); 1061 if (spi == -ERANGE) 1062 return true; 1063 if (spi < 0) 1064 return false; 1065 1066 for (i = 0; i < nr_slots; i++) { 1067 struct bpf_stack_state *slot = &state->stack[spi - i]; 1068 1069 for (j = 0; j < BPF_REG_SIZE; j++) 1070 if (slot->slot_type[j] == STACK_ITER) 1071 return false; 1072 } 1073 1074 return true; 1075 } 1076 1077 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1078 struct btf *btf, u32 btf_id, int nr_slots) 1079 { 1080 struct bpf_func_state *state = func(env, reg); 1081 int spi, i, j; 1082 1083 spi = iter_get_spi(env, reg, nr_slots); 1084 if (spi < 0) 1085 return -EINVAL; 1086 1087 for (i = 0; i < nr_slots; i++) { 1088 struct bpf_stack_state *slot = &state->stack[spi - i]; 1089 struct bpf_reg_state *st = &slot->spilled_ptr; 1090 1091 if (st->type & PTR_UNTRUSTED) 1092 return -EPROTO; 1093 /* only main (first) slot has ref_obj_id set */ 1094 if (i == 0 && !st->ref_obj_id) 1095 return -EINVAL; 1096 if (i != 0 && st->ref_obj_id) 1097 return -EINVAL; 1098 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1099 return -EINVAL; 1100 1101 for (j = 0; j < BPF_REG_SIZE; j++) 1102 if (slot->slot_type[j] != STACK_ITER) 1103 return -EINVAL; 1104 } 1105 1106 return 0; 1107 } 1108 1109 /* Check if given stack slot is "special": 1110 * - spilled register state (STACK_SPILL); 1111 * - dynptr state (STACK_DYNPTR); 1112 * - iter state (STACK_ITER). 1113 */ 1114 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1115 { 1116 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1117 1118 switch (type) { 1119 case STACK_SPILL: 1120 case STACK_DYNPTR: 1121 case STACK_ITER: 1122 return true; 1123 case STACK_INVALID: 1124 case STACK_MISC: 1125 case STACK_ZERO: 1126 return false; 1127 default: 1128 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1129 return true; 1130 } 1131 } 1132 1133 /* The reg state of a pointer or a bounded scalar was saved when 1134 * it was spilled to the stack. 1135 */ 1136 static bool is_spilled_reg(const struct bpf_stack_state *stack) 1137 { 1138 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1139 } 1140 1141 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack) 1142 { 1143 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL && 1144 stack->spilled_ptr.type == SCALAR_VALUE; 1145 } 1146 1147 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which 1148 * case they are equivalent, or it's STACK_ZERO, in which case we preserve 1149 * more precise STACK_ZERO. 1150 * Note, in uprivileged mode leaving STACK_INVALID is wrong, so we take 1151 * env->allow_ptr_leaks into account and force STACK_MISC, if necessary. 1152 */ 1153 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype) 1154 { 1155 if (*stype == STACK_ZERO) 1156 return; 1157 if (env->allow_ptr_leaks && *stype == STACK_INVALID) 1158 return; 1159 *stype = STACK_MISC; 1160 } 1161 1162 static void scrub_spilled_slot(u8 *stype) 1163 { 1164 if (*stype != STACK_INVALID) 1165 *stype = STACK_MISC; 1166 } 1167 1168 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1169 * small to hold src. This is different from krealloc since we don't want to preserve 1170 * the contents of dst. 1171 * 1172 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1173 * not be allocated. 1174 */ 1175 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1176 { 1177 size_t alloc_bytes; 1178 void *orig = dst; 1179 size_t bytes; 1180 1181 if (ZERO_OR_NULL_PTR(src)) 1182 goto out; 1183 1184 if (unlikely(check_mul_overflow(n, size, &bytes))) 1185 return NULL; 1186 1187 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1188 dst = krealloc(orig, alloc_bytes, flags); 1189 if (!dst) { 1190 kfree(orig); 1191 return NULL; 1192 } 1193 1194 memcpy(dst, src, bytes); 1195 out: 1196 return dst ? dst : ZERO_SIZE_PTR; 1197 } 1198 1199 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1200 * small to hold new_n items. new items are zeroed out if the array grows. 1201 * 1202 * Contrary to krealloc_array, does not free arr if new_n is zero. 1203 */ 1204 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1205 { 1206 size_t alloc_size; 1207 void *new_arr; 1208 1209 if (!new_n || old_n == new_n) 1210 goto out; 1211 1212 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1213 new_arr = krealloc(arr, alloc_size, GFP_KERNEL); 1214 if (!new_arr) { 1215 kfree(arr); 1216 return NULL; 1217 } 1218 arr = new_arr; 1219 1220 if (new_n > old_n) 1221 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1222 1223 out: 1224 return arr ? arr : ZERO_SIZE_PTR; 1225 } 1226 1227 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1228 { 1229 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1230 sizeof(struct bpf_reference_state), GFP_KERNEL); 1231 if (!dst->refs) 1232 return -ENOMEM; 1233 1234 dst->acquired_refs = src->acquired_refs; 1235 return 0; 1236 } 1237 1238 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1239 { 1240 size_t n = src->allocated_stack / BPF_REG_SIZE; 1241 1242 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1243 GFP_KERNEL); 1244 if (!dst->stack) 1245 return -ENOMEM; 1246 1247 dst->allocated_stack = src->allocated_stack; 1248 return 0; 1249 } 1250 1251 static int resize_reference_state(struct bpf_func_state *state, size_t n) 1252 { 1253 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1254 sizeof(struct bpf_reference_state)); 1255 if (!state->refs) 1256 return -ENOMEM; 1257 1258 state->acquired_refs = n; 1259 return 0; 1260 } 1261 1262 /* Possibly update state->allocated_stack to be at least size bytes. Also 1263 * possibly update the function's high-water mark in its bpf_subprog_info. 1264 */ 1265 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) 1266 { 1267 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE; 1268 1269 if (old_n >= n) 1270 return 0; 1271 1272 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1273 if (!state->stack) 1274 return -ENOMEM; 1275 1276 state->allocated_stack = size; 1277 1278 /* update known max for given subprogram */ 1279 if (env->subprog_info[state->subprogno].stack_depth < size) 1280 env->subprog_info[state->subprogno].stack_depth = size; 1281 1282 return 0; 1283 } 1284 1285 /* Acquire a pointer id from the env and update the state->refs to include 1286 * this new pointer reference. 1287 * On success, returns a valid pointer id to associate with the register 1288 * On failure, returns a negative errno. 1289 */ 1290 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1291 { 1292 struct bpf_func_state *state = cur_func(env); 1293 int new_ofs = state->acquired_refs; 1294 int id, err; 1295 1296 err = resize_reference_state(state, state->acquired_refs + 1); 1297 if (err) 1298 return err; 1299 id = ++env->id_gen; 1300 state->refs[new_ofs].id = id; 1301 state->refs[new_ofs].insn_idx = insn_idx; 1302 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0; 1303 1304 return id; 1305 } 1306 1307 /* release function corresponding to acquire_reference_state(). Idempotent. */ 1308 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 1309 { 1310 int i, last_idx; 1311 1312 last_idx = state->acquired_refs - 1; 1313 for (i = 0; i < state->acquired_refs; i++) { 1314 if (state->refs[i].id == ptr_id) { 1315 /* Cannot release caller references in callbacks */ 1316 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 1317 return -EINVAL; 1318 if (last_idx && i != last_idx) 1319 memcpy(&state->refs[i], &state->refs[last_idx], 1320 sizeof(*state->refs)); 1321 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1322 state->acquired_refs--; 1323 return 0; 1324 } 1325 } 1326 return -EINVAL; 1327 } 1328 1329 static void free_func_state(struct bpf_func_state *state) 1330 { 1331 if (!state) 1332 return; 1333 kfree(state->refs); 1334 kfree(state->stack); 1335 kfree(state); 1336 } 1337 1338 static void clear_jmp_history(struct bpf_verifier_state *state) 1339 { 1340 kfree(state->jmp_history); 1341 state->jmp_history = NULL; 1342 state->jmp_history_cnt = 0; 1343 } 1344 1345 static void free_verifier_state(struct bpf_verifier_state *state, 1346 bool free_self) 1347 { 1348 int i; 1349 1350 for (i = 0; i <= state->curframe; i++) { 1351 free_func_state(state->frame[i]); 1352 state->frame[i] = NULL; 1353 } 1354 clear_jmp_history(state); 1355 if (free_self) 1356 kfree(state); 1357 } 1358 1359 /* copy verifier state from src to dst growing dst stack space 1360 * when necessary to accommodate larger src stack 1361 */ 1362 static int copy_func_state(struct bpf_func_state *dst, 1363 const struct bpf_func_state *src) 1364 { 1365 int err; 1366 1367 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 1368 err = copy_reference_state(dst, src); 1369 if (err) 1370 return err; 1371 return copy_stack_state(dst, src); 1372 } 1373 1374 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1375 const struct bpf_verifier_state *src) 1376 { 1377 struct bpf_func_state *dst; 1378 int i, err; 1379 1380 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1381 src->jmp_history_cnt, sizeof(*dst_state->jmp_history), 1382 GFP_USER); 1383 if (!dst_state->jmp_history) 1384 return -ENOMEM; 1385 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1386 1387 /* if dst has more stack frames then src frame, free them, this is also 1388 * necessary in case of exceptional exits using bpf_throw. 1389 */ 1390 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1391 free_func_state(dst_state->frame[i]); 1392 dst_state->frame[i] = NULL; 1393 } 1394 dst_state->speculative = src->speculative; 1395 dst_state->active_rcu_lock = src->active_rcu_lock; 1396 dst_state->curframe = src->curframe; 1397 dst_state->active_lock.ptr = src->active_lock.ptr; 1398 dst_state->active_lock.id = src->active_lock.id; 1399 dst_state->branches = src->branches; 1400 dst_state->parent = src->parent; 1401 dst_state->first_insn_idx = src->first_insn_idx; 1402 dst_state->last_insn_idx = src->last_insn_idx; 1403 dst_state->dfs_depth = src->dfs_depth; 1404 dst_state->callback_unroll_depth = src->callback_unroll_depth; 1405 dst_state->used_as_loop_entry = src->used_as_loop_entry; 1406 for (i = 0; i <= src->curframe; i++) { 1407 dst = dst_state->frame[i]; 1408 if (!dst) { 1409 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1410 if (!dst) 1411 return -ENOMEM; 1412 dst_state->frame[i] = dst; 1413 } 1414 err = copy_func_state(dst, src->frame[i]); 1415 if (err) 1416 return err; 1417 } 1418 return 0; 1419 } 1420 1421 static u32 state_htab_size(struct bpf_verifier_env *env) 1422 { 1423 return env->prog->len; 1424 } 1425 1426 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx) 1427 { 1428 struct bpf_verifier_state *cur = env->cur_state; 1429 struct bpf_func_state *state = cur->frame[cur->curframe]; 1430 1431 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 1432 } 1433 1434 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b) 1435 { 1436 int fr; 1437 1438 if (a->curframe != b->curframe) 1439 return false; 1440 1441 for (fr = a->curframe; fr >= 0; fr--) 1442 if (a->frame[fr]->callsite != b->frame[fr]->callsite) 1443 return false; 1444 1445 return true; 1446 } 1447 1448 /* Open coded iterators allow back-edges in the state graph in order to 1449 * check unbounded loops that iterators. 1450 * 1451 * In is_state_visited() it is necessary to know if explored states are 1452 * part of some loops in order to decide whether non-exact states 1453 * comparison could be used: 1454 * - non-exact states comparison establishes sub-state relation and uses 1455 * read and precision marks to do so, these marks are propagated from 1456 * children states and thus are not guaranteed to be final in a loop; 1457 * - exact states comparison just checks if current and explored states 1458 * are identical (and thus form a back-edge). 1459 * 1460 * Paper "A New Algorithm for Identifying Loops in Decompilation" 1461 * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient 1462 * algorithm for loop structure detection and gives an overview of 1463 * relevant terminology. It also has helpful illustrations. 1464 * 1465 * [1] https://api.semanticscholar.org/CorpusID:15784067 1466 * 1467 * We use a similar algorithm but because loop nested structure is 1468 * irrelevant for verifier ours is significantly simpler and resembles 1469 * strongly connected components algorithm from Sedgewick's textbook. 1470 * 1471 * Define topmost loop entry as a first node of the loop traversed in a 1472 * depth first search starting from initial state. The goal of the loop 1473 * tracking algorithm is to associate topmost loop entries with states 1474 * derived from these entries. 1475 * 1476 * For each step in the DFS states traversal algorithm needs to identify 1477 * the following situations: 1478 * 1479 * initial initial initial 1480 * | | | 1481 * V V V 1482 * ... ... .---------> hdr 1483 * | | | | 1484 * V V | V 1485 * cur .-> succ | .------... 1486 * | | | | | | 1487 * V | V | V V 1488 * succ '-- cur | ... ... 1489 * | | | 1490 * | V V 1491 * | succ <- cur 1492 * | | 1493 * | V 1494 * | ... 1495 * | | 1496 * '----' 1497 * 1498 * (A) successor state of cur (B) successor state of cur or it's entry 1499 * not yet traversed are in current DFS path, thus cur and succ 1500 * are members of the same outermost loop 1501 * 1502 * initial initial 1503 * | | 1504 * V V 1505 * ... ... 1506 * | | 1507 * V V 1508 * .------... .------... 1509 * | | | | 1510 * V V V V 1511 * .-> hdr ... ... ... 1512 * | | | | | 1513 * | V V V V 1514 * | succ <- cur succ <- cur 1515 * | | | 1516 * | V V 1517 * | ... ... 1518 * | | | 1519 * '----' exit 1520 * 1521 * (C) successor state of cur is a part of some loop but this loop 1522 * does not include cur or successor state is not in a loop at all. 1523 * 1524 * Algorithm could be described as the following python code: 1525 * 1526 * traversed = set() # Set of traversed nodes 1527 * entries = {} # Mapping from node to loop entry 1528 * depths = {} # Depth level assigned to graph node 1529 * path = set() # Current DFS path 1530 * 1531 * # Find outermost loop entry known for n 1532 * def get_loop_entry(n): 1533 * h = entries.get(n, None) 1534 * while h in entries and entries[h] != h: 1535 * h = entries[h] 1536 * return h 1537 * 1538 * # Update n's loop entry if h's outermost entry comes 1539 * # before n's outermost entry in current DFS path. 1540 * def update_loop_entry(n, h): 1541 * n1 = get_loop_entry(n) or n 1542 * h1 = get_loop_entry(h) or h 1543 * if h1 in path and depths[h1] <= depths[n1]: 1544 * entries[n] = h1 1545 * 1546 * def dfs(n, depth): 1547 * traversed.add(n) 1548 * path.add(n) 1549 * depths[n] = depth 1550 * for succ in G.successors(n): 1551 * if succ not in traversed: 1552 * # Case A: explore succ and update cur's loop entry 1553 * # only if succ's entry is in current DFS path. 1554 * dfs(succ, depth + 1) 1555 * h = get_loop_entry(succ) 1556 * update_loop_entry(n, h) 1557 * else: 1558 * # Case B or C depending on `h1 in path` check in update_loop_entry(). 1559 * update_loop_entry(n, succ) 1560 * path.remove(n) 1561 * 1562 * To adapt this algorithm for use with verifier: 1563 * - use st->branch == 0 as a signal that DFS of succ had been finished 1564 * and cur's loop entry has to be updated (case A), handle this in 1565 * update_branch_counts(); 1566 * - use st->branch > 0 as a signal that st is in the current DFS path; 1567 * - handle cases B and C in is_state_visited(); 1568 * - update topmost loop entry for intermediate states in get_loop_entry(). 1569 */ 1570 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st) 1571 { 1572 struct bpf_verifier_state *topmost = st->loop_entry, *old; 1573 1574 while (topmost && topmost->loop_entry && topmost != topmost->loop_entry) 1575 topmost = topmost->loop_entry; 1576 /* Update loop entries for intermediate states to avoid this 1577 * traversal in future get_loop_entry() calls. 1578 */ 1579 while (st && st->loop_entry != topmost) { 1580 old = st->loop_entry; 1581 st->loop_entry = topmost; 1582 st = old; 1583 } 1584 return topmost; 1585 } 1586 1587 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr) 1588 { 1589 struct bpf_verifier_state *cur1, *hdr1; 1590 1591 cur1 = get_loop_entry(cur) ?: cur; 1592 hdr1 = get_loop_entry(hdr) ?: hdr; 1593 /* The head1->branches check decides between cases B and C in 1594 * comment for get_loop_entry(). If hdr1->branches == 0 then 1595 * head's topmost loop entry is not in current DFS path, 1596 * hence 'cur' and 'hdr' are not in the same loop and there is 1597 * no need to update cur->loop_entry. 1598 */ 1599 if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) { 1600 cur->loop_entry = hdr; 1601 hdr->used_as_loop_entry = true; 1602 } 1603 } 1604 1605 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1606 { 1607 while (st) { 1608 u32 br = --st->branches; 1609 1610 /* br == 0 signals that DFS exploration for 'st' is finished, 1611 * thus it is necessary to update parent's loop entry if it 1612 * turned out that st is a part of some loop. 1613 * This is a part of 'case A' in get_loop_entry() comment. 1614 */ 1615 if (br == 0 && st->parent && st->loop_entry) 1616 update_loop_entry(st->parent, st->loop_entry); 1617 1618 /* WARN_ON(br > 1) technically makes sense here, 1619 * but see comment in push_stack(), hence: 1620 */ 1621 WARN_ONCE((int)br < 0, 1622 "BUG update_branch_counts:branches_to_explore=%d\n", 1623 br); 1624 if (br) 1625 break; 1626 st = st->parent; 1627 } 1628 } 1629 1630 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1631 int *insn_idx, bool pop_log) 1632 { 1633 struct bpf_verifier_state *cur = env->cur_state; 1634 struct bpf_verifier_stack_elem *elem, *head = env->head; 1635 int err; 1636 1637 if (env->head == NULL) 1638 return -ENOENT; 1639 1640 if (cur) { 1641 err = copy_verifier_state(cur, &head->st); 1642 if (err) 1643 return err; 1644 } 1645 if (pop_log) 1646 bpf_vlog_reset(&env->log, head->log_pos); 1647 if (insn_idx) 1648 *insn_idx = head->insn_idx; 1649 if (prev_insn_idx) 1650 *prev_insn_idx = head->prev_insn_idx; 1651 elem = head->next; 1652 free_verifier_state(&head->st, false); 1653 kfree(head); 1654 env->head = elem; 1655 env->stack_size--; 1656 return 0; 1657 } 1658 1659 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1660 int insn_idx, int prev_insn_idx, 1661 bool speculative) 1662 { 1663 struct bpf_verifier_state *cur = env->cur_state; 1664 struct bpf_verifier_stack_elem *elem; 1665 int err; 1666 1667 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1668 if (!elem) 1669 goto err; 1670 1671 elem->insn_idx = insn_idx; 1672 elem->prev_insn_idx = prev_insn_idx; 1673 elem->next = env->head; 1674 elem->log_pos = env->log.end_pos; 1675 env->head = elem; 1676 env->stack_size++; 1677 err = copy_verifier_state(&elem->st, cur); 1678 if (err) 1679 goto err; 1680 elem->st.speculative |= speculative; 1681 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1682 verbose(env, "The sequence of %d jumps is too complex.\n", 1683 env->stack_size); 1684 goto err; 1685 } 1686 if (elem->st.parent) { 1687 ++elem->st.parent->branches; 1688 /* WARN_ON(branches > 2) technically makes sense here, 1689 * but 1690 * 1. speculative states will bump 'branches' for non-branch 1691 * instructions 1692 * 2. is_state_visited() heuristics may decide not to create 1693 * a new state for a sequence of branches and all such current 1694 * and cloned states will be pointing to a single parent state 1695 * which might have large 'branches' count. 1696 */ 1697 } 1698 return &elem->st; 1699 err: 1700 free_verifier_state(env->cur_state, true); 1701 env->cur_state = NULL; 1702 /* pop all elements and return */ 1703 while (!pop_stack(env, NULL, NULL, false)); 1704 return NULL; 1705 } 1706 1707 #define CALLER_SAVED_REGS 6 1708 static const int caller_saved[CALLER_SAVED_REGS] = { 1709 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1710 }; 1711 1712 /* This helper doesn't clear reg->id */ 1713 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1714 { 1715 reg->var_off = tnum_const(imm); 1716 reg->smin_value = (s64)imm; 1717 reg->smax_value = (s64)imm; 1718 reg->umin_value = imm; 1719 reg->umax_value = imm; 1720 1721 reg->s32_min_value = (s32)imm; 1722 reg->s32_max_value = (s32)imm; 1723 reg->u32_min_value = (u32)imm; 1724 reg->u32_max_value = (u32)imm; 1725 } 1726 1727 /* Mark the unknown part of a register (variable offset or scalar value) as 1728 * known to have the value @imm. 1729 */ 1730 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1731 { 1732 /* Clear off and union(map_ptr, range) */ 1733 memset(((u8 *)reg) + sizeof(reg->type), 0, 1734 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1735 reg->id = 0; 1736 reg->ref_obj_id = 0; 1737 ___mark_reg_known(reg, imm); 1738 } 1739 1740 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1741 { 1742 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1743 reg->s32_min_value = (s32)imm; 1744 reg->s32_max_value = (s32)imm; 1745 reg->u32_min_value = (u32)imm; 1746 reg->u32_max_value = (u32)imm; 1747 } 1748 1749 /* Mark the 'variable offset' part of a register as zero. This should be 1750 * used only on registers holding a pointer type. 1751 */ 1752 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1753 { 1754 __mark_reg_known(reg, 0); 1755 } 1756 1757 static void __mark_reg_const_zero(struct bpf_reg_state *reg) 1758 { 1759 __mark_reg_known(reg, 0); 1760 reg->type = SCALAR_VALUE; 1761 } 1762 1763 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1764 struct bpf_reg_state *regs, u32 regno) 1765 { 1766 if (WARN_ON(regno >= MAX_BPF_REG)) { 1767 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1768 /* Something bad happened, let's kill all regs */ 1769 for (regno = 0; regno < MAX_BPF_REG; regno++) 1770 __mark_reg_not_init(env, regs + regno); 1771 return; 1772 } 1773 __mark_reg_known_zero(regs + regno); 1774 } 1775 1776 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1777 bool first_slot, int dynptr_id) 1778 { 1779 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1780 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1781 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1782 */ 1783 __mark_reg_known_zero(reg); 1784 reg->type = CONST_PTR_TO_DYNPTR; 1785 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1786 reg->id = dynptr_id; 1787 reg->dynptr.type = type; 1788 reg->dynptr.first_slot = first_slot; 1789 } 1790 1791 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1792 { 1793 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1794 const struct bpf_map *map = reg->map_ptr; 1795 1796 if (map->inner_map_meta) { 1797 reg->type = CONST_PTR_TO_MAP; 1798 reg->map_ptr = map->inner_map_meta; 1799 /* transfer reg's id which is unique for every map_lookup_elem 1800 * as UID of the inner map. 1801 */ 1802 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 1803 reg->map_uid = reg->id; 1804 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1805 reg->type = PTR_TO_XDP_SOCK; 1806 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1807 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1808 reg->type = PTR_TO_SOCKET; 1809 } else { 1810 reg->type = PTR_TO_MAP_VALUE; 1811 } 1812 return; 1813 } 1814 1815 reg->type &= ~PTR_MAYBE_NULL; 1816 } 1817 1818 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 1819 struct btf_field_graph_root *ds_head) 1820 { 1821 __mark_reg_known_zero(®s[regno]); 1822 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 1823 regs[regno].btf = ds_head->btf; 1824 regs[regno].btf_id = ds_head->value_btf_id; 1825 regs[regno].off = ds_head->node_offset; 1826 } 1827 1828 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1829 { 1830 return type_is_pkt_pointer(reg->type); 1831 } 1832 1833 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1834 { 1835 return reg_is_pkt_pointer(reg) || 1836 reg->type == PTR_TO_PACKET_END; 1837 } 1838 1839 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 1840 { 1841 return base_type(reg->type) == PTR_TO_MEM && 1842 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP); 1843 } 1844 1845 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1846 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1847 enum bpf_reg_type which) 1848 { 1849 /* The register can already have a range from prior markings. 1850 * This is fine as long as it hasn't been advanced from its 1851 * origin. 1852 */ 1853 return reg->type == which && 1854 reg->id == 0 && 1855 reg->off == 0 && 1856 tnum_equals_const(reg->var_off, 0); 1857 } 1858 1859 /* Reset the min/max bounds of a register */ 1860 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1861 { 1862 reg->smin_value = S64_MIN; 1863 reg->smax_value = S64_MAX; 1864 reg->umin_value = 0; 1865 reg->umax_value = U64_MAX; 1866 1867 reg->s32_min_value = S32_MIN; 1868 reg->s32_max_value = S32_MAX; 1869 reg->u32_min_value = 0; 1870 reg->u32_max_value = U32_MAX; 1871 } 1872 1873 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1874 { 1875 reg->smin_value = S64_MIN; 1876 reg->smax_value = S64_MAX; 1877 reg->umin_value = 0; 1878 reg->umax_value = U64_MAX; 1879 } 1880 1881 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1882 { 1883 reg->s32_min_value = S32_MIN; 1884 reg->s32_max_value = S32_MAX; 1885 reg->u32_min_value = 0; 1886 reg->u32_max_value = U32_MAX; 1887 } 1888 1889 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1890 { 1891 struct tnum var32_off = tnum_subreg(reg->var_off); 1892 1893 /* min signed is max(sign bit) | min(other bits) */ 1894 reg->s32_min_value = max_t(s32, reg->s32_min_value, 1895 var32_off.value | (var32_off.mask & S32_MIN)); 1896 /* max signed is min(sign bit) | max(other bits) */ 1897 reg->s32_max_value = min_t(s32, reg->s32_max_value, 1898 var32_off.value | (var32_off.mask & S32_MAX)); 1899 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 1900 reg->u32_max_value = min(reg->u32_max_value, 1901 (u32)(var32_off.value | var32_off.mask)); 1902 } 1903 1904 static void __update_reg64_bounds(struct bpf_reg_state *reg) 1905 { 1906 /* min signed is max(sign bit) | min(other bits) */ 1907 reg->smin_value = max_t(s64, reg->smin_value, 1908 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 1909 /* max signed is min(sign bit) | max(other bits) */ 1910 reg->smax_value = min_t(s64, reg->smax_value, 1911 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 1912 reg->umin_value = max(reg->umin_value, reg->var_off.value); 1913 reg->umax_value = min(reg->umax_value, 1914 reg->var_off.value | reg->var_off.mask); 1915 } 1916 1917 static void __update_reg_bounds(struct bpf_reg_state *reg) 1918 { 1919 __update_reg32_bounds(reg); 1920 __update_reg64_bounds(reg); 1921 } 1922 1923 /* Uses signed min/max values to inform unsigned, and vice-versa */ 1924 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 1925 { 1926 /* If upper 32 bits of u64/s64 range don't change, we can use lower 32 1927 * bits to improve our u32/s32 boundaries. 1928 * 1929 * E.g., the case where we have upper 32 bits as zero ([10, 20] in 1930 * u64) is pretty trivial, it's obvious that in u32 we'll also have 1931 * [10, 20] range. But this property holds for any 64-bit range as 1932 * long as upper 32 bits in that entire range of values stay the same. 1933 * 1934 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311] 1935 * in decimal) has the same upper 32 bits throughout all the values in 1936 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15]) 1937 * range. 1938 * 1939 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32, 1940 * following the rules outlined below about u64/s64 correspondence 1941 * (which equally applies to u32 vs s32 correspondence). In general it 1942 * depends on actual hexadecimal values of 32-bit range. They can form 1943 * only valid u32, or only valid s32 ranges in some cases. 1944 * 1945 * So we use all these insights to derive bounds for subregisters here. 1946 */ 1947 if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) { 1948 /* u64 to u32 casting preserves validity of low 32 bits as 1949 * a range, if upper 32 bits are the same 1950 */ 1951 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value); 1952 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value); 1953 1954 if ((s32)reg->umin_value <= (s32)reg->umax_value) { 1955 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 1956 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 1957 } 1958 } 1959 if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) { 1960 /* low 32 bits should form a proper u32 range */ 1961 if ((u32)reg->smin_value <= (u32)reg->smax_value) { 1962 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value); 1963 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value); 1964 } 1965 /* low 32 bits should form a proper s32 range */ 1966 if ((s32)reg->smin_value <= (s32)reg->smax_value) { 1967 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 1968 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 1969 } 1970 } 1971 /* Special case where upper bits form a small sequence of two 1972 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to 1973 * 0x00000000 is also valid), while lower bits form a proper s32 range 1974 * going from negative numbers to positive numbers. E.g., let's say we 1975 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]). 1976 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff, 1977 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits, 1978 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]). 1979 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in 1980 * upper 32 bits. As a random example, s64 range 1981 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range 1982 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister. 1983 */ 1984 if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) && 1985 (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) { 1986 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 1987 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 1988 } 1989 if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) && 1990 (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) { 1991 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 1992 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 1993 } 1994 /* if u32 range forms a valid s32 range (due to matching sign bit), 1995 * try to learn from that 1996 */ 1997 if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) { 1998 reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value); 1999 reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value); 2000 } 2001 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2002 * are the same, so combine. This works even in the negative case, e.g. 2003 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2004 */ 2005 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2006 reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value); 2007 reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value); 2008 } 2009 } 2010 2011 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 2012 { 2013 /* If u64 range forms a valid s64 range (due to matching sign bit), 2014 * try to learn from that. Let's do a bit of ASCII art to see when 2015 * this is happening. Let's take u64 range first: 2016 * 2017 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2018 * |-------------------------------|--------------------------------| 2019 * 2020 * Valid u64 range is formed when umin and umax are anywhere in the 2021 * range [0, U64_MAX], and umin <= umax. u64 case is simple and 2022 * straightforward. Let's see how s64 range maps onto the same range 2023 * of values, annotated below the line for comparison: 2024 * 2025 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2026 * |-------------------------------|--------------------------------| 2027 * 0 S64_MAX S64_MIN -1 2028 * 2029 * So s64 values basically start in the middle and they are logically 2030 * contiguous to the right of it, wrapping around from -1 to 0, and 2031 * then finishing as S64_MAX (0x7fffffffffffffff) right before 2032 * S64_MIN. We can try drawing the continuity of u64 vs s64 values 2033 * more visually as mapped to sign-agnostic range of hex values. 2034 * 2035 * u64 start u64 end 2036 * _______________________________________________________________ 2037 * / \ 2038 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2039 * |-------------------------------|--------------------------------| 2040 * 0 S64_MAX S64_MIN -1 2041 * / \ 2042 * >------------------------------ -------------------------------> 2043 * s64 continues... s64 end s64 start s64 "midpoint" 2044 * 2045 * What this means is that, in general, we can't always derive 2046 * something new about u64 from any random s64 range, and vice versa. 2047 * 2048 * But we can do that in two particular cases. One is when entire 2049 * u64/s64 range is *entirely* contained within left half of the above 2050 * diagram or when it is *entirely* contained in the right half. I.e.: 2051 * 2052 * |-------------------------------|--------------------------------| 2053 * ^ ^ ^ ^ 2054 * A B C D 2055 * 2056 * [A, B] and [C, D] are contained entirely in their respective halves 2057 * and form valid contiguous ranges as both u64 and s64 values. [A, B] 2058 * will be non-negative both as u64 and s64 (and in fact it will be 2059 * identical ranges no matter the signedness). [C, D] treated as s64 2060 * will be a range of negative values, while in u64 it will be 2061 * non-negative range of values larger than 0x8000000000000000. 2062 * 2063 * Now, any other range here can't be represented in both u64 and s64 2064 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid 2065 * contiguous u64 ranges, but they are discontinuous in s64. [B, C] 2066 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX], 2067 * for example. Similarly, valid s64 range [D, A] (going from negative 2068 * to positive values), would be two separate [D, U64_MAX] and [0, A] 2069 * ranges as u64. Currently reg_state can't represent two segments per 2070 * numeric domain, so in such situations we can only derive maximal 2071 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64). 2072 * 2073 * So we use these facts to derive umin/umax from smin/smax and vice 2074 * versa only if they stay within the same "half". This is equivalent 2075 * to checking sign bit: lower half will have sign bit as zero, upper 2076 * half have sign bit 1. Below in code we simplify this by just 2077 * casting umin/umax as smin/smax and checking if they form valid 2078 * range, and vice versa. Those are equivalent checks. 2079 */ 2080 if ((s64)reg->umin_value <= (s64)reg->umax_value) { 2081 reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value); 2082 reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value); 2083 } 2084 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2085 * are the same, so combine. This works even in the negative case, e.g. 2086 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2087 */ 2088 if ((u64)reg->smin_value <= (u64)reg->smax_value) { 2089 reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); 2090 reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); 2091 } 2092 } 2093 2094 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg) 2095 { 2096 /* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit 2097 * values on both sides of 64-bit range in hope to have tigher range. 2098 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from 2099 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff]. 2100 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound 2101 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of 2102 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a 2103 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff]. 2104 * We just need to make sure that derived bounds we are intersecting 2105 * with are well-formed ranges in respecitve s64 or u64 domain, just 2106 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments. 2107 */ 2108 __u64 new_umin, new_umax; 2109 __s64 new_smin, new_smax; 2110 2111 /* u32 -> u64 tightening, it's always well-formed */ 2112 new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value; 2113 new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value; 2114 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2115 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2116 /* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */ 2117 new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value; 2118 new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value; 2119 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2120 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2121 2122 /* if s32 can be treated as valid u32 range, we can use it as well */ 2123 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2124 /* s32 -> u64 tightening */ 2125 new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value; 2126 new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value; 2127 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2128 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2129 /* s32 -> s64 tightening */ 2130 new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value; 2131 new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value; 2132 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2133 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2134 } 2135 } 2136 2137 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2138 { 2139 __reg32_deduce_bounds(reg); 2140 __reg64_deduce_bounds(reg); 2141 __reg_deduce_mixed_bounds(reg); 2142 } 2143 2144 /* Attempts to improve var_off based on unsigned min/max information */ 2145 static void __reg_bound_offset(struct bpf_reg_state *reg) 2146 { 2147 struct tnum var64_off = tnum_intersect(reg->var_off, 2148 tnum_range(reg->umin_value, 2149 reg->umax_value)); 2150 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2151 tnum_range(reg->u32_min_value, 2152 reg->u32_max_value)); 2153 2154 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2155 } 2156 2157 static void reg_bounds_sync(struct bpf_reg_state *reg) 2158 { 2159 /* We might have learned new bounds from the var_off. */ 2160 __update_reg_bounds(reg); 2161 /* We might have learned something about the sign bit. */ 2162 __reg_deduce_bounds(reg); 2163 __reg_deduce_bounds(reg); 2164 /* We might have learned some bits from the bounds. */ 2165 __reg_bound_offset(reg); 2166 /* Intersecting with the old var_off might have improved our bounds 2167 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2168 * then new var_off is (0; 0x7f...fc) which improves our umax. 2169 */ 2170 __update_reg_bounds(reg); 2171 } 2172 2173 static int reg_bounds_sanity_check(struct bpf_verifier_env *env, 2174 struct bpf_reg_state *reg, const char *ctx) 2175 { 2176 const char *msg; 2177 2178 if (reg->umin_value > reg->umax_value || 2179 reg->smin_value > reg->smax_value || 2180 reg->u32_min_value > reg->u32_max_value || 2181 reg->s32_min_value > reg->s32_max_value) { 2182 msg = "range bounds violation"; 2183 goto out; 2184 } 2185 2186 if (tnum_is_const(reg->var_off)) { 2187 u64 uval = reg->var_off.value; 2188 s64 sval = (s64)uval; 2189 2190 if (reg->umin_value != uval || reg->umax_value != uval || 2191 reg->smin_value != sval || reg->smax_value != sval) { 2192 msg = "const tnum out of sync with range bounds"; 2193 goto out; 2194 } 2195 } 2196 2197 if (tnum_subreg_is_const(reg->var_off)) { 2198 u32 uval32 = tnum_subreg(reg->var_off).value; 2199 s32 sval32 = (s32)uval32; 2200 2201 if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 || 2202 reg->s32_min_value != sval32 || reg->s32_max_value != sval32) { 2203 msg = "const subreg tnum out of sync with range bounds"; 2204 goto out; 2205 } 2206 } 2207 2208 return 0; 2209 out: 2210 verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] " 2211 "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n", 2212 ctx, msg, reg->umin_value, reg->umax_value, 2213 reg->smin_value, reg->smax_value, 2214 reg->u32_min_value, reg->u32_max_value, 2215 reg->s32_min_value, reg->s32_max_value, 2216 reg->var_off.value, reg->var_off.mask); 2217 if (env->test_reg_invariants) 2218 return -EFAULT; 2219 __mark_reg_unbounded(reg); 2220 return 0; 2221 } 2222 2223 static bool __reg32_bound_s64(s32 a) 2224 { 2225 return a >= 0 && a <= S32_MAX; 2226 } 2227 2228 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 2229 { 2230 reg->umin_value = reg->u32_min_value; 2231 reg->umax_value = reg->u32_max_value; 2232 2233 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 2234 * be positive otherwise set to worse case bounds and refine later 2235 * from tnum. 2236 */ 2237 if (__reg32_bound_s64(reg->s32_min_value) && 2238 __reg32_bound_s64(reg->s32_max_value)) { 2239 reg->smin_value = reg->s32_min_value; 2240 reg->smax_value = reg->s32_max_value; 2241 } else { 2242 reg->smin_value = 0; 2243 reg->smax_value = U32_MAX; 2244 } 2245 } 2246 2247 /* Mark a register as having a completely unknown (scalar) value. */ 2248 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2249 struct bpf_reg_state *reg) 2250 { 2251 /* 2252 * Clear type, off, and union(map_ptr, range) and 2253 * padding between 'type' and union 2254 */ 2255 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2256 reg->type = SCALAR_VALUE; 2257 reg->id = 0; 2258 reg->ref_obj_id = 0; 2259 reg->var_off = tnum_unknown; 2260 reg->frameno = 0; 2261 reg->precise = !env->bpf_capable; 2262 __mark_reg_unbounded(reg); 2263 } 2264 2265 static void mark_reg_unknown(struct bpf_verifier_env *env, 2266 struct bpf_reg_state *regs, u32 regno) 2267 { 2268 if (WARN_ON(regno >= MAX_BPF_REG)) { 2269 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 2270 /* Something bad happened, let's kill all regs except FP */ 2271 for (regno = 0; regno < BPF_REG_FP; regno++) 2272 __mark_reg_not_init(env, regs + regno); 2273 return; 2274 } 2275 __mark_reg_unknown(env, regs + regno); 2276 } 2277 2278 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 2279 struct bpf_reg_state *reg) 2280 { 2281 __mark_reg_unknown(env, reg); 2282 reg->type = NOT_INIT; 2283 } 2284 2285 static void mark_reg_not_init(struct bpf_verifier_env *env, 2286 struct bpf_reg_state *regs, u32 regno) 2287 { 2288 if (WARN_ON(regno >= MAX_BPF_REG)) { 2289 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 2290 /* Something bad happened, let's kill all regs except FP */ 2291 for (regno = 0; regno < BPF_REG_FP; regno++) 2292 __mark_reg_not_init(env, regs + regno); 2293 return; 2294 } 2295 __mark_reg_not_init(env, regs + regno); 2296 } 2297 2298 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 2299 struct bpf_reg_state *regs, u32 regno, 2300 enum bpf_reg_type reg_type, 2301 struct btf *btf, u32 btf_id, 2302 enum bpf_type_flag flag) 2303 { 2304 if (reg_type == SCALAR_VALUE) { 2305 mark_reg_unknown(env, regs, regno); 2306 return; 2307 } 2308 mark_reg_known_zero(env, regs, regno); 2309 regs[regno].type = PTR_TO_BTF_ID | flag; 2310 regs[regno].btf = btf; 2311 regs[regno].btf_id = btf_id; 2312 } 2313 2314 #define DEF_NOT_SUBREG (0) 2315 static void init_reg_state(struct bpf_verifier_env *env, 2316 struct bpf_func_state *state) 2317 { 2318 struct bpf_reg_state *regs = state->regs; 2319 int i; 2320 2321 for (i = 0; i < MAX_BPF_REG; i++) { 2322 mark_reg_not_init(env, regs, i); 2323 regs[i].live = REG_LIVE_NONE; 2324 regs[i].parent = NULL; 2325 regs[i].subreg_def = DEF_NOT_SUBREG; 2326 } 2327 2328 /* frame pointer */ 2329 regs[BPF_REG_FP].type = PTR_TO_STACK; 2330 mark_reg_known_zero(env, regs, BPF_REG_FP); 2331 regs[BPF_REG_FP].frameno = state->frameno; 2332 } 2333 2334 static struct bpf_retval_range retval_range(s32 minval, s32 maxval) 2335 { 2336 return (struct bpf_retval_range){ minval, maxval }; 2337 } 2338 2339 #define BPF_MAIN_FUNC (-1) 2340 static void init_func_state(struct bpf_verifier_env *env, 2341 struct bpf_func_state *state, 2342 int callsite, int frameno, int subprogno) 2343 { 2344 state->callsite = callsite; 2345 state->frameno = frameno; 2346 state->subprogno = subprogno; 2347 state->callback_ret_range = retval_range(0, 0); 2348 init_reg_state(env, state); 2349 mark_verifier_state_scratched(env); 2350 } 2351 2352 /* Similar to push_stack(), but for async callbacks */ 2353 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2354 int insn_idx, int prev_insn_idx, 2355 int subprog) 2356 { 2357 struct bpf_verifier_stack_elem *elem; 2358 struct bpf_func_state *frame; 2359 2360 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2361 if (!elem) 2362 goto err; 2363 2364 elem->insn_idx = insn_idx; 2365 elem->prev_insn_idx = prev_insn_idx; 2366 elem->next = env->head; 2367 elem->log_pos = env->log.end_pos; 2368 env->head = elem; 2369 env->stack_size++; 2370 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2371 verbose(env, 2372 "The sequence of %d jumps is too complex for async cb.\n", 2373 env->stack_size); 2374 goto err; 2375 } 2376 /* Unlike push_stack() do not copy_verifier_state(). 2377 * The caller state doesn't matter. 2378 * This is async callback. It starts in a fresh stack. 2379 * Initialize it similar to do_check_common(). 2380 */ 2381 elem->st.branches = 1; 2382 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 2383 if (!frame) 2384 goto err; 2385 init_func_state(env, frame, 2386 BPF_MAIN_FUNC /* callsite */, 2387 0 /* frameno within this callchain */, 2388 subprog /* subprog number within this prog */); 2389 elem->st.frame[0] = frame; 2390 return &elem->st; 2391 err: 2392 free_verifier_state(env->cur_state, true); 2393 env->cur_state = NULL; 2394 /* pop all elements and return */ 2395 while (!pop_stack(env, NULL, NULL, false)); 2396 return NULL; 2397 } 2398 2399 2400 enum reg_arg_type { 2401 SRC_OP, /* register is used as source operand */ 2402 DST_OP, /* register is used as destination operand */ 2403 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2404 }; 2405 2406 static int cmp_subprogs(const void *a, const void *b) 2407 { 2408 return ((struct bpf_subprog_info *)a)->start - 2409 ((struct bpf_subprog_info *)b)->start; 2410 } 2411 2412 static int find_subprog(struct bpf_verifier_env *env, int off) 2413 { 2414 struct bpf_subprog_info *p; 2415 2416 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 2417 sizeof(env->subprog_info[0]), cmp_subprogs); 2418 if (!p) 2419 return -ENOENT; 2420 return p - env->subprog_info; 2421 2422 } 2423 2424 static int add_subprog(struct bpf_verifier_env *env, int off) 2425 { 2426 int insn_cnt = env->prog->len; 2427 int ret; 2428 2429 if (off >= insn_cnt || off < 0) { 2430 verbose(env, "call to invalid destination\n"); 2431 return -EINVAL; 2432 } 2433 ret = find_subprog(env, off); 2434 if (ret >= 0) 2435 return ret; 2436 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2437 verbose(env, "too many subprograms\n"); 2438 return -E2BIG; 2439 } 2440 /* determine subprog starts. The end is one before the next starts */ 2441 env->subprog_info[env->subprog_cnt++].start = off; 2442 sort(env->subprog_info, env->subprog_cnt, 2443 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2444 return env->subprog_cnt - 1; 2445 } 2446 2447 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env) 2448 { 2449 struct bpf_prog_aux *aux = env->prog->aux; 2450 struct btf *btf = aux->btf; 2451 const struct btf_type *t; 2452 u32 main_btf_id, id; 2453 const char *name; 2454 int ret, i; 2455 2456 /* Non-zero func_info_cnt implies valid btf */ 2457 if (!aux->func_info_cnt) 2458 return 0; 2459 main_btf_id = aux->func_info[0].type_id; 2460 2461 t = btf_type_by_id(btf, main_btf_id); 2462 if (!t) { 2463 verbose(env, "invalid btf id for main subprog in func_info\n"); 2464 return -EINVAL; 2465 } 2466 2467 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:"); 2468 if (IS_ERR(name)) { 2469 ret = PTR_ERR(name); 2470 /* If there is no tag present, there is no exception callback */ 2471 if (ret == -ENOENT) 2472 ret = 0; 2473 else if (ret == -EEXIST) 2474 verbose(env, "multiple exception callback tags for main subprog\n"); 2475 return ret; 2476 } 2477 2478 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC); 2479 if (ret < 0) { 2480 verbose(env, "exception callback '%s' could not be found in BTF\n", name); 2481 return ret; 2482 } 2483 id = ret; 2484 t = btf_type_by_id(btf, id); 2485 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) { 2486 verbose(env, "exception callback '%s' must have global linkage\n", name); 2487 return -EINVAL; 2488 } 2489 ret = 0; 2490 for (i = 0; i < aux->func_info_cnt; i++) { 2491 if (aux->func_info[i].type_id != id) 2492 continue; 2493 ret = aux->func_info[i].insn_off; 2494 /* Further func_info and subprog checks will also happen 2495 * later, so assume this is the right insn_off for now. 2496 */ 2497 if (!ret) { 2498 verbose(env, "invalid exception callback insn_off in func_info: 0\n"); 2499 ret = -EINVAL; 2500 } 2501 } 2502 if (!ret) { 2503 verbose(env, "exception callback type id not found in func_info\n"); 2504 ret = -EINVAL; 2505 } 2506 return ret; 2507 } 2508 2509 #define MAX_KFUNC_DESCS 256 2510 #define MAX_KFUNC_BTFS 256 2511 2512 struct bpf_kfunc_desc { 2513 struct btf_func_model func_model; 2514 u32 func_id; 2515 s32 imm; 2516 u16 offset; 2517 unsigned long addr; 2518 }; 2519 2520 struct bpf_kfunc_btf { 2521 struct btf *btf; 2522 struct module *module; 2523 u16 offset; 2524 }; 2525 2526 struct bpf_kfunc_desc_tab { 2527 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during 2528 * verification. JITs do lookups by bpf_insn, where func_id may not be 2529 * available, therefore at the end of verification do_misc_fixups() 2530 * sorts this by imm and offset. 2531 */ 2532 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 2533 u32 nr_descs; 2534 }; 2535 2536 struct bpf_kfunc_btf_tab { 2537 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2538 u32 nr_descs; 2539 }; 2540 2541 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2542 { 2543 const struct bpf_kfunc_desc *d0 = a; 2544 const struct bpf_kfunc_desc *d1 = b; 2545 2546 /* func_id is not greater than BTF_MAX_TYPE */ 2547 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2548 } 2549 2550 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2551 { 2552 const struct bpf_kfunc_btf *d0 = a; 2553 const struct bpf_kfunc_btf *d1 = b; 2554 2555 return d0->offset - d1->offset; 2556 } 2557 2558 static const struct bpf_kfunc_desc * 2559 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2560 { 2561 struct bpf_kfunc_desc desc = { 2562 .func_id = func_id, 2563 .offset = offset, 2564 }; 2565 struct bpf_kfunc_desc_tab *tab; 2566 2567 tab = prog->aux->kfunc_tab; 2568 return bsearch(&desc, tab->descs, tab->nr_descs, 2569 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2570 } 2571 2572 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2573 u16 btf_fd_idx, u8 **func_addr) 2574 { 2575 const struct bpf_kfunc_desc *desc; 2576 2577 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2578 if (!desc) 2579 return -EFAULT; 2580 2581 *func_addr = (u8 *)desc->addr; 2582 return 0; 2583 } 2584 2585 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2586 s16 offset) 2587 { 2588 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2589 struct bpf_kfunc_btf_tab *tab; 2590 struct bpf_kfunc_btf *b; 2591 struct module *mod; 2592 struct btf *btf; 2593 int btf_fd; 2594 2595 tab = env->prog->aux->kfunc_btf_tab; 2596 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2597 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2598 if (!b) { 2599 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2600 verbose(env, "too many different module BTFs\n"); 2601 return ERR_PTR(-E2BIG); 2602 } 2603 2604 if (bpfptr_is_null(env->fd_array)) { 2605 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2606 return ERR_PTR(-EPROTO); 2607 } 2608 2609 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2610 offset * sizeof(btf_fd), 2611 sizeof(btf_fd))) 2612 return ERR_PTR(-EFAULT); 2613 2614 btf = btf_get_by_fd(btf_fd); 2615 if (IS_ERR(btf)) { 2616 verbose(env, "invalid module BTF fd specified\n"); 2617 return btf; 2618 } 2619 2620 if (!btf_is_module(btf)) { 2621 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2622 btf_put(btf); 2623 return ERR_PTR(-EINVAL); 2624 } 2625 2626 mod = btf_try_get_module(btf); 2627 if (!mod) { 2628 btf_put(btf); 2629 return ERR_PTR(-ENXIO); 2630 } 2631 2632 b = &tab->descs[tab->nr_descs++]; 2633 b->btf = btf; 2634 b->module = mod; 2635 b->offset = offset; 2636 2637 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2638 kfunc_btf_cmp_by_off, NULL); 2639 } 2640 return b->btf; 2641 } 2642 2643 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2644 { 2645 if (!tab) 2646 return; 2647 2648 while (tab->nr_descs--) { 2649 module_put(tab->descs[tab->nr_descs].module); 2650 btf_put(tab->descs[tab->nr_descs].btf); 2651 } 2652 kfree(tab); 2653 } 2654 2655 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2656 { 2657 if (offset) { 2658 if (offset < 0) { 2659 /* In the future, this can be allowed to increase limit 2660 * of fd index into fd_array, interpreted as u16. 2661 */ 2662 verbose(env, "negative offset disallowed for kernel module function call\n"); 2663 return ERR_PTR(-EINVAL); 2664 } 2665 2666 return __find_kfunc_desc_btf(env, offset); 2667 } 2668 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2669 } 2670 2671 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 2672 { 2673 const struct btf_type *func, *func_proto; 2674 struct bpf_kfunc_btf_tab *btf_tab; 2675 struct bpf_kfunc_desc_tab *tab; 2676 struct bpf_prog_aux *prog_aux; 2677 struct bpf_kfunc_desc *desc; 2678 const char *func_name; 2679 struct btf *desc_btf; 2680 unsigned long call_imm; 2681 unsigned long addr; 2682 int err; 2683 2684 prog_aux = env->prog->aux; 2685 tab = prog_aux->kfunc_tab; 2686 btf_tab = prog_aux->kfunc_btf_tab; 2687 if (!tab) { 2688 if (!btf_vmlinux) { 2689 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2690 return -ENOTSUPP; 2691 } 2692 2693 if (!env->prog->jit_requested) { 2694 verbose(env, "JIT is required for calling kernel function\n"); 2695 return -ENOTSUPP; 2696 } 2697 2698 if (!bpf_jit_supports_kfunc_call()) { 2699 verbose(env, "JIT does not support calling kernel function\n"); 2700 return -ENOTSUPP; 2701 } 2702 2703 if (!env->prog->gpl_compatible) { 2704 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2705 return -EINVAL; 2706 } 2707 2708 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 2709 if (!tab) 2710 return -ENOMEM; 2711 prog_aux->kfunc_tab = tab; 2712 } 2713 2714 /* func_id == 0 is always invalid, but instead of returning an error, be 2715 * conservative and wait until the code elimination pass before returning 2716 * error, so that invalid calls that get pruned out can be in BPF programs 2717 * loaded from userspace. It is also required that offset be untouched 2718 * for such calls. 2719 */ 2720 if (!func_id && !offset) 2721 return 0; 2722 2723 if (!btf_tab && offset) { 2724 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 2725 if (!btf_tab) 2726 return -ENOMEM; 2727 prog_aux->kfunc_btf_tab = btf_tab; 2728 } 2729 2730 desc_btf = find_kfunc_desc_btf(env, offset); 2731 if (IS_ERR(desc_btf)) { 2732 verbose(env, "failed to find BTF for kernel function\n"); 2733 return PTR_ERR(desc_btf); 2734 } 2735 2736 if (find_kfunc_desc(env->prog, func_id, offset)) 2737 return 0; 2738 2739 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2740 verbose(env, "too many different kernel function calls\n"); 2741 return -E2BIG; 2742 } 2743 2744 func = btf_type_by_id(desc_btf, func_id); 2745 if (!func || !btf_type_is_func(func)) { 2746 verbose(env, "kernel btf_id %u is not a function\n", 2747 func_id); 2748 return -EINVAL; 2749 } 2750 func_proto = btf_type_by_id(desc_btf, func->type); 2751 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2752 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 2753 func_id); 2754 return -EINVAL; 2755 } 2756 2757 func_name = btf_name_by_offset(desc_btf, func->name_off); 2758 addr = kallsyms_lookup_name(func_name); 2759 if (!addr) { 2760 verbose(env, "cannot find address for kernel function %s\n", 2761 func_name); 2762 return -EINVAL; 2763 } 2764 specialize_kfunc(env, func_id, offset, &addr); 2765 2766 if (bpf_jit_supports_far_kfunc_call()) { 2767 call_imm = func_id; 2768 } else { 2769 call_imm = BPF_CALL_IMM(addr); 2770 /* Check whether the relative offset overflows desc->imm */ 2771 if ((unsigned long)(s32)call_imm != call_imm) { 2772 verbose(env, "address of kernel function %s is out of range\n", 2773 func_name); 2774 return -EINVAL; 2775 } 2776 } 2777 2778 if (bpf_dev_bound_kfunc_id(func_id)) { 2779 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2780 if (err) 2781 return err; 2782 } 2783 2784 desc = &tab->descs[tab->nr_descs++]; 2785 desc->func_id = func_id; 2786 desc->imm = call_imm; 2787 desc->offset = offset; 2788 desc->addr = addr; 2789 err = btf_distill_func_proto(&env->log, desc_btf, 2790 func_proto, func_name, 2791 &desc->func_model); 2792 if (!err) 2793 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2794 kfunc_desc_cmp_by_id_off, NULL); 2795 return err; 2796 } 2797 2798 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b) 2799 { 2800 const struct bpf_kfunc_desc *d0 = a; 2801 const struct bpf_kfunc_desc *d1 = b; 2802 2803 if (d0->imm != d1->imm) 2804 return d0->imm < d1->imm ? -1 : 1; 2805 if (d0->offset != d1->offset) 2806 return d0->offset < d1->offset ? -1 : 1; 2807 return 0; 2808 } 2809 2810 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog) 2811 { 2812 struct bpf_kfunc_desc_tab *tab; 2813 2814 tab = prog->aux->kfunc_tab; 2815 if (!tab) 2816 return; 2817 2818 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2819 kfunc_desc_cmp_by_imm_off, NULL); 2820 } 2821 2822 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2823 { 2824 return !!prog->aux->kfunc_tab; 2825 } 2826 2827 const struct btf_func_model * 2828 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 2829 const struct bpf_insn *insn) 2830 { 2831 const struct bpf_kfunc_desc desc = { 2832 .imm = insn->imm, 2833 .offset = insn->off, 2834 }; 2835 const struct bpf_kfunc_desc *res; 2836 struct bpf_kfunc_desc_tab *tab; 2837 2838 tab = prog->aux->kfunc_tab; 2839 res = bsearch(&desc, tab->descs, tab->nr_descs, 2840 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off); 2841 2842 return res ? &res->func_model : NULL; 2843 } 2844 2845 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 2846 { 2847 struct bpf_subprog_info *subprog = env->subprog_info; 2848 int i, ret, insn_cnt = env->prog->len, ex_cb_insn; 2849 struct bpf_insn *insn = env->prog->insnsi; 2850 2851 /* Add entry function. */ 2852 ret = add_subprog(env, 0); 2853 if (ret) 2854 return ret; 2855 2856 for (i = 0; i < insn_cnt; i++, insn++) { 2857 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 2858 !bpf_pseudo_kfunc_call(insn)) 2859 continue; 2860 2861 if (!env->bpf_capable) { 2862 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2863 return -EPERM; 2864 } 2865 2866 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 2867 ret = add_subprog(env, i + insn->imm + 1); 2868 else 2869 ret = add_kfunc_call(env, insn->imm, insn->off); 2870 2871 if (ret < 0) 2872 return ret; 2873 } 2874 2875 ret = bpf_find_exception_callback_insn_off(env); 2876 if (ret < 0) 2877 return ret; 2878 ex_cb_insn = ret; 2879 2880 /* If ex_cb_insn > 0, this means that the main program has a subprog 2881 * marked using BTF decl tag to serve as the exception callback. 2882 */ 2883 if (ex_cb_insn) { 2884 ret = add_subprog(env, ex_cb_insn); 2885 if (ret < 0) 2886 return ret; 2887 for (i = 1; i < env->subprog_cnt; i++) { 2888 if (env->subprog_info[i].start != ex_cb_insn) 2889 continue; 2890 env->exception_callback_subprog = i; 2891 break; 2892 } 2893 } 2894 2895 /* Add a fake 'exit' subprog which could simplify subprog iteration 2896 * logic. 'subprog_cnt' should not be increased. 2897 */ 2898 subprog[env->subprog_cnt].start = insn_cnt; 2899 2900 if (env->log.level & BPF_LOG_LEVEL2) 2901 for (i = 0; i < env->subprog_cnt; i++) 2902 verbose(env, "func#%d @%d\n", i, subprog[i].start); 2903 2904 return 0; 2905 } 2906 2907 static int check_subprogs(struct bpf_verifier_env *env) 2908 { 2909 int i, subprog_start, subprog_end, off, cur_subprog = 0; 2910 struct bpf_subprog_info *subprog = env->subprog_info; 2911 struct bpf_insn *insn = env->prog->insnsi; 2912 int insn_cnt = env->prog->len; 2913 2914 /* now check that all jumps are within the same subprog */ 2915 subprog_start = subprog[cur_subprog].start; 2916 subprog_end = subprog[cur_subprog + 1].start; 2917 for (i = 0; i < insn_cnt; i++) { 2918 u8 code = insn[i].code; 2919 2920 if (code == (BPF_JMP | BPF_CALL) && 2921 insn[i].src_reg == 0 && 2922 insn[i].imm == BPF_FUNC_tail_call) 2923 subprog[cur_subprog].has_tail_call = true; 2924 if (BPF_CLASS(code) == BPF_LD && 2925 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 2926 subprog[cur_subprog].has_ld_abs = true; 2927 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 2928 goto next; 2929 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 2930 goto next; 2931 if (code == (BPF_JMP32 | BPF_JA)) 2932 off = i + insn[i].imm + 1; 2933 else 2934 off = i + insn[i].off + 1; 2935 if (off < subprog_start || off >= subprog_end) { 2936 verbose(env, "jump out of range from insn %d to %d\n", i, off); 2937 return -EINVAL; 2938 } 2939 next: 2940 if (i == subprog_end - 1) { 2941 /* to avoid fall-through from one subprog into another 2942 * the last insn of the subprog should be either exit 2943 * or unconditional jump back or bpf_throw call 2944 */ 2945 if (code != (BPF_JMP | BPF_EXIT) && 2946 code != (BPF_JMP32 | BPF_JA) && 2947 code != (BPF_JMP | BPF_JA)) { 2948 verbose(env, "last insn is not an exit or jmp\n"); 2949 return -EINVAL; 2950 } 2951 subprog_start = subprog_end; 2952 cur_subprog++; 2953 if (cur_subprog < env->subprog_cnt) 2954 subprog_end = subprog[cur_subprog + 1].start; 2955 } 2956 } 2957 return 0; 2958 } 2959 2960 /* Parentage chain of this register (or stack slot) should take care of all 2961 * issues like callee-saved registers, stack slot allocation time, etc. 2962 */ 2963 static int mark_reg_read(struct bpf_verifier_env *env, 2964 const struct bpf_reg_state *state, 2965 struct bpf_reg_state *parent, u8 flag) 2966 { 2967 bool writes = parent == state->parent; /* Observe write marks */ 2968 int cnt = 0; 2969 2970 while (parent) { 2971 /* if read wasn't screened by an earlier write ... */ 2972 if (writes && state->live & REG_LIVE_WRITTEN) 2973 break; 2974 if (parent->live & REG_LIVE_DONE) { 2975 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 2976 reg_type_str(env, parent->type), 2977 parent->var_off.value, parent->off); 2978 return -EFAULT; 2979 } 2980 /* The first condition is more likely to be true than the 2981 * second, checked it first. 2982 */ 2983 if ((parent->live & REG_LIVE_READ) == flag || 2984 parent->live & REG_LIVE_READ64) 2985 /* The parentage chain never changes and 2986 * this parent was already marked as LIVE_READ. 2987 * There is no need to keep walking the chain again and 2988 * keep re-marking all parents as LIVE_READ. 2989 * This case happens when the same register is read 2990 * multiple times without writes into it in-between. 2991 * Also, if parent has the stronger REG_LIVE_READ64 set, 2992 * then no need to set the weak REG_LIVE_READ32. 2993 */ 2994 break; 2995 /* ... then we depend on parent's value */ 2996 parent->live |= flag; 2997 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 2998 if (flag == REG_LIVE_READ64) 2999 parent->live &= ~REG_LIVE_READ32; 3000 state = parent; 3001 parent = state->parent; 3002 writes = true; 3003 cnt++; 3004 } 3005 3006 if (env->longest_mark_read_walk < cnt) 3007 env->longest_mark_read_walk = cnt; 3008 return 0; 3009 } 3010 3011 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3012 { 3013 struct bpf_func_state *state = func(env, reg); 3014 int spi, ret; 3015 3016 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 3017 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 3018 * check_kfunc_call. 3019 */ 3020 if (reg->type == CONST_PTR_TO_DYNPTR) 3021 return 0; 3022 spi = dynptr_get_spi(env, reg); 3023 if (spi < 0) 3024 return spi; 3025 /* Caller ensures dynptr is valid and initialized, which means spi is in 3026 * bounds and spi is the first dynptr slot. Simply mark stack slot as 3027 * read. 3028 */ 3029 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr, 3030 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64); 3031 if (ret) 3032 return ret; 3033 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr, 3034 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64); 3035 } 3036 3037 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3038 int spi, int nr_slots) 3039 { 3040 struct bpf_func_state *state = func(env, reg); 3041 int err, i; 3042 3043 for (i = 0; i < nr_slots; i++) { 3044 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr; 3045 3046 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64); 3047 if (err) 3048 return err; 3049 3050 mark_stack_slot_scratched(env, spi - i); 3051 } 3052 3053 return 0; 3054 } 3055 3056 /* This function is supposed to be used by the following 32-bit optimization 3057 * code only. It returns TRUE if the source or destination register operates 3058 * on 64-bit, otherwise return FALSE. 3059 */ 3060 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 3061 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 3062 { 3063 u8 code, class, op; 3064 3065 code = insn->code; 3066 class = BPF_CLASS(code); 3067 op = BPF_OP(code); 3068 if (class == BPF_JMP) { 3069 /* BPF_EXIT for "main" will reach here. Return TRUE 3070 * conservatively. 3071 */ 3072 if (op == BPF_EXIT) 3073 return true; 3074 if (op == BPF_CALL) { 3075 /* BPF to BPF call will reach here because of marking 3076 * caller saved clobber with DST_OP_NO_MARK for which we 3077 * don't care the register def because they are anyway 3078 * marked as NOT_INIT already. 3079 */ 3080 if (insn->src_reg == BPF_PSEUDO_CALL) 3081 return false; 3082 /* Helper call will reach here because of arg type 3083 * check, conservatively return TRUE. 3084 */ 3085 if (t == SRC_OP) 3086 return true; 3087 3088 return false; 3089 } 3090 } 3091 3092 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3093 return false; 3094 3095 if (class == BPF_ALU64 || class == BPF_JMP || 3096 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3097 return true; 3098 3099 if (class == BPF_ALU || class == BPF_JMP32) 3100 return false; 3101 3102 if (class == BPF_LDX) { 3103 if (t != SRC_OP) 3104 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX; 3105 /* LDX source must be ptr. */ 3106 return true; 3107 } 3108 3109 if (class == BPF_STX) { 3110 /* BPF_STX (including atomic variants) has multiple source 3111 * operands, one of which is a ptr. Check whether the caller is 3112 * asking about it. 3113 */ 3114 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3115 return true; 3116 return BPF_SIZE(code) == BPF_DW; 3117 } 3118 3119 if (class == BPF_LD) { 3120 u8 mode = BPF_MODE(code); 3121 3122 /* LD_IMM64 */ 3123 if (mode == BPF_IMM) 3124 return true; 3125 3126 /* Both LD_IND and LD_ABS return 32-bit data. */ 3127 if (t != SRC_OP) 3128 return false; 3129 3130 /* Implicit ctx ptr. */ 3131 if (regno == BPF_REG_6) 3132 return true; 3133 3134 /* Explicit source could be any width. */ 3135 return true; 3136 } 3137 3138 if (class == BPF_ST) 3139 /* The only source register for BPF_ST is a ptr. */ 3140 return true; 3141 3142 /* Conservatively return true at default. */ 3143 return true; 3144 } 3145 3146 /* Return the regno defined by the insn, or -1. */ 3147 static int insn_def_regno(const struct bpf_insn *insn) 3148 { 3149 switch (BPF_CLASS(insn->code)) { 3150 case BPF_JMP: 3151 case BPF_JMP32: 3152 case BPF_ST: 3153 return -1; 3154 case BPF_STX: 3155 if (BPF_MODE(insn->code) == BPF_ATOMIC && 3156 (insn->imm & BPF_FETCH)) { 3157 if (insn->imm == BPF_CMPXCHG) 3158 return BPF_REG_0; 3159 else 3160 return insn->src_reg; 3161 } else { 3162 return -1; 3163 } 3164 default: 3165 return insn->dst_reg; 3166 } 3167 } 3168 3169 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 3170 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 3171 { 3172 int dst_reg = insn_def_regno(insn); 3173 3174 if (dst_reg == -1) 3175 return false; 3176 3177 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 3178 } 3179 3180 static void mark_insn_zext(struct bpf_verifier_env *env, 3181 struct bpf_reg_state *reg) 3182 { 3183 s32 def_idx = reg->subreg_def; 3184 3185 if (def_idx == DEF_NOT_SUBREG) 3186 return; 3187 3188 env->insn_aux_data[def_idx - 1].zext_dst = true; 3189 /* The dst will be zero extended, so won't be sub-register anymore. */ 3190 reg->subreg_def = DEF_NOT_SUBREG; 3191 } 3192 3193 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno, 3194 enum reg_arg_type t) 3195 { 3196 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3197 struct bpf_reg_state *reg; 3198 bool rw64; 3199 3200 if (regno >= MAX_BPF_REG) { 3201 verbose(env, "R%d is invalid\n", regno); 3202 return -EINVAL; 3203 } 3204 3205 mark_reg_scratched(env, regno); 3206 3207 reg = ®s[regno]; 3208 rw64 = is_reg64(env, insn, regno, reg, t); 3209 if (t == SRC_OP) { 3210 /* check whether register used as source operand can be read */ 3211 if (reg->type == NOT_INIT) { 3212 verbose(env, "R%d !read_ok\n", regno); 3213 return -EACCES; 3214 } 3215 /* We don't need to worry about FP liveness because it's read-only */ 3216 if (regno == BPF_REG_FP) 3217 return 0; 3218 3219 if (rw64) 3220 mark_insn_zext(env, reg); 3221 3222 return mark_reg_read(env, reg, reg->parent, 3223 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 3224 } else { 3225 /* check whether register used as dest operand can be written to */ 3226 if (regno == BPF_REG_FP) { 3227 verbose(env, "frame pointer is read only\n"); 3228 return -EACCES; 3229 } 3230 reg->live |= REG_LIVE_WRITTEN; 3231 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3232 if (t == DST_OP) 3233 mark_reg_unknown(env, regs, regno); 3234 } 3235 return 0; 3236 } 3237 3238 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3239 enum reg_arg_type t) 3240 { 3241 struct bpf_verifier_state *vstate = env->cur_state; 3242 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3243 3244 return __check_reg_arg(env, state->regs, regno, t); 3245 } 3246 3247 static int insn_stack_access_flags(int frameno, int spi) 3248 { 3249 return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno; 3250 } 3251 3252 static int insn_stack_access_spi(int insn_flags) 3253 { 3254 return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK; 3255 } 3256 3257 static int insn_stack_access_frameno(int insn_flags) 3258 { 3259 return insn_flags & INSN_F_FRAMENO_MASK; 3260 } 3261 3262 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 3263 { 3264 env->insn_aux_data[idx].jmp_point = true; 3265 } 3266 3267 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 3268 { 3269 return env->insn_aux_data[insn_idx].jmp_point; 3270 } 3271 3272 /* for any branch, call, exit record the history of jmps in the given state */ 3273 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur, 3274 int insn_flags) 3275 { 3276 u32 cnt = cur->jmp_history_cnt; 3277 struct bpf_jmp_history_entry *p; 3278 size_t alloc_size; 3279 3280 /* combine instruction flags if we already recorded this instruction */ 3281 if (env->cur_hist_ent) { 3282 /* atomic instructions push insn_flags twice, for READ and 3283 * WRITE sides, but they should agree on stack slot 3284 */ 3285 WARN_ONCE((env->cur_hist_ent->flags & insn_flags) && 3286 (env->cur_hist_ent->flags & insn_flags) != insn_flags, 3287 "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n", 3288 env->insn_idx, env->cur_hist_ent->flags, insn_flags); 3289 env->cur_hist_ent->flags |= insn_flags; 3290 return 0; 3291 } 3292 3293 cnt++; 3294 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 3295 p = krealloc(cur->jmp_history, alloc_size, GFP_USER); 3296 if (!p) 3297 return -ENOMEM; 3298 cur->jmp_history = p; 3299 3300 p = &cur->jmp_history[cnt - 1]; 3301 p->idx = env->insn_idx; 3302 p->prev_idx = env->prev_insn_idx; 3303 p->flags = insn_flags; 3304 cur->jmp_history_cnt = cnt; 3305 env->cur_hist_ent = p; 3306 3307 return 0; 3308 } 3309 3310 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st, 3311 u32 hist_end, int insn_idx) 3312 { 3313 if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx) 3314 return &st->jmp_history[hist_end - 1]; 3315 return NULL; 3316 } 3317 3318 /* Backtrack one insn at a time. If idx is not at the top of recorded 3319 * history then previous instruction came from straight line execution. 3320 * Return -ENOENT if we exhausted all instructions within given state. 3321 * 3322 * It's legal to have a bit of a looping with the same starting and ending 3323 * insn index within the same state, e.g.: 3->4->5->3, so just because current 3324 * instruction index is the same as state's first_idx doesn't mean we are 3325 * done. If there is still some jump history left, we should keep going. We 3326 * need to take into account that we might have a jump history between given 3327 * state's parent and itself, due to checkpointing. In this case, we'll have 3328 * history entry recording a jump from last instruction of parent state and 3329 * first instruction of given state. 3330 */ 3331 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 3332 u32 *history) 3333 { 3334 u32 cnt = *history; 3335 3336 if (i == st->first_insn_idx) { 3337 if (cnt == 0) 3338 return -ENOENT; 3339 if (cnt == 1 && st->jmp_history[0].idx == i) 3340 return -ENOENT; 3341 } 3342 3343 if (cnt && st->jmp_history[cnt - 1].idx == i) { 3344 i = st->jmp_history[cnt - 1].prev_idx; 3345 (*history)--; 3346 } else { 3347 i--; 3348 } 3349 return i; 3350 } 3351 3352 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3353 { 3354 const struct btf_type *func; 3355 struct btf *desc_btf; 3356 3357 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3358 return NULL; 3359 3360 desc_btf = find_kfunc_desc_btf(data, insn->off); 3361 if (IS_ERR(desc_btf)) 3362 return "<error>"; 3363 3364 func = btf_type_by_id(desc_btf, insn->imm); 3365 return btf_name_by_offset(desc_btf, func->name_off); 3366 } 3367 3368 static inline void bt_init(struct backtrack_state *bt, u32 frame) 3369 { 3370 bt->frame = frame; 3371 } 3372 3373 static inline void bt_reset(struct backtrack_state *bt) 3374 { 3375 struct bpf_verifier_env *env = bt->env; 3376 3377 memset(bt, 0, sizeof(*bt)); 3378 bt->env = env; 3379 } 3380 3381 static inline u32 bt_empty(struct backtrack_state *bt) 3382 { 3383 u64 mask = 0; 3384 int i; 3385 3386 for (i = 0; i <= bt->frame; i++) 3387 mask |= bt->reg_masks[i] | bt->stack_masks[i]; 3388 3389 return mask == 0; 3390 } 3391 3392 static inline int bt_subprog_enter(struct backtrack_state *bt) 3393 { 3394 if (bt->frame == MAX_CALL_FRAMES - 1) { 3395 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame); 3396 WARN_ONCE(1, "verifier backtracking bug"); 3397 return -EFAULT; 3398 } 3399 bt->frame++; 3400 return 0; 3401 } 3402 3403 static inline int bt_subprog_exit(struct backtrack_state *bt) 3404 { 3405 if (bt->frame == 0) { 3406 verbose(bt->env, "BUG subprog exit from frame 0\n"); 3407 WARN_ONCE(1, "verifier backtracking bug"); 3408 return -EFAULT; 3409 } 3410 bt->frame--; 3411 return 0; 3412 } 3413 3414 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3415 { 3416 bt->reg_masks[frame] |= 1 << reg; 3417 } 3418 3419 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3420 { 3421 bt->reg_masks[frame] &= ~(1 << reg); 3422 } 3423 3424 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg) 3425 { 3426 bt_set_frame_reg(bt, bt->frame, reg); 3427 } 3428 3429 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg) 3430 { 3431 bt_clear_frame_reg(bt, bt->frame, reg); 3432 } 3433 3434 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3435 { 3436 bt->stack_masks[frame] |= 1ull << slot; 3437 } 3438 3439 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3440 { 3441 bt->stack_masks[frame] &= ~(1ull << slot); 3442 } 3443 3444 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot) 3445 { 3446 bt_set_frame_slot(bt, bt->frame, slot); 3447 } 3448 3449 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot) 3450 { 3451 bt_clear_frame_slot(bt, bt->frame, slot); 3452 } 3453 3454 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame) 3455 { 3456 return bt->reg_masks[frame]; 3457 } 3458 3459 static inline u32 bt_reg_mask(struct backtrack_state *bt) 3460 { 3461 return bt->reg_masks[bt->frame]; 3462 } 3463 3464 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame) 3465 { 3466 return bt->stack_masks[frame]; 3467 } 3468 3469 static inline u64 bt_stack_mask(struct backtrack_state *bt) 3470 { 3471 return bt->stack_masks[bt->frame]; 3472 } 3473 3474 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg) 3475 { 3476 return bt->reg_masks[bt->frame] & (1 << reg); 3477 } 3478 3479 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot) 3480 { 3481 return bt->stack_masks[frame] & (1ull << slot); 3482 } 3483 3484 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot) 3485 { 3486 return bt_is_frame_slot_set(bt, bt->frame, slot); 3487 } 3488 3489 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */ 3490 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask) 3491 { 3492 DECLARE_BITMAP(mask, 64); 3493 bool first = true; 3494 int i, n; 3495 3496 buf[0] = '\0'; 3497 3498 bitmap_from_u64(mask, reg_mask); 3499 for_each_set_bit(i, mask, 32) { 3500 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i); 3501 first = false; 3502 buf += n; 3503 buf_sz -= n; 3504 if (buf_sz < 0) 3505 break; 3506 } 3507 } 3508 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */ 3509 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask) 3510 { 3511 DECLARE_BITMAP(mask, 64); 3512 bool first = true; 3513 int i, n; 3514 3515 buf[0] = '\0'; 3516 3517 bitmap_from_u64(mask, stack_mask); 3518 for_each_set_bit(i, mask, 64) { 3519 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8); 3520 first = false; 3521 buf += n; 3522 buf_sz -= n; 3523 if (buf_sz < 0) 3524 break; 3525 } 3526 } 3527 3528 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx); 3529 3530 /* For given verifier state backtrack_insn() is called from the last insn to 3531 * the first insn. Its purpose is to compute a bitmask of registers and 3532 * stack slots that needs precision in the parent verifier state. 3533 * 3534 * @idx is an index of the instruction we are currently processing; 3535 * @subseq_idx is an index of the subsequent instruction that: 3536 * - *would be* executed next, if jump history is viewed in forward order; 3537 * - *was* processed previously during backtracking. 3538 */ 3539 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx, 3540 struct bpf_jmp_history_entry *hist, struct backtrack_state *bt) 3541 { 3542 const struct bpf_insn_cbs cbs = { 3543 .cb_call = disasm_kfunc_name, 3544 .cb_print = verbose, 3545 .private_data = env, 3546 }; 3547 struct bpf_insn *insn = env->prog->insnsi + idx; 3548 u8 class = BPF_CLASS(insn->code); 3549 u8 opcode = BPF_OP(insn->code); 3550 u8 mode = BPF_MODE(insn->code); 3551 u32 dreg = insn->dst_reg; 3552 u32 sreg = insn->src_reg; 3553 u32 spi, i, fr; 3554 3555 if (insn->code == 0) 3556 return 0; 3557 if (env->log.level & BPF_LOG_LEVEL2) { 3558 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt)); 3559 verbose(env, "mark_precise: frame%d: regs=%s ", 3560 bt->frame, env->tmp_str_buf); 3561 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt)); 3562 verbose(env, "stack=%s before ", env->tmp_str_buf); 3563 verbose(env, "%d: ", idx); 3564 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3565 } 3566 3567 if (class == BPF_ALU || class == BPF_ALU64) { 3568 if (!bt_is_reg_set(bt, dreg)) 3569 return 0; 3570 if (opcode == BPF_END || opcode == BPF_NEG) { 3571 /* sreg is reserved and unused 3572 * dreg still need precision before this insn 3573 */ 3574 return 0; 3575 } else if (opcode == BPF_MOV) { 3576 if (BPF_SRC(insn->code) == BPF_X) { 3577 /* dreg = sreg or dreg = (s8, s16, s32)sreg 3578 * dreg needs precision after this insn 3579 * sreg needs precision before this insn 3580 */ 3581 bt_clear_reg(bt, dreg); 3582 bt_set_reg(bt, sreg); 3583 } else { 3584 /* dreg = K 3585 * dreg needs precision after this insn. 3586 * Corresponding register is already marked 3587 * as precise=true in this verifier state. 3588 * No further markings in parent are necessary 3589 */ 3590 bt_clear_reg(bt, dreg); 3591 } 3592 } else { 3593 if (BPF_SRC(insn->code) == BPF_X) { 3594 /* dreg += sreg 3595 * both dreg and sreg need precision 3596 * before this insn 3597 */ 3598 bt_set_reg(bt, sreg); 3599 } /* else dreg += K 3600 * dreg still needs precision before this insn 3601 */ 3602 } 3603 } else if (class == BPF_LDX) { 3604 if (!bt_is_reg_set(bt, dreg)) 3605 return 0; 3606 bt_clear_reg(bt, dreg); 3607 3608 /* scalars can only be spilled into stack w/o losing precision. 3609 * Load from any other memory can be zero extended. 3610 * The desire to keep that precision is already indicated 3611 * by 'precise' mark in corresponding register of this state. 3612 * No further tracking necessary. 3613 */ 3614 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 3615 return 0; 3616 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 3617 * that [fp - off] slot contains scalar that needs to be 3618 * tracked with precision 3619 */ 3620 spi = insn_stack_access_spi(hist->flags); 3621 fr = insn_stack_access_frameno(hist->flags); 3622 bt_set_frame_slot(bt, fr, spi); 3623 } else if (class == BPF_STX || class == BPF_ST) { 3624 if (bt_is_reg_set(bt, dreg)) 3625 /* stx & st shouldn't be using _scalar_ dst_reg 3626 * to access memory. It means backtracking 3627 * encountered a case of pointer subtraction. 3628 */ 3629 return -ENOTSUPP; 3630 /* scalars can only be spilled into stack */ 3631 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 3632 return 0; 3633 spi = insn_stack_access_spi(hist->flags); 3634 fr = insn_stack_access_frameno(hist->flags); 3635 if (!bt_is_frame_slot_set(bt, fr, spi)) 3636 return 0; 3637 bt_clear_frame_slot(bt, fr, spi); 3638 if (class == BPF_STX) 3639 bt_set_reg(bt, sreg); 3640 } else if (class == BPF_JMP || class == BPF_JMP32) { 3641 if (bpf_pseudo_call(insn)) { 3642 int subprog_insn_idx, subprog; 3643 3644 subprog_insn_idx = idx + insn->imm + 1; 3645 subprog = find_subprog(env, subprog_insn_idx); 3646 if (subprog < 0) 3647 return -EFAULT; 3648 3649 if (subprog_is_global(env, subprog)) { 3650 /* check that jump history doesn't have any 3651 * extra instructions from subprog; the next 3652 * instruction after call to global subprog 3653 * should be literally next instruction in 3654 * caller program 3655 */ 3656 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug"); 3657 /* r1-r5 are invalidated after subprog call, 3658 * so for global func call it shouldn't be set 3659 * anymore 3660 */ 3661 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3662 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3663 WARN_ONCE(1, "verifier backtracking bug"); 3664 return -EFAULT; 3665 } 3666 /* global subprog always sets R0 */ 3667 bt_clear_reg(bt, BPF_REG_0); 3668 return 0; 3669 } else { 3670 /* static subprog call instruction, which 3671 * means that we are exiting current subprog, 3672 * so only r1-r5 could be still requested as 3673 * precise, r0 and r6-r10 or any stack slot in 3674 * the current frame should be zero by now 3675 */ 3676 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3677 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3678 WARN_ONCE(1, "verifier backtracking bug"); 3679 return -EFAULT; 3680 } 3681 /* we are now tracking register spills correctly, 3682 * so any instance of leftover slots is a bug 3683 */ 3684 if (bt_stack_mask(bt) != 0) { 3685 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt)); 3686 WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)"); 3687 return -EFAULT; 3688 } 3689 /* propagate r1-r5 to the caller */ 3690 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 3691 if (bt_is_reg_set(bt, i)) { 3692 bt_clear_reg(bt, i); 3693 bt_set_frame_reg(bt, bt->frame - 1, i); 3694 } 3695 } 3696 if (bt_subprog_exit(bt)) 3697 return -EFAULT; 3698 return 0; 3699 } 3700 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) { 3701 /* exit from callback subprog to callback-calling helper or 3702 * kfunc call. Use idx/subseq_idx check to discern it from 3703 * straight line code backtracking. 3704 * Unlike the subprog call handling above, we shouldn't 3705 * propagate precision of r1-r5 (if any requested), as they are 3706 * not actually arguments passed directly to callback subprogs 3707 */ 3708 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3709 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3710 WARN_ONCE(1, "verifier backtracking bug"); 3711 return -EFAULT; 3712 } 3713 if (bt_stack_mask(bt) != 0) { 3714 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt)); 3715 WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)"); 3716 return -EFAULT; 3717 } 3718 /* clear r1-r5 in callback subprog's mask */ 3719 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3720 bt_clear_reg(bt, i); 3721 if (bt_subprog_exit(bt)) 3722 return -EFAULT; 3723 return 0; 3724 } else if (opcode == BPF_CALL) { 3725 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 3726 * catch this error later. Make backtracking conservative 3727 * with ENOTSUPP. 3728 */ 3729 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 3730 return -ENOTSUPP; 3731 /* regular helper call sets R0 */ 3732 bt_clear_reg(bt, BPF_REG_0); 3733 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3734 /* if backtracing was looking for registers R1-R5 3735 * they should have been found already. 3736 */ 3737 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3738 WARN_ONCE(1, "verifier backtracking bug"); 3739 return -EFAULT; 3740 } 3741 } else if (opcode == BPF_EXIT) { 3742 bool r0_precise; 3743 3744 /* Backtracking to a nested function call, 'idx' is a part of 3745 * the inner frame 'subseq_idx' is a part of the outer frame. 3746 * In case of a regular function call, instructions giving 3747 * precision to registers R1-R5 should have been found already. 3748 * In case of a callback, it is ok to have R1-R5 marked for 3749 * backtracking, as these registers are set by the function 3750 * invoking callback. 3751 */ 3752 if (subseq_idx >= 0 && calls_callback(env, subseq_idx)) 3753 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3754 bt_clear_reg(bt, i); 3755 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3756 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3757 WARN_ONCE(1, "verifier backtracking bug"); 3758 return -EFAULT; 3759 } 3760 3761 /* BPF_EXIT in subprog or callback always returns 3762 * right after the call instruction, so by checking 3763 * whether the instruction at subseq_idx-1 is subprog 3764 * call or not we can distinguish actual exit from 3765 * *subprog* from exit from *callback*. In the former 3766 * case, we need to propagate r0 precision, if 3767 * necessary. In the former we never do that. 3768 */ 3769 r0_precise = subseq_idx - 1 >= 0 && 3770 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) && 3771 bt_is_reg_set(bt, BPF_REG_0); 3772 3773 bt_clear_reg(bt, BPF_REG_0); 3774 if (bt_subprog_enter(bt)) 3775 return -EFAULT; 3776 3777 if (r0_precise) 3778 bt_set_reg(bt, BPF_REG_0); 3779 /* r6-r9 and stack slots will stay set in caller frame 3780 * bitmasks until we return back from callee(s) 3781 */ 3782 return 0; 3783 } else if (BPF_SRC(insn->code) == BPF_X) { 3784 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg)) 3785 return 0; 3786 /* dreg <cond> sreg 3787 * Both dreg and sreg need precision before 3788 * this insn. If only sreg was marked precise 3789 * before it would be equally necessary to 3790 * propagate it to dreg. 3791 */ 3792 bt_set_reg(bt, dreg); 3793 bt_set_reg(bt, sreg); 3794 /* else dreg <cond> K 3795 * Only dreg still needs precision before 3796 * this insn, so for the K-based conditional 3797 * there is nothing new to be marked. 3798 */ 3799 } 3800 } else if (class == BPF_LD) { 3801 if (!bt_is_reg_set(bt, dreg)) 3802 return 0; 3803 bt_clear_reg(bt, dreg); 3804 /* It's ld_imm64 or ld_abs or ld_ind. 3805 * For ld_imm64 no further tracking of precision 3806 * into parent is necessary 3807 */ 3808 if (mode == BPF_IND || mode == BPF_ABS) 3809 /* to be analyzed */ 3810 return -ENOTSUPP; 3811 } 3812 return 0; 3813 } 3814 3815 /* the scalar precision tracking algorithm: 3816 * . at the start all registers have precise=false. 3817 * . scalar ranges are tracked as normal through alu and jmp insns. 3818 * . once precise value of the scalar register is used in: 3819 * . ptr + scalar alu 3820 * . if (scalar cond K|scalar) 3821 * . helper_call(.., scalar, ...) where ARG_CONST is expected 3822 * backtrack through the verifier states and mark all registers and 3823 * stack slots with spilled constants that these scalar regisers 3824 * should be precise. 3825 * . during state pruning two registers (or spilled stack slots) 3826 * are equivalent if both are not precise. 3827 * 3828 * Note the verifier cannot simply walk register parentage chain, 3829 * since many different registers and stack slots could have been 3830 * used to compute single precise scalar. 3831 * 3832 * The approach of starting with precise=true for all registers and then 3833 * backtrack to mark a register as not precise when the verifier detects 3834 * that program doesn't care about specific value (e.g., when helper 3835 * takes register as ARG_ANYTHING parameter) is not safe. 3836 * 3837 * It's ok to walk single parentage chain of the verifier states. 3838 * It's possible that this backtracking will go all the way till 1st insn. 3839 * All other branches will be explored for needing precision later. 3840 * 3841 * The backtracking needs to deal with cases like: 3842 * 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) 3843 * r9 -= r8 3844 * r5 = r9 3845 * if r5 > 0x79f goto pc+7 3846 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 3847 * r5 += 1 3848 * ... 3849 * call bpf_perf_event_output#25 3850 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 3851 * 3852 * and this case: 3853 * r6 = 1 3854 * call foo // uses callee's r6 inside to compute r0 3855 * r0 += r6 3856 * if r0 == 0 goto 3857 * 3858 * to track above reg_mask/stack_mask needs to be independent for each frame. 3859 * 3860 * Also if parent's curframe > frame where backtracking started, 3861 * the verifier need to mark registers in both frames, otherwise callees 3862 * may incorrectly prune callers. This is similar to 3863 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 3864 * 3865 * For now backtracking falls back into conservative marking. 3866 */ 3867 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 3868 struct bpf_verifier_state *st) 3869 { 3870 struct bpf_func_state *func; 3871 struct bpf_reg_state *reg; 3872 int i, j; 3873 3874 if (env->log.level & BPF_LOG_LEVEL2) { 3875 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n", 3876 st->curframe); 3877 } 3878 3879 /* big hammer: mark all scalars precise in this path. 3880 * pop_stack may still get !precise scalars. 3881 * We also skip current state and go straight to first parent state, 3882 * because precision markings in current non-checkpointed state are 3883 * not needed. See why in the comment in __mark_chain_precision below. 3884 */ 3885 for (st = st->parent; st; st = st->parent) { 3886 for (i = 0; i <= st->curframe; i++) { 3887 func = st->frame[i]; 3888 for (j = 0; j < BPF_REG_FP; j++) { 3889 reg = &func->regs[j]; 3890 if (reg->type != SCALAR_VALUE || reg->precise) 3891 continue; 3892 reg->precise = true; 3893 if (env->log.level & BPF_LOG_LEVEL2) { 3894 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n", 3895 i, j); 3896 } 3897 } 3898 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3899 if (!is_spilled_reg(&func->stack[j])) 3900 continue; 3901 reg = &func->stack[j].spilled_ptr; 3902 if (reg->type != SCALAR_VALUE || reg->precise) 3903 continue; 3904 reg->precise = true; 3905 if (env->log.level & BPF_LOG_LEVEL2) { 3906 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n", 3907 i, -(j + 1) * 8); 3908 } 3909 } 3910 } 3911 } 3912 } 3913 3914 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 3915 { 3916 struct bpf_func_state *func; 3917 struct bpf_reg_state *reg; 3918 int i, j; 3919 3920 for (i = 0; i <= st->curframe; i++) { 3921 func = st->frame[i]; 3922 for (j = 0; j < BPF_REG_FP; j++) { 3923 reg = &func->regs[j]; 3924 if (reg->type != SCALAR_VALUE) 3925 continue; 3926 reg->precise = false; 3927 } 3928 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3929 if (!is_spilled_reg(&func->stack[j])) 3930 continue; 3931 reg = &func->stack[j].spilled_ptr; 3932 if (reg->type != SCALAR_VALUE) 3933 continue; 3934 reg->precise = false; 3935 } 3936 } 3937 } 3938 3939 static bool idset_contains(struct bpf_idset *s, u32 id) 3940 { 3941 u32 i; 3942 3943 for (i = 0; i < s->count; ++i) 3944 if (s->ids[i] == id) 3945 return true; 3946 3947 return false; 3948 } 3949 3950 static int idset_push(struct bpf_idset *s, u32 id) 3951 { 3952 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids))) 3953 return -EFAULT; 3954 s->ids[s->count++] = id; 3955 return 0; 3956 } 3957 3958 static void idset_reset(struct bpf_idset *s) 3959 { 3960 s->count = 0; 3961 } 3962 3963 /* Collect a set of IDs for all registers currently marked as precise in env->bt. 3964 * Mark all registers with these IDs as precise. 3965 */ 3966 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 3967 { 3968 struct bpf_idset *precise_ids = &env->idset_scratch; 3969 struct backtrack_state *bt = &env->bt; 3970 struct bpf_func_state *func; 3971 struct bpf_reg_state *reg; 3972 DECLARE_BITMAP(mask, 64); 3973 int i, fr; 3974 3975 idset_reset(precise_ids); 3976 3977 for (fr = bt->frame; fr >= 0; fr--) { 3978 func = st->frame[fr]; 3979 3980 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 3981 for_each_set_bit(i, mask, 32) { 3982 reg = &func->regs[i]; 3983 if (!reg->id || reg->type != SCALAR_VALUE) 3984 continue; 3985 if (idset_push(precise_ids, reg->id)) 3986 return -EFAULT; 3987 } 3988 3989 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 3990 for_each_set_bit(i, mask, 64) { 3991 if (i >= func->allocated_stack / BPF_REG_SIZE) 3992 break; 3993 if (!is_spilled_scalar_reg(&func->stack[i])) 3994 continue; 3995 reg = &func->stack[i].spilled_ptr; 3996 if (!reg->id) 3997 continue; 3998 if (idset_push(precise_ids, reg->id)) 3999 return -EFAULT; 4000 } 4001 } 4002 4003 for (fr = 0; fr <= st->curframe; ++fr) { 4004 func = st->frame[fr]; 4005 4006 for (i = BPF_REG_0; i < BPF_REG_10; ++i) { 4007 reg = &func->regs[i]; 4008 if (!reg->id) 4009 continue; 4010 if (!idset_contains(precise_ids, reg->id)) 4011 continue; 4012 bt_set_frame_reg(bt, fr, i); 4013 } 4014 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) { 4015 if (!is_spilled_scalar_reg(&func->stack[i])) 4016 continue; 4017 reg = &func->stack[i].spilled_ptr; 4018 if (!reg->id) 4019 continue; 4020 if (!idset_contains(precise_ids, reg->id)) 4021 continue; 4022 bt_set_frame_slot(bt, fr, i); 4023 } 4024 } 4025 4026 return 0; 4027 } 4028 4029 /* 4030 * __mark_chain_precision() backtracks BPF program instruction sequence and 4031 * chain of verifier states making sure that register *regno* (if regno >= 0) 4032 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 4033 * SCALARS, as well as any other registers and slots that contribute to 4034 * a tracked state of given registers/stack slots, depending on specific BPF 4035 * assembly instructions (see backtrack_insns() for exact instruction handling 4036 * logic). This backtracking relies on recorded jmp_history and is able to 4037 * traverse entire chain of parent states. This process ends only when all the 4038 * necessary registers/slots and their transitive dependencies are marked as 4039 * precise. 4040 * 4041 * One important and subtle aspect is that precise marks *do not matter* in 4042 * the currently verified state (current state). It is important to understand 4043 * why this is the case. 4044 * 4045 * First, note that current state is the state that is not yet "checkpointed", 4046 * i.e., it is not yet put into env->explored_states, and it has no children 4047 * states as well. It's ephemeral, and can end up either a) being discarded if 4048 * compatible explored state is found at some point or BPF_EXIT instruction is 4049 * reached or b) checkpointed and put into env->explored_states, branching out 4050 * into one or more children states. 4051 * 4052 * In the former case, precise markings in current state are completely 4053 * ignored by state comparison code (see regsafe() for details). Only 4054 * checkpointed ("old") state precise markings are important, and if old 4055 * state's register/slot is precise, regsafe() assumes current state's 4056 * register/slot as precise and checks value ranges exactly and precisely. If 4057 * states turn out to be compatible, current state's necessary precise 4058 * markings and any required parent states' precise markings are enforced 4059 * after the fact with propagate_precision() logic, after the fact. But it's 4060 * important to realize that in this case, even after marking current state 4061 * registers/slots as precise, we immediately discard current state. So what 4062 * actually matters is any of the precise markings propagated into current 4063 * state's parent states, which are always checkpointed (due to b) case above). 4064 * As such, for scenario a) it doesn't matter if current state has precise 4065 * markings set or not. 4066 * 4067 * Now, for the scenario b), checkpointing and forking into child(ren) 4068 * state(s). Note that before current state gets to checkpointing step, any 4069 * processed instruction always assumes precise SCALAR register/slot 4070 * knowledge: if precise value or range is useful to prune jump branch, BPF 4071 * verifier takes this opportunity enthusiastically. Similarly, when 4072 * register's value is used to calculate offset or memory address, exact 4073 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 4074 * what we mentioned above about state comparison ignoring precise markings 4075 * during state comparison, BPF verifier ignores and also assumes precise 4076 * markings *at will* during instruction verification process. But as verifier 4077 * assumes precision, it also propagates any precision dependencies across 4078 * parent states, which are not yet finalized, so can be further restricted 4079 * based on new knowledge gained from restrictions enforced by their children 4080 * states. This is so that once those parent states are finalized, i.e., when 4081 * they have no more active children state, state comparison logic in 4082 * is_state_visited() would enforce strict and precise SCALAR ranges, if 4083 * required for correctness. 4084 * 4085 * To build a bit more intuition, note also that once a state is checkpointed, 4086 * the path we took to get to that state is not important. This is crucial 4087 * property for state pruning. When state is checkpointed and finalized at 4088 * some instruction index, it can be correctly and safely used to "short 4089 * circuit" any *compatible* state that reaches exactly the same instruction 4090 * index. I.e., if we jumped to that instruction from a completely different 4091 * code path than original finalized state was derived from, it doesn't 4092 * matter, current state can be discarded because from that instruction 4093 * forward having a compatible state will ensure we will safely reach the 4094 * exit. States describe preconditions for further exploration, but completely 4095 * forget the history of how we got here. 4096 * 4097 * This also means that even if we needed precise SCALAR range to get to 4098 * finalized state, but from that point forward *that same* SCALAR register is 4099 * never used in a precise context (i.e., it's precise value is not needed for 4100 * correctness), it's correct and safe to mark such register as "imprecise" 4101 * (i.e., precise marking set to false). This is what we rely on when we do 4102 * not set precise marking in current state. If no child state requires 4103 * precision for any given SCALAR register, it's safe to dictate that it can 4104 * be imprecise. If any child state does require this register to be precise, 4105 * we'll mark it precise later retroactively during precise markings 4106 * propagation from child state to parent states. 4107 * 4108 * Skipping precise marking setting in current state is a mild version of 4109 * relying on the above observation. But we can utilize this property even 4110 * more aggressively by proactively forgetting any precise marking in the 4111 * current state (which we inherited from the parent state), right before we 4112 * checkpoint it and branch off into new child state. This is done by 4113 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 4114 * finalized states which help in short circuiting more future states. 4115 */ 4116 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno) 4117 { 4118 struct backtrack_state *bt = &env->bt; 4119 struct bpf_verifier_state *st = env->cur_state; 4120 int first_idx = st->first_insn_idx; 4121 int last_idx = env->insn_idx; 4122 int subseq_idx = -1; 4123 struct bpf_func_state *func; 4124 struct bpf_reg_state *reg; 4125 bool skip_first = true; 4126 int i, fr, err; 4127 4128 if (!env->bpf_capable) 4129 return 0; 4130 4131 /* set frame number from which we are starting to backtrack */ 4132 bt_init(bt, env->cur_state->curframe); 4133 4134 /* Do sanity checks against current state of register and/or stack 4135 * slot, but don't set precise flag in current state, as precision 4136 * tracking in the current state is unnecessary. 4137 */ 4138 func = st->frame[bt->frame]; 4139 if (regno >= 0) { 4140 reg = &func->regs[regno]; 4141 if (reg->type != SCALAR_VALUE) { 4142 WARN_ONCE(1, "backtracing misuse"); 4143 return -EFAULT; 4144 } 4145 bt_set_reg(bt, regno); 4146 } 4147 4148 if (bt_empty(bt)) 4149 return 0; 4150 4151 for (;;) { 4152 DECLARE_BITMAP(mask, 64); 4153 u32 history = st->jmp_history_cnt; 4154 struct bpf_jmp_history_entry *hist; 4155 4156 if (env->log.level & BPF_LOG_LEVEL2) { 4157 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n", 4158 bt->frame, last_idx, first_idx, subseq_idx); 4159 } 4160 4161 /* If some register with scalar ID is marked as precise, 4162 * make sure that all registers sharing this ID are also precise. 4163 * This is needed to estimate effect of find_equal_scalars(). 4164 * Do this at the last instruction of each state, 4165 * bpf_reg_state::id fields are valid for these instructions. 4166 * 4167 * Allows to track precision in situation like below: 4168 * 4169 * r2 = unknown value 4170 * ... 4171 * --- state #0 --- 4172 * ... 4173 * r1 = r2 // r1 and r2 now share the same ID 4174 * ... 4175 * --- state #1 {r1.id = A, r2.id = A} --- 4176 * ... 4177 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1 4178 * ... 4179 * --- state #2 {r1.id = A, r2.id = A} --- 4180 * r3 = r10 4181 * r3 += r1 // need to mark both r1 and r2 4182 */ 4183 if (mark_precise_scalar_ids(env, st)) 4184 return -EFAULT; 4185 4186 if (last_idx < 0) { 4187 /* we are at the entry into subprog, which 4188 * is expected for global funcs, but only if 4189 * requested precise registers are R1-R5 4190 * (which are global func's input arguments) 4191 */ 4192 if (st->curframe == 0 && 4193 st->frame[0]->subprogno > 0 && 4194 st->frame[0]->callsite == BPF_MAIN_FUNC && 4195 bt_stack_mask(bt) == 0 && 4196 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) { 4197 bitmap_from_u64(mask, bt_reg_mask(bt)); 4198 for_each_set_bit(i, mask, 32) { 4199 reg = &st->frame[0]->regs[i]; 4200 bt_clear_reg(bt, i); 4201 if (reg->type == SCALAR_VALUE) 4202 reg->precise = true; 4203 } 4204 return 0; 4205 } 4206 4207 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n", 4208 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt)); 4209 WARN_ONCE(1, "verifier backtracking bug"); 4210 return -EFAULT; 4211 } 4212 4213 for (i = last_idx;;) { 4214 if (skip_first) { 4215 err = 0; 4216 skip_first = false; 4217 } else { 4218 hist = get_jmp_hist_entry(st, history, i); 4219 err = backtrack_insn(env, i, subseq_idx, hist, bt); 4220 } 4221 if (err == -ENOTSUPP) { 4222 mark_all_scalars_precise(env, env->cur_state); 4223 bt_reset(bt); 4224 return 0; 4225 } else if (err) { 4226 return err; 4227 } 4228 if (bt_empty(bt)) 4229 /* Found assignment(s) into tracked register in this state. 4230 * Since this state is already marked, just return. 4231 * Nothing to be tracked further in the parent state. 4232 */ 4233 return 0; 4234 subseq_idx = i; 4235 i = get_prev_insn_idx(st, i, &history); 4236 if (i == -ENOENT) 4237 break; 4238 if (i >= env->prog->len) { 4239 /* This can happen if backtracking reached insn 0 4240 * and there are still reg_mask or stack_mask 4241 * to backtrack. 4242 * It means the backtracking missed the spot where 4243 * particular register was initialized with a constant. 4244 */ 4245 verbose(env, "BUG backtracking idx %d\n", i); 4246 WARN_ONCE(1, "verifier backtracking bug"); 4247 return -EFAULT; 4248 } 4249 } 4250 st = st->parent; 4251 if (!st) 4252 break; 4253 4254 for (fr = bt->frame; fr >= 0; fr--) { 4255 func = st->frame[fr]; 4256 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4257 for_each_set_bit(i, mask, 32) { 4258 reg = &func->regs[i]; 4259 if (reg->type != SCALAR_VALUE) { 4260 bt_clear_frame_reg(bt, fr, i); 4261 continue; 4262 } 4263 if (reg->precise) 4264 bt_clear_frame_reg(bt, fr, i); 4265 else 4266 reg->precise = true; 4267 } 4268 4269 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4270 for_each_set_bit(i, mask, 64) { 4271 if (i >= func->allocated_stack / BPF_REG_SIZE) { 4272 verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n", 4273 i, func->allocated_stack / BPF_REG_SIZE); 4274 WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)"); 4275 return -EFAULT; 4276 } 4277 4278 if (!is_spilled_scalar_reg(&func->stack[i])) { 4279 bt_clear_frame_slot(bt, fr, i); 4280 continue; 4281 } 4282 reg = &func->stack[i].spilled_ptr; 4283 if (reg->precise) 4284 bt_clear_frame_slot(bt, fr, i); 4285 else 4286 reg->precise = true; 4287 } 4288 if (env->log.level & BPF_LOG_LEVEL2) { 4289 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4290 bt_frame_reg_mask(bt, fr)); 4291 verbose(env, "mark_precise: frame%d: parent state regs=%s ", 4292 fr, env->tmp_str_buf); 4293 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4294 bt_frame_stack_mask(bt, fr)); 4295 verbose(env, "stack=%s: ", env->tmp_str_buf); 4296 print_verifier_state(env, func, true); 4297 } 4298 } 4299 4300 if (bt_empty(bt)) 4301 return 0; 4302 4303 subseq_idx = first_idx; 4304 last_idx = st->last_insn_idx; 4305 first_idx = st->first_insn_idx; 4306 } 4307 4308 /* if we still have requested precise regs or slots, we missed 4309 * something (e.g., stack access through non-r10 register), so 4310 * fallback to marking all precise 4311 */ 4312 if (!bt_empty(bt)) { 4313 mark_all_scalars_precise(env, env->cur_state); 4314 bt_reset(bt); 4315 } 4316 4317 return 0; 4318 } 4319 4320 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 4321 { 4322 return __mark_chain_precision(env, regno); 4323 } 4324 4325 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 4326 * desired reg and stack masks across all relevant frames 4327 */ 4328 static int mark_chain_precision_batch(struct bpf_verifier_env *env) 4329 { 4330 return __mark_chain_precision(env, -1); 4331 } 4332 4333 static bool is_spillable_regtype(enum bpf_reg_type type) 4334 { 4335 switch (base_type(type)) { 4336 case PTR_TO_MAP_VALUE: 4337 case PTR_TO_STACK: 4338 case PTR_TO_CTX: 4339 case PTR_TO_PACKET: 4340 case PTR_TO_PACKET_META: 4341 case PTR_TO_PACKET_END: 4342 case PTR_TO_FLOW_KEYS: 4343 case CONST_PTR_TO_MAP: 4344 case PTR_TO_SOCKET: 4345 case PTR_TO_SOCK_COMMON: 4346 case PTR_TO_TCP_SOCK: 4347 case PTR_TO_XDP_SOCK: 4348 case PTR_TO_BTF_ID: 4349 case PTR_TO_BUF: 4350 case PTR_TO_MEM: 4351 case PTR_TO_FUNC: 4352 case PTR_TO_MAP_KEY: 4353 return true; 4354 default: 4355 return false; 4356 } 4357 } 4358 4359 /* Does this register contain a constant zero? */ 4360 static bool register_is_null(struct bpf_reg_state *reg) 4361 { 4362 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 4363 } 4364 4365 /* check if register is a constant scalar value */ 4366 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32) 4367 { 4368 return reg->type == SCALAR_VALUE && 4369 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off); 4370 } 4371 4372 /* assuming is_reg_const() is true, return constant value of a register */ 4373 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32) 4374 { 4375 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value; 4376 } 4377 4378 static bool __is_scalar_unbounded(struct bpf_reg_state *reg) 4379 { 4380 return tnum_is_unknown(reg->var_off) && 4381 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX && 4382 reg->umin_value == 0 && reg->umax_value == U64_MAX && 4383 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX && 4384 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX; 4385 } 4386 4387 static bool register_is_bounded(struct bpf_reg_state *reg) 4388 { 4389 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg); 4390 } 4391 4392 static bool __is_pointer_value(bool allow_ptr_leaks, 4393 const struct bpf_reg_state *reg) 4394 { 4395 if (allow_ptr_leaks) 4396 return false; 4397 4398 return reg->type != SCALAR_VALUE; 4399 } 4400 4401 /* Copy src state preserving dst->parent and dst->live fields */ 4402 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 4403 { 4404 struct bpf_reg_state *parent = dst->parent; 4405 enum bpf_reg_liveness live = dst->live; 4406 4407 *dst = *src; 4408 dst->parent = parent; 4409 dst->live = live; 4410 } 4411 4412 static void save_register_state(struct bpf_verifier_env *env, 4413 struct bpf_func_state *state, 4414 int spi, struct bpf_reg_state *reg, 4415 int size) 4416 { 4417 int i; 4418 4419 copy_register_state(&state->stack[spi].spilled_ptr, reg); 4420 if (size == BPF_REG_SIZE) 4421 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4422 4423 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 4424 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 4425 4426 /* size < 8 bytes spill */ 4427 for (; i; i--) 4428 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]); 4429 } 4430 4431 static bool is_bpf_st_mem(struct bpf_insn *insn) 4432 { 4433 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 4434 } 4435 4436 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 4437 * stack boundary and alignment are checked in check_mem_access() 4438 */ 4439 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 4440 /* stack frame we're writing to */ 4441 struct bpf_func_state *state, 4442 int off, int size, int value_regno, 4443 int insn_idx) 4444 { 4445 struct bpf_func_state *cur; /* state of the current function */ 4446 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 4447 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4448 struct bpf_reg_state *reg = NULL; 4449 int insn_flags = insn_stack_access_flags(state->frameno, spi); 4450 4451 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 4452 * so it's aligned access and [off, off + size) are within stack limits 4453 */ 4454 if (!env->allow_ptr_leaks && 4455 is_spilled_reg(&state->stack[spi]) && 4456 size != BPF_REG_SIZE) { 4457 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 4458 return -EACCES; 4459 } 4460 4461 cur = env->cur_state->frame[env->cur_state->curframe]; 4462 if (value_regno >= 0) 4463 reg = &cur->regs[value_regno]; 4464 if (!env->bypass_spec_v4) { 4465 bool sanitize = reg && is_spillable_regtype(reg->type); 4466 4467 for (i = 0; i < size; i++) { 4468 u8 type = state->stack[spi].slot_type[i]; 4469 4470 if (type != STACK_MISC && type != STACK_ZERO) { 4471 sanitize = true; 4472 break; 4473 } 4474 } 4475 4476 if (sanitize) 4477 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 4478 } 4479 4480 err = destroy_if_dynptr_stack_slot(env, state, spi); 4481 if (err) 4482 return err; 4483 4484 mark_stack_slot_scratched(env, spi); 4485 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && env->bpf_capable) { 4486 save_register_state(env, state, spi, reg, size); 4487 /* Break the relation on a narrowing spill. */ 4488 if (fls64(reg->umax_value) > BITS_PER_BYTE * size) 4489 state->stack[spi].spilled_ptr.id = 0; 4490 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 4491 insn->imm != 0 && env->bpf_capable) { 4492 struct bpf_reg_state fake_reg = {}; 4493 4494 __mark_reg_known(&fake_reg, insn->imm); 4495 fake_reg.type = SCALAR_VALUE; 4496 save_register_state(env, state, spi, &fake_reg, size); 4497 insn_flags = 0; /* not a register spill */ 4498 } else if (reg && is_spillable_regtype(reg->type)) { 4499 /* register containing pointer is being spilled into stack */ 4500 if (size != BPF_REG_SIZE) { 4501 verbose_linfo(env, insn_idx, "; "); 4502 verbose(env, "invalid size of register spill\n"); 4503 return -EACCES; 4504 } 4505 if (state != cur && reg->type == PTR_TO_STACK) { 4506 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4507 return -EINVAL; 4508 } 4509 save_register_state(env, state, spi, reg, size); 4510 } else { 4511 u8 type = STACK_MISC; 4512 4513 /* regular write of data into stack destroys any spilled ptr */ 4514 state->stack[spi].spilled_ptr.type = NOT_INIT; 4515 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 4516 if (is_stack_slot_special(&state->stack[spi])) 4517 for (i = 0; i < BPF_REG_SIZE; i++) 4518 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 4519 4520 /* only mark the slot as written if all 8 bytes were written 4521 * otherwise read propagation may incorrectly stop too soon 4522 * when stack slots are partially written. 4523 * This heuristic means that read propagation will be 4524 * conservative, since it will add reg_live_read marks 4525 * to stack slots all the way to first state when programs 4526 * writes+reads less than 8 bytes 4527 */ 4528 if (size == BPF_REG_SIZE) 4529 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4530 4531 /* when we zero initialize stack slots mark them as such */ 4532 if ((reg && register_is_null(reg)) || 4533 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4534 /* STACK_ZERO case happened because register spill 4535 * wasn't properly aligned at the stack slot boundary, 4536 * so it's not a register spill anymore; force 4537 * originating register to be precise to make 4538 * STACK_ZERO correct for subsequent states 4539 */ 4540 err = mark_chain_precision(env, value_regno); 4541 if (err) 4542 return err; 4543 type = STACK_ZERO; 4544 } 4545 4546 /* Mark slots affected by this stack write. */ 4547 for (i = 0; i < size; i++) 4548 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 4549 insn_flags = 0; /* not a register spill */ 4550 } 4551 4552 if (insn_flags) 4553 return push_jmp_history(env, env->cur_state, insn_flags); 4554 return 0; 4555 } 4556 4557 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 4558 * known to contain a variable offset. 4559 * This function checks whether the write is permitted and conservatively 4560 * tracks the effects of the write, considering that each stack slot in the 4561 * dynamic range is potentially written to. 4562 * 4563 * 'off' includes 'regno->off'. 4564 * 'value_regno' can be -1, meaning that an unknown value is being written to 4565 * the stack. 4566 * 4567 * Spilled pointers in range are not marked as written because we don't know 4568 * what's going to be actually written. This means that read propagation for 4569 * future reads cannot be terminated by this write. 4570 * 4571 * For privileged programs, uninitialized stack slots are considered 4572 * initialized by this write (even though we don't know exactly what offsets 4573 * are going to be written to). The idea is that we don't want the verifier to 4574 * reject future reads that access slots written to through variable offsets. 4575 */ 4576 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4577 /* func where register points to */ 4578 struct bpf_func_state *state, 4579 int ptr_regno, int off, int size, 4580 int value_regno, int insn_idx) 4581 { 4582 struct bpf_func_state *cur; /* state of the current function */ 4583 int min_off, max_off; 4584 int i, err; 4585 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 4586 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4587 bool writing_zero = false; 4588 /* set if the fact that we're writing a zero is used to let any 4589 * stack slots remain STACK_ZERO 4590 */ 4591 bool zero_used = false; 4592 4593 cur = env->cur_state->frame[env->cur_state->curframe]; 4594 ptr_reg = &cur->regs[ptr_regno]; 4595 min_off = ptr_reg->smin_value + off; 4596 max_off = ptr_reg->smax_value + off + size; 4597 if (value_regno >= 0) 4598 value_reg = &cur->regs[value_regno]; 4599 if ((value_reg && register_is_null(value_reg)) || 4600 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4601 writing_zero = true; 4602 4603 for (i = min_off; i < max_off; i++) { 4604 int spi; 4605 4606 spi = __get_spi(i); 4607 err = destroy_if_dynptr_stack_slot(env, state, spi); 4608 if (err) 4609 return err; 4610 } 4611 4612 /* Variable offset writes destroy any spilled pointers in range. */ 4613 for (i = min_off; i < max_off; i++) { 4614 u8 new_type, *stype; 4615 int slot, spi; 4616 4617 slot = -i - 1; 4618 spi = slot / BPF_REG_SIZE; 4619 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4620 mark_stack_slot_scratched(env, spi); 4621 4622 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4623 /* Reject the write if range we may write to has not 4624 * been initialized beforehand. If we didn't reject 4625 * here, the ptr status would be erased below (even 4626 * though not all slots are actually overwritten), 4627 * possibly opening the door to leaks. 4628 * 4629 * We do however catch STACK_INVALID case below, and 4630 * only allow reading possibly uninitialized memory 4631 * later for CAP_PERFMON, as the write may not happen to 4632 * that slot. 4633 */ 4634 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4635 insn_idx, i); 4636 return -EINVAL; 4637 } 4638 4639 /* Erase all spilled pointers. */ 4640 state->stack[spi].spilled_ptr.type = NOT_INIT; 4641 4642 /* Update the slot type. */ 4643 new_type = STACK_MISC; 4644 if (writing_zero && *stype == STACK_ZERO) { 4645 new_type = STACK_ZERO; 4646 zero_used = true; 4647 } 4648 /* If the slot is STACK_INVALID, we check whether it's OK to 4649 * pretend that it will be initialized by this write. The slot 4650 * might not actually be written to, and so if we mark it as 4651 * initialized future reads might leak uninitialized memory. 4652 * For privileged programs, we will accept such reads to slots 4653 * that may or may not be written because, if we're reject 4654 * them, the error would be too confusing. 4655 */ 4656 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4657 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4658 insn_idx, i); 4659 return -EINVAL; 4660 } 4661 *stype = new_type; 4662 } 4663 if (zero_used) { 4664 /* backtracking doesn't work for STACK_ZERO yet. */ 4665 err = mark_chain_precision(env, value_regno); 4666 if (err) 4667 return err; 4668 } 4669 return 0; 4670 } 4671 4672 /* When register 'dst_regno' is assigned some values from stack[min_off, 4673 * max_off), we set the register's type according to the types of the 4674 * respective stack slots. If all the stack values are known to be zeros, then 4675 * so is the destination reg. Otherwise, the register is considered to be 4676 * SCALAR. This function does not deal with register filling; the caller must 4677 * ensure that all spilled registers in the stack range have been marked as 4678 * read. 4679 */ 4680 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4681 /* func where src register points to */ 4682 struct bpf_func_state *ptr_state, 4683 int min_off, int max_off, int dst_regno) 4684 { 4685 struct bpf_verifier_state *vstate = env->cur_state; 4686 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4687 int i, slot, spi; 4688 u8 *stype; 4689 int zeros = 0; 4690 4691 for (i = min_off; i < max_off; i++) { 4692 slot = -i - 1; 4693 spi = slot / BPF_REG_SIZE; 4694 mark_stack_slot_scratched(env, spi); 4695 stype = ptr_state->stack[spi].slot_type; 4696 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4697 break; 4698 zeros++; 4699 } 4700 if (zeros == max_off - min_off) { 4701 /* any access_size read into register is zero extended, 4702 * so the whole register == const_zero 4703 */ 4704 __mark_reg_const_zero(&state->regs[dst_regno]); 4705 /* backtracking doesn't support STACK_ZERO yet, 4706 * so mark it precise here, so that later 4707 * backtracking can stop here. 4708 * Backtracking may not need this if this register 4709 * doesn't participate in pointer adjustment. 4710 * Forward propagation of precise flag is not 4711 * necessary either. This mark is only to stop 4712 * backtracking. Any register that contributed 4713 * to const 0 was marked precise before spill. 4714 */ 4715 state->regs[dst_regno].precise = true; 4716 } else { 4717 /* have read misc data from the stack */ 4718 mark_reg_unknown(env, state->regs, dst_regno); 4719 } 4720 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4721 } 4722 4723 /* Read the stack at 'off' and put the results into the register indicated by 4724 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4725 * spilled reg. 4726 * 4727 * 'dst_regno' can be -1, meaning that the read value is not going to a 4728 * register. 4729 * 4730 * The access is assumed to be within the current stack bounds. 4731 */ 4732 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4733 /* func where src register points to */ 4734 struct bpf_func_state *reg_state, 4735 int off, int size, int dst_regno) 4736 { 4737 struct bpf_verifier_state *vstate = env->cur_state; 4738 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4739 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4740 struct bpf_reg_state *reg; 4741 u8 *stype, type; 4742 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi); 4743 4744 stype = reg_state->stack[spi].slot_type; 4745 reg = ®_state->stack[spi].spilled_ptr; 4746 4747 mark_stack_slot_scratched(env, spi); 4748 4749 if (is_spilled_reg(®_state->stack[spi])) { 4750 u8 spill_size = 1; 4751 4752 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4753 spill_size++; 4754 4755 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4756 if (reg->type != SCALAR_VALUE) { 4757 verbose_linfo(env, env->insn_idx, "; "); 4758 verbose(env, "invalid size of register fill\n"); 4759 return -EACCES; 4760 } 4761 4762 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4763 if (dst_regno < 0) 4764 return 0; 4765 4766 if (!(off % BPF_REG_SIZE) && size == spill_size) { 4767 /* The earlier check_reg_arg() has decided the 4768 * subreg_def for this insn. Save it first. 4769 */ 4770 s32 subreg_def = state->regs[dst_regno].subreg_def; 4771 4772 copy_register_state(&state->regs[dst_regno], reg); 4773 state->regs[dst_regno].subreg_def = subreg_def; 4774 } else { 4775 int spill_cnt = 0, zero_cnt = 0; 4776 4777 for (i = 0; i < size; i++) { 4778 type = stype[(slot - i) % BPF_REG_SIZE]; 4779 if (type == STACK_SPILL) { 4780 spill_cnt++; 4781 continue; 4782 } 4783 if (type == STACK_MISC) 4784 continue; 4785 if (type == STACK_ZERO) { 4786 zero_cnt++; 4787 continue; 4788 } 4789 if (type == STACK_INVALID && env->allow_uninit_stack) 4790 continue; 4791 verbose(env, "invalid read from stack off %d+%d size %d\n", 4792 off, i, size); 4793 return -EACCES; 4794 } 4795 4796 if (spill_cnt == size && 4797 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 4798 __mark_reg_const_zero(&state->regs[dst_regno]); 4799 /* this IS register fill, so keep insn_flags */ 4800 } else if (zero_cnt == size) { 4801 /* similarly to mark_reg_stack_read(), preserve zeroes */ 4802 __mark_reg_const_zero(&state->regs[dst_regno]); 4803 insn_flags = 0; /* not restoring original register state */ 4804 } else { 4805 mark_reg_unknown(env, state->regs, dst_regno); 4806 insn_flags = 0; /* not restoring original register state */ 4807 } 4808 } 4809 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4810 } else if (dst_regno >= 0) { 4811 /* restore register state from stack */ 4812 copy_register_state(&state->regs[dst_regno], reg); 4813 /* mark reg as written since spilled pointer state likely 4814 * has its liveness marks cleared by is_state_visited() 4815 * which resets stack/reg liveness for state transitions 4816 */ 4817 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4818 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 4819 /* If dst_regno==-1, the caller is asking us whether 4820 * it is acceptable to use this value as a SCALAR_VALUE 4821 * (e.g. for XADD). 4822 * We must not allow unprivileged callers to do that 4823 * with spilled pointers. 4824 */ 4825 verbose(env, "leaking pointer from stack off %d\n", 4826 off); 4827 return -EACCES; 4828 } 4829 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4830 } else { 4831 for (i = 0; i < size; i++) { 4832 type = stype[(slot - i) % BPF_REG_SIZE]; 4833 if (type == STACK_MISC) 4834 continue; 4835 if (type == STACK_ZERO) 4836 continue; 4837 if (type == STACK_INVALID && env->allow_uninit_stack) 4838 continue; 4839 verbose(env, "invalid read from stack off %d+%d size %d\n", 4840 off, i, size); 4841 return -EACCES; 4842 } 4843 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4844 if (dst_regno >= 0) 4845 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 4846 insn_flags = 0; /* we are not restoring spilled register */ 4847 } 4848 if (insn_flags) 4849 return push_jmp_history(env, env->cur_state, insn_flags); 4850 return 0; 4851 } 4852 4853 enum bpf_access_src { 4854 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 4855 ACCESS_HELPER = 2, /* the access is performed by a helper */ 4856 }; 4857 4858 static int check_stack_range_initialized(struct bpf_verifier_env *env, 4859 int regno, int off, int access_size, 4860 bool zero_size_allowed, 4861 enum bpf_access_src type, 4862 struct bpf_call_arg_meta *meta); 4863 4864 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 4865 { 4866 return cur_regs(env) + regno; 4867 } 4868 4869 /* Read the stack at 'ptr_regno + off' and put the result into the register 4870 * 'dst_regno'. 4871 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 4872 * but not its variable offset. 4873 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 4874 * 4875 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 4876 * filling registers (i.e. reads of spilled register cannot be detected when 4877 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 4878 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 4879 * offset; for a fixed offset check_stack_read_fixed_off should be used 4880 * instead. 4881 */ 4882 static int check_stack_read_var_off(struct bpf_verifier_env *env, 4883 int ptr_regno, int off, int size, int dst_regno) 4884 { 4885 /* The state of the source register. */ 4886 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4887 struct bpf_func_state *ptr_state = func(env, reg); 4888 int err; 4889 int min_off, max_off; 4890 4891 /* Note that we pass a NULL meta, so raw access will not be permitted. 4892 */ 4893 err = check_stack_range_initialized(env, ptr_regno, off, size, 4894 false, ACCESS_DIRECT, NULL); 4895 if (err) 4896 return err; 4897 4898 min_off = reg->smin_value + off; 4899 max_off = reg->smax_value + off; 4900 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 4901 return 0; 4902 } 4903 4904 /* check_stack_read dispatches to check_stack_read_fixed_off or 4905 * check_stack_read_var_off. 4906 * 4907 * The caller must ensure that the offset falls within the allocated stack 4908 * bounds. 4909 * 4910 * 'dst_regno' is a register which will receive the value from the stack. It 4911 * can be -1, meaning that the read value is not going to a register. 4912 */ 4913 static int check_stack_read(struct bpf_verifier_env *env, 4914 int ptr_regno, int off, int size, 4915 int dst_regno) 4916 { 4917 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4918 struct bpf_func_state *state = func(env, reg); 4919 int err; 4920 /* Some accesses are only permitted with a static offset. */ 4921 bool var_off = !tnum_is_const(reg->var_off); 4922 4923 /* The offset is required to be static when reads don't go to a 4924 * register, in order to not leak pointers (see 4925 * check_stack_read_fixed_off). 4926 */ 4927 if (dst_regno < 0 && var_off) { 4928 char tn_buf[48]; 4929 4930 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4931 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 4932 tn_buf, off, size); 4933 return -EACCES; 4934 } 4935 /* Variable offset is prohibited for unprivileged mode for simplicity 4936 * since it requires corresponding support in Spectre masking for stack 4937 * ALU. See also retrieve_ptr_limit(). The check in 4938 * check_stack_access_for_ptr_arithmetic() called by 4939 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 4940 * with variable offsets, therefore no check is required here. Further, 4941 * just checking it here would be insufficient as speculative stack 4942 * writes could still lead to unsafe speculative behaviour. 4943 */ 4944 if (!var_off) { 4945 off += reg->var_off.value; 4946 err = check_stack_read_fixed_off(env, state, off, size, 4947 dst_regno); 4948 } else { 4949 /* Variable offset stack reads need more conservative handling 4950 * than fixed offset ones. Note that dst_regno >= 0 on this 4951 * branch. 4952 */ 4953 err = check_stack_read_var_off(env, ptr_regno, off, size, 4954 dst_regno); 4955 } 4956 return err; 4957 } 4958 4959 4960 /* check_stack_write dispatches to check_stack_write_fixed_off or 4961 * check_stack_write_var_off. 4962 * 4963 * 'ptr_regno' is the register used as a pointer into the stack. 4964 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 4965 * 'value_regno' is the register whose value we're writing to the stack. It can 4966 * be -1, meaning that we're not writing from a register. 4967 * 4968 * The caller must ensure that the offset falls within the maximum stack size. 4969 */ 4970 static int check_stack_write(struct bpf_verifier_env *env, 4971 int ptr_regno, int off, int size, 4972 int value_regno, int insn_idx) 4973 { 4974 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4975 struct bpf_func_state *state = func(env, reg); 4976 int err; 4977 4978 if (tnum_is_const(reg->var_off)) { 4979 off += reg->var_off.value; 4980 err = check_stack_write_fixed_off(env, state, off, size, 4981 value_regno, insn_idx); 4982 } else { 4983 /* Variable offset stack reads need more conservative handling 4984 * than fixed offset ones. 4985 */ 4986 err = check_stack_write_var_off(env, state, 4987 ptr_regno, off, size, 4988 value_regno, insn_idx); 4989 } 4990 return err; 4991 } 4992 4993 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 4994 int off, int size, enum bpf_access_type type) 4995 { 4996 struct bpf_reg_state *regs = cur_regs(env); 4997 struct bpf_map *map = regs[regno].map_ptr; 4998 u32 cap = bpf_map_flags_to_cap(map); 4999 5000 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 5001 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 5002 map->value_size, off, size); 5003 return -EACCES; 5004 } 5005 5006 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 5007 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 5008 map->value_size, off, size); 5009 return -EACCES; 5010 } 5011 5012 return 0; 5013 } 5014 5015 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 5016 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 5017 int off, int size, u32 mem_size, 5018 bool zero_size_allowed) 5019 { 5020 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 5021 struct bpf_reg_state *reg; 5022 5023 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 5024 return 0; 5025 5026 reg = &cur_regs(env)[regno]; 5027 switch (reg->type) { 5028 case PTR_TO_MAP_KEY: 5029 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 5030 mem_size, off, size); 5031 break; 5032 case PTR_TO_MAP_VALUE: 5033 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 5034 mem_size, off, size); 5035 break; 5036 case PTR_TO_PACKET: 5037 case PTR_TO_PACKET_META: 5038 case PTR_TO_PACKET_END: 5039 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 5040 off, size, regno, reg->id, off, mem_size); 5041 break; 5042 case PTR_TO_MEM: 5043 default: 5044 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 5045 mem_size, off, size); 5046 } 5047 5048 return -EACCES; 5049 } 5050 5051 /* check read/write into a memory region with possible variable offset */ 5052 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 5053 int off, int size, u32 mem_size, 5054 bool zero_size_allowed) 5055 { 5056 struct bpf_verifier_state *vstate = env->cur_state; 5057 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5058 struct bpf_reg_state *reg = &state->regs[regno]; 5059 int err; 5060 5061 /* We may have adjusted the register pointing to memory region, so we 5062 * need to try adding each of min_value and max_value to off 5063 * to make sure our theoretical access will be safe. 5064 * 5065 * The minimum value is only important with signed 5066 * comparisons where we can't assume the floor of a 5067 * value is 0. If we are using signed variables for our 5068 * index'es we need to make sure that whatever we use 5069 * will have a set floor within our range. 5070 */ 5071 if (reg->smin_value < 0 && 5072 (reg->smin_value == S64_MIN || 5073 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5074 reg->smin_value + off < 0)) { 5075 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5076 regno); 5077 return -EACCES; 5078 } 5079 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5080 mem_size, zero_size_allowed); 5081 if (err) { 5082 verbose(env, "R%d min value is outside of the allowed memory range\n", 5083 regno); 5084 return err; 5085 } 5086 5087 /* If we haven't set a max value then we need to bail since we can't be 5088 * sure we won't do bad things. 5089 * If reg->umax_value + off could overflow, treat that as unbounded too. 5090 */ 5091 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5092 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5093 regno); 5094 return -EACCES; 5095 } 5096 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5097 mem_size, zero_size_allowed); 5098 if (err) { 5099 verbose(env, "R%d max value is outside of the allowed memory range\n", 5100 regno); 5101 return err; 5102 } 5103 5104 return 0; 5105 } 5106 5107 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5108 const struct bpf_reg_state *reg, int regno, 5109 bool fixed_off_ok) 5110 { 5111 /* Access to this pointer-typed register or passing it to a helper 5112 * is only allowed in its original, unmodified form. 5113 */ 5114 5115 if (reg->off < 0) { 5116 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5117 reg_type_str(env, reg->type), regno, reg->off); 5118 return -EACCES; 5119 } 5120 5121 if (!fixed_off_ok && reg->off) { 5122 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5123 reg_type_str(env, reg->type), regno, reg->off); 5124 return -EACCES; 5125 } 5126 5127 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5128 char tn_buf[48]; 5129 5130 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5131 verbose(env, "variable %s access var_off=%s disallowed\n", 5132 reg_type_str(env, reg->type), tn_buf); 5133 return -EACCES; 5134 } 5135 5136 return 0; 5137 } 5138 5139 int check_ptr_off_reg(struct bpf_verifier_env *env, 5140 const struct bpf_reg_state *reg, int regno) 5141 { 5142 return __check_ptr_off_reg(env, reg, regno, false); 5143 } 5144 5145 static int map_kptr_match_type(struct bpf_verifier_env *env, 5146 struct btf_field *kptr_field, 5147 struct bpf_reg_state *reg, u32 regno) 5148 { 5149 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5150 int perm_flags; 5151 const char *reg_name = ""; 5152 5153 if (btf_is_kernel(reg->btf)) { 5154 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5155 5156 /* Only unreferenced case accepts untrusted pointers */ 5157 if (kptr_field->type == BPF_KPTR_UNREF) 5158 perm_flags |= PTR_UNTRUSTED; 5159 } else { 5160 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5161 if (kptr_field->type == BPF_KPTR_PERCPU) 5162 perm_flags |= MEM_PERCPU; 5163 } 5164 5165 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5166 goto bad_type; 5167 5168 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5169 reg_name = btf_type_name(reg->btf, reg->btf_id); 5170 5171 /* For ref_ptr case, release function check should ensure we get one 5172 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5173 * normal store of unreferenced kptr, we must ensure var_off is zero. 5174 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5175 * reg->off and reg->ref_obj_id are not needed here. 5176 */ 5177 if (__check_ptr_off_reg(env, reg, regno, true)) 5178 return -EACCES; 5179 5180 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5181 * we also need to take into account the reg->off. 5182 * 5183 * We want to support cases like: 5184 * 5185 * struct foo { 5186 * struct bar br; 5187 * struct baz bz; 5188 * }; 5189 * 5190 * struct foo *v; 5191 * v = func(); // PTR_TO_BTF_ID 5192 * val->foo = v; // reg->off is zero, btf and btf_id match type 5193 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5194 * // first member type of struct after comparison fails 5195 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5196 * // to match type 5197 * 5198 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5199 * is zero. We must also ensure that btf_struct_ids_match does not walk 5200 * the struct to match type against first member of struct, i.e. reject 5201 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5202 * strict mode to true for type match. 5203 */ 5204 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5205 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5206 kptr_field->type != BPF_KPTR_UNREF)) 5207 goto bad_type; 5208 return 0; 5209 bad_type: 5210 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5211 reg_type_str(env, reg->type), reg_name); 5212 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5213 if (kptr_field->type == BPF_KPTR_UNREF) 5214 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5215 targ_name); 5216 else 5217 verbose(env, "\n"); 5218 return -EINVAL; 5219 } 5220 5221 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5222 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5223 */ 5224 static bool in_rcu_cs(struct bpf_verifier_env *env) 5225 { 5226 return env->cur_state->active_rcu_lock || 5227 env->cur_state->active_lock.ptr || 5228 !env->prog->aux->sleepable; 5229 } 5230 5231 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5232 BTF_SET_START(rcu_protected_types) 5233 BTF_ID(struct, prog_test_ref_kfunc) 5234 #ifdef CONFIG_CGROUPS 5235 BTF_ID(struct, cgroup) 5236 #endif 5237 BTF_ID(struct, bpf_cpumask) 5238 BTF_ID(struct, task_struct) 5239 BTF_SET_END(rcu_protected_types) 5240 5241 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5242 { 5243 if (!btf_is_kernel(btf)) 5244 return true; 5245 return btf_id_set_contains(&rcu_protected_types, btf_id); 5246 } 5247 5248 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 5249 { 5250 struct btf_struct_meta *meta; 5251 5252 if (btf_is_kernel(kptr_field->kptr.btf)) 5253 return NULL; 5254 5255 meta = btf_find_struct_meta(kptr_field->kptr.btf, 5256 kptr_field->kptr.btf_id); 5257 5258 return meta ? meta->record : NULL; 5259 } 5260 5261 static bool rcu_safe_kptr(const struct btf_field *field) 5262 { 5263 const struct btf_field_kptr *kptr = &field->kptr; 5264 5265 return field->type == BPF_KPTR_PERCPU || 5266 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 5267 } 5268 5269 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 5270 { 5271 struct btf_record *rec; 5272 u32 ret; 5273 5274 ret = PTR_MAYBE_NULL; 5275 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 5276 ret |= MEM_RCU; 5277 if (kptr_field->type == BPF_KPTR_PERCPU) 5278 ret |= MEM_PERCPU; 5279 else if (!btf_is_kernel(kptr_field->kptr.btf)) 5280 ret |= MEM_ALLOC; 5281 5282 rec = kptr_pointee_btf_record(kptr_field); 5283 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 5284 ret |= NON_OWN_REF; 5285 } else { 5286 ret |= PTR_UNTRUSTED; 5287 } 5288 5289 return ret; 5290 } 5291 5292 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5293 int value_regno, int insn_idx, 5294 struct btf_field *kptr_field) 5295 { 5296 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5297 int class = BPF_CLASS(insn->code); 5298 struct bpf_reg_state *val_reg; 5299 5300 /* Things we already checked for in check_map_access and caller: 5301 * - Reject cases where variable offset may touch kptr 5302 * - size of access (must be BPF_DW) 5303 * - tnum_is_const(reg->var_off) 5304 * - kptr_field->offset == off + reg->var_off.value 5305 */ 5306 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5307 if (BPF_MODE(insn->code) != BPF_MEM) { 5308 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5309 return -EACCES; 5310 } 5311 5312 /* We only allow loading referenced kptr, since it will be marked as 5313 * untrusted, similar to unreferenced kptr. 5314 */ 5315 if (class != BPF_LDX && 5316 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 5317 verbose(env, "store to referenced kptr disallowed\n"); 5318 return -EACCES; 5319 } 5320 5321 if (class == BPF_LDX) { 5322 val_reg = reg_state(env, value_regno); 5323 /* We can simply mark the value_regno receiving the pointer 5324 * value from map as PTR_TO_BTF_ID, with the correct type. 5325 */ 5326 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5327 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field)); 5328 /* For mark_ptr_or_null_reg */ 5329 val_reg->id = ++env->id_gen; 5330 } else if (class == BPF_STX) { 5331 val_reg = reg_state(env, value_regno); 5332 if (!register_is_null(val_reg) && 5333 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5334 return -EACCES; 5335 } else if (class == BPF_ST) { 5336 if (insn->imm) { 5337 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5338 kptr_field->offset); 5339 return -EACCES; 5340 } 5341 } else { 5342 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5343 return -EACCES; 5344 } 5345 return 0; 5346 } 5347 5348 /* check read/write into a map element with possible variable offset */ 5349 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5350 int off, int size, bool zero_size_allowed, 5351 enum bpf_access_src src) 5352 { 5353 struct bpf_verifier_state *vstate = env->cur_state; 5354 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5355 struct bpf_reg_state *reg = &state->regs[regno]; 5356 struct bpf_map *map = reg->map_ptr; 5357 struct btf_record *rec; 5358 int err, i; 5359 5360 err = check_mem_region_access(env, regno, off, size, map->value_size, 5361 zero_size_allowed); 5362 if (err) 5363 return err; 5364 5365 if (IS_ERR_OR_NULL(map->record)) 5366 return 0; 5367 rec = map->record; 5368 for (i = 0; i < rec->cnt; i++) { 5369 struct btf_field *field = &rec->fields[i]; 5370 u32 p = field->offset; 5371 5372 /* If any part of a field can be touched by load/store, reject 5373 * this program. To check that [x1, x2) overlaps with [y1, y2), 5374 * it is sufficient to check x1 < y2 && y1 < x2. 5375 */ 5376 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 5377 p < reg->umax_value + off + size) { 5378 switch (field->type) { 5379 case BPF_KPTR_UNREF: 5380 case BPF_KPTR_REF: 5381 case BPF_KPTR_PERCPU: 5382 if (src != ACCESS_DIRECT) { 5383 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 5384 return -EACCES; 5385 } 5386 if (!tnum_is_const(reg->var_off)) { 5387 verbose(env, "kptr access cannot have variable offset\n"); 5388 return -EACCES; 5389 } 5390 if (p != off + reg->var_off.value) { 5391 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 5392 p, off + reg->var_off.value); 5393 return -EACCES; 5394 } 5395 if (size != bpf_size_to_bytes(BPF_DW)) { 5396 verbose(env, "kptr access size must be BPF_DW\n"); 5397 return -EACCES; 5398 } 5399 break; 5400 default: 5401 verbose(env, "%s cannot be accessed directly by load/store\n", 5402 btf_field_type_name(field->type)); 5403 return -EACCES; 5404 } 5405 } 5406 } 5407 return 0; 5408 } 5409 5410 #define MAX_PACKET_OFF 0xffff 5411 5412 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5413 const struct bpf_call_arg_meta *meta, 5414 enum bpf_access_type t) 5415 { 5416 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5417 5418 switch (prog_type) { 5419 /* Program types only with direct read access go here! */ 5420 case BPF_PROG_TYPE_LWT_IN: 5421 case BPF_PROG_TYPE_LWT_OUT: 5422 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5423 case BPF_PROG_TYPE_SK_REUSEPORT: 5424 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5425 case BPF_PROG_TYPE_CGROUP_SKB: 5426 if (t == BPF_WRITE) 5427 return false; 5428 fallthrough; 5429 5430 /* Program types with direct read + write access go here! */ 5431 case BPF_PROG_TYPE_SCHED_CLS: 5432 case BPF_PROG_TYPE_SCHED_ACT: 5433 case BPF_PROG_TYPE_XDP: 5434 case BPF_PROG_TYPE_LWT_XMIT: 5435 case BPF_PROG_TYPE_SK_SKB: 5436 case BPF_PROG_TYPE_SK_MSG: 5437 if (meta) 5438 return meta->pkt_access; 5439 5440 env->seen_direct_write = true; 5441 return true; 5442 5443 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5444 if (t == BPF_WRITE) 5445 env->seen_direct_write = true; 5446 5447 return true; 5448 5449 default: 5450 return false; 5451 } 5452 } 5453 5454 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5455 int size, bool zero_size_allowed) 5456 { 5457 struct bpf_reg_state *regs = cur_regs(env); 5458 struct bpf_reg_state *reg = ®s[regno]; 5459 int err; 5460 5461 /* We may have added a variable offset to the packet pointer; but any 5462 * reg->range we have comes after that. We are only checking the fixed 5463 * offset. 5464 */ 5465 5466 /* We don't allow negative numbers, because we aren't tracking enough 5467 * detail to prove they're safe. 5468 */ 5469 if (reg->smin_value < 0) { 5470 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5471 regno); 5472 return -EACCES; 5473 } 5474 5475 err = reg->range < 0 ? -EINVAL : 5476 __check_mem_access(env, regno, off, size, reg->range, 5477 zero_size_allowed); 5478 if (err) { 5479 verbose(env, "R%d offset is outside of the packet\n", regno); 5480 return err; 5481 } 5482 5483 /* __check_mem_access has made sure "off + size - 1" is within u16. 5484 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5485 * otherwise find_good_pkt_pointers would have refused to set range info 5486 * that __check_mem_access would have rejected this pkt access. 5487 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5488 */ 5489 env->prog->aux->max_pkt_offset = 5490 max_t(u32, env->prog->aux->max_pkt_offset, 5491 off + reg->umax_value + size - 1); 5492 5493 return err; 5494 } 5495 5496 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5497 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5498 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5499 struct btf **btf, u32 *btf_id) 5500 { 5501 struct bpf_insn_access_aux info = { 5502 .reg_type = *reg_type, 5503 .log = &env->log, 5504 }; 5505 5506 if (env->ops->is_valid_access && 5507 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5508 /* A non zero info.ctx_field_size indicates that this field is a 5509 * candidate for later verifier transformation to load the whole 5510 * field and then apply a mask when accessed with a narrower 5511 * access than actual ctx access size. A zero info.ctx_field_size 5512 * will only allow for whole field access and rejects any other 5513 * type of narrower access. 5514 */ 5515 *reg_type = info.reg_type; 5516 5517 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5518 *btf = info.btf; 5519 *btf_id = info.btf_id; 5520 } else { 5521 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5522 } 5523 /* remember the offset of last byte accessed in ctx */ 5524 if (env->prog->aux->max_ctx_offset < off + size) 5525 env->prog->aux->max_ctx_offset = off + size; 5526 return 0; 5527 } 5528 5529 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5530 return -EACCES; 5531 } 5532 5533 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5534 int size) 5535 { 5536 if (size < 0 || off < 0 || 5537 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5538 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5539 off, size); 5540 return -EACCES; 5541 } 5542 return 0; 5543 } 5544 5545 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5546 u32 regno, int off, int size, 5547 enum bpf_access_type t) 5548 { 5549 struct bpf_reg_state *regs = cur_regs(env); 5550 struct bpf_reg_state *reg = ®s[regno]; 5551 struct bpf_insn_access_aux info = {}; 5552 bool valid; 5553 5554 if (reg->smin_value < 0) { 5555 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5556 regno); 5557 return -EACCES; 5558 } 5559 5560 switch (reg->type) { 5561 case PTR_TO_SOCK_COMMON: 5562 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5563 break; 5564 case PTR_TO_SOCKET: 5565 valid = bpf_sock_is_valid_access(off, size, t, &info); 5566 break; 5567 case PTR_TO_TCP_SOCK: 5568 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5569 break; 5570 case PTR_TO_XDP_SOCK: 5571 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5572 break; 5573 default: 5574 valid = false; 5575 } 5576 5577 5578 if (valid) { 5579 env->insn_aux_data[insn_idx].ctx_field_size = 5580 info.ctx_field_size; 5581 return 0; 5582 } 5583 5584 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5585 regno, reg_type_str(env, reg->type), off, size); 5586 5587 return -EACCES; 5588 } 5589 5590 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5591 { 5592 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5593 } 5594 5595 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5596 { 5597 const struct bpf_reg_state *reg = reg_state(env, regno); 5598 5599 return reg->type == PTR_TO_CTX; 5600 } 5601 5602 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5603 { 5604 const struct bpf_reg_state *reg = reg_state(env, regno); 5605 5606 return type_is_sk_pointer(reg->type); 5607 } 5608 5609 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5610 { 5611 const struct bpf_reg_state *reg = reg_state(env, regno); 5612 5613 return type_is_pkt_pointer(reg->type); 5614 } 5615 5616 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5617 { 5618 const struct bpf_reg_state *reg = reg_state(env, regno); 5619 5620 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5621 return reg->type == PTR_TO_FLOW_KEYS; 5622 } 5623 5624 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5625 #ifdef CONFIG_NET 5626 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5627 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5628 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5629 #endif 5630 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5631 }; 5632 5633 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5634 { 5635 /* A referenced register is always trusted. */ 5636 if (reg->ref_obj_id) 5637 return true; 5638 5639 /* Types listed in the reg2btf_ids are always trusted */ 5640 if (reg2btf_ids[base_type(reg->type)]) 5641 return true; 5642 5643 /* If a register is not referenced, it is trusted if it has the 5644 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5645 * other type modifiers may be safe, but we elect to take an opt-in 5646 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5647 * not. 5648 * 5649 * Eventually, we should make PTR_TRUSTED the single source of truth 5650 * for whether a register is trusted. 5651 */ 5652 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5653 !bpf_type_has_unsafe_modifiers(reg->type); 5654 } 5655 5656 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5657 { 5658 return reg->type & MEM_RCU; 5659 } 5660 5661 static void clear_trusted_flags(enum bpf_type_flag *flag) 5662 { 5663 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5664 } 5665 5666 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5667 const struct bpf_reg_state *reg, 5668 int off, int size, bool strict) 5669 { 5670 struct tnum reg_off; 5671 int ip_align; 5672 5673 /* Byte size accesses are always allowed. */ 5674 if (!strict || size == 1) 5675 return 0; 5676 5677 /* For platforms that do not have a Kconfig enabling 5678 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5679 * NET_IP_ALIGN is universally set to '2'. And on platforms 5680 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5681 * to this code only in strict mode where we want to emulate 5682 * the NET_IP_ALIGN==2 checking. Therefore use an 5683 * unconditional IP align value of '2'. 5684 */ 5685 ip_align = 2; 5686 5687 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5688 if (!tnum_is_aligned(reg_off, size)) { 5689 char tn_buf[48]; 5690 5691 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5692 verbose(env, 5693 "misaligned packet access off %d+%s+%d+%d size %d\n", 5694 ip_align, tn_buf, reg->off, off, size); 5695 return -EACCES; 5696 } 5697 5698 return 0; 5699 } 5700 5701 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5702 const struct bpf_reg_state *reg, 5703 const char *pointer_desc, 5704 int off, int size, bool strict) 5705 { 5706 struct tnum reg_off; 5707 5708 /* Byte size accesses are always allowed. */ 5709 if (!strict || size == 1) 5710 return 0; 5711 5712 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5713 if (!tnum_is_aligned(reg_off, size)) { 5714 char tn_buf[48]; 5715 5716 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5717 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5718 pointer_desc, tn_buf, reg->off, off, size); 5719 return -EACCES; 5720 } 5721 5722 return 0; 5723 } 5724 5725 static int check_ptr_alignment(struct bpf_verifier_env *env, 5726 const struct bpf_reg_state *reg, int off, 5727 int size, bool strict_alignment_once) 5728 { 5729 bool strict = env->strict_alignment || strict_alignment_once; 5730 const char *pointer_desc = ""; 5731 5732 switch (reg->type) { 5733 case PTR_TO_PACKET: 5734 case PTR_TO_PACKET_META: 5735 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5736 * right in front, treat it the very same way. 5737 */ 5738 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5739 case PTR_TO_FLOW_KEYS: 5740 pointer_desc = "flow keys "; 5741 break; 5742 case PTR_TO_MAP_KEY: 5743 pointer_desc = "key "; 5744 break; 5745 case PTR_TO_MAP_VALUE: 5746 pointer_desc = "value "; 5747 break; 5748 case PTR_TO_CTX: 5749 pointer_desc = "context "; 5750 break; 5751 case PTR_TO_STACK: 5752 pointer_desc = "stack "; 5753 /* The stack spill tracking logic in check_stack_write_fixed_off() 5754 * and check_stack_read_fixed_off() relies on stack accesses being 5755 * aligned. 5756 */ 5757 strict = true; 5758 break; 5759 case PTR_TO_SOCKET: 5760 pointer_desc = "sock "; 5761 break; 5762 case PTR_TO_SOCK_COMMON: 5763 pointer_desc = "sock_common "; 5764 break; 5765 case PTR_TO_TCP_SOCK: 5766 pointer_desc = "tcp_sock "; 5767 break; 5768 case PTR_TO_XDP_SOCK: 5769 pointer_desc = "xdp_sock "; 5770 break; 5771 default: 5772 break; 5773 } 5774 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5775 strict); 5776 } 5777 5778 /* starting from main bpf function walk all instructions of the function 5779 * and recursively walk all callees that given function can call. 5780 * Ignore jump and exit insns. 5781 * Since recursion is prevented by check_cfg() this algorithm 5782 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 5783 */ 5784 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx) 5785 { 5786 struct bpf_subprog_info *subprog = env->subprog_info; 5787 struct bpf_insn *insn = env->prog->insnsi; 5788 int depth = 0, frame = 0, i, subprog_end; 5789 bool tail_call_reachable = false; 5790 int ret_insn[MAX_CALL_FRAMES]; 5791 int ret_prog[MAX_CALL_FRAMES]; 5792 int j; 5793 5794 i = subprog[idx].start; 5795 process_func: 5796 /* protect against potential stack overflow that might happen when 5797 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5798 * depth for such case down to 256 so that the worst case scenario 5799 * would result in 8k stack size (32 which is tailcall limit * 256 = 5800 * 8k). 5801 * 5802 * To get the idea what might happen, see an example: 5803 * func1 -> sub rsp, 128 5804 * subfunc1 -> sub rsp, 256 5805 * tailcall1 -> add rsp, 256 5806 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5807 * subfunc2 -> sub rsp, 64 5808 * subfunc22 -> sub rsp, 128 5809 * tailcall2 -> add rsp, 128 5810 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5811 * 5812 * tailcall will unwind the current stack frame but it will not get rid 5813 * of caller's stack as shown on the example above. 5814 */ 5815 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5816 verbose(env, 5817 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5818 depth); 5819 return -EACCES; 5820 } 5821 /* round up to 32-bytes, since this is granularity 5822 * of interpreter stack size 5823 */ 5824 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5825 if (depth > MAX_BPF_STACK) { 5826 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5827 frame + 1, depth); 5828 return -EACCES; 5829 } 5830 continue_func: 5831 subprog_end = subprog[idx + 1].start; 5832 for (; i < subprog_end; i++) { 5833 int next_insn, sidx; 5834 5835 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 5836 bool err = false; 5837 5838 if (!is_bpf_throw_kfunc(insn + i)) 5839 continue; 5840 if (subprog[idx].is_cb) 5841 err = true; 5842 for (int c = 0; c < frame && !err; c++) { 5843 if (subprog[ret_prog[c]].is_cb) { 5844 err = true; 5845 break; 5846 } 5847 } 5848 if (!err) 5849 continue; 5850 verbose(env, 5851 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 5852 i, idx); 5853 return -EINVAL; 5854 } 5855 5856 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5857 continue; 5858 /* remember insn and function to return to */ 5859 ret_insn[frame] = i + 1; 5860 ret_prog[frame] = idx; 5861 5862 /* find the callee */ 5863 next_insn = i + insn[i].imm + 1; 5864 sidx = find_subprog(env, next_insn); 5865 if (sidx < 0) { 5866 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5867 next_insn); 5868 return -EFAULT; 5869 } 5870 if (subprog[sidx].is_async_cb) { 5871 if (subprog[sidx].has_tail_call) { 5872 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 5873 return -EFAULT; 5874 } 5875 /* async callbacks don't increase bpf prog stack size unless called directly */ 5876 if (!bpf_pseudo_call(insn + i)) 5877 continue; 5878 if (subprog[sidx].is_exception_cb) { 5879 verbose(env, "insn %d cannot call exception cb directly\n", i); 5880 return -EINVAL; 5881 } 5882 } 5883 i = next_insn; 5884 idx = sidx; 5885 5886 if (subprog[idx].has_tail_call) 5887 tail_call_reachable = true; 5888 5889 frame++; 5890 if (frame >= MAX_CALL_FRAMES) { 5891 verbose(env, "the call stack of %d frames is too deep !\n", 5892 frame); 5893 return -E2BIG; 5894 } 5895 goto process_func; 5896 } 5897 /* if tail call got detected across bpf2bpf calls then mark each of the 5898 * currently present subprog frames as tail call reachable subprogs; 5899 * this info will be utilized by JIT so that we will be preserving the 5900 * tail call counter throughout bpf2bpf calls combined with tailcalls 5901 */ 5902 if (tail_call_reachable) 5903 for (j = 0; j < frame; j++) { 5904 if (subprog[ret_prog[j]].is_exception_cb) { 5905 verbose(env, "cannot tail call within exception cb\n"); 5906 return -EINVAL; 5907 } 5908 subprog[ret_prog[j]].tail_call_reachable = true; 5909 } 5910 if (subprog[0].tail_call_reachable) 5911 env->prog->aux->tail_call_reachable = true; 5912 5913 /* end of for() loop means the last insn of the 'subprog' 5914 * was reached. Doesn't matter whether it was JA or EXIT 5915 */ 5916 if (frame == 0) 5917 return 0; 5918 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5919 frame--; 5920 i = ret_insn[frame]; 5921 idx = ret_prog[frame]; 5922 goto continue_func; 5923 } 5924 5925 static int check_max_stack_depth(struct bpf_verifier_env *env) 5926 { 5927 struct bpf_subprog_info *si = env->subprog_info; 5928 int ret; 5929 5930 for (int i = 0; i < env->subprog_cnt; i++) { 5931 if (!i || si[i].is_async_cb) { 5932 ret = check_max_stack_depth_subprog(env, i); 5933 if (ret < 0) 5934 return ret; 5935 } 5936 continue; 5937 } 5938 return 0; 5939 } 5940 5941 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 5942 static int get_callee_stack_depth(struct bpf_verifier_env *env, 5943 const struct bpf_insn *insn, int idx) 5944 { 5945 int start = idx + insn->imm + 1, subprog; 5946 5947 subprog = find_subprog(env, start); 5948 if (subprog < 0) { 5949 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5950 start); 5951 return -EFAULT; 5952 } 5953 return env->subprog_info[subprog].stack_depth; 5954 } 5955 #endif 5956 5957 static int __check_buffer_access(struct bpf_verifier_env *env, 5958 const char *buf_info, 5959 const struct bpf_reg_state *reg, 5960 int regno, int off, int size) 5961 { 5962 if (off < 0) { 5963 verbose(env, 5964 "R%d invalid %s buffer access: off=%d, size=%d\n", 5965 regno, buf_info, off, size); 5966 return -EACCES; 5967 } 5968 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5969 char tn_buf[48]; 5970 5971 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5972 verbose(env, 5973 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 5974 regno, off, tn_buf); 5975 return -EACCES; 5976 } 5977 5978 return 0; 5979 } 5980 5981 static int check_tp_buffer_access(struct bpf_verifier_env *env, 5982 const struct bpf_reg_state *reg, 5983 int regno, int off, int size) 5984 { 5985 int err; 5986 5987 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 5988 if (err) 5989 return err; 5990 5991 if (off + size > env->prog->aux->max_tp_access) 5992 env->prog->aux->max_tp_access = off + size; 5993 5994 return 0; 5995 } 5996 5997 static int check_buffer_access(struct bpf_verifier_env *env, 5998 const struct bpf_reg_state *reg, 5999 int regno, int off, int size, 6000 bool zero_size_allowed, 6001 u32 *max_access) 6002 { 6003 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 6004 int err; 6005 6006 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 6007 if (err) 6008 return err; 6009 6010 if (off + size > *max_access) 6011 *max_access = off + size; 6012 6013 return 0; 6014 } 6015 6016 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 6017 static void zext_32_to_64(struct bpf_reg_state *reg) 6018 { 6019 reg->var_off = tnum_subreg(reg->var_off); 6020 __reg_assign_32_into_64(reg); 6021 } 6022 6023 /* truncate register to smaller size (in bytes) 6024 * must be called with size < BPF_REG_SIZE 6025 */ 6026 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 6027 { 6028 u64 mask; 6029 6030 /* clear high bits in bit representation */ 6031 reg->var_off = tnum_cast(reg->var_off, size); 6032 6033 /* fix arithmetic bounds */ 6034 mask = ((u64)1 << (size * 8)) - 1; 6035 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 6036 reg->umin_value &= mask; 6037 reg->umax_value &= mask; 6038 } else { 6039 reg->umin_value = 0; 6040 reg->umax_value = mask; 6041 } 6042 reg->smin_value = reg->umin_value; 6043 reg->smax_value = reg->umax_value; 6044 6045 /* If size is smaller than 32bit register the 32bit register 6046 * values are also truncated so we push 64-bit bounds into 6047 * 32-bit bounds. Above were truncated < 32-bits already. 6048 */ 6049 if (size < 4) { 6050 __mark_reg32_unbounded(reg); 6051 reg_bounds_sync(reg); 6052 } 6053 } 6054 6055 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 6056 { 6057 if (size == 1) { 6058 reg->smin_value = reg->s32_min_value = S8_MIN; 6059 reg->smax_value = reg->s32_max_value = S8_MAX; 6060 } else if (size == 2) { 6061 reg->smin_value = reg->s32_min_value = S16_MIN; 6062 reg->smax_value = reg->s32_max_value = S16_MAX; 6063 } else { 6064 /* size == 4 */ 6065 reg->smin_value = reg->s32_min_value = S32_MIN; 6066 reg->smax_value = reg->s32_max_value = S32_MAX; 6067 } 6068 reg->umin_value = reg->u32_min_value = 0; 6069 reg->umax_value = U64_MAX; 6070 reg->u32_max_value = U32_MAX; 6071 reg->var_off = tnum_unknown; 6072 } 6073 6074 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6075 { 6076 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6077 u64 top_smax_value, top_smin_value; 6078 u64 num_bits = size * 8; 6079 6080 if (tnum_is_const(reg->var_off)) { 6081 u64_cval = reg->var_off.value; 6082 if (size == 1) 6083 reg->var_off = tnum_const((s8)u64_cval); 6084 else if (size == 2) 6085 reg->var_off = tnum_const((s16)u64_cval); 6086 else 6087 /* size == 4 */ 6088 reg->var_off = tnum_const((s32)u64_cval); 6089 6090 u64_cval = reg->var_off.value; 6091 reg->smax_value = reg->smin_value = u64_cval; 6092 reg->umax_value = reg->umin_value = u64_cval; 6093 reg->s32_max_value = reg->s32_min_value = u64_cval; 6094 reg->u32_max_value = reg->u32_min_value = u64_cval; 6095 return; 6096 } 6097 6098 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6099 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6100 6101 if (top_smax_value != top_smin_value) 6102 goto out; 6103 6104 /* find the s64_min and s64_min after sign extension */ 6105 if (size == 1) { 6106 init_s64_max = (s8)reg->smax_value; 6107 init_s64_min = (s8)reg->smin_value; 6108 } else if (size == 2) { 6109 init_s64_max = (s16)reg->smax_value; 6110 init_s64_min = (s16)reg->smin_value; 6111 } else { 6112 init_s64_max = (s32)reg->smax_value; 6113 init_s64_min = (s32)reg->smin_value; 6114 } 6115 6116 s64_max = max(init_s64_max, init_s64_min); 6117 s64_min = min(init_s64_max, init_s64_min); 6118 6119 /* both of s64_max/s64_min positive or negative */ 6120 if ((s64_max >= 0) == (s64_min >= 0)) { 6121 reg->smin_value = reg->s32_min_value = s64_min; 6122 reg->smax_value = reg->s32_max_value = s64_max; 6123 reg->umin_value = reg->u32_min_value = s64_min; 6124 reg->umax_value = reg->u32_max_value = s64_max; 6125 reg->var_off = tnum_range(s64_min, s64_max); 6126 return; 6127 } 6128 6129 out: 6130 set_sext64_default_val(reg, size); 6131 } 6132 6133 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6134 { 6135 if (size == 1) { 6136 reg->s32_min_value = S8_MIN; 6137 reg->s32_max_value = S8_MAX; 6138 } else { 6139 /* size == 2 */ 6140 reg->s32_min_value = S16_MIN; 6141 reg->s32_max_value = S16_MAX; 6142 } 6143 reg->u32_min_value = 0; 6144 reg->u32_max_value = U32_MAX; 6145 } 6146 6147 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6148 { 6149 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6150 u32 top_smax_value, top_smin_value; 6151 u32 num_bits = size * 8; 6152 6153 if (tnum_is_const(reg->var_off)) { 6154 u32_val = reg->var_off.value; 6155 if (size == 1) 6156 reg->var_off = tnum_const((s8)u32_val); 6157 else 6158 reg->var_off = tnum_const((s16)u32_val); 6159 6160 u32_val = reg->var_off.value; 6161 reg->s32_min_value = reg->s32_max_value = u32_val; 6162 reg->u32_min_value = reg->u32_max_value = u32_val; 6163 return; 6164 } 6165 6166 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 6167 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 6168 6169 if (top_smax_value != top_smin_value) 6170 goto out; 6171 6172 /* find the s32_min and s32_min after sign extension */ 6173 if (size == 1) { 6174 init_s32_max = (s8)reg->s32_max_value; 6175 init_s32_min = (s8)reg->s32_min_value; 6176 } else { 6177 /* size == 2 */ 6178 init_s32_max = (s16)reg->s32_max_value; 6179 init_s32_min = (s16)reg->s32_min_value; 6180 } 6181 s32_max = max(init_s32_max, init_s32_min); 6182 s32_min = min(init_s32_max, init_s32_min); 6183 6184 if ((s32_min >= 0) == (s32_max >= 0)) { 6185 reg->s32_min_value = s32_min; 6186 reg->s32_max_value = s32_max; 6187 reg->u32_min_value = (u32)s32_min; 6188 reg->u32_max_value = (u32)s32_max; 6189 return; 6190 } 6191 6192 out: 6193 set_sext32_default_val(reg, size); 6194 } 6195 6196 static bool bpf_map_is_rdonly(const struct bpf_map *map) 6197 { 6198 /* A map is considered read-only if the following condition are true: 6199 * 6200 * 1) BPF program side cannot change any of the map content. The 6201 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6202 * and was set at map creation time. 6203 * 2) The map value(s) have been initialized from user space by a 6204 * loader and then "frozen", such that no new map update/delete 6205 * operations from syscall side are possible for the rest of 6206 * the map's lifetime from that point onwards. 6207 * 3) Any parallel/pending map update/delete operations from syscall 6208 * side have been completed. Only after that point, it's safe to 6209 * assume that map value(s) are immutable. 6210 */ 6211 return (map->map_flags & BPF_F_RDONLY_PROG) && 6212 READ_ONCE(map->frozen) && 6213 !bpf_map_write_active(map); 6214 } 6215 6216 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6217 bool is_ldsx) 6218 { 6219 void *ptr; 6220 u64 addr; 6221 int err; 6222 6223 err = map->ops->map_direct_value_addr(map, &addr, off); 6224 if (err) 6225 return err; 6226 ptr = (void *)(long)addr + off; 6227 6228 switch (size) { 6229 case sizeof(u8): 6230 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6231 break; 6232 case sizeof(u16): 6233 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6234 break; 6235 case sizeof(u32): 6236 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6237 break; 6238 case sizeof(u64): 6239 *val = *(u64 *)ptr; 6240 break; 6241 default: 6242 return -EINVAL; 6243 } 6244 return 0; 6245 } 6246 6247 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6248 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6249 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6250 6251 /* 6252 * Allow list few fields as RCU trusted or full trusted. 6253 * This logic doesn't allow mix tagging and will be removed once GCC supports 6254 * btf_type_tag. 6255 */ 6256 6257 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6258 BTF_TYPE_SAFE_RCU(struct task_struct) { 6259 const cpumask_t *cpus_ptr; 6260 struct css_set __rcu *cgroups; 6261 struct task_struct __rcu *real_parent; 6262 struct task_struct *group_leader; 6263 }; 6264 6265 BTF_TYPE_SAFE_RCU(struct cgroup) { 6266 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6267 struct kernfs_node *kn; 6268 }; 6269 6270 BTF_TYPE_SAFE_RCU(struct css_set) { 6271 struct cgroup *dfl_cgrp; 6272 }; 6273 6274 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6275 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6276 struct file __rcu *exe_file; 6277 }; 6278 6279 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6280 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6281 */ 6282 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6283 struct sock *sk; 6284 }; 6285 6286 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6287 struct sock *sk; 6288 }; 6289 6290 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6291 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6292 struct seq_file *seq; 6293 }; 6294 6295 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6296 struct bpf_iter_meta *meta; 6297 struct task_struct *task; 6298 }; 6299 6300 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6301 struct file *file; 6302 }; 6303 6304 BTF_TYPE_SAFE_TRUSTED(struct file) { 6305 struct inode *f_inode; 6306 }; 6307 6308 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 6309 /* no negative dentry-s in places where bpf can see it */ 6310 struct inode *d_inode; 6311 }; 6312 6313 BTF_TYPE_SAFE_TRUSTED(struct socket) { 6314 struct sock *sk; 6315 }; 6316 6317 static bool type_is_rcu(struct bpf_verifier_env *env, 6318 struct bpf_reg_state *reg, 6319 const char *field_name, u32 btf_id) 6320 { 6321 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6322 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6323 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6324 6325 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6326 } 6327 6328 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6329 struct bpf_reg_state *reg, 6330 const char *field_name, u32 btf_id) 6331 { 6332 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6333 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6334 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6335 6336 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6337 } 6338 6339 static bool type_is_trusted(struct bpf_verifier_env *env, 6340 struct bpf_reg_state *reg, 6341 const char *field_name, u32 btf_id) 6342 { 6343 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 6344 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6345 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6346 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6347 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 6348 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket)); 6349 6350 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6351 } 6352 6353 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6354 struct bpf_reg_state *regs, 6355 int regno, int off, int size, 6356 enum bpf_access_type atype, 6357 int value_regno) 6358 { 6359 struct bpf_reg_state *reg = regs + regno; 6360 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6361 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6362 const char *field_name = NULL; 6363 enum bpf_type_flag flag = 0; 6364 u32 btf_id = 0; 6365 int ret; 6366 6367 if (!env->allow_ptr_leaks) { 6368 verbose(env, 6369 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6370 tname); 6371 return -EPERM; 6372 } 6373 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6374 verbose(env, 6375 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6376 tname); 6377 return -EINVAL; 6378 } 6379 if (off < 0) { 6380 verbose(env, 6381 "R%d is ptr_%s invalid negative access: off=%d\n", 6382 regno, tname, off); 6383 return -EACCES; 6384 } 6385 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6386 char tn_buf[48]; 6387 6388 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6389 verbose(env, 6390 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6391 regno, tname, off, tn_buf); 6392 return -EACCES; 6393 } 6394 6395 if (reg->type & MEM_USER) { 6396 verbose(env, 6397 "R%d is ptr_%s access user memory: off=%d\n", 6398 regno, tname, off); 6399 return -EACCES; 6400 } 6401 6402 if (reg->type & MEM_PERCPU) { 6403 verbose(env, 6404 "R%d is ptr_%s access percpu memory: off=%d\n", 6405 regno, tname, off); 6406 return -EACCES; 6407 } 6408 6409 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6410 if (!btf_is_kernel(reg->btf)) { 6411 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 6412 return -EFAULT; 6413 } 6414 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6415 } else { 6416 /* Writes are permitted with default btf_struct_access for 6417 * program allocated objects (which always have ref_obj_id > 0), 6418 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6419 */ 6420 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6421 verbose(env, "only read is supported\n"); 6422 return -EACCES; 6423 } 6424 6425 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6426 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 6427 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 6428 return -EFAULT; 6429 } 6430 6431 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6432 } 6433 6434 if (ret < 0) 6435 return ret; 6436 6437 if (ret != PTR_TO_BTF_ID) { 6438 /* just mark; */ 6439 6440 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6441 /* If this is an untrusted pointer, all pointers formed by walking it 6442 * also inherit the untrusted flag. 6443 */ 6444 flag = PTR_UNTRUSTED; 6445 6446 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6447 /* By default any pointer obtained from walking a trusted pointer is no 6448 * longer trusted, unless the field being accessed has explicitly been 6449 * marked as inheriting its parent's state of trust (either full or RCU). 6450 * For example: 6451 * 'cgroups' pointer is untrusted if task->cgroups dereference 6452 * happened in a sleepable program outside of bpf_rcu_read_lock() 6453 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6454 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6455 * 6456 * A regular RCU-protected pointer with __rcu tag can also be deemed 6457 * trusted if we are in an RCU CS. Such pointer can be NULL. 6458 */ 6459 if (type_is_trusted(env, reg, field_name, btf_id)) { 6460 flag |= PTR_TRUSTED; 6461 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6462 if (type_is_rcu(env, reg, field_name, btf_id)) { 6463 /* ignore __rcu tag and mark it MEM_RCU */ 6464 flag |= MEM_RCU; 6465 } else if (flag & MEM_RCU || 6466 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6467 /* __rcu tagged pointers can be NULL */ 6468 flag |= MEM_RCU | PTR_MAYBE_NULL; 6469 6470 /* We always trust them */ 6471 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6472 flag & PTR_UNTRUSTED) 6473 flag &= ~PTR_UNTRUSTED; 6474 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6475 /* keep as-is */ 6476 } else { 6477 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6478 clear_trusted_flags(&flag); 6479 } 6480 } else { 6481 /* 6482 * If not in RCU CS or MEM_RCU pointer can be NULL then 6483 * aggressively mark as untrusted otherwise such 6484 * pointers will be plain PTR_TO_BTF_ID without flags 6485 * and will be allowed to be passed into helpers for 6486 * compat reasons. 6487 */ 6488 flag = PTR_UNTRUSTED; 6489 } 6490 } else { 6491 /* Old compat. Deprecated */ 6492 clear_trusted_flags(&flag); 6493 } 6494 6495 if (atype == BPF_READ && value_regno >= 0) 6496 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6497 6498 return 0; 6499 } 6500 6501 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6502 struct bpf_reg_state *regs, 6503 int regno, int off, int size, 6504 enum bpf_access_type atype, 6505 int value_regno) 6506 { 6507 struct bpf_reg_state *reg = regs + regno; 6508 struct bpf_map *map = reg->map_ptr; 6509 struct bpf_reg_state map_reg; 6510 enum bpf_type_flag flag = 0; 6511 const struct btf_type *t; 6512 const char *tname; 6513 u32 btf_id; 6514 int ret; 6515 6516 if (!btf_vmlinux) { 6517 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6518 return -ENOTSUPP; 6519 } 6520 6521 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6522 verbose(env, "map_ptr access not supported for map type %d\n", 6523 map->map_type); 6524 return -ENOTSUPP; 6525 } 6526 6527 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6528 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6529 6530 if (!env->allow_ptr_leaks) { 6531 verbose(env, 6532 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6533 tname); 6534 return -EPERM; 6535 } 6536 6537 if (off < 0) { 6538 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6539 regno, tname, off); 6540 return -EACCES; 6541 } 6542 6543 if (atype != BPF_READ) { 6544 verbose(env, "only read from %s is supported\n", tname); 6545 return -EACCES; 6546 } 6547 6548 /* Simulate access to a PTR_TO_BTF_ID */ 6549 memset(&map_reg, 0, sizeof(map_reg)); 6550 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6551 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6552 if (ret < 0) 6553 return ret; 6554 6555 if (value_regno >= 0) 6556 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6557 6558 return 0; 6559 } 6560 6561 /* Check that the stack access at the given offset is within bounds. The 6562 * maximum valid offset is -1. 6563 * 6564 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6565 * -state->allocated_stack for reads. 6566 */ 6567 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 6568 s64 off, 6569 struct bpf_func_state *state, 6570 enum bpf_access_type t) 6571 { 6572 int min_valid_off; 6573 6574 if (t == BPF_WRITE || env->allow_uninit_stack) 6575 min_valid_off = -MAX_BPF_STACK; 6576 else 6577 min_valid_off = -state->allocated_stack; 6578 6579 if (off < min_valid_off || off > -1) 6580 return -EACCES; 6581 return 0; 6582 } 6583 6584 /* Check that the stack access at 'regno + off' falls within the maximum stack 6585 * bounds. 6586 * 6587 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6588 */ 6589 static int check_stack_access_within_bounds( 6590 struct bpf_verifier_env *env, 6591 int regno, int off, int access_size, 6592 enum bpf_access_src src, enum bpf_access_type type) 6593 { 6594 struct bpf_reg_state *regs = cur_regs(env); 6595 struct bpf_reg_state *reg = regs + regno; 6596 struct bpf_func_state *state = func(env, reg); 6597 s64 min_off, max_off; 6598 int err; 6599 char *err_extra; 6600 6601 if (src == ACCESS_HELPER) 6602 /* We don't know if helpers are reading or writing (or both). */ 6603 err_extra = " indirect access to"; 6604 else if (type == BPF_READ) 6605 err_extra = " read from"; 6606 else 6607 err_extra = " write to"; 6608 6609 if (tnum_is_const(reg->var_off)) { 6610 min_off = (s64)reg->var_off.value + off; 6611 max_off = min_off + access_size; 6612 } else { 6613 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6614 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6615 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6616 err_extra, regno); 6617 return -EACCES; 6618 } 6619 min_off = reg->smin_value + off; 6620 max_off = reg->smax_value + off + access_size; 6621 } 6622 6623 err = check_stack_slot_within_bounds(env, min_off, state, type); 6624 if (!err && max_off > 0) 6625 err = -EINVAL; /* out of stack access into non-negative offsets */ 6626 6627 if (err) { 6628 if (tnum_is_const(reg->var_off)) { 6629 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 6630 err_extra, regno, off, access_size); 6631 } else { 6632 char tn_buf[48]; 6633 6634 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6635 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n", 6636 err_extra, regno, tn_buf, off, access_size); 6637 } 6638 return err; 6639 } 6640 6641 return grow_stack_state(env, state, round_up(-min_off, BPF_REG_SIZE)); 6642 } 6643 6644 /* check whether memory at (regno + off) is accessible for t = (read | write) 6645 * if t==write, value_regno is a register which value is stored into memory 6646 * if t==read, value_regno is a register which will receive the value from memory 6647 * if t==write && value_regno==-1, some unknown value is stored into memory 6648 * if t==read && value_regno==-1, don't care what we read from memory 6649 */ 6650 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6651 int off, int bpf_size, enum bpf_access_type t, 6652 int value_regno, bool strict_alignment_once, bool is_ldsx) 6653 { 6654 struct bpf_reg_state *regs = cur_regs(env); 6655 struct bpf_reg_state *reg = regs + regno; 6656 int size, err = 0; 6657 6658 size = bpf_size_to_bytes(bpf_size); 6659 if (size < 0) 6660 return size; 6661 6662 /* alignment checks will add in reg->off themselves */ 6663 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6664 if (err) 6665 return err; 6666 6667 /* for access checks, reg->off is just part of off */ 6668 off += reg->off; 6669 6670 if (reg->type == PTR_TO_MAP_KEY) { 6671 if (t == BPF_WRITE) { 6672 verbose(env, "write to change key R%d not allowed\n", regno); 6673 return -EACCES; 6674 } 6675 6676 err = check_mem_region_access(env, regno, off, size, 6677 reg->map_ptr->key_size, false); 6678 if (err) 6679 return err; 6680 if (value_regno >= 0) 6681 mark_reg_unknown(env, regs, value_regno); 6682 } else if (reg->type == PTR_TO_MAP_VALUE) { 6683 struct btf_field *kptr_field = NULL; 6684 6685 if (t == BPF_WRITE && value_regno >= 0 && 6686 is_pointer_value(env, value_regno)) { 6687 verbose(env, "R%d leaks addr into map\n", value_regno); 6688 return -EACCES; 6689 } 6690 err = check_map_access_type(env, regno, off, size, t); 6691 if (err) 6692 return err; 6693 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6694 if (err) 6695 return err; 6696 if (tnum_is_const(reg->var_off)) 6697 kptr_field = btf_record_find(reg->map_ptr->record, 6698 off + reg->var_off.value, BPF_KPTR); 6699 if (kptr_field) { 6700 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6701 } else if (t == BPF_READ && value_regno >= 0) { 6702 struct bpf_map *map = reg->map_ptr; 6703 6704 /* if map is read-only, track its contents as scalars */ 6705 if (tnum_is_const(reg->var_off) && 6706 bpf_map_is_rdonly(map) && 6707 map->ops->map_direct_value_addr) { 6708 int map_off = off + reg->var_off.value; 6709 u64 val = 0; 6710 6711 err = bpf_map_direct_read(map, map_off, size, 6712 &val, is_ldsx); 6713 if (err) 6714 return err; 6715 6716 regs[value_regno].type = SCALAR_VALUE; 6717 __mark_reg_known(®s[value_regno], val); 6718 } else { 6719 mark_reg_unknown(env, regs, value_regno); 6720 } 6721 } 6722 } else if (base_type(reg->type) == PTR_TO_MEM) { 6723 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6724 6725 if (type_may_be_null(reg->type)) { 6726 verbose(env, "R%d invalid mem access '%s'\n", regno, 6727 reg_type_str(env, reg->type)); 6728 return -EACCES; 6729 } 6730 6731 if (t == BPF_WRITE && rdonly_mem) { 6732 verbose(env, "R%d cannot write into %s\n", 6733 regno, reg_type_str(env, reg->type)); 6734 return -EACCES; 6735 } 6736 6737 if (t == BPF_WRITE && value_regno >= 0 && 6738 is_pointer_value(env, value_regno)) { 6739 verbose(env, "R%d leaks addr into mem\n", value_regno); 6740 return -EACCES; 6741 } 6742 6743 err = check_mem_region_access(env, regno, off, size, 6744 reg->mem_size, false); 6745 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6746 mark_reg_unknown(env, regs, value_regno); 6747 } else if (reg->type == PTR_TO_CTX) { 6748 enum bpf_reg_type reg_type = SCALAR_VALUE; 6749 struct btf *btf = NULL; 6750 u32 btf_id = 0; 6751 6752 if (t == BPF_WRITE && value_regno >= 0 && 6753 is_pointer_value(env, value_regno)) { 6754 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6755 return -EACCES; 6756 } 6757 6758 err = check_ptr_off_reg(env, reg, regno); 6759 if (err < 0) 6760 return err; 6761 6762 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 6763 &btf_id); 6764 if (err) 6765 verbose_linfo(env, insn_idx, "; "); 6766 if (!err && t == BPF_READ && value_regno >= 0) { 6767 /* ctx access returns either a scalar, or a 6768 * PTR_TO_PACKET[_META,_END]. In the latter 6769 * case, we know the offset is zero. 6770 */ 6771 if (reg_type == SCALAR_VALUE) { 6772 mark_reg_unknown(env, regs, value_regno); 6773 } else { 6774 mark_reg_known_zero(env, regs, 6775 value_regno); 6776 if (type_may_be_null(reg_type)) 6777 regs[value_regno].id = ++env->id_gen; 6778 /* A load of ctx field could have different 6779 * actual load size with the one encoded in the 6780 * insn. When the dst is PTR, it is for sure not 6781 * a sub-register. 6782 */ 6783 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6784 if (base_type(reg_type) == PTR_TO_BTF_ID) { 6785 regs[value_regno].btf = btf; 6786 regs[value_regno].btf_id = btf_id; 6787 } 6788 } 6789 regs[value_regno].type = reg_type; 6790 } 6791 6792 } else if (reg->type == PTR_TO_STACK) { 6793 /* Basic bounds checks. */ 6794 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 6795 if (err) 6796 return err; 6797 6798 if (t == BPF_READ) 6799 err = check_stack_read(env, regno, off, size, 6800 value_regno); 6801 else 6802 err = check_stack_write(env, regno, off, size, 6803 value_regno, insn_idx); 6804 } else if (reg_is_pkt_pointer(reg)) { 6805 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6806 verbose(env, "cannot write into packet\n"); 6807 return -EACCES; 6808 } 6809 if (t == BPF_WRITE && value_regno >= 0 && 6810 is_pointer_value(env, value_regno)) { 6811 verbose(env, "R%d leaks addr into packet\n", 6812 value_regno); 6813 return -EACCES; 6814 } 6815 err = check_packet_access(env, regno, off, size, false); 6816 if (!err && t == BPF_READ && value_regno >= 0) 6817 mark_reg_unknown(env, regs, value_regno); 6818 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6819 if (t == BPF_WRITE && value_regno >= 0 && 6820 is_pointer_value(env, value_regno)) { 6821 verbose(env, "R%d leaks addr into flow keys\n", 6822 value_regno); 6823 return -EACCES; 6824 } 6825 6826 err = check_flow_keys_access(env, off, size); 6827 if (!err && t == BPF_READ && value_regno >= 0) 6828 mark_reg_unknown(env, regs, value_regno); 6829 } else if (type_is_sk_pointer(reg->type)) { 6830 if (t == BPF_WRITE) { 6831 verbose(env, "R%d cannot write into %s\n", 6832 regno, reg_type_str(env, reg->type)); 6833 return -EACCES; 6834 } 6835 err = check_sock_access(env, insn_idx, regno, off, size, t); 6836 if (!err && value_regno >= 0) 6837 mark_reg_unknown(env, regs, value_regno); 6838 } else if (reg->type == PTR_TO_TP_BUFFER) { 6839 err = check_tp_buffer_access(env, reg, regno, off, size); 6840 if (!err && t == BPF_READ && value_regno >= 0) 6841 mark_reg_unknown(env, regs, value_regno); 6842 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6843 !type_may_be_null(reg->type)) { 6844 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 6845 value_regno); 6846 } else if (reg->type == CONST_PTR_TO_MAP) { 6847 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 6848 value_regno); 6849 } else if (base_type(reg->type) == PTR_TO_BUF) { 6850 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6851 u32 *max_access; 6852 6853 if (rdonly_mem) { 6854 if (t == BPF_WRITE) { 6855 verbose(env, "R%d cannot write into %s\n", 6856 regno, reg_type_str(env, reg->type)); 6857 return -EACCES; 6858 } 6859 max_access = &env->prog->aux->max_rdonly_access; 6860 } else { 6861 max_access = &env->prog->aux->max_rdwr_access; 6862 } 6863 6864 err = check_buffer_access(env, reg, regno, off, size, false, 6865 max_access); 6866 6867 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6868 mark_reg_unknown(env, regs, value_regno); 6869 } else { 6870 verbose(env, "R%d invalid mem access '%s'\n", regno, 6871 reg_type_str(env, reg->type)); 6872 return -EACCES; 6873 } 6874 6875 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6876 regs[value_regno].type == SCALAR_VALUE) { 6877 if (!is_ldsx) 6878 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6879 coerce_reg_to_size(®s[value_regno], size); 6880 else 6881 coerce_reg_to_size_sx(®s[value_regno], size); 6882 } 6883 return err; 6884 } 6885 6886 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 6887 { 6888 int load_reg; 6889 int err; 6890 6891 switch (insn->imm) { 6892 case BPF_ADD: 6893 case BPF_ADD | BPF_FETCH: 6894 case BPF_AND: 6895 case BPF_AND | BPF_FETCH: 6896 case BPF_OR: 6897 case BPF_OR | BPF_FETCH: 6898 case BPF_XOR: 6899 case BPF_XOR | BPF_FETCH: 6900 case BPF_XCHG: 6901 case BPF_CMPXCHG: 6902 break; 6903 default: 6904 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 6905 return -EINVAL; 6906 } 6907 6908 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6909 verbose(env, "invalid atomic operand size\n"); 6910 return -EINVAL; 6911 } 6912 6913 /* check src1 operand */ 6914 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6915 if (err) 6916 return err; 6917 6918 /* check src2 operand */ 6919 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6920 if (err) 6921 return err; 6922 6923 if (insn->imm == BPF_CMPXCHG) { 6924 /* Check comparison of R0 with memory location */ 6925 const u32 aux_reg = BPF_REG_0; 6926 6927 err = check_reg_arg(env, aux_reg, SRC_OP); 6928 if (err) 6929 return err; 6930 6931 if (is_pointer_value(env, aux_reg)) { 6932 verbose(env, "R%d leaks addr into mem\n", aux_reg); 6933 return -EACCES; 6934 } 6935 } 6936 6937 if (is_pointer_value(env, insn->src_reg)) { 6938 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 6939 return -EACCES; 6940 } 6941 6942 if (is_ctx_reg(env, insn->dst_reg) || 6943 is_pkt_reg(env, insn->dst_reg) || 6944 is_flow_key_reg(env, insn->dst_reg) || 6945 is_sk_reg(env, insn->dst_reg)) { 6946 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6947 insn->dst_reg, 6948 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6949 return -EACCES; 6950 } 6951 6952 if (insn->imm & BPF_FETCH) { 6953 if (insn->imm == BPF_CMPXCHG) 6954 load_reg = BPF_REG_0; 6955 else 6956 load_reg = insn->src_reg; 6957 6958 /* check and record load of old value */ 6959 err = check_reg_arg(env, load_reg, DST_OP); 6960 if (err) 6961 return err; 6962 } else { 6963 /* This instruction accesses a memory location but doesn't 6964 * actually load it into a register. 6965 */ 6966 load_reg = -1; 6967 } 6968 6969 /* Check whether we can read the memory, with second call for fetch 6970 * case to simulate the register fill. 6971 */ 6972 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6973 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 6974 if (!err && load_reg >= 0) 6975 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6976 BPF_SIZE(insn->code), BPF_READ, load_reg, 6977 true, false); 6978 if (err) 6979 return err; 6980 6981 /* Check whether we can write into the same memory. */ 6982 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6983 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 6984 if (err) 6985 return err; 6986 return 0; 6987 } 6988 6989 /* When register 'regno' is used to read the stack (either directly or through 6990 * a helper function) make sure that it's within stack boundary and, depending 6991 * on the access type and privileges, that all elements of the stack are 6992 * initialized. 6993 * 6994 * 'off' includes 'regno->off', but not its dynamic part (if any). 6995 * 6996 * All registers that have been spilled on the stack in the slots within the 6997 * read offsets are marked as read. 6998 */ 6999 static int check_stack_range_initialized( 7000 struct bpf_verifier_env *env, int regno, int off, 7001 int access_size, bool zero_size_allowed, 7002 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 7003 { 7004 struct bpf_reg_state *reg = reg_state(env, regno); 7005 struct bpf_func_state *state = func(env, reg); 7006 int err, min_off, max_off, i, j, slot, spi; 7007 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 7008 enum bpf_access_type bounds_check_type; 7009 /* Some accesses can write anything into the stack, others are 7010 * read-only. 7011 */ 7012 bool clobber = false; 7013 7014 if (access_size == 0 && !zero_size_allowed) { 7015 verbose(env, "invalid zero-sized read\n"); 7016 return -EACCES; 7017 } 7018 7019 if (type == ACCESS_HELPER) { 7020 /* The bounds checks for writes are more permissive than for 7021 * reads. However, if raw_mode is not set, we'll do extra 7022 * checks below. 7023 */ 7024 bounds_check_type = BPF_WRITE; 7025 clobber = true; 7026 } else { 7027 bounds_check_type = BPF_READ; 7028 } 7029 err = check_stack_access_within_bounds(env, regno, off, access_size, 7030 type, bounds_check_type); 7031 if (err) 7032 return err; 7033 7034 7035 if (tnum_is_const(reg->var_off)) { 7036 min_off = max_off = reg->var_off.value + off; 7037 } else { 7038 /* Variable offset is prohibited for unprivileged mode for 7039 * simplicity since it requires corresponding support in 7040 * Spectre masking for stack ALU. 7041 * See also retrieve_ptr_limit(). 7042 */ 7043 if (!env->bypass_spec_v1) { 7044 char tn_buf[48]; 7045 7046 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7047 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 7048 regno, err_extra, tn_buf); 7049 return -EACCES; 7050 } 7051 /* Only initialized buffer on stack is allowed to be accessed 7052 * with variable offset. With uninitialized buffer it's hard to 7053 * guarantee that whole memory is marked as initialized on 7054 * helper return since specific bounds are unknown what may 7055 * cause uninitialized stack leaking. 7056 */ 7057 if (meta && meta->raw_mode) 7058 meta = NULL; 7059 7060 min_off = reg->smin_value + off; 7061 max_off = reg->smax_value + off; 7062 } 7063 7064 if (meta && meta->raw_mode) { 7065 /* Ensure we won't be overwriting dynptrs when simulating byte 7066 * by byte access in check_helper_call using meta.access_size. 7067 * This would be a problem if we have a helper in the future 7068 * which takes: 7069 * 7070 * helper(uninit_mem, len, dynptr) 7071 * 7072 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 7073 * may end up writing to dynptr itself when touching memory from 7074 * arg 1. This can be relaxed on a case by case basis for known 7075 * safe cases, but reject due to the possibilitiy of aliasing by 7076 * default. 7077 */ 7078 for (i = min_off; i < max_off + access_size; i++) { 7079 int stack_off = -i - 1; 7080 7081 spi = __get_spi(i); 7082 /* raw_mode may write past allocated_stack */ 7083 if (state->allocated_stack <= stack_off) 7084 continue; 7085 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 7086 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 7087 return -EACCES; 7088 } 7089 } 7090 meta->access_size = access_size; 7091 meta->regno = regno; 7092 return 0; 7093 } 7094 7095 for (i = min_off; i < max_off + access_size; i++) { 7096 u8 *stype; 7097 7098 slot = -i - 1; 7099 spi = slot / BPF_REG_SIZE; 7100 if (state->allocated_stack <= slot) { 7101 verbose(env, "verifier bug: allocated_stack too small"); 7102 return -EFAULT; 7103 } 7104 7105 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 7106 if (*stype == STACK_MISC) 7107 goto mark; 7108 if ((*stype == STACK_ZERO) || 7109 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 7110 if (clobber) { 7111 /* helper can write anything into the stack */ 7112 *stype = STACK_MISC; 7113 } 7114 goto mark; 7115 } 7116 7117 if (is_spilled_reg(&state->stack[spi]) && 7118 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 7119 env->allow_ptr_leaks)) { 7120 if (clobber) { 7121 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 7122 for (j = 0; j < BPF_REG_SIZE; j++) 7123 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 7124 } 7125 goto mark; 7126 } 7127 7128 if (tnum_is_const(reg->var_off)) { 7129 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 7130 err_extra, regno, min_off, i - min_off, access_size); 7131 } else { 7132 char tn_buf[48]; 7133 7134 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7135 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 7136 err_extra, regno, tn_buf, i - min_off, access_size); 7137 } 7138 return -EACCES; 7139 mark: 7140 /* reading any byte out of 8-byte 'spill_slot' will cause 7141 * the whole slot to be marked as 'read' 7142 */ 7143 mark_reg_read(env, &state->stack[spi].spilled_ptr, 7144 state->stack[spi].spilled_ptr.parent, 7145 REG_LIVE_READ64); 7146 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 7147 * be sure that whether stack slot is written to or not. Hence, 7148 * we must still conservatively propagate reads upwards even if 7149 * helper may write to the entire memory range. 7150 */ 7151 } 7152 return 0; 7153 } 7154 7155 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 7156 int access_size, bool zero_size_allowed, 7157 struct bpf_call_arg_meta *meta) 7158 { 7159 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7160 u32 *max_access; 7161 7162 switch (base_type(reg->type)) { 7163 case PTR_TO_PACKET: 7164 case PTR_TO_PACKET_META: 7165 return check_packet_access(env, regno, reg->off, access_size, 7166 zero_size_allowed); 7167 case PTR_TO_MAP_KEY: 7168 if (meta && meta->raw_mode) { 7169 verbose(env, "R%d cannot write into %s\n", regno, 7170 reg_type_str(env, reg->type)); 7171 return -EACCES; 7172 } 7173 return check_mem_region_access(env, regno, reg->off, access_size, 7174 reg->map_ptr->key_size, false); 7175 case PTR_TO_MAP_VALUE: 7176 if (check_map_access_type(env, regno, reg->off, access_size, 7177 meta && meta->raw_mode ? BPF_WRITE : 7178 BPF_READ)) 7179 return -EACCES; 7180 return check_map_access(env, regno, reg->off, access_size, 7181 zero_size_allowed, ACCESS_HELPER); 7182 case PTR_TO_MEM: 7183 if (type_is_rdonly_mem(reg->type)) { 7184 if (meta && meta->raw_mode) { 7185 verbose(env, "R%d cannot write into %s\n", regno, 7186 reg_type_str(env, reg->type)); 7187 return -EACCES; 7188 } 7189 } 7190 return check_mem_region_access(env, regno, reg->off, 7191 access_size, reg->mem_size, 7192 zero_size_allowed); 7193 case PTR_TO_BUF: 7194 if (type_is_rdonly_mem(reg->type)) { 7195 if (meta && meta->raw_mode) { 7196 verbose(env, "R%d cannot write into %s\n", regno, 7197 reg_type_str(env, reg->type)); 7198 return -EACCES; 7199 } 7200 7201 max_access = &env->prog->aux->max_rdonly_access; 7202 } else { 7203 max_access = &env->prog->aux->max_rdwr_access; 7204 } 7205 return check_buffer_access(env, reg, regno, reg->off, 7206 access_size, zero_size_allowed, 7207 max_access); 7208 case PTR_TO_STACK: 7209 return check_stack_range_initialized( 7210 env, 7211 regno, reg->off, access_size, 7212 zero_size_allowed, ACCESS_HELPER, meta); 7213 case PTR_TO_BTF_ID: 7214 return check_ptr_to_btf_access(env, regs, regno, reg->off, 7215 access_size, BPF_READ, -1); 7216 case PTR_TO_CTX: 7217 /* in case the function doesn't know how to access the context, 7218 * (because we are in a program of type SYSCALL for example), we 7219 * can not statically check its size. 7220 * Dynamically check it now. 7221 */ 7222 if (!env->ops->convert_ctx_access) { 7223 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 7224 int offset = access_size - 1; 7225 7226 /* Allow zero-byte read from PTR_TO_CTX */ 7227 if (access_size == 0) 7228 return zero_size_allowed ? 0 : -EACCES; 7229 7230 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 7231 atype, -1, false, false); 7232 } 7233 7234 fallthrough; 7235 default: /* scalar_value or invalid ptr */ 7236 /* Allow zero-byte read from NULL, regardless of pointer type */ 7237 if (zero_size_allowed && access_size == 0 && 7238 register_is_null(reg)) 7239 return 0; 7240 7241 verbose(env, "R%d type=%s ", regno, 7242 reg_type_str(env, reg->type)); 7243 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7244 return -EACCES; 7245 } 7246 } 7247 7248 static int check_mem_size_reg(struct bpf_verifier_env *env, 7249 struct bpf_reg_state *reg, u32 regno, 7250 bool zero_size_allowed, 7251 struct bpf_call_arg_meta *meta) 7252 { 7253 int err; 7254 7255 /* This is used to refine r0 return value bounds for helpers 7256 * that enforce this value as an upper bound on return values. 7257 * See do_refine_retval_range() for helpers that can refine 7258 * the return value. C type of helper is u32 so we pull register 7259 * bound from umax_value however, if negative verifier errors 7260 * out. Only upper bounds can be learned because retval is an 7261 * int type and negative retvals are allowed. 7262 */ 7263 meta->msize_max_value = reg->umax_value; 7264 7265 /* The register is SCALAR_VALUE; the access check 7266 * happens using its boundaries. 7267 */ 7268 if (!tnum_is_const(reg->var_off)) 7269 /* For unprivileged variable accesses, disable raw 7270 * mode so that the program is required to 7271 * initialize all the memory that the helper could 7272 * just partially fill up. 7273 */ 7274 meta = NULL; 7275 7276 if (reg->smin_value < 0) { 7277 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7278 regno); 7279 return -EACCES; 7280 } 7281 7282 if (reg->umin_value == 0) { 7283 err = check_helper_mem_access(env, regno - 1, 0, 7284 zero_size_allowed, 7285 meta); 7286 if (err) 7287 return err; 7288 } 7289 7290 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7291 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7292 regno); 7293 return -EACCES; 7294 } 7295 err = check_helper_mem_access(env, regno - 1, 7296 reg->umax_value, 7297 zero_size_allowed, meta); 7298 if (!err) 7299 err = mark_chain_precision(env, regno); 7300 return err; 7301 } 7302 7303 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7304 u32 regno, u32 mem_size) 7305 { 7306 bool may_be_null = type_may_be_null(reg->type); 7307 struct bpf_reg_state saved_reg; 7308 struct bpf_call_arg_meta meta; 7309 int err; 7310 7311 if (register_is_null(reg)) 7312 return 0; 7313 7314 memset(&meta, 0, sizeof(meta)); 7315 /* Assuming that the register contains a value check if the memory 7316 * access is safe. Temporarily save and restore the register's state as 7317 * the conversion shouldn't be visible to a caller. 7318 */ 7319 if (may_be_null) { 7320 saved_reg = *reg; 7321 mark_ptr_not_null_reg(reg); 7322 } 7323 7324 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 7325 /* Check access for BPF_WRITE */ 7326 meta.raw_mode = true; 7327 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 7328 7329 if (may_be_null) 7330 *reg = saved_reg; 7331 7332 return err; 7333 } 7334 7335 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7336 u32 regno) 7337 { 7338 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7339 bool may_be_null = type_may_be_null(mem_reg->type); 7340 struct bpf_reg_state saved_reg; 7341 struct bpf_call_arg_meta meta; 7342 int err; 7343 7344 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7345 7346 memset(&meta, 0, sizeof(meta)); 7347 7348 if (may_be_null) { 7349 saved_reg = *mem_reg; 7350 mark_ptr_not_null_reg(mem_reg); 7351 } 7352 7353 err = check_mem_size_reg(env, reg, regno, true, &meta); 7354 /* Check access for BPF_WRITE */ 7355 meta.raw_mode = true; 7356 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 7357 7358 if (may_be_null) 7359 *mem_reg = saved_reg; 7360 return err; 7361 } 7362 7363 /* Implementation details: 7364 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7365 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7366 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7367 * Two separate bpf_obj_new will also have different reg->id. 7368 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7369 * clears reg->id after value_or_null->value transition, since the verifier only 7370 * cares about the range of access to valid map value pointer and doesn't care 7371 * about actual address of the map element. 7372 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7373 * reg->id > 0 after value_or_null->value transition. By doing so 7374 * two bpf_map_lookups will be considered two different pointers that 7375 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7376 * returned from bpf_obj_new. 7377 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7378 * dead-locks. 7379 * Since only one bpf_spin_lock is allowed the checks are simpler than 7380 * reg_is_refcounted() logic. The verifier needs to remember only 7381 * one spin_lock instead of array of acquired_refs. 7382 * cur_state->active_lock remembers which map value element or allocated 7383 * object got locked and clears it after bpf_spin_unlock. 7384 */ 7385 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 7386 bool is_lock) 7387 { 7388 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7389 struct bpf_verifier_state *cur = env->cur_state; 7390 bool is_const = tnum_is_const(reg->var_off); 7391 u64 val = reg->var_off.value; 7392 struct bpf_map *map = NULL; 7393 struct btf *btf = NULL; 7394 struct btf_record *rec; 7395 7396 if (!is_const) { 7397 verbose(env, 7398 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 7399 regno); 7400 return -EINVAL; 7401 } 7402 if (reg->type == PTR_TO_MAP_VALUE) { 7403 map = reg->map_ptr; 7404 if (!map->btf) { 7405 verbose(env, 7406 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 7407 map->name); 7408 return -EINVAL; 7409 } 7410 } else { 7411 btf = reg->btf; 7412 } 7413 7414 rec = reg_btf_record(reg); 7415 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 7416 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 7417 map ? map->name : "kptr"); 7418 return -EINVAL; 7419 } 7420 if (rec->spin_lock_off != val + reg->off) { 7421 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 7422 val + reg->off, rec->spin_lock_off); 7423 return -EINVAL; 7424 } 7425 if (is_lock) { 7426 if (cur->active_lock.ptr) { 7427 verbose(env, 7428 "Locking two bpf_spin_locks are not allowed\n"); 7429 return -EINVAL; 7430 } 7431 if (map) 7432 cur->active_lock.ptr = map; 7433 else 7434 cur->active_lock.ptr = btf; 7435 cur->active_lock.id = reg->id; 7436 } else { 7437 void *ptr; 7438 7439 if (map) 7440 ptr = map; 7441 else 7442 ptr = btf; 7443 7444 if (!cur->active_lock.ptr) { 7445 verbose(env, "bpf_spin_unlock without taking a lock\n"); 7446 return -EINVAL; 7447 } 7448 if (cur->active_lock.ptr != ptr || 7449 cur->active_lock.id != reg->id) { 7450 verbose(env, "bpf_spin_unlock of different lock\n"); 7451 return -EINVAL; 7452 } 7453 7454 invalidate_non_owning_refs(env); 7455 7456 cur->active_lock.ptr = NULL; 7457 cur->active_lock.id = 0; 7458 } 7459 return 0; 7460 } 7461 7462 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7463 struct bpf_call_arg_meta *meta) 7464 { 7465 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7466 bool is_const = tnum_is_const(reg->var_off); 7467 struct bpf_map *map = reg->map_ptr; 7468 u64 val = reg->var_off.value; 7469 7470 if (!is_const) { 7471 verbose(env, 7472 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 7473 regno); 7474 return -EINVAL; 7475 } 7476 if (!map->btf) { 7477 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 7478 map->name); 7479 return -EINVAL; 7480 } 7481 if (!btf_record_has_field(map->record, BPF_TIMER)) { 7482 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 7483 return -EINVAL; 7484 } 7485 if (map->record->timer_off != val + reg->off) { 7486 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 7487 val + reg->off, map->record->timer_off); 7488 return -EINVAL; 7489 } 7490 if (meta->map_ptr) { 7491 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 7492 return -EFAULT; 7493 } 7494 meta->map_uid = reg->map_uid; 7495 meta->map_ptr = map; 7496 return 0; 7497 } 7498 7499 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7500 struct bpf_call_arg_meta *meta) 7501 { 7502 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7503 struct bpf_map *map_ptr = reg->map_ptr; 7504 struct btf_field *kptr_field; 7505 u32 kptr_off; 7506 7507 if (!tnum_is_const(reg->var_off)) { 7508 verbose(env, 7509 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7510 regno); 7511 return -EINVAL; 7512 } 7513 if (!map_ptr->btf) { 7514 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7515 map_ptr->name); 7516 return -EINVAL; 7517 } 7518 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 7519 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 7520 return -EINVAL; 7521 } 7522 7523 meta->map_ptr = map_ptr; 7524 kptr_off = reg->off + reg->var_off.value; 7525 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 7526 if (!kptr_field) { 7527 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7528 return -EACCES; 7529 } 7530 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7531 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7532 return -EACCES; 7533 } 7534 meta->kptr_field = kptr_field; 7535 return 0; 7536 } 7537 7538 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7539 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7540 * 7541 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7542 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7543 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7544 * 7545 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7546 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7547 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7548 * mutate the view of the dynptr and also possibly destroy it. In the latter 7549 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7550 * memory that dynptr points to. 7551 * 7552 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7553 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7554 * readonly dynptr view yet, hence only the first case is tracked and checked. 7555 * 7556 * This is consistent with how C applies the const modifier to a struct object, 7557 * where the pointer itself inside bpf_dynptr becomes const but not what it 7558 * points to. 7559 * 7560 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7561 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7562 */ 7563 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7564 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7565 { 7566 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7567 int err; 7568 7569 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7570 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7571 */ 7572 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7573 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 7574 return -EFAULT; 7575 } 7576 7577 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7578 * constructing a mutable bpf_dynptr object. 7579 * 7580 * Currently, this is only possible with PTR_TO_STACK 7581 * pointing to a region of at least 16 bytes which doesn't 7582 * contain an existing bpf_dynptr. 7583 * 7584 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7585 * mutated or destroyed. However, the memory it points to 7586 * may be mutated. 7587 * 7588 * None - Points to a initialized dynptr that can be mutated and 7589 * destroyed, including mutation of the memory it points 7590 * to. 7591 */ 7592 if (arg_type & MEM_UNINIT) { 7593 int i; 7594 7595 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7596 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7597 return -EINVAL; 7598 } 7599 7600 /* we write BPF_DW bits (8 bytes) at a time */ 7601 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7602 err = check_mem_access(env, insn_idx, regno, 7603 i, BPF_DW, BPF_WRITE, -1, false, false); 7604 if (err) 7605 return err; 7606 } 7607 7608 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7609 } else /* MEM_RDONLY and None case from above */ { 7610 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7611 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7612 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7613 return -EINVAL; 7614 } 7615 7616 if (!is_dynptr_reg_valid_init(env, reg)) { 7617 verbose(env, 7618 "Expected an initialized dynptr as arg #%d\n", 7619 regno); 7620 return -EINVAL; 7621 } 7622 7623 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7624 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7625 verbose(env, 7626 "Expected a dynptr of type %s as arg #%d\n", 7627 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 7628 return -EINVAL; 7629 } 7630 7631 err = mark_dynptr_read(env, reg); 7632 } 7633 return err; 7634 } 7635 7636 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7637 { 7638 struct bpf_func_state *state = func(env, reg); 7639 7640 return state->stack[spi].spilled_ptr.ref_obj_id; 7641 } 7642 7643 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7644 { 7645 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7646 } 7647 7648 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7649 { 7650 return meta->kfunc_flags & KF_ITER_NEW; 7651 } 7652 7653 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7654 { 7655 return meta->kfunc_flags & KF_ITER_NEXT; 7656 } 7657 7658 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7659 { 7660 return meta->kfunc_flags & KF_ITER_DESTROY; 7661 } 7662 7663 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg) 7664 { 7665 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7666 * kfunc is iter state pointer 7667 */ 7668 return arg == 0 && is_iter_kfunc(meta); 7669 } 7670 7671 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7672 struct bpf_kfunc_call_arg_meta *meta) 7673 { 7674 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7675 const struct btf_type *t; 7676 const struct btf_param *arg; 7677 int spi, err, i, nr_slots; 7678 u32 btf_id; 7679 7680 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */ 7681 arg = &btf_params(meta->func_proto)[0]; 7682 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */ 7683 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */ 7684 nr_slots = t->size / BPF_REG_SIZE; 7685 7686 if (is_iter_new_kfunc(meta)) { 7687 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7688 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7689 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 7690 iter_type_str(meta->btf, btf_id), regno); 7691 return -EINVAL; 7692 } 7693 7694 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7695 err = check_mem_access(env, insn_idx, regno, 7696 i, BPF_DW, BPF_WRITE, -1, false, false); 7697 if (err) 7698 return err; 7699 } 7700 7701 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 7702 if (err) 7703 return err; 7704 } else { 7705 /* iter_next() or iter_destroy() expect initialized iter state*/ 7706 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 7707 switch (err) { 7708 case 0: 7709 break; 7710 case -EINVAL: 7711 verbose(env, "expected an initialized iter_%s as arg #%d\n", 7712 iter_type_str(meta->btf, btf_id), regno); 7713 return err; 7714 case -EPROTO: 7715 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 7716 return err; 7717 default: 7718 return err; 7719 } 7720 7721 spi = iter_get_spi(env, reg, nr_slots); 7722 if (spi < 0) 7723 return spi; 7724 7725 err = mark_iter_read(env, reg, spi, nr_slots); 7726 if (err) 7727 return err; 7728 7729 /* remember meta->iter info for process_iter_next_call() */ 7730 meta->iter.spi = spi; 7731 meta->iter.frameno = reg->frameno; 7732 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 7733 7734 if (is_iter_destroy_kfunc(meta)) { 7735 err = unmark_stack_slots_iter(env, reg, nr_slots); 7736 if (err) 7737 return err; 7738 } 7739 } 7740 7741 return 0; 7742 } 7743 7744 /* Look for a previous loop entry at insn_idx: nearest parent state 7745 * stopped at insn_idx with callsites matching those in cur->frame. 7746 */ 7747 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 7748 struct bpf_verifier_state *cur, 7749 int insn_idx) 7750 { 7751 struct bpf_verifier_state_list *sl; 7752 struct bpf_verifier_state *st; 7753 7754 /* Explored states are pushed in stack order, most recent states come first */ 7755 sl = *explored_state(env, insn_idx); 7756 for (; sl; sl = sl->next) { 7757 /* If st->branches != 0 state is a part of current DFS verification path, 7758 * hence cur & st for a loop. 7759 */ 7760 st = &sl->state; 7761 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 7762 st->dfs_depth < cur->dfs_depth) 7763 return st; 7764 } 7765 7766 return NULL; 7767 } 7768 7769 static void reset_idmap_scratch(struct bpf_verifier_env *env); 7770 static bool regs_exact(const struct bpf_reg_state *rold, 7771 const struct bpf_reg_state *rcur, 7772 struct bpf_idmap *idmap); 7773 7774 static void maybe_widen_reg(struct bpf_verifier_env *env, 7775 struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 7776 struct bpf_idmap *idmap) 7777 { 7778 if (rold->type != SCALAR_VALUE) 7779 return; 7780 if (rold->type != rcur->type) 7781 return; 7782 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap)) 7783 return; 7784 __mark_reg_unknown(env, rcur); 7785 } 7786 7787 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 7788 struct bpf_verifier_state *old, 7789 struct bpf_verifier_state *cur) 7790 { 7791 struct bpf_func_state *fold, *fcur; 7792 int i, fr; 7793 7794 reset_idmap_scratch(env); 7795 for (fr = old->curframe; fr >= 0; fr--) { 7796 fold = old->frame[fr]; 7797 fcur = cur->frame[fr]; 7798 7799 for (i = 0; i < MAX_BPF_REG; i++) 7800 maybe_widen_reg(env, 7801 &fold->regs[i], 7802 &fcur->regs[i], 7803 &env->idmap_scratch); 7804 7805 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) { 7806 if (!is_spilled_reg(&fold->stack[i]) || 7807 !is_spilled_reg(&fcur->stack[i])) 7808 continue; 7809 7810 maybe_widen_reg(env, 7811 &fold->stack[i].spilled_ptr, 7812 &fcur->stack[i].spilled_ptr, 7813 &env->idmap_scratch); 7814 } 7815 } 7816 return 0; 7817 } 7818 7819 /* process_iter_next_call() is called when verifier gets to iterator's next 7820 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7821 * to it as just "iter_next()" in comments below. 7822 * 7823 * BPF verifier relies on a crucial contract for any iter_next() 7824 * implementation: it should *eventually* return NULL, and once that happens 7825 * it should keep returning NULL. That is, once iterator exhausts elements to 7826 * iterate, it should never reset or spuriously return new elements. 7827 * 7828 * With the assumption of such contract, process_iter_next_call() simulates 7829 * a fork in the verifier state to validate loop logic correctness and safety 7830 * without having to simulate infinite amount of iterations. 7831 * 7832 * In current state, we first assume that iter_next() returned NULL and 7833 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7834 * conditions we should not form an infinite loop and should eventually reach 7835 * exit. 7836 * 7837 * Besides that, we also fork current state and enqueue it for later 7838 * verification. In a forked state we keep iterator state as ACTIVE 7839 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7840 * also bump iteration depth to prevent erroneous infinite loop detection 7841 * later on (see iter_active_depths_differ() comment for details). In this 7842 * state we assume that we'll eventually loop back to another iter_next() 7843 * calls (it could be in exactly same location or in some other instruction, 7844 * it doesn't matter, we don't make any unnecessary assumptions about this, 7845 * everything revolves around iterator state in a stack slot, not which 7846 * instruction is calling iter_next()). When that happens, we either will come 7847 * to iter_next() with equivalent state and can conclude that next iteration 7848 * will proceed in exactly the same way as we just verified, so it's safe to 7849 * assume that loop converges. If not, we'll go on another iteration 7850 * simulation with a different input state, until all possible starting states 7851 * are validated or we reach maximum number of instructions limit. 7852 * 7853 * This way, we will either exhaustively discover all possible input states 7854 * that iterator loop can start with and eventually will converge, or we'll 7855 * effectively regress into bounded loop simulation logic and either reach 7856 * maximum number of instructions if loop is not provably convergent, or there 7857 * is some statically known limit on number of iterations (e.g., if there is 7858 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7859 * 7860 * Iteration convergence logic in is_state_visited() relies on exact 7861 * states comparison, which ignores read and precision marks. 7862 * This is necessary because read and precision marks are not finalized 7863 * while in the loop. Exact comparison might preclude convergence for 7864 * simple programs like below: 7865 * 7866 * i = 0; 7867 * while(iter_next(&it)) 7868 * i++; 7869 * 7870 * At each iteration step i++ would produce a new distinct state and 7871 * eventually instruction processing limit would be reached. 7872 * 7873 * To avoid such behavior speculatively forget (widen) range for 7874 * imprecise scalar registers, if those registers were not precise at the 7875 * end of the previous iteration and do not match exactly. 7876 * 7877 * This is a conservative heuristic that allows to verify wide range of programs, 7878 * however it precludes verification of programs that conjure an 7879 * imprecise value on the first loop iteration and use it as precise on a second. 7880 * For example, the following safe program would fail to verify: 7881 * 7882 * struct bpf_num_iter it; 7883 * int arr[10]; 7884 * int i = 0, a = 0; 7885 * bpf_iter_num_new(&it, 0, 10); 7886 * while (bpf_iter_num_next(&it)) { 7887 * if (a == 0) { 7888 * a = 1; 7889 * i = 7; // Because i changed verifier would forget 7890 * // it's range on second loop entry. 7891 * } else { 7892 * arr[i] = 42; // This would fail to verify. 7893 * } 7894 * } 7895 * bpf_iter_num_destroy(&it); 7896 */ 7897 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7898 struct bpf_kfunc_call_arg_meta *meta) 7899 { 7900 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 7901 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7902 struct bpf_reg_state *cur_iter, *queued_iter; 7903 int iter_frameno = meta->iter.frameno; 7904 int iter_spi = meta->iter.spi; 7905 7906 BTF_TYPE_EMIT(struct bpf_iter); 7907 7908 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7909 7910 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 7911 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 7912 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 7913 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 7914 return -EFAULT; 7915 } 7916 7917 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 7918 /* Because iter_next() call is a checkpoint is_state_visitied() 7919 * should guarantee parent state with same call sites and insn_idx. 7920 */ 7921 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 7922 !same_callsites(cur_st->parent, cur_st)) { 7923 verbose(env, "bug: bad parent state for iter next call"); 7924 return -EFAULT; 7925 } 7926 /* Note cur_st->parent in the call below, it is necessary to skip 7927 * checkpoint created for cur_st by is_state_visited() 7928 * right at this instruction. 7929 */ 7930 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 7931 /* branch out active iter state */ 7932 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 7933 if (!queued_st) 7934 return -ENOMEM; 7935 7936 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7937 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 7938 queued_iter->iter.depth++; 7939 if (prev_st) 7940 widen_imprecise_scalars(env, prev_st, queued_st); 7941 7942 queued_fr = queued_st->frame[queued_st->curframe]; 7943 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 7944 } 7945 7946 /* switch to DRAINED state, but keep the depth unchanged */ 7947 /* mark current iter state as drained and assume returned NULL */ 7948 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 7949 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]); 7950 7951 return 0; 7952 } 7953 7954 static bool arg_type_is_mem_size(enum bpf_arg_type type) 7955 { 7956 return type == ARG_CONST_SIZE || 7957 type == ARG_CONST_SIZE_OR_ZERO; 7958 } 7959 7960 static bool arg_type_is_release(enum bpf_arg_type type) 7961 { 7962 return type & OBJ_RELEASE; 7963 } 7964 7965 static bool arg_type_is_dynptr(enum bpf_arg_type type) 7966 { 7967 return base_type(type) == ARG_PTR_TO_DYNPTR; 7968 } 7969 7970 static int int_ptr_type_to_size(enum bpf_arg_type type) 7971 { 7972 if (type == ARG_PTR_TO_INT) 7973 return sizeof(u32); 7974 else if (type == ARG_PTR_TO_LONG) 7975 return sizeof(u64); 7976 7977 return -EINVAL; 7978 } 7979 7980 static int resolve_map_arg_type(struct bpf_verifier_env *env, 7981 const struct bpf_call_arg_meta *meta, 7982 enum bpf_arg_type *arg_type) 7983 { 7984 if (!meta->map_ptr) { 7985 /* kernel subsystem misconfigured verifier */ 7986 verbose(env, "invalid map_ptr to access map->type\n"); 7987 return -EACCES; 7988 } 7989 7990 switch (meta->map_ptr->map_type) { 7991 case BPF_MAP_TYPE_SOCKMAP: 7992 case BPF_MAP_TYPE_SOCKHASH: 7993 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 7994 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 7995 } else { 7996 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 7997 return -EINVAL; 7998 } 7999 break; 8000 case BPF_MAP_TYPE_BLOOM_FILTER: 8001 if (meta->func_id == BPF_FUNC_map_peek_elem) 8002 *arg_type = ARG_PTR_TO_MAP_VALUE; 8003 break; 8004 default: 8005 break; 8006 } 8007 return 0; 8008 } 8009 8010 struct bpf_reg_types { 8011 const enum bpf_reg_type types[10]; 8012 u32 *btf_id; 8013 }; 8014 8015 static const struct bpf_reg_types sock_types = { 8016 .types = { 8017 PTR_TO_SOCK_COMMON, 8018 PTR_TO_SOCKET, 8019 PTR_TO_TCP_SOCK, 8020 PTR_TO_XDP_SOCK, 8021 }, 8022 }; 8023 8024 #ifdef CONFIG_NET 8025 static const struct bpf_reg_types btf_id_sock_common_types = { 8026 .types = { 8027 PTR_TO_SOCK_COMMON, 8028 PTR_TO_SOCKET, 8029 PTR_TO_TCP_SOCK, 8030 PTR_TO_XDP_SOCK, 8031 PTR_TO_BTF_ID, 8032 PTR_TO_BTF_ID | PTR_TRUSTED, 8033 }, 8034 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 8035 }; 8036 #endif 8037 8038 static const struct bpf_reg_types mem_types = { 8039 .types = { 8040 PTR_TO_STACK, 8041 PTR_TO_PACKET, 8042 PTR_TO_PACKET_META, 8043 PTR_TO_MAP_KEY, 8044 PTR_TO_MAP_VALUE, 8045 PTR_TO_MEM, 8046 PTR_TO_MEM | MEM_RINGBUF, 8047 PTR_TO_BUF, 8048 PTR_TO_BTF_ID | PTR_TRUSTED, 8049 }, 8050 }; 8051 8052 static const struct bpf_reg_types int_ptr_types = { 8053 .types = { 8054 PTR_TO_STACK, 8055 PTR_TO_PACKET, 8056 PTR_TO_PACKET_META, 8057 PTR_TO_MAP_KEY, 8058 PTR_TO_MAP_VALUE, 8059 }, 8060 }; 8061 8062 static const struct bpf_reg_types spin_lock_types = { 8063 .types = { 8064 PTR_TO_MAP_VALUE, 8065 PTR_TO_BTF_ID | MEM_ALLOC, 8066 } 8067 }; 8068 8069 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 8070 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 8071 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 8072 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 8073 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 8074 static const struct bpf_reg_types btf_ptr_types = { 8075 .types = { 8076 PTR_TO_BTF_ID, 8077 PTR_TO_BTF_ID | PTR_TRUSTED, 8078 PTR_TO_BTF_ID | MEM_RCU, 8079 }, 8080 }; 8081 static const struct bpf_reg_types percpu_btf_ptr_types = { 8082 .types = { 8083 PTR_TO_BTF_ID | MEM_PERCPU, 8084 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 8085 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 8086 } 8087 }; 8088 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 8089 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 8090 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8091 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 8092 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8093 static const struct bpf_reg_types dynptr_types = { 8094 .types = { 8095 PTR_TO_STACK, 8096 CONST_PTR_TO_DYNPTR, 8097 } 8098 }; 8099 8100 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 8101 [ARG_PTR_TO_MAP_KEY] = &mem_types, 8102 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 8103 [ARG_CONST_SIZE] = &scalar_types, 8104 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 8105 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 8106 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 8107 [ARG_PTR_TO_CTX] = &context_types, 8108 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 8109 #ifdef CONFIG_NET 8110 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 8111 #endif 8112 [ARG_PTR_TO_SOCKET] = &fullsock_types, 8113 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 8114 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 8115 [ARG_PTR_TO_MEM] = &mem_types, 8116 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 8117 [ARG_PTR_TO_INT] = &int_ptr_types, 8118 [ARG_PTR_TO_LONG] = &int_ptr_types, 8119 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 8120 [ARG_PTR_TO_FUNC] = &func_ptr_types, 8121 [ARG_PTR_TO_STACK] = &stack_ptr_types, 8122 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 8123 [ARG_PTR_TO_TIMER] = &timer_types, 8124 [ARG_PTR_TO_KPTR] = &kptr_types, 8125 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 8126 }; 8127 8128 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 8129 enum bpf_arg_type arg_type, 8130 const u32 *arg_btf_id, 8131 struct bpf_call_arg_meta *meta) 8132 { 8133 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8134 enum bpf_reg_type expected, type = reg->type; 8135 const struct bpf_reg_types *compatible; 8136 int i, j; 8137 8138 compatible = compatible_reg_types[base_type(arg_type)]; 8139 if (!compatible) { 8140 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 8141 return -EFAULT; 8142 } 8143 8144 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 8145 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 8146 * 8147 * Same for MAYBE_NULL: 8148 * 8149 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 8150 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 8151 * 8152 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 8153 * 8154 * Therefore we fold these flags depending on the arg_type before comparison. 8155 */ 8156 if (arg_type & MEM_RDONLY) 8157 type &= ~MEM_RDONLY; 8158 if (arg_type & PTR_MAYBE_NULL) 8159 type &= ~PTR_MAYBE_NULL; 8160 if (base_type(arg_type) == ARG_PTR_TO_MEM) 8161 type &= ~DYNPTR_TYPE_FLAG_MASK; 8162 8163 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) { 8164 type &= ~MEM_ALLOC; 8165 type &= ~MEM_PERCPU; 8166 } 8167 8168 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 8169 expected = compatible->types[i]; 8170 if (expected == NOT_INIT) 8171 break; 8172 8173 if (type == expected) 8174 goto found; 8175 } 8176 8177 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 8178 for (j = 0; j + 1 < i; j++) 8179 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 8180 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 8181 return -EACCES; 8182 8183 found: 8184 if (base_type(reg->type) != PTR_TO_BTF_ID) 8185 return 0; 8186 8187 if (compatible == &mem_types) { 8188 if (!(arg_type & MEM_RDONLY)) { 8189 verbose(env, 8190 "%s() may write into memory pointed by R%d type=%s\n", 8191 func_id_name(meta->func_id), 8192 regno, reg_type_str(env, reg->type)); 8193 return -EACCES; 8194 } 8195 return 0; 8196 } 8197 8198 switch ((int)reg->type) { 8199 case PTR_TO_BTF_ID: 8200 case PTR_TO_BTF_ID | PTR_TRUSTED: 8201 case PTR_TO_BTF_ID | MEM_RCU: 8202 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 8203 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 8204 { 8205 /* For bpf_sk_release, it needs to match against first member 8206 * 'struct sock_common', hence make an exception for it. This 8207 * allows bpf_sk_release to work for multiple socket types. 8208 */ 8209 bool strict_type_match = arg_type_is_release(arg_type) && 8210 meta->func_id != BPF_FUNC_sk_release; 8211 8212 if (type_may_be_null(reg->type) && 8213 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 8214 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 8215 return -EACCES; 8216 } 8217 8218 if (!arg_btf_id) { 8219 if (!compatible->btf_id) { 8220 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 8221 return -EFAULT; 8222 } 8223 arg_btf_id = compatible->btf_id; 8224 } 8225 8226 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8227 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8228 return -EACCES; 8229 } else { 8230 if (arg_btf_id == BPF_PTR_POISON) { 8231 verbose(env, "verifier internal error:"); 8232 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 8233 regno); 8234 return -EACCES; 8235 } 8236 8237 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 8238 btf_vmlinux, *arg_btf_id, 8239 strict_type_match)) { 8240 verbose(env, "R%d is of type %s but %s is expected\n", 8241 regno, btf_type_name(reg->btf, reg->btf_id), 8242 btf_type_name(btf_vmlinux, *arg_btf_id)); 8243 return -EACCES; 8244 } 8245 } 8246 break; 8247 } 8248 case PTR_TO_BTF_ID | MEM_ALLOC: 8249 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 8250 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8251 meta->func_id != BPF_FUNC_kptr_xchg) { 8252 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 8253 return -EFAULT; 8254 } 8255 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8256 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8257 return -EACCES; 8258 } 8259 break; 8260 case PTR_TO_BTF_ID | MEM_PERCPU: 8261 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 8262 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8263 /* Handled by helper specific checks */ 8264 break; 8265 default: 8266 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 8267 return -EFAULT; 8268 } 8269 return 0; 8270 } 8271 8272 static struct btf_field * 8273 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8274 { 8275 struct btf_field *field; 8276 struct btf_record *rec; 8277 8278 rec = reg_btf_record(reg); 8279 if (!rec) 8280 return NULL; 8281 8282 field = btf_record_find(rec, off, fields); 8283 if (!field) 8284 return NULL; 8285 8286 return field; 8287 } 8288 8289 int check_func_arg_reg_off(struct bpf_verifier_env *env, 8290 const struct bpf_reg_state *reg, int regno, 8291 enum bpf_arg_type arg_type) 8292 { 8293 u32 type = reg->type; 8294 8295 /* When referenced register is passed to release function, its fixed 8296 * offset must be 0. 8297 * 8298 * We will check arg_type_is_release reg has ref_obj_id when storing 8299 * meta->release_regno. 8300 */ 8301 if (arg_type_is_release(arg_type)) { 8302 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8303 * may not directly point to the object being released, but to 8304 * dynptr pointing to such object, which might be at some offset 8305 * on the stack. In that case, we simply to fallback to the 8306 * default handling. 8307 */ 8308 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8309 return 0; 8310 8311 /* Doing check_ptr_off_reg check for the offset will catch this 8312 * because fixed_off_ok is false, but checking here allows us 8313 * to give the user a better error message. 8314 */ 8315 if (reg->off) { 8316 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 8317 regno); 8318 return -EINVAL; 8319 } 8320 return __check_ptr_off_reg(env, reg, regno, false); 8321 } 8322 8323 switch (type) { 8324 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8325 case PTR_TO_STACK: 8326 case PTR_TO_PACKET: 8327 case PTR_TO_PACKET_META: 8328 case PTR_TO_MAP_KEY: 8329 case PTR_TO_MAP_VALUE: 8330 case PTR_TO_MEM: 8331 case PTR_TO_MEM | MEM_RDONLY: 8332 case PTR_TO_MEM | MEM_RINGBUF: 8333 case PTR_TO_BUF: 8334 case PTR_TO_BUF | MEM_RDONLY: 8335 case SCALAR_VALUE: 8336 return 0; 8337 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8338 * fixed offset. 8339 */ 8340 case PTR_TO_BTF_ID: 8341 case PTR_TO_BTF_ID | MEM_ALLOC: 8342 case PTR_TO_BTF_ID | PTR_TRUSTED: 8343 case PTR_TO_BTF_ID | MEM_RCU: 8344 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8345 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8346 /* When referenced PTR_TO_BTF_ID is passed to release function, 8347 * its fixed offset must be 0. In the other cases, fixed offset 8348 * can be non-zero. This was already checked above. So pass 8349 * fixed_off_ok as true to allow fixed offset for all other 8350 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8351 * still need to do checks instead of returning. 8352 */ 8353 return __check_ptr_off_reg(env, reg, regno, true); 8354 default: 8355 return __check_ptr_off_reg(env, reg, regno, false); 8356 } 8357 } 8358 8359 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8360 const struct bpf_func_proto *fn, 8361 struct bpf_reg_state *regs) 8362 { 8363 struct bpf_reg_state *state = NULL; 8364 int i; 8365 8366 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8367 if (arg_type_is_dynptr(fn->arg_type[i])) { 8368 if (state) { 8369 verbose(env, "verifier internal error: multiple dynptr args\n"); 8370 return NULL; 8371 } 8372 state = ®s[BPF_REG_1 + i]; 8373 } 8374 8375 if (!state) 8376 verbose(env, "verifier internal error: no dynptr arg found\n"); 8377 8378 return state; 8379 } 8380 8381 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8382 { 8383 struct bpf_func_state *state = func(env, reg); 8384 int spi; 8385 8386 if (reg->type == CONST_PTR_TO_DYNPTR) 8387 return reg->id; 8388 spi = dynptr_get_spi(env, reg); 8389 if (spi < 0) 8390 return spi; 8391 return state->stack[spi].spilled_ptr.id; 8392 } 8393 8394 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8395 { 8396 struct bpf_func_state *state = func(env, reg); 8397 int spi; 8398 8399 if (reg->type == CONST_PTR_TO_DYNPTR) 8400 return reg->ref_obj_id; 8401 spi = dynptr_get_spi(env, reg); 8402 if (spi < 0) 8403 return spi; 8404 return state->stack[spi].spilled_ptr.ref_obj_id; 8405 } 8406 8407 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8408 struct bpf_reg_state *reg) 8409 { 8410 struct bpf_func_state *state = func(env, reg); 8411 int spi; 8412 8413 if (reg->type == CONST_PTR_TO_DYNPTR) 8414 return reg->dynptr.type; 8415 8416 spi = __get_spi(reg->off); 8417 if (spi < 0) { 8418 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8419 return BPF_DYNPTR_TYPE_INVALID; 8420 } 8421 8422 return state->stack[spi].spilled_ptr.dynptr.type; 8423 } 8424 8425 static int check_reg_const_str(struct bpf_verifier_env *env, 8426 struct bpf_reg_state *reg, u32 regno) 8427 { 8428 struct bpf_map *map = reg->map_ptr; 8429 int err; 8430 int map_off; 8431 u64 map_addr; 8432 char *str_ptr; 8433 8434 if (reg->type != PTR_TO_MAP_VALUE) 8435 return -EINVAL; 8436 8437 if (!bpf_map_is_rdonly(map)) { 8438 verbose(env, "R%d does not point to a readonly map'\n", regno); 8439 return -EACCES; 8440 } 8441 8442 if (!tnum_is_const(reg->var_off)) { 8443 verbose(env, "R%d is not a constant address'\n", regno); 8444 return -EACCES; 8445 } 8446 8447 if (!map->ops->map_direct_value_addr) { 8448 verbose(env, "no direct value access support for this map type\n"); 8449 return -EACCES; 8450 } 8451 8452 err = check_map_access(env, regno, reg->off, 8453 map->value_size - reg->off, false, 8454 ACCESS_HELPER); 8455 if (err) 8456 return err; 8457 8458 map_off = reg->off + reg->var_off.value; 8459 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8460 if (err) { 8461 verbose(env, "direct value access on string failed\n"); 8462 return err; 8463 } 8464 8465 str_ptr = (char *)(long)(map_addr); 8466 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8467 verbose(env, "string is not zero-terminated\n"); 8468 return -EINVAL; 8469 } 8470 return 0; 8471 } 8472 8473 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8474 struct bpf_call_arg_meta *meta, 8475 const struct bpf_func_proto *fn, 8476 int insn_idx) 8477 { 8478 u32 regno = BPF_REG_1 + arg; 8479 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8480 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8481 enum bpf_reg_type type = reg->type; 8482 u32 *arg_btf_id = NULL; 8483 int err = 0; 8484 8485 if (arg_type == ARG_DONTCARE) 8486 return 0; 8487 8488 err = check_reg_arg(env, regno, SRC_OP); 8489 if (err) 8490 return err; 8491 8492 if (arg_type == ARG_ANYTHING) { 8493 if (is_pointer_value(env, regno)) { 8494 verbose(env, "R%d leaks addr into helper function\n", 8495 regno); 8496 return -EACCES; 8497 } 8498 return 0; 8499 } 8500 8501 if (type_is_pkt_pointer(type) && 8502 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8503 verbose(env, "helper access to the packet is not allowed\n"); 8504 return -EACCES; 8505 } 8506 8507 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8508 err = resolve_map_arg_type(env, meta, &arg_type); 8509 if (err) 8510 return err; 8511 } 8512 8513 if (register_is_null(reg) && type_may_be_null(arg_type)) 8514 /* A NULL register has a SCALAR_VALUE type, so skip 8515 * type checking. 8516 */ 8517 goto skip_type_check; 8518 8519 /* arg_btf_id and arg_size are in a union. */ 8520 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8521 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8522 arg_btf_id = fn->arg_btf_id[arg]; 8523 8524 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 8525 if (err) 8526 return err; 8527 8528 err = check_func_arg_reg_off(env, reg, regno, arg_type); 8529 if (err) 8530 return err; 8531 8532 skip_type_check: 8533 if (arg_type_is_release(arg_type)) { 8534 if (arg_type_is_dynptr(arg_type)) { 8535 struct bpf_func_state *state = func(env, reg); 8536 int spi; 8537 8538 /* Only dynptr created on stack can be released, thus 8539 * the get_spi and stack state checks for spilled_ptr 8540 * should only be done before process_dynptr_func for 8541 * PTR_TO_STACK. 8542 */ 8543 if (reg->type == PTR_TO_STACK) { 8544 spi = dynptr_get_spi(env, reg); 8545 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8546 verbose(env, "arg %d is an unacquired reference\n", regno); 8547 return -EINVAL; 8548 } 8549 } else { 8550 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8551 return -EINVAL; 8552 } 8553 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 8554 verbose(env, "R%d must be referenced when passed to release function\n", 8555 regno); 8556 return -EINVAL; 8557 } 8558 if (meta->release_regno) { 8559 verbose(env, "verifier internal error: more than one release argument\n"); 8560 return -EFAULT; 8561 } 8562 meta->release_regno = regno; 8563 } 8564 8565 if (reg->ref_obj_id) { 8566 if (meta->ref_obj_id) { 8567 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 8568 regno, reg->ref_obj_id, 8569 meta->ref_obj_id); 8570 return -EFAULT; 8571 } 8572 meta->ref_obj_id = reg->ref_obj_id; 8573 } 8574 8575 switch (base_type(arg_type)) { 8576 case ARG_CONST_MAP_PTR: 8577 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8578 if (meta->map_ptr) { 8579 /* Use map_uid (which is unique id of inner map) to reject: 8580 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8581 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8582 * if (inner_map1 && inner_map2) { 8583 * timer = bpf_map_lookup_elem(inner_map1); 8584 * if (timer) 8585 * // mismatch would have been allowed 8586 * bpf_timer_init(timer, inner_map2); 8587 * } 8588 * 8589 * Comparing map_ptr is enough to distinguish normal and outer maps. 8590 */ 8591 if (meta->map_ptr != reg->map_ptr || 8592 meta->map_uid != reg->map_uid) { 8593 verbose(env, 8594 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8595 meta->map_uid, reg->map_uid); 8596 return -EINVAL; 8597 } 8598 } 8599 meta->map_ptr = reg->map_ptr; 8600 meta->map_uid = reg->map_uid; 8601 break; 8602 case ARG_PTR_TO_MAP_KEY: 8603 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8604 * check that [key, key + map->key_size) are within 8605 * stack limits and initialized 8606 */ 8607 if (!meta->map_ptr) { 8608 /* in function declaration map_ptr must come before 8609 * map_key, so that it's verified and known before 8610 * we have to check map_key here. Otherwise it means 8611 * that kernel subsystem misconfigured verifier 8612 */ 8613 verbose(env, "invalid map_ptr to access map->key\n"); 8614 return -EACCES; 8615 } 8616 err = check_helper_mem_access(env, regno, 8617 meta->map_ptr->key_size, false, 8618 NULL); 8619 break; 8620 case ARG_PTR_TO_MAP_VALUE: 8621 if (type_may_be_null(arg_type) && register_is_null(reg)) 8622 return 0; 8623 8624 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8625 * check [value, value + map->value_size) validity 8626 */ 8627 if (!meta->map_ptr) { 8628 /* kernel subsystem misconfigured verifier */ 8629 verbose(env, "invalid map_ptr to access map->value\n"); 8630 return -EACCES; 8631 } 8632 meta->raw_mode = arg_type & MEM_UNINIT; 8633 err = check_helper_mem_access(env, regno, 8634 meta->map_ptr->value_size, false, 8635 meta); 8636 break; 8637 case ARG_PTR_TO_PERCPU_BTF_ID: 8638 if (!reg->btf_id) { 8639 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8640 return -EACCES; 8641 } 8642 meta->ret_btf = reg->btf; 8643 meta->ret_btf_id = reg->btf_id; 8644 break; 8645 case ARG_PTR_TO_SPIN_LOCK: 8646 if (in_rbtree_lock_required_cb(env)) { 8647 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8648 return -EACCES; 8649 } 8650 if (meta->func_id == BPF_FUNC_spin_lock) { 8651 err = process_spin_lock(env, regno, true); 8652 if (err) 8653 return err; 8654 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8655 err = process_spin_lock(env, regno, false); 8656 if (err) 8657 return err; 8658 } else { 8659 verbose(env, "verifier internal error\n"); 8660 return -EFAULT; 8661 } 8662 break; 8663 case ARG_PTR_TO_TIMER: 8664 err = process_timer_func(env, regno, meta); 8665 if (err) 8666 return err; 8667 break; 8668 case ARG_PTR_TO_FUNC: 8669 meta->subprogno = reg->subprogno; 8670 break; 8671 case ARG_PTR_TO_MEM: 8672 /* The access to this pointer is only checked when we hit the 8673 * next is_mem_size argument below. 8674 */ 8675 meta->raw_mode = arg_type & MEM_UNINIT; 8676 if (arg_type & MEM_FIXED_SIZE) { 8677 err = check_helper_mem_access(env, regno, 8678 fn->arg_size[arg], false, 8679 meta); 8680 } 8681 break; 8682 case ARG_CONST_SIZE: 8683 err = check_mem_size_reg(env, reg, regno, false, meta); 8684 break; 8685 case ARG_CONST_SIZE_OR_ZERO: 8686 err = check_mem_size_reg(env, reg, regno, true, meta); 8687 break; 8688 case ARG_PTR_TO_DYNPTR: 8689 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 8690 if (err) 8691 return err; 8692 break; 8693 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8694 if (!tnum_is_const(reg->var_off)) { 8695 verbose(env, "R%d is not a known constant'\n", 8696 regno); 8697 return -EACCES; 8698 } 8699 meta->mem_size = reg->var_off.value; 8700 err = mark_chain_precision(env, regno); 8701 if (err) 8702 return err; 8703 break; 8704 case ARG_PTR_TO_INT: 8705 case ARG_PTR_TO_LONG: 8706 { 8707 int size = int_ptr_type_to_size(arg_type); 8708 8709 err = check_helper_mem_access(env, regno, size, false, meta); 8710 if (err) 8711 return err; 8712 err = check_ptr_alignment(env, reg, 0, size, true); 8713 break; 8714 } 8715 case ARG_PTR_TO_CONST_STR: 8716 { 8717 err = check_reg_const_str(env, reg, regno); 8718 if (err) 8719 return err; 8720 break; 8721 } 8722 case ARG_PTR_TO_KPTR: 8723 err = process_kptr_func(env, regno, meta); 8724 if (err) 8725 return err; 8726 break; 8727 } 8728 8729 return err; 8730 } 8731 8732 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8733 { 8734 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8735 enum bpf_prog_type type = resolve_prog_type(env->prog); 8736 8737 if (func_id != BPF_FUNC_map_update_elem) 8738 return false; 8739 8740 /* It's not possible to get access to a locked struct sock in these 8741 * contexts, so updating is safe. 8742 */ 8743 switch (type) { 8744 case BPF_PROG_TYPE_TRACING: 8745 if (eatype == BPF_TRACE_ITER) 8746 return true; 8747 break; 8748 case BPF_PROG_TYPE_SOCKET_FILTER: 8749 case BPF_PROG_TYPE_SCHED_CLS: 8750 case BPF_PROG_TYPE_SCHED_ACT: 8751 case BPF_PROG_TYPE_XDP: 8752 case BPF_PROG_TYPE_SK_REUSEPORT: 8753 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8754 case BPF_PROG_TYPE_SK_LOOKUP: 8755 return true; 8756 default: 8757 break; 8758 } 8759 8760 verbose(env, "cannot update sockmap in this context\n"); 8761 return false; 8762 } 8763 8764 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8765 { 8766 return env->prog->jit_requested && 8767 bpf_jit_supports_subprog_tailcalls(); 8768 } 8769 8770 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8771 struct bpf_map *map, int func_id) 8772 { 8773 if (!map) 8774 return 0; 8775 8776 /* We need a two way check, first is from map perspective ... */ 8777 switch (map->map_type) { 8778 case BPF_MAP_TYPE_PROG_ARRAY: 8779 if (func_id != BPF_FUNC_tail_call) 8780 goto error; 8781 break; 8782 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8783 if (func_id != BPF_FUNC_perf_event_read && 8784 func_id != BPF_FUNC_perf_event_output && 8785 func_id != BPF_FUNC_skb_output && 8786 func_id != BPF_FUNC_perf_event_read_value && 8787 func_id != BPF_FUNC_xdp_output) 8788 goto error; 8789 break; 8790 case BPF_MAP_TYPE_RINGBUF: 8791 if (func_id != BPF_FUNC_ringbuf_output && 8792 func_id != BPF_FUNC_ringbuf_reserve && 8793 func_id != BPF_FUNC_ringbuf_query && 8794 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8795 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8796 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8797 goto error; 8798 break; 8799 case BPF_MAP_TYPE_USER_RINGBUF: 8800 if (func_id != BPF_FUNC_user_ringbuf_drain) 8801 goto error; 8802 break; 8803 case BPF_MAP_TYPE_STACK_TRACE: 8804 if (func_id != BPF_FUNC_get_stackid) 8805 goto error; 8806 break; 8807 case BPF_MAP_TYPE_CGROUP_ARRAY: 8808 if (func_id != BPF_FUNC_skb_under_cgroup && 8809 func_id != BPF_FUNC_current_task_under_cgroup) 8810 goto error; 8811 break; 8812 case BPF_MAP_TYPE_CGROUP_STORAGE: 8813 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8814 if (func_id != BPF_FUNC_get_local_storage) 8815 goto error; 8816 break; 8817 case BPF_MAP_TYPE_DEVMAP: 8818 case BPF_MAP_TYPE_DEVMAP_HASH: 8819 if (func_id != BPF_FUNC_redirect_map && 8820 func_id != BPF_FUNC_map_lookup_elem) 8821 goto error; 8822 break; 8823 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8824 * appear. 8825 */ 8826 case BPF_MAP_TYPE_CPUMAP: 8827 if (func_id != BPF_FUNC_redirect_map) 8828 goto error; 8829 break; 8830 case BPF_MAP_TYPE_XSKMAP: 8831 if (func_id != BPF_FUNC_redirect_map && 8832 func_id != BPF_FUNC_map_lookup_elem) 8833 goto error; 8834 break; 8835 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8836 case BPF_MAP_TYPE_HASH_OF_MAPS: 8837 if (func_id != BPF_FUNC_map_lookup_elem) 8838 goto error; 8839 break; 8840 case BPF_MAP_TYPE_SOCKMAP: 8841 if (func_id != BPF_FUNC_sk_redirect_map && 8842 func_id != BPF_FUNC_sock_map_update && 8843 func_id != BPF_FUNC_map_delete_elem && 8844 func_id != BPF_FUNC_msg_redirect_map && 8845 func_id != BPF_FUNC_sk_select_reuseport && 8846 func_id != BPF_FUNC_map_lookup_elem && 8847 !may_update_sockmap(env, func_id)) 8848 goto error; 8849 break; 8850 case BPF_MAP_TYPE_SOCKHASH: 8851 if (func_id != BPF_FUNC_sk_redirect_hash && 8852 func_id != BPF_FUNC_sock_hash_update && 8853 func_id != BPF_FUNC_map_delete_elem && 8854 func_id != BPF_FUNC_msg_redirect_hash && 8855 func_id != BPF_FUNC_sk_select_reuseport && 8856 func_id != BPF_FUNC_map_lookup_elem && 8857 !may_update_sockmap(env, func_id)) 8858 goto error; 8859 break; 8860 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8861 if (func_id != BPF_FUNC_sk_select_reuseport) 8862 goto error; 8863 break; 8864 case BPF_MAP_TYPE_QUEUE: 8865 case BPF_MAP_TYPE_STACK: 8866 if (func_id != BPF_FUNC_map_peek_elem && 8867 func_id != BPF_FUNC_map_pop_elem && 8868 func_id != BPF_FUNC_map_push_elem) 8869 goto error; 8870 break; 8871 case BPF_MAP_TYPE_SK_STORAGE: 8872 if (func_id != BPF_FUNC_sk_storage_get && 8873 func_id != BPF_FUNC_sk_storage_delete && 8874 func_id != BPF_FUNC_kptr_xchg) 8875 goto error; 8876 break; 8877 case BPF_MAP_TYPE_INODE_STORAGE: 8878 if (func_id != BPF_FUNC_inode_storage_get && 8879 func_id != BPF_FUNC_inode_storage_delete && 8880 func_id != BPF_FUNC_kptr_xchg) 8881 goto error; 8882 break; 8883 case BPF_MAP_TYPE_TASK_STORAGE: 8884 if (func_id != BPF_FUNC_task_storage_get && 8885 func_id != BPF_FUNC_task_storage_delete && 8886 func_id != BPF_FUNC_kptr_xchg) 8887 goto error; 8888 break; 8889 case BPF_MAP_TYPE_CGRP_STORAGE: 8890 if (func_id != BPF_FUNC_cgrp_storage_get && 8891 func_id != BPF_FUNC_cgrp_storage_delete && 8892 func_id != BPF_FUNC_kptr_xchg) 8893 goto error; 8894 break; 8895 case BPF_MAP_TYPE_BLOOM_FILTER: 8896 if (func_id != BPF_FUNC_map_peek_elem && 8897 func_id != BPF_FUNC_map_push_elem) 8898 goto error; 8899 break; 8900 default: 8901 break; 8902 } 8903 8904 /* ... and second from the function itself. */ 8905 switch (func_id) { 8906 case BPF_FUNC_tail_call: 8907 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8908 goto error; 8909 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 8910 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 8911 return -EINVAL; 8912 } 8913 break; 8914 case BPF_FUNC_perf_event_read: 8915 case BPF_FUNC_perf_event_output: 8916 case BPF_FUNC_perf_event_read_value: 8917 case BPF_FUNC_skb_output: 8918 case BPF_FUNC_xdp_output: 8919 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 8920 goto error; 8921 break; 8922 case BPF_FUNC_ringbuf_output: 8923 case BPF_FUNC_ringbuf_reserve: 8924 case BPF_FUNC_ringbuf_query: 8925 case BPF_FUNC_ringbuf_reserve_dynptr: 8926 case BPF_FUNC_ringbuf_submit_dynptr: 8927 case BPF_FUNC_ringbuf_discard_dynptr: 8928 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 8929 goto error; 8930 break; 8931 case BPF_FUNC_user_ringbuf_drain: 8932 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 8933 goto error; 8934 break; 8935 case BPF_FUNC_get_stackid: 8936 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 8937 goto error; 8938 break; 8939 case BPF_FUNC_current_task_under_cgroup: 8940 case BPF_FUNC_skb_under_cgroup: 8941 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 8942 goto error; 8943 break; 8944 case BPF_FUNC_redirect_map: 8945 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 8946 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 8947 map->map_type != BPF_MAP_TYPE_CPUMAP && 8948 map->map_type != BPF_MAP_TYPE_XSKMAP) 8949 goto error; 8950 break; 8951 case BPF_FUNC_sk_redirect_map: 8952 case BPF_FUNC_msg_redirect_map: 8953 case BPF_FUNC_sock_map_update: 8954 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 8955 goto error; 8956 break; 8957 case BPF_FUNC_sk_redirect_hash: 8958 case BPF_FUNC_msg_redirect_hash: 8959 case BPF_FUNC_sock_hash_update: 8960 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 8961 goto error; 8962 break; 8963 case BPF_FUNC_get_local_storage: 8964 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 8965 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 8966 goto error; 8967 break; 8968 case BPF_FUNC_sk_select_reuseport: 8969 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 8970 map->map_type != BPF_MAP_TYPE_SOCKMAP && 8971 map->map_type != BPF_MAP_TYPE_SOCKHASH) 8972 goto error; 8973 break; 8974 case BPF_FUNC_map_pop_elem: 8975 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8976 map->map_type != BPF_MAP_TYPE_STACK) 8977 goto error; 8978 break; 8979 case BPF_FUNC_map_peek_elem: 8980 case BPF_FUNC_map_push_elem: 8981 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8982 map->map_type != BPF_MAP_TYPE_STACK && 8983 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 8984 goto error; 8985 break; 8986 case BPF_FUNC_map_lookup_percpu_elem: 8987 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 8988 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 8989 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 8990 goto error; 8991 break; 8992 case BPF_FUNC_sk_storage_get: 8993 case BPF_FUNC_sk_storage_delete: 8994 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 8995 goto error; 8996 break; 8997 case BPF_FUNC_inode_storage_get: 8998 case BPF_FUNC_inode_storage_delete: 8999 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 9000 goto error; 9001 break; 9002 case BPF_FUNC_task_storage_get: 9003 case BPF_FUNC_task_storage_delete: 9004 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 9005 goto error; 9006 break; 9007 case BPF_FUNC_cgrp_storage_get: 9008 case BPF_FUNC_cgrp_storage_delete: 9009 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 9010 goto error; 9011 break; 9012 default: 9013 break; 9014 } 9015 9016 return 0; 9017 error: 9018 verbose(env, "cannot pass map_type %d into func %s#%d\n", 9019 map->map_type, func_id_name(func_id), func_id); 9020 return -EINVAL; 9021 } 9022 9023 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 9024 { 9025 int count = 0; 9026 9027 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 9028 count++; 9029 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 9030 count++; 9031 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 9032 count++; 9033 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 9034 count++; 9035 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 9036 count++; 9037 9038 /* We only support one arg being in raw mode at the moment, 9039 * which is sufficient for the helper functions we have 9040 * right now. 9041 */ 9042 return count <= 1; 9043 } 9044 9045 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 9046 { 9047 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 9048 bool has_size = fn->arg_size[arg] != 0; 9049 bool is_next_size = false; 9050 9051 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 9052 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 9053 9054 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 9055 return is_next_size; 9056 9057 return has_size == is_next_size || is_next_size == is_fixed; 9058 } 9059 9060 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 9061 { 9062 /* bpf_xxx(..., buf, len) call will access 'len' 9063 * bytes from memory 'buf'. Both arg types need 9064 * to be paired, so make sure there's no buggy 9065 * helper function specification. 9066 */ 9067 if (arg_type_is_mem_size(fn->arg1_type) || 9068 check_args_pair_invalid(fn, 0) || 9069 check_args_pair_invalid(fn, 1) || 9070 check_args_pair_invalid(fn, 2) || 9071 check_args_pair_invalid(fn, 3) || 9072 check_args_pair_invalid(fn, 4)) 9073 return false; 9074 9075 return true; 9076 } 9077 9078 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 9079 { 9080 int i; 9081 9082 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 9083 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 9084 return !!fn->arg_btf_id[i]; 9085 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 9086 return fn->arg_btf_id[i] == BPF_PTR_POISON; 9087 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 9088 /* arg_btf_id and arg_size are in a union. */ 9089 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 9090 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 9091 return false; 9092 } 9093 9094 return true; 9095 } 9096 9097 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 9098 { 9099 return check_raw_mode_ok(fn) && 9100 check_arg_pair_ok(fn) && 9101 check_btf_id_ok(fn) ? 0 : -EINVAL; 9102 } 9103 9104 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 9105 * are now invalid, so turn them into unknown SCALAR_VALUE. 9106 * 9107 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 9108 * since these slices point to packet data. 9109 */ 9110 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 9111 { 9112 struct bpf_func_state *state; 9113 struct bpf_reg_state *reg; 9114 9115 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9116 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 9117 mark_reg_invalid(env, reg); 9118 })); 9119 } 9120 9121 enum { 9122 AT_PKT_END = -1, 9123 BEYOND_PKT_END = -2, 9124 }; 9125 9126 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 9127 { 9128 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9129 struct bpf_reg_state *reg = &state->regs[regn]; 9130 9131 if (reg->type != PTR_TO_PACKET) 9132 /* PTR_TO_PACKET_META is not supported yet */ 9133 return; 9134 9135 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 9136 * How far beyond pkt_end it goes is unknown. 9137 * if (!range_open) it's the case of pkt >= pkt_end 9138 * if (range_open) it's the case of pkt > pkt_end 9139 * hence this pointer is at least 1 byte bigger than pkt_end 9140 */ 9141 if (range_open) 9142 reg->range = BEYOND_PKT_END; 9143 else 9144 reg->range = AT_PKT_END; 9145 } 9146 9147 /* The pointer with the specified id has released its reference to kernel 9148 * resources. Identify all copies of the same pointer and clear the reference. 9149 */ 9150 static int release_reference(struct bpf_verifier_env *env, 9151 int ref_obj_id) 9152 { 9153 struct bpf_func_state *state; 9154 struct bpf_reg_state *reg; 9155 int err; 9156 9157 err = release_reference_state(cur_func(env), ref_obj_id); 9158 if (err) 9159 return err; 9160 9161 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9162 if (reg->ref_obj_id == ref_obj_id) 9163 mark_reg_invalid(env, reg); 9164 })); 9165 9166 return 0; 9167 } 9168 9169 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9170 { 9171 struct bpf_func_state *unused; 9172 struct bpf_reg_state *reg; 9173 9174 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9175 if (type_is_non_owning_ref(reg->type)) 9176 mark_reg_invalid(env, reg); 9177 })); 9178 } 9179 9180 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9181 struct bpf_reg_state *regs) 9182 { 9183 int i; 9184 9185 /* after the call registers r0 - r5 were scratched */ 9186 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9187 mark_reg_not_init(env, regs, caller_saved[i]); 9188 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9189 } 9190 } 9191 9192 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9193 struct bpf_func_state *caller, 9194 struct bpf_func_state *callee, 9195 int insn_idx); 9196 9197 static int set_callee_state(struct bpf_verifier_env *env, 9198 struct bpf_func_state *caller, 9199 struct bpf_func_state *callee, int insn_idx); 9200 9201 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9202 set_callee_state_fn set_callee_state_cb, 9203 struct bpf_verifier_state *state) 9204 { 9205 struct bpf_func_state *caller, *callee; 9206 int err; 9207 9208 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9209 verbose(env, "the call stack of %d frames is too deep\n", 9210 state->curframe + 2); 9211 return -E2BIG; 9212 } 9213 9214 if (state->frame[state->curframe + 1]) { 9215 verbose(env, "verifier bug. Frame %d already allocated\n", 9216 state->curframe + 1); 9217 return -EFAULT; 9218 } 9219 9220 caller = state->frame[state->curframe]; 9221 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 9222 if (!callee) 9223 return -ENOMEM; 9224 state->frame[state->curframe + 1] = callee; 9225 9226 /* callee cannot access r0, r6 - r9 for reading and has to write 9227 * into its own stack before reading from it. 9228 * callee can read/write into caller's stack 9229 */ 9230 init_func_state(env, callee, 9231 /* remember the callsite, it will be used by bpf_exit */ 9232 callsite, 9233 state->curframe + 1 /* frameno within this callchain */, 9234 subprog /* subprog number within this prog */); 9235 /* Transfer references to the callee */ 9236 err = copy_reference_state(callee, caller); 9237 err = err ?: set_callee_state_cb(env, caller, callee, callsite); 9238 if (err) 9239 goto err_out; 9240 9241 /* only increment it after check_reg_arg() finished */ 9242 state->curframe++; 9243 9244 return 0; 9245 9246 err_out: 9247 free_func_state(callee); 9248 state->frame[state->curframe + 1] = NULL; 9249 return err; 9250 } 9251 9252 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9253 int insn_idx, int subprog, 9254 set_callee_state_fn set_callee_state_cb) 9255 { 9256 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9257 struct bpf_func_state *caller, *callee; 9258 int err; 9259 9260 caller = state->frame[state->curframe]; 9261 err = btf_check_subprog_call(env, subprog, caller->regs); 9262 if (err == -EFAULT) 9263 return err; 9264 9265 /* set_callee_state is used for direct subprog calls, but we are 9266 * interested in validating only BPF helpers that can call subprogs as 9267 * callbacks 9268 */ 9269 env->subprog_info[subprog].is_cb = true; 9270 if (bpf_pseudo_kfunc_call(insn) && 9271 !is_sync_callback_calling_kfunc(insn->imm)) { 9272 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 9273 func_id_name(insn->imm), insn->imm); 9274 return -EFAULT; 9275 } else if (!bpf_pseudo_kfunc_call(insn) && 9276 !is_callback_calling_function(insn->imm)) { /* helper */ 9277 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 9278 func_id_name(insn->imm), insn->imm); 9279 return -EFAULT; 9280 } 9281 9282 if (insn->code == (BPF_JMP | BPF_CALL) && 9283 insn->src_reg == 0 && 9284 insn->imm == BPF_FUNC_timer_set_callback) { 9285 struct bpf_verifier_state *async_cb; 9286 9287 /* there is no real recursion here. timer callbacks are async */ 9288 env->subprog_info[subprog].is_async_cb = true; 9289 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9290 insn_idx, subprog); 9291 if (!async_cb) 9292 return -EFAULT; 9293 callee = async_cb->frame[0]; 9294 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9295 9296 /* Convert bpf_timer_set_callback() args into timer callback args */ 9297 err = set_callee_state_cb(env, caller, callee, insn_idx); 9298 if (err) 9299 return err; 9300 9301 return 0; 9302 } 9303 9304 /* for callback functions enqueue entry to callback and 9305 * proceed with next instruction within current frame. 9306 */ 9307 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9308 if (!callback_state) 9309 return -ENOMEM; 9310 9311 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9312 callback_state); 9313 if (err) 9314 return err; 9315 9316 callback_state->callback_unroll_depth++; 9317 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9318 caller->callback_depth = 0; 9319 return 0; 9320 } 9321 9322 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9323 int *insn_idx) 9324 { 9325 struct bpf_verifier_state *state = env->cur_state; 9326 struct bpf_func_state *caller; 9327 int err, subprog, target_insn; 9328 9329 target_insn = *insn_idx + insn->imm + 1; 9330 subprog = find_subprog(env, target_insn); 9331 if (subprog < 0) { 9332 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn); 9333 return -EFAULT; 9334 } 9335 9336 caller = state->frame[state->curframe]; 9337 err = btf_check_subprog_call(env, subprog, caller->regs); 9338 if (err == -EFAULT) 9339 return err; 9340 if (subprog_is_global(env, subprog)) { 9341 const char *sub_name = subprog_name(env, subprog); 9342 9343 if (err) { 9344 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 9345 subprog, sub_name); 9346 return err; 9347 } 9348 9349 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 9350 subprog, sub_name); 9351 /* mark global subprog for verifying after main prog */ 9352 subprog_aux(env, subprog)->called = true; 9353 clear_caller_saved_regs(env, caller->regs); 9354 9355 /* All global functions return a 64-bit SCALAR_VALUE */ 9356 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9357 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9358 9359 /* continue with next insn after call */ 9360 return 0; 9361 } 9362 9363 /* for regular function entry setup new frame and continue 9364 * from that frame. 9365 */ 9366 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9367 if (err) 9368 return err; 9369 9370 clear_caller_saved_regs(env, caller->regs); 9371 9372 /* and go analyze first insn of the callee */ 9373 *insn_idx = env->subprog_info[subprog].start - 1; 9374 9375 if (env->log.level & BPF_LOG_LEVEL) { 9376 verbose(env, "caller:\n"); 9377 print_verifier_state(env, caller, true); 9378 verbose(env, "callee:\n"); 9379 print_verifier_state(env, state->frame[state->curframe], true); 9380 } 9381 9382 return 0; 9383 } 9384 9385 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9386 struct bpf_func_state *caller, 9387 struct bpf_func_state *callee) 9388 { 9389 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9390 * void *callback_ctx, u64 flags); 9391 * callback_fn(struct bpf_map *map, void *key, void *value, 9392 * void *callback_ctx); 9393 */ 9394 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9395 9396 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9397 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9398 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9399 9400 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9401 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9402 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9403 9404 /* pointer to stack or null */ 9405 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9406 9407 /* unused */ 9408 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9409 return 0; 9410 } 9411 9412 static int set_callee_state(struct bpf_verifier_env *env, 9413 struct bpf_func_state *caller, 9414 struct bpf_func_state *callee, int insn_idx) 9415 { 9416 int i; 9417 9418 /* copy r1 - r5 args that callee can access. The copy includes parent 9419 * pointers, which connects us up to the liveness chain 9420 */ 9421 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9422 callee->regs[i] = caller->regs[i]; 9423 return 0; 9424 } 9425 9426 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9427 struct bpf_func_state *caller, 9428 struct bpf_func_state *callee, 9429 int insn_idx) 9430 { 9431 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9432 struct bpf_map *map; 9433 int err; 9434 9435 if (bpf_map_ptr_poisoned(insn_aux)) { 9436 verbose(env, "tail_call abusing map_ptr\n"); 9437 return -EINVAL; 9438 } 9439 9440 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 9441 if (!map->ops->map_set_for_each_callback_args || 9442 !map->ops->map_for_each_callback) { 9443 verbose(env, "callback function not allowed for map\n"); 9444 return -ENOTSUPP; 9445 } 9446 9447 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9448 if (err) 9449 return err; 9450 9451 callee->in_callback_fn = true; 9452 callee->callback_ret_range = retval_range(0, 1); 9453 return 0; 9454 } 9455 9456 static int set_loop_callback_state(struct bpf_verifier_env *env, 9457 struct bpf_func_state *caller, 9458 struct bpf_func_state *callee, 9459 int insn_idx) 9460 { 9461 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9462 * u64 flags); 9463 * callback_fn(u32 index, void *callback_ctx); 9464 */ 9465 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9466 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9467 9468 /* unused */ 9469 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9470 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9471 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9472 9473 callee->in_callback_fn = true; 9474 callee->callback_ret_range = retval_range(0, 1); 9475 return 0; 9476 } 9477 9478 static int set_timer_callback_state(struct bpf_verifier_env *env, 9479 struct bpf_func_state *caller, 9480 struct bpf_func_state *callee, 9481 int insn_idx) 9482 { 9483 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9484 9485 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9486 * callback_fn(struct bpf_map *map, void *key, void *value); 9487 */ 9488 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9489 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9490 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9491 9492 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9493 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9494 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9495 9496 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9497 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9498 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9499 9500 /* unused */ 9501 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9502 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9503 callee->in_async_callback_fn = true; 9504 callee->callback_ret_range = retval_range(0, 1); 9505 return 0; 9506 } 9507 9508 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9509 struct bpf_func_state *caller, 9510 struct bpf_func_state *callee, 9511 int insn_idx) 9512 { 9513 /* bpf_find_vma(struct task_struct *task, u64 addr, 9514 * void *callback_fn, void *callback_ctx, u64 flags) 9515 * (callback_fn)(struct task_struct *task, 9516 * struct vm_area_struct *vma, void *callback_ctx); 9517 */ 9518 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9519 9520 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9521 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9522 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9523 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA], 9524 9525 /* pointer to stack or null */ 9526 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9527 9528 /* unused */ 9529 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9530 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9531 callee->in_callback_fn = true; 9532 callee->callback_ret_range = retval_range(0, 1); 9533 return 0; 9534 } 9535 9536 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9537 struct bpf_func_state *caller, 9538 struct bpf_func_state *callee, 9539 int insn_idx) 9540 { 9541 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9542 * callback_ctx, u64 flags); 9543 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9544 */ 9545 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9546 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9547 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9548 9549 /* unused */ 9550 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9551 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9552 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9553 9554 callee->in_callback_fn = true; 9555 callee->callback_ret_range = retval_range(0, 1); 9556 return 0; 9557 } 9558 9559 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9560 struct bpf_func_state *caller, 9561 struct bpf_func_state *callee, 9562 int insn_idx) 9563 { 9564 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9565 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9566 * 9567 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9568 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9569 * by this point, so look at 'root' 9570 */ 9571 struct btf_field *field; 9572 9573 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 9574 BPF_RB_ROOT); 9575 if (!field || !field->graph_root.value_btf_id) 9576 return -EFAULT; 9577 9578 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9579 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9580 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9581 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9582 9583 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9584 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9585 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9586 callee->in_callback_fn = true; 9587 callee->callback_ret_range = retval_range(0, 1); 9588 return 0; 9589 } 9590 9591 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9592 9593 /* Are we currently verifying the callback for a rbtree helper that must 9594 * be called with lock held? If so, no need to complain about unreleased 9595 * lock 9596 */ 9597 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9598 { 9599 struct bpf_verifier_state *state = env->cur_state; 9600 struct bpf_insn *insn = env->prog->insnsi; 9601 struct bpf_func_state *callee; 9602 int kfunc_btf_id; 9603 9604 if (!state->curframe) 9605 return false; 9606 9607 callee = state->frame[state->curframe]; 9608 9609 if (!callee->in_callback_fn) 9610 return false; 9611 9612 kfunc_btf_id = insn[callee->callsite].imm; 9613 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9614 } 9615 9616 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg) 9617 { 9618 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval; 9619 } 9620 9621 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9622 { 9623 struct bpf_verifier_state *state = env->cur_state, *prev_st; 9624 struct bpf_func_state *caller, *callee; 9625 struct bpf_reg_state *r0; 9626 bool in_callback_fn; 9627 int err; 9628 9629 callee = state->frame[state->curframe]; 9630 r0 = &callee->regs[BPF_REG_0]; 9631 if (r0->type == PTR_TO_STACK) { 9632 /* technically it's ok to return caller's stack pointer 9633 * (or caller's caller's pointer) back to the caller, 9634 * since these pointers are valid. Only current stack 9635 * pointer will be invalid as soon as function exits, 9636 * but let's be conservative 9637 */ 9638 verbose(env, "cannot return stack pointer to the caller\n"); 9639 return -EINVAL; 9640 } 9641 9642 caller = state->frame[state->curframe - 1]; 9643 if (callee->in_callback_fn) { 9644 if (r0->type != SCALAR_VALUE) { 9645 verbose(env, "R0 not a scalar value\n"); 9646 return -EACCES; 9647 } 9648 9649 /* we are going to rely on register's precise value */ 9650 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64); 9651 err = err ?: mark_chain_precision(env, BPF_REG_0); 9652 if (err) 9653 return err; 9654 9655 /* enforce R0 return value range */ 9656 if (!retval_range_within(callee->callback_ret_range, r0)) { 9657 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 9658 "At callback return", "R0"); 9659 return -EINVAL; 9660 } 9661 if (!calls_callback(env, callee->callsite)) { 9662 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n", 9663 *insn_idx, callee->callsite); 9664 return -EFAULT; 9665 } 9666 } else { 9667 /* return to the caller whatever r0 had in the callee */ 9668 caller->regs[BPF_REG_0] = *r0; 9669 } 9670 9671 /* callback_fn frame should have released its own additions to parent's 9672 * reference state at this point, or check_reference_leak would 9673 * complain, hence it must be the same as the caller. There is no need 9674 * to copy it back. 9675 */ 9676 if (!callee->in_callback_fn) { 9677 /* Transfer references to the caller */ 9678 err = copy_reference_state(caller, callee); 9679 if (err) 9680 return err; 9681 } 9682 9683 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 9684 * there function call logic would reschedule callback visit. If iteration 9685 * converges is_state_visited() would prune that visit eventually. 9686 */ 9687 in_callback_fn = callee->in_callback_fn; 9688 if (in_callback_fn) 9689 *insn_idx = callee->callsite; 9690 else 9691 *insn_idx = callee->callsite + 1; 9692 9693 if (env->log.level & BPF_LOG_LEVEL) { 9694 verbose(env, "returning from callee:\n"); 9695 print_verifier_state(env, callee, true); 9696 verbose(env, "to caller at %d:\n", *insn_idx); 9697 print_verifier_state(env, caller, true); 9698 } 9699 /* clear everything in the callee. In case of exceptional exits using 9700 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 9701 free_func_state(callee); 9702 state->frame[state->curframe--] = NULL; 9703 9704 /* for callbacks widen imprecise scalars to make programs like below verify: 9705 * 9706 * struct ctx { int i; } 9707 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 9708 * ... 9709 * struct ctx = { .i = 0; } 9710 * bpf_loop(100, cb, &ctx, 0); 9711 * 9712 * This is similar to what is done in process_iter_next_call() for open 9713 * coded iterators. 9714 */ 9715 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 9716 if (prev_st) { 9717 err = widen_imprecise_scalars(env, prev_st, state); 9718 if (err) 9719 return err; 9720 } 9721 return 0; 9722 } 9723 9724 static int do_refine_retval_range(struct bpf_verifier_env *env, 9725 struct bpf_reg_state *regs, int ret_type, 9726 int func_id, 9727 struct bpf_call_arg_meta *meta) 9728 { 9729 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 9730 9731 if (ret_type != RET_INTEGER) 9732 return 0; 9733 9734 switch (func_id) { 9735 case BPF_FUNC_get_stack: 9736 case BPF_FUNC_get_task_stack: 9737 case BPF_FUNC_probe_read_str: 9738 case BPF_FUNC_probe_read_kernel_str: 9739 case BPF_FUNC_probe_read_user_str: 9740 ret_reg->smax_value = meta->msize_max_value; 9741 ret_reg->s32_max_value = meta->msize_max_value; 9742 ret_reg->smin_value = -MAX_ERRNO; 9743 ret_reg->s32_min_value = -MAX_ERRNO; 9744 reg_bounds_sync(ret_reg); 9745 break; 9746 case BPF_FUNC_get_smp_processor_id: 9747 ret_reg->umax_value = nr_cpu_ids - 1; 9748 ret_reg->u32_max_value = nr_cpu_ids - 1; 9749 ret_reg->smax_value = nr_cpu_ids - 1; 9750 ret_reg->s32_max_value = nr_cpu_ids - 1; 9751 ret_reg->umin_value = 0; 9752 ret_reg->u32_min_value = 0; 9753 ret_reg->smin_value = 0; 9754 ret_reg->s32_min_value = 0; 9755 reg_bounds_sync(ret_reg); 9756 break; 9757 } 9758 9759 return reg_bounds_sanity_check(env, ret_reg, "retval"); 9760 } 9761 9762 static int 9763 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9764 int func_id, int insn_idx) 9765 { 9766 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9767 struct bpf_map *map = meta->map_ptr; 9768 9769 if (func_id != BPF_FUNC_tail_call && 9770 func_id != BPF_FUNC_map_lookup_elem && 9771 func_id != BPF_FUNC_map_update_elem && 9772 func_id != BPF_FUNC_map_delete_elem && 9773 func_id != BPF_FUNC_map_push_elem && 9774 func_id != BPF_FUNC_map_pop_elem && 9775 func_id != BPF_FUNC_map_peek_elem && 9776 func_id != BPF_FUNC_for_each_map_elem && 9777 func_id != BPF_FUNC_redirect_map && 9778 func_id != BPF_FUNC_map_lookup_percpu_elem) 9779 return 0; 9780 9781 if (map == NULL) { 9782 verbose(env, "kernel subsystem misconfigured verifier\n"); 9783 return -EINVAL; 9784 } 9785 9786 /* In case of read-only, some additional restrictions 9787 * need to be applied in order to prevent altering the 9788 * state of the map from program side. 9789 */ 9790 if ((map->map_flags & BPF_F_RDONLY_PROG) && 9791 (func_id == BPF_FUNC_map_delete_elem || 9792 func_id == BPF_FUNC_map_update_elem || 9793 func_id == BPF_FUNC_map_push_elem || 9794 func_id == BPF_FUNC_map_pop_elem)) { 9795 verbose(env, "write into map forbidden\n"); 9796 return -EACCES; 9797 } 9798 9799 if (!BPF_MAP_PTR(aux->map_ptr_state)) 9800 bpf_map_ptr_store(aux, meta->map_ptr, 9801 !meta->map_ptr->bypass_spec_v1); 9802 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 9803 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 9804 !meta->map_ptr->bypass_spec_v1); 9805 return 0; 9806 } 9807 9808 static int 9809 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9810 int func_id, int insn_idx) 9811 { 9812 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9813 struct bpf_reg_state *regs = cur_regs(env), *reg; 9814 struct bpf_map *map = meta->map_ptr; 9815 u64 val, max; 9816 int err; 9817 9818 if (func_id != BPF_FUNC_tail_call) 9819 return 0; 9820 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 9821 verbose(env, "kernel subsystem misconfigured verifier\n"); 9822 return -EINVAL; 9823 } 9824 9825 reg = ®s[BPF_REG_3]; 9826 val = reg->var_off.value; 9827 max = map->max_entries; 9828 9829 if (!(is_reg_const(reg, false) && val < max)) { 9830 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9831 return 0; 9832 } 9833 9834 err = mark_chain_precision(env, BPF_REG_3); 9835 if (err) 9836 return err; 9837 if (bpf_map_key_unseen(aux)) 9838 bpf_map_key_store(aux, val); 9839 else if (!bpf_map_key_poisoned(aux) && 9840 bpf_map_key_immediate(aux) != val) 9841 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9842 return 0; 9843 } 9844 9845 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 9846 { 9847 struct bpf_func_state *state = cur_func(env); 9848 bool refs_lingering = false; 9849 int i; 9850 9851 if (!exception_exit && state->frameno && !state->in_callback_fn) 9852 return 0; 9853 9854 for (i = 0; i < state->acquired_refs; i++) { 9855 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 9856 continue; 9857 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 9858 state->refs[i].id, state->refs[i].insn_idx); 9859 refs_lingering = true; 9860 } 9861 return refs_lingering ? -EINVAL : 0; 9862 } 9863 9864 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 9865 struct bpf_reg_state *regs) 9866 { 9867 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 9868 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 9869 struct bpf_map *fmt_map = fmt_reg->map_ptr; 9870 struct bpf_bprintf_data data = {}; 9871 int err, fmt_map_off, num_args; 9872 u64 fmt_addr; 9873 char *fmt; 9874 9875 /* data must be an array of u64 */ 9876 if (data_len_reg->var_off.value % 8) 9877 return -EINVAL; 9878 num_args = data_len_reg->var_off.value / 8; 9879 9880 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 9881 * and map_direct_value_addr is set. 9882 */ 9883 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 9884 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 9885 fmt_map_off); 9886 if (err) { 9887 verbose(env, "verifier bug\n"); 9888 return -EFAULT; 9889 } 9890 fmt = (char *)(long)fmt_addr + fmt_map_off; 9891 9892 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 9893 * can focus on validating the format specifiers. 9894 */ 9895 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 9896 if (err < 0) 9897 verbose(env, "Invalid format string\n"); 9898 9899 return err; 9900 } 9901 9902 static int check_get_func_ip(struct bpf_verifier_env *env) 9903 { 9904 enum bpf_prog_type type = resolve_prog_type(env->prog); 9905 int func_id = BPF_FUNC_get_func_ip; 9906 9907 if (type == BPF_PROG_TYPE_TRACING) { 9908 if (!bpf_prog_has_trampoline(env->prog)) { 9909 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 9910 func_id_name(func_id), func_id); 9911 return -ENOTSUPP; 9912 } 9913 return 0; 9914 } else if (type == BPF_PROG_TYPE_KPROBE) { 9915 return 0; 9916 } 9917 9918 verbose(env, "func %s#%d not supported for program type %d\n", 9919 func_id_name(func_id), func_id, type); 9920 return -ENOTSUPP; 9921 } 9922 9923 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 9924 { 9925 return &env->insn_aux_data[env->insn_idx]; 9926 } 9927 9928 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 9929 { 9930 struct bpf_reg_state *regs = cur_regs(env); 9931 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 9932 bool reg_is_null = register_is_null(reg); 9933 9934 if (reg_is_null) 9935 mark_chain_precision(env, BPF_REG_4); 9936 9937 return reg_is_null; 9938 } 9939 9940 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 9941 { 9942 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 9943 9944 if (!state->initialized) { 9945 state->initialized = 1; 9946 state->fit_for_inline = loop_flag_is_zero(env); 9947 state->callback_subprogno = subprogno; 9948 return; 9949 } 9950 9951 if (!state->fit_for_inline) 9952 return; 9953 9954 state->fit_for_inline = (loop_flag_is_zero(env) && 9955 state->callback_subprogno == subprogno); 9956 } 9957 9958 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9959 int *insn_idx_p) 9960 { 9961 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 9962 bool returns_cpu_specific_alloc_ptr = false; 9963 const struct bpf_func_proto *fn = NULL; 9964 enum bpf_return_type ret_type; 9965 enum bpf_type_flag ret_flag; 9966 struct bpf_reg_state *regs; 9967 struct bpf_call_arg_meta meta; 9968 int insn_idx = *insn_idx_p; 9969 bool changes_data; 9970 int i, err, func_id; 9971 9972 /* find function prototype */ 9973 func_id = insn->imm; 9974 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 9975 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 9976 func_id); 9977 return -EINVAL; 9978 } 9979 9980 if (env->ops->get_func_proto) 9981 fn = env->ops->get_func_proto(func_id, env->prog); 9982 if (!fn) { 9983 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 9984 func_id); 9985 return -EINVAL; 9986 } 9987 9988 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 9989 if (!env->prog->gpl_compatible && fn->gpl_only) { 9990 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 9991 return -EINVAL; 9992 } 9993 9994 if (fn->allowed && !fn->allowed(env->prog)) { 9995 verbose(env, "helper call is not allowed in probe\n"); 9996 return -EINVAL; 9997 } 9998 9999 if (!env->prog->aux->sleepable && fn->might_sleep) { 10000 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 10001 return -EINVAL; 10002 } 10003 10004 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10005 changes_data = bpf_helper_changes_pkt_data(fn->func); 10006 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10007 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 10008 func_id_name(func_id), func_id); 10009 return -EINVAL; 10010 } 10011 10012 memset(&meta, 0, sizeof(meta)); 10013 meta.pkt_access = fn->pkt_access; 10014 10015 err = check_func_proto(fn, func_id); 10016 if (err) { 10017 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 10018 func_id_name(func_id), func_id); 10019 return err; 10020 } 10021 10022 if (env->cur_state->active_rcu_lock) { 10023 if (fn->might_sleep) { 10024 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 10025 func_id_name(func_id), func_id); 10026 return -EINVAL; 10027 } 10028 10029 if (env->prog->aux->sleepable && is_storage_get_function(func_id)) 10030 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10031 } 10032 10033 meta.func_id = func_id; 10034 /* check args */ 10035 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10036 err = check_func_arg(env, i, &meta, fn, insn_idx); 10037 if (err) 10038 return err; 10039 } 10040 10041 err = record_func_map(env, &meta, func_id, insn_idx); 10042 if (err) 10043 return err; 10044 10045 err = record_func_key(env, &meta, func_id, insn_idx); 10046 if (err) 10047 return err; 10048 10049 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10050 * is inferred from register state. 10051 */ 10052 for (i = 0; i < meta.access_size; i++) { 10053 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 10054 BPF_WRITE, -1, false, false); 10055 if (err) 10056 return err; 10057 } 10058 10059 regs = cur_regs(env); 10060 10061 if (meta.release_regno) { 10062 err = -EINVAL; 10063 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 10064 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 10065 * is safe to do directly. 10066 */ 10067 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 10068 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 10069 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 10070 return -EFAULT; 10071 } 10072 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 10073 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 10074 u32 ref_obj_id = meta.ref_obj_id; 10075 bool in_rcu = in_rcu_cs(env); 10076 struct bpf_func_state *state; 10077 struct bpf_reg_state *reg; 10078 10079 err = release_reference_state(cur_func(env), ref_obj_id); 10080 if (!err) { 10081 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10082 if (reg->ref_obj_id == ref_obj_id) { 10083 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 10084 reg->ref_obj_id = 0; 10085 reg->type &= ~MEM_ALLOC; 10086 reg->type |= MEM_RCU; 10087 } else { 10088 mark_reg_invalid(env, reg); 10089 } 10090 } 10091 })); 10092 } 10093 } else if (meta.ref_obj_id) { 10094 err = release_reference(env, meta.ref_obj_id); 10095 } else if (register_is_null(®s[meta.release_regno])) { 10096 /* meta.ref_obj_id can only be 0 if register that is meant to be 10097 * released is NULL, which must be > R0. 10098 */ 10099 err = 0; 10100 } 10101 if (err) { 10102 verbose(env, "func %s#%d reference has not been acquired before\n", 10103 func_id_name(func_id), func_id); 10104 return err; 10105 } 10106 } 10107 10108 switch (func_id) { 10109 case BPF_FUNC_tail_call: 10110 err = check_reference_leak(env, false); 10111 if (err) { 10112 verbose(env, "tail_call would lead to reference leak\n"); 10113 return err; 10114 } 10115 break; 10116 case BPF_FUNC_get_local_storage: 10117 /* check that flags argument in get_local_storage(map, flags) is 0, 10118 * this is required because get_local_storage() can't return an error. 10119 */ 10120 if (!register_is_null(®s[BPF_REG_2])) { 10121 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10122 return -EINVAL; 10123 } 10124 break; 10125 case BPF_FUNC_for_each_map_elem: 10126 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10127 set_map_elem_callback_state); 10128 break; 10129 case BPF_FUNC_timer_set_callback: 10130 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10131 set_timer_callback_state); 10132 break; 10133 case BPF_FUNC_find_vma: 10134 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10135 set_find_vma_callback_state); 10136 break; 10137 case BPF_FUNC_snprintf: 10138 err = check_bpf_snprintf_call(env, regs); 10139 break; 10140 case BPF_FUNC_loop: 10141 update_loop_inline_state(env, meta.subprogno); 10142 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10143 * is finished, thus mark it precise. 10144 */ 10145 err = mark_chain_precision(env, BPF_REG_1); 10146 if (err) 10147 return err; 10148 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) { 10149 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10150 set_loop_callback_state); 10151 } else { 10152 cur_func(env)->callback_depth = 0; 10153 if (env->log.level & BPF_LOG_LEVEL2) 10154 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10155 env->cur_state->curframe); 10156 } 10157 break; 10158 case BPF_FUNC_dynptr_from_mem: 10159 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10160 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10161 reg_type_str(env, regs[BPF_REG_1].type)); 10162 return -EACCES; 10163 } 10164 break; 10165 case BPF_FUNC_set_retval: 10166 if (prog_type == BPF_PROG_TYPE_LSM && 10167 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10168 if (!env->prog->aux->attach_func_proto->type) { 10169 /* Make sure programs that attach to void 10170 * hooks don't try to modify return value. 10171 */ 10172 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10173 return -EINVAL; 10174 } 10175 } 10176 break; 10177 case BPF_FUNC_dynptr_data: 10178 { 10179 struct bpf_reg_state *reg; 10180 int id, ref_obj_id; 10181 10182 reg = get_dynptr_arg_reg(env, fn, regs); 10183 if (!reg) 10184 return -EFAULT; 10185 10186 10187 if (meta.dynptr_id) { 10188 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 10189 return -EFAULT; 10190 } 10191 if (meta.ref_obj_id) { 10192 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 10193 return -EFAULT; 10194 } 10195 10196 id = dynptr_id(env, reg); 10197 if (id < 0) { 10198 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 10199 return id; 10200 } 10201 10202 ref_obj_id = dynptr_ref_obj_id(env, reg); 10203 if (ref_obj_id < 0) { 10204 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 10205 return ref_obj_id; 10206 } 10207 10208 meta.dynptr_id = id; 10209 meta.ref_obj_id = ref_obj_id; 10210 10211 break; 10212 } 10213 case BPF_FUNC_dynptr_write: 10214 { 10215 enum bpf_dynptr_type dynptr_type; 10216 struct bpf_reg_state *reg; 10217 10218 reg = get_dynptr_arg_reg(env, fn, regs); 10219 if (!reg) 10220 return -EFAULT; 10221 10222 dynptr_type = dynptr_get_type(env, reg); 10223 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10224 return -EFAULT; 10225 10226 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 10227 /* this will trigger clear_all_pkt_pointers(), which will 10228 * invalidate all dynptr slices associated with the skb 10229 */ 10230 changes_data = true; 10231 10232 break; 10233 } 10234 case BPF_FUNC_per_cpu_ptr: 10235 case BPF_FUNC_this_cpu_ptr: 10236 { 10237 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 10238 const struct btf_type *type; 10239 10240 if (reg->type & MEM_RCU) { 10241 type = btf_type_by_id(reg->btf, reg->btf_id); 10242 if (!type || !btf_type_is_struct(type)) { 10243 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 10244 return -EFAULT; 10245 } 10246 returns_cpu_specific_alloc_ptr = true; 10247 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 10248 } 10249 break; 10250 } 10251 case BPF_FUNC_user_ringbuf_drain: 10252 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10253 set_user_ringbuf_callback_state); 10254 break; 10255 } 10256 10257 if (err) 10258 return err; 10259 10260 /* reset caller saved regs */ 10261 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10262 mark_reg_not_init(env, regs, caller_saved[i]); 10263 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10264 } 10265 10266 /* helper call returns 64-bit value. */ 10267 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10268 10269 /* update return register (already marked as written above) */ 10270 ret_type = fn->ret_type; 10271 ret_flag = type_flag(ret_type); 10272 10273 switch (base_type(ret_type)) { 10274 case RET_INTEGER: 10275 /* sets type to SCALAR_VALUE */ 10276 mark_reg_unknown(env, regs, BPF_REG_0); 10277 break; 10278 case RET_VOID: 10279 regs[BPF_REG_0].type = NOT_INIT; 10280 break; 10281 case RET_PTR_TO_MAP_VALUE: 10282 /* There is no offset yet applied, variable or fixed */ 10283 mark_reg_known_zero(env, regs, BPF_REG_0); 10284 /* remember map_ptr, so that check_map_access() 10285 * can check 'value_size' boundary of memory access 10286 * to map element returned from bpf_map_lookup_elem() 10287 */ 10288 if (meta.map_ptr == NULL) { 10289 verbose(env, 10290 "kernel subsystem misconfigured verifier\n"); 10291 return -EINVAL; 10292 } 10293 regs[BPF_REG_0].map_ptr = meta.map_ptr; 10294 regs[BPF_REG_0].map_uid = meta.map_uid; 10295 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10296 if (!type_may_be_null(ret_type) && 10297 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 10298 regs[BPF_REG_0].id = ++env->id_gen; 10299 } 10300 break; 10301 case RET_PTR_TO_SOCKET: 10302 mark_reg_known_zero(env, regs, BPF_REG_0); 10303 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10304 break; 10305 case RET_PTR_TO_SOCK_COMMON: 10306 mark_reg_known_zero(env, regs, BPF_REG_0); 10307 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10308 break; 10309 case RET_PTR_TO_TCP_SOCK: 10310 mark_reg_known_zero(env, regs, BPF_REG_0); 10311 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10312 break; 10313 case RET_PTR_TO_MEM: 10314 mark_reg_known_zero(env, regs, BPF_REG_0); 10315 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10316 regs[BPF_REG_0].mem_size = meta.mem_size; 10317 break; 10318 case RET_PTR_TO_MEM_OR_BTF_ID: 10319 { 10320 const struct btf_type *t; 10321 10322 mark_reg_known_zero(env, regs, BPF_REG_0); 10323 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10324 if (!btf_type_is_struct(t)) { 10325 u32 tsize; 10326 const struct btf_type *ret; 10327 const char *tname; 10328 10329 /* resolve the type size of ksym. */ 10330 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10331 if (IS_ERR(ret)) { 10332 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10333 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10334 tname, PTR_ERR(ret)); 10335 return -EINVAL; 10336 } 10337 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10338 regs[BPF_REG_0].mem_size = tsize; 10339 } else { 10340 if (returns_cpu_specific_alloc_ptr) { 10341 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10342 } else { 10343 /* MEM_RDONLY may be carried from ret_flag, but it 10344 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10345 * it will confuse the check of PTR_TO_BTF_ID in 10346 * check_mem_access(). 10347 */ 10348 ret_flag &= ~MEM_RDONLY; 10349 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10350 } 10351 10352 regs[BPF_REG_0].btf = meta.ret_btf; 10353 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10354 } 10355 break; 10356 } 10357 case RET_PTR_TO_BTF_ID: 10358 { 10359 struct btf *ret_btf; 10360 int ret_btf_id; 10361 10362 mark_reg_known_zero(env, regs, BPF_REG_0); 10363 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10364 if (func_id == BPF_FUNC_kptr_xchg) { 10365 ret_btf = meta.kptr_field->kptr.btf; 10366 ret_btf_id = meta.kptr_field->kptr.btf_id; 10367 if (!btf_is_kernel(ret_btf)) { 10368 regs[BPF_REG_0].type |= MEM_ALLOC; 10369 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10370 regs[BPF_REG_0].type |= MEM_PERCPU; 10371 } 10372 } else { 10373 if (fn->ret_btf_id == BPF_PTR_POISON) { 10374 verbose(env, "verifier internal error:"); 10375 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 10376 func_id_name(func_id)); 10377 return -EINVAL; 10378 } 10379 ret_btf = btf_vmlinux; 10380 ret_btf_id = *fn->ret_btf_id; 10381 } 10382 if (ret_btf_id == 0) { 10383 verbose(env, "invalid return type %u of func %s#%d\n", 10384 base_type(ret_type), func_id_name(func_id), 10385 func_id); 10386 return -EINVAL; 10387 } 10388 regs[BPF_REG_0].btf = ret_btf; 10389 regs[BPF_REG_0].btf_id = ret_btf_id; 10390 break; 10391 } 10392 default: 10393 verbose(env, "unknown return type %u of func %s#%d\n", 10394 base_type(ret_type), func_id_name(func_id), func_id); 10395 return -EINVAL; 10396 } 10397 10398 if (type_may_be_null(regs[BPF_REG_0].type)) 10399 regs[BPF_REG_0].id = ++env->id_gen; 10400 10401 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 10402 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 10403 func_id_name(func_id), func_id); 10404 return -EFAULT; 10405 } 10406 10407 if (is_dynptr_ref_function(func_id)) 10408 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 10409 10410 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 10411 /* For release_reference() */ 10412 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10413 } else if (is_acquire_function(func_id, meta.map_ptr)) { 10414 int id = acquire_reference_state(env, insn_idx); 10415 10416 if (id < 0) 10417 return id; 10418 /* For mark_ptr_or_null_reg() */ 10419 regs[BPF_REG_0].id = id; 10420 /* For release_reference() */ 10421 regs[BPF_REG_0].ref_obj_id = id; 10422 } 10423 10424 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 10425 if (err) 10426 return err; 10427 10428 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 10429 if (err) 10430 return err; 10431 10432 if ((func_id == BPF_FUNC_get_stack || 10433 func_id == BPF_FUNC_get_task_stack) && 10434 !env->prog->has_callchain_buf) { 10435 const char *err_str; 10436 10437 #ifdef CONFIG_PERF_EVENTS 10438 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10439 err_str = "cannot get callchain buffer for func %s#%d\n"; 10440 #else 10441 err = -ENOTSUPP; 10442 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10443 #endif 10444 if (err) { 10445 verbose(env, err_str, func_id_name(func_id), func_id); 10446 return err; 10447 } 10448 10449 env->prog->has_callchain_buf = true; 10450 } 10451 10452 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10453 env->prog->call_get_stack = true; 10454 10455 if (func_id == BPF_FUNC_get_func_ip) { 10456 if (check_get_func_ip(env)) 10457 return -ENOTSUPP; 10458 env->prog->call_get_func_ip = true; 10459 } 10460 10461 if (changes_data) 10462 clear_all_pkt_pointers(env); 10463 return 0; 10464 } 10465 10466 /* mark_btf_func_reg_size() is used when the reg size is determined by 10467 * the BTF func_proto's return value size and argument. 10468 */ 10469 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10470 size_t reg_size) 10471 { 10472 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 10473 10474 if (regno == BPF_REG_0) { 10475 /* Function return value */ 10476 reg->live |= REG_LIVE_WRITTEN; 10477 reg->subreg_def = reg_size == sizeof(u64) ? 10478 DEF_NOT_SUBREG : env->insn_idx + 1; 10479 } else { 10480 /* Function argument */ 10481 if (reg_size == sizeof(u64)) { 10482 mark_insn_zext(env, reg); 10483 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 10484 } else { 10485 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 10486 } 10487 } 10488 } 10489 10490 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10491 { 10492 return meta->kfunc_flags & KF_ACQUIRE; 10493 } 10494 10495 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10496 { 10497 return meta->kfunc_flags & KF_RELEASE; 10498 } 10499 10500 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 10501 { 10502 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 10503 } 10504 10505 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 10506 { 10507 return meta->kfunc_flags & KF_SLEEPABLE; 10508 } 10509 10510 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10511 { 10512 return meta->kfunc_flags & KF_DESTRUCTIVE; 10513 } 10514 10515 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10516 { 10517 return meta->kfunc_flags & KF_RCU; 10518 } 10519 10520 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 10521 { 10522 return meta->kfunc_flags & KF_RCU_PROTECTED; 10523 } 10524 10525 static bool __kfunc_param_match_suffix(const struct btf *btf, 10526 const struct btf_param *arg, 10527 const char *suffix) 10528 { 10529 int suffix_len = strlen(suffix), len; 10530 const char *param_name; 10531 10532 /* In the future, this can be ported to use BTF tagging */ 10533 param_name = btf_name_by_offset(btf, arg->name_off); 10534 if (str_is_empty(param_name)) 10535 return false; 10536 len = strlen(param_name); 10537 if (len < suffix_len) 10538 return false; 10539 param_name += len - suffix_len; 10540 return !strncmp(param_name, suffix, suffix_len); 10541 } 10542 10543 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10544 const struct btf_param *arg, 10545 const struct bpf_reg_state *reg) 10546 { 10547 const struct btf_type *t; 10548 10549 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10550 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10551 return false; 10552 10553 return __kfunc_param_match_suffix(btf, arg, "__sz"); 10554 } 10555 10556 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10557 const struct btf_param *arg, 10558 const struct bpf_reg_state *reg) 10559 { 10560 const struct btf_type *t; 10561 10562 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10563 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10564 return false; 10565 10566 return __kfunc_param_match_suffix(btf, arg, "__szk"); 10567 } 10568 10569 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 10570 { 10571 return __kfunc_param_match_suffix(btf, arg, "__opt"); 10572 } 10573 10574 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10575 { 10576 return __kfunc_param_match_suffix(btf, arg, "__k"); 10577 } 10578 10579 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10580 { 10581 return __kfunc_param_match_suffix(btf, arg, "__ign"); 10582 } 10583 10584 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10585 { 10586 return __kfunc_param_match_suffix(btf, arg, "__alloc"); 10587 } 10588 10589 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10590 { 10591 return __kfunc_param_match_suffix(btf, arg, "__uninit"); 10592 } 10593 10594 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10595 { 10596 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr"); 10597 } 10598 10599 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 10600 { 10601 return __kfunc_param_match_suffix(btf, arg, "__nullable"); 10602 } 10603 10604 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 10605 { 10606 return __kfunc_param_match_suffix(btf, arg, "__str"); 10607 } 10608 10609 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10610 const struct btf_param *arg, 10611 const char *name) 10612 { 10613 int len, target_len = strlen(name); 10614 const char *param_name; 10615 10616 param_name = btf_name_by_offset(btf, arg->name_off); 10617 if (str_is_empty(param_name)) 10618 return false; 10619 len = strlen(param_name); 10620 if (len != target_len) 10621 return false; 10622 if (strcmp(param_name, name)) 10623 return false; 10624 10625 return true; 10626 } 10627 10628 enum { 10629 KF_ARG_DYNPTR_ID, 10630 KF_ARG_LIST_HEAD_ID, 10631 KF_ARG_LIST_NODE_ID, 10632 KF_ARG_RB_ROOT_ID, 10633 KF_ARG_RB_NODE_ID, 10634 }; 10635 10636 BTF_ID_LIST(kf_arg_btf_ids) 10637 BTF_ID(struct, bpf_dynptr_kern) 10638 BTF_ID(struct, bpf_list_head) 10639 BTF_ID(struct, bpf_list_node) 10640 BTF_ID(struct, bpf_rb_root) 10641 BTF_ID(struct, bpf_rb_node) 10642 10643 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10644 const struct btf_param *arg, int type) 10645 { 10646 const struct btf_type *t; 10647 u32 res_id; 10648 10649 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10650 if (!t) 10651 return false; 10652 if (!btf_type_is_ptr(t)) 10653 return false; 10654 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10655 if (!t) 10656 return false; 10657 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10658 } 10659 10660 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10661 { 10662 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10663 } 10664 10665 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10666 { 10667 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10668 } 10669 10670 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10671 { 10672 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10673 } 10674 10675 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10676 { 10677 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10678 } 10679 10680 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10681 { 10682 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10683 } 10684 10685 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10686 const struct btf_param *arg) 10687 { 10688 const struct btf_type *t; 10689 10690 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10691 if (!t) 10692 return false; 10693 10694 return true; 10695 } 10696 10697 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10698 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10699 const struct btf *btf, 10700 const struct btf_type *t, int rec) 10701 { 10702 const struct btf_type *member_type; 10703 const struct btf_member *member; 10704 u32 i; 10705 10706 if (!btf_type_is_struct(t)) 10707 return false; 10708 10709 for_each_member(i, t, member) { 10710 const struct btf_array *array; 10711 10712 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 10713 if (btf_type_is_struct(member_type)) { 10714 if (rec >= 3) { 10715 verbose(env, "max struct nesting depth exceeded\n"); 10716 return false; 10717 } 10718 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 10719 return false; 10720 continue; 10721 } 10722 if (btf_type_is_array(member_type)) { 10723 array = btf_array(member_type); 10724 if (!array->nelems) 10725 return false; 10726 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 10727 if (!btf_type_is_scalar(member_type)) 10728 return false; 10729 continue; 10730 } 10731 if (!btf_type_is_scalar(member_type)) 10732 return false; 10733 } 10734 return true; 10735 } 10736 10737 enum kfunc_ptr_arg_type { 10738 KF_ARG_PTR_TO_CTX, 10739 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 10740 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 10741 KF_ARG_PTR_TO_DYNPTR, 10742 KF_ARG_PTR_TO_ITER, 10743 KF_ARG_PTR_TO_LIST_HEAD, 10744 KF_ARG_PTR_TO_LIST_NODE, 10745 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 10746 KF_ARG_PTR_TO_MEM, 10747 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 10748 KF_ARG_PTR_TO_CALLBACK, 10749 KF_ARG_PTR_TO_RB_ROOT, 10750 KF_ARG_PTR_TO_RB_NODE, 10751 KF_ARG_PTR_TO_NULL, 10752 KF_ARG_PTR_TO_CONST_STR, 10753 }; 10754 10755 enum special_kfunc_type { 10756 KF_bpf_obj_new_impl, 10757 KF_bpf_obj_drop_impl, 10758 KF_bpf_refcount_acquire_impl, 10759 KF_bpf_list_push_front_impl, 10760 KF_bpf_list_push_back_impl, 10761 KF_bpf_list_pop_front, 10762 KF_bpf_list_pop_back, 10763 KF_bpf_cast_to_kern_ctx, 10764 KF_bpf_rdonly_cast, 10765 KF_bpf_rcu_read_lock, 10766 KF_bpf_rcu_read_unlock, 10767 KF_bpf_rbtree_remove, 10768 KF_bpf_rbtree_add_impl, 10769 KF_bpf_rbtree_first, 10770 KF_bpf_dynptr_from_skb, 10771 KF_bpf_dynptr_from_xdp, 10772 KF_bpf_dynptr_slice, 10773 KF_bpf_dynptr_slice_rdwr, 10774 KF_bpf_dynptr_clone, 10775 KF_bpf_percpu_obj_new_impl, 10776 KF_bpf_percpu_obj_drop_impl, 10777 KF_bpf_throw, 10778 KF_bpf_iter_css_task_new, 10779 }; 10780 10781 BTF_SET_START(special_kfunc_set) 10782 BTF_ID(func, bpf_obj_new_impl) 10783 BTF_ID(func, bpf_obj_drop_impl) 10784 BTF_ID(func, bpf_refcount_acquire_impl) 10785 BTF_ID(func, bpf_list_push_front_impl) 10786 BTF_ID(func, bpf_list_push_back_impl) 10787 BTF_ID(func, bpf_list_pop_front) 10788 BTF_ID(func, bpf_list_pop_back) 10789 BTF_ID(func, bpf_cast_to_kern_ctx) 10790 BTF_ID(func, bpf_rdonly_cast) 10791 BTF_ID(func, bpf_rbtree_remove) 10792 BTF_ID(func, bpf_rbtree_add_impl) 10793 BTF_ID(func, bpf_rbtree_first) 10794 BTF_ID(func, bpf_dynptr_from_skb) 10795 BTF_ID(func, bpf_dynptr_from_xdp) 10796 BTF_ID(func, bpf_dynptr_slice) 10797 BTF_ID(func, bpf_dynptr_slice_rdwr) 10798 BTF_ID(func, bpf_dynptr_clone) 10799 BTF_ID(func, bpf_percpu_obj_new_impl) 10800 BTF_ID(func, bpf_percpu_obj_drop_impl) 10801 BTF_ID(func, bpf_throw) 10802 #ifdef CONFIG_CGROUPS 10803 BTF_ID(func, bpf_iter_css_task_new) 10804 #endif 10805 BTF_SET_END(special_kfunc_set) 10806 10807 BTF_ID_LIST(special_kfunc_list) 10808 BTF_ID(func, bpf_obj_new_impl) 10809 BTF_ID(func, bpf_obj_drop_impl) 10810 BTF_ID(func, bpf_refcount_acquire_impl) 10811 BTF_ID(func, bpf_list_push_front_impl) 10812 BTF_ID(func, bpf_list_push_back_impl) 10813 BTF_ID(func, bpf_list_pop_front) 10814 BTF_ID(func, bpf_list_pop_back) 10815 BTF_ID(func, bpf_cast_to_kern_ctx) 10816 BTF_ID(func, bpf_rdonly_cast) 10817 BTF_ID(func, bpf_rcu_read_lock) 10818 BTF_ID(func, bpf_rcu_read_unlock) 10819 BTF_ID(func, bpf_rbtree_remove) 10820 BTF_ID(func, bpf_rbtree_add_impl) 10821 BTF_ID(func, bpf_rbtree_first) 10822 BTF_ID(func, bpf_dynptr_from_skb) 10823 BTF_ID(func, bpf_dynptr_from_xdp) 10824 BTF_ID(func, bpf_dynptr_slice) 10825 BTF_ID(func, bpf_dynptr_slice_rdwr) 10826 BTF_ID(func, bpf_dynptr_clone) 10827 BTF_ID(func, bpf_percpu_obj_new_impl) 10828 BTF_ID(func, bpf_percpu_obj_drop_impl) 10829 BTF_ID(func, bpf_throw) 10830 #ifdef CONFIG_CGROUPS 10831 BTF_ID(func, bpf_iter_css_task_new) 10832 #else 10833 BTF_ID_UNUSED 10834 #endif 10835 10836 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 10837 { 10838 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 10839 meta->arg_owning_ref) { 10840 return false; 10841 } 10842 10843 return meta->kfunc_flags & KF_RET_NULL; 10844 } 10845 10846 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 10847 { 10848 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 10849 } 10850 10851 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 10852 { 10853 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 10854 } 10855 10856 static enum kfunc_ptr_arg_type 10857 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 10858 struct bpf_kfunc_call_arg_meta *meta, 10859 const struct btf_type *t, const struct btf_type *ref_t, 10860 const char *ref_tname, const struct btf_param *args, 10861 int argno, int nargs) 10862 { 10863 u32 regno = argno + 1; 10864 struct bpf_reg_state *regs = cur_regs(env); 10865 struct bpf_reg_state *reg = ®s[regno]; 10866 bool arg_mem_size = false; 10867 10868 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 10869 return KF_ARG_PTR_TO_CTX; 10870 10871 /* In this function, we verify the kfunc's BTF as per the argument type, 10872 * leaving the rest of the verification with respect to the register 10873 * type to our caller. When a set of conditions hold in the BTF type of 10874 * arguments, we resolve it to a known kfunc_ptr_arg_type. 10875 */ 10876 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 10877 return KF_ARG_PTR_TO_CTX; 10878 10879 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 10880 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 10881 10882 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 10883 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 10884 10885 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 10886 return KF_ARG_PTR_TO_DYNPTR; 10887 10888 if (is_kfunc_arg_iter(meta, argno)) 10889 return KF_ARG_PTR_TO_ITER; 10890 10891 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 10892 return KF_ARG_PTR_TO_LIST_HEAD; 10893 10894 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 10895 return KF_ARG_PTR_TO_LIST_NODE; 10896 10897 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 10898 return KF_ARG_PTR_TO_RB_ROOT; 10899 10900 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 10901 return KF_ARG_PTR_TO_RB_NODE; 10902 10903 if (is_kfunc_arg_const_str(meta->btf, &args[argno])) 10904 return KF_ARG_PTR_TO_CONST_STR; 10905 10906 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 10907 if (!btf_type_is_struct(ref_t)) { 10908 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 10909 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 10910 return -EINVAL; 10911 } 10912 return KF_ARG_PTR_TO_BTF_ID; 10913 } 10914 10915 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 10916 return KF_ARG_PTR_TO_CALLBACK; 10917 10918 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg)) 10919 return KF_ARG_PTR_TO_NULL; 10920 10921 if (argno + 1 < nargs && 10922 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 10923 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 10924 arg_mem_size = true; 10925 10926 /* This is the catch all argument type of register types supported by 10927 * check_helper_mem_access. However, we only allow when argument type is 10928 * pointer to scalar, or struct composed (recursively) of scalars. When 10929 * arg_mem_size is true, the pointer can be void *. 10930 */ 10931 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 10932 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 10933 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 10934 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 10935 return -EINVAL; 10936 } 10937 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 10938 } 10939 10940 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 10941 struct bpf_reg_state *reg, 10942 const struct btf_type *ref_t, 10943 const char *ref_tname, u32 ref_id, 10944 struct bpf_kfunc_call_arg_meta *meta, 10945 int argno) 10946 { 10947 const struct btf_type *reg_ref_t; 10948 bool strict_type_match = false; 10949 const struct btf *reg_btf; 10950 const char *reg_ref_tname; 10951 u32 reg_ref_id; 10952 10953 if (base_type(reg->type) == PTR_TO_BTF_ID) { 10954 reg_btf = reg->btf; 10955 reg_ref_id = reg->btf_id; 10956 } else { 10957 reg_btf = btf_vmlinux; 10958 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 10959 } 10960 10961 /* Enforce strict type matching for calls to kfuncs that are acquiring 10962 * or releasing a reference, or are no-cast aliases. We do _not_ 10963 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 10964 * as we want to enable BPF programs to pass types that are bitwise 10965 * equivalent without forcing them to explicitly cast with something 10966 * like bpf_cast_to_kern_ctx(). 10967 * 10968 * For example, say we had a type like the following: 10969 * 10970 * struct bpf_cpumask { 10971 * cpumask_t cpumask; 10972 * refcount_t usage; 10973 * }; 10974 * 10975 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 10976 * to a struct cpumask, so it would be safe to pass a struct 10977 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 10978 * 10979 * The philosophy here is similar to how we allow scalars of different 10980 * types to be passed to kfuncs as long as the size is the same. The 10981 * only difference here is that we're simply allowing 10982 * btf_struct_ids_match() to walk the struct at the 0th offset, and 10983 * resolve types. 10984 */ 10985 if (is_kfunc_acquire(meta) || 10986 (is_kfunc_release(meta) && reg->ref_obj_id) || 10987 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 10988 strict_type_match = true; 10989 10990 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 10991 10992 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 10993 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 10994 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 10995 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 10996 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 10997 btf_type_str(reg_ref_t), reg_ref_tname); 10998 return -EINVAL; 10999 } 11000 return 0; 11001 } 11002 11003 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11004 { 11005 struct bpf_verifier_state *state = env->cur_state; 11006 struct btf_record *rec = reg_btf_record(reg); 11007 11008 if (!state->active_lock.ptr) { 11009 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 11010 return -EFAULT; 11011 } 11012 11013 if (type_flag(reg->type) & NON_OWN_REF) { 11014 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 11015 return -EFAULT; 11016 } 11017 11018 reg->type |= NON_OWN_REF; 11019 if (rec->refcount_off >= 0) 11020 reg->type |= MEM_RCU; 11021 11022 return 0; 11023 } 11024 11025 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 11026 { 11027 struct bpf_func_state *state, *unused; 11028 struct bpf_reg_state *reg; 11029 int i; 11030 11031 state = cur_func(env); 11032 11033 if (!ref_obj_id) { 11034 verbose(env, "verifier internal error: ref_obj_id is zero for " 11035 "owning -> non-owning conversion\n"); 11036 return -EFAULT; 11037 } 11038 11039 for (i = 0; i < state->acquired_refs; i++) { 11040 if (state->refs[i].id != ref_obj_id) 11041 continue; 11042 11043 /* Clear ref_obj_id here so release_reference doesn't clobber 11044 * the whole reg 11045 */ 11046 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11047 if (reg->ref_obj_id == ref_obj_id) { 11048 reg->ref_obj_id = 0; 11049 ref_set_non_owning(env, reg); 11050 } 11051 })); 11052 return 0; 11053 } 11054 11055 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 11056 return -EFAULT; 11057 } 11058 11059 /* Implementation details: 11060 * 11061 * Each register points to some region of memory, which we define as an 11062 * allocation. Each allocation may embed a bpf_spin_lock which protects any 11063 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 11064 * allocation. The lock and the data it protects are colocated in the same 11065 * memory region. 11066 * 11067 * Hence, everytime a register holds a pointer value pointing to such 11068 * allocation, the verifier preserves a unique reg->id for it. 11069 * 11070 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 11071 * bpf_spin_lock is called. 11072 * 11073 * To enable this, lock state in the verifier captures two values: 11074 * active_lock.ptr = Register's type specific pointer 11075 * active_lock.id = A unique ID for each register pointer value 11076 * 11077 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11078 * supported register types. 11079 * 11080 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11081 * allocated objects is the reg->btf pointer. 11082 * 11083 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11084 * can establish the provenance of the map value statically for each distinct 11085 * lookup into such maps. They always contain a single map value hence unique 11086 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11087 * 11088 * So, in case of global variables, they use array maps with max_entries = 1, 11089 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11090 * into the same map value as max_entries is 1, as described above). 11091 * 11092 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11093 * outer map pointer (in verifier context), but each lookup into an inner map 11094 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11095 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11096 * will get different reg->id assigned to each lookup, hence different 11097 * active_lock.id. 11098 * 11099 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11100 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11101 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11102 */ 11103 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11104 { 11105 void *ptr; 11106 u32 id; 11107 11108 switch ((int)reg->type) { 11109 case PTR_TO_MAP_VALUE: 11110 ptr = reg->map_ptr; 11111 break; 11112 case PTR_TO_BTF_ID | MEM_ALLOC: 11113 ptr = reg->btf; 11114 break; 11115 default: 11116 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 11117 return -EFAULT; 11118 } 11119 id = reg->id; 11120 11121 if (!env->cur_state->active_lock.ptr) 11122 return -EINVAL; 11123 if (env->cur_state->active_lock.ptr != ptr || 11124 env->cur_state->active_lock.id != id) { 11125 verbose(env, "held lock and object are not in the same allocation\n"); 11126 return -EINVAL; 11127 } 11128 return 0; 11129 } 11130 11131 static bool is_bpf_list_api_kfunc(u32 btf_id) 11132 { 11133 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11134 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11135 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11136 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 11137 } 11138 11139 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11140 { 11141 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 11142 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11143 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 11144 } 11145 11146 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11147 { 11148 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 11149 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11150 } 11151 11152 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11153 { 11154 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11155 } 11156 11157 static bool is_bpf_throw_kfunc(struct bpf_insn *insn) 11158 { 11159 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 11160 insn->imm == special_kfunc_list[KF_bpf_throw]; 11161 } 11162 11163 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11164 { 11165 return is_bpf_rbtree_api_kfunc(btf_id); 11166 } 11167 11168 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11169 enum btf_field_type head_field_type, 11170 u32 kfunc_btf_id) 11171 { 11172 bool ret; 11173 11174 switch (head_field_type) { 11175 case BPF_LIST_HEAD: 11176 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11177 break; 11178 case BPF_RB_ROOT: 11179 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11180 break; 11181 default: 11182 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11183 btf_field_type_name(head_field_type)); 11184 return false; 11185 } 11186 11187 if (!ret) 11188 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11189 btf_field_type_name(head_field_type)); 11190 return ret; 11191 } 11192 11193 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11194 enum btf_field_type node_field_type, 11195 u32 kfunc_btf_id) 11196 { 11197 bool ret; 11198 11199 switch (node_field_type) { 11200 case BPF_LIST_NODE: 11201 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11202 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 11203 break; 11204 case BPF_RB_NODE: 11205 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11206 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 11207 break; 11208 default: 11209 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11210 btf_field_type_name(node_field_type)); 11211 return false; 11212 } 11213 11214 if (!ret) 11215 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11216 btf_field_type_name(node_field_type)); 11217 return ret; 11218 } 11219 11220 static int 11221 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11222 struct bpf_reg_state *reg, u32 regno, 11223 struct bpf_kfunc_call_arg_meta *meta, 11224 enum btf_field_type head_field_type, 11225 struct btf_field **head_field) 11226 { 11227 const char *head_type_name; 11228 struct btf_field *field; 11229 struct btf_record *rec; 11230 u32 head_off; 11231 11232 if (meta->btf != btf_vmlinux) { 11233 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11234 return -EFAULT; 11235 } 11236 11237 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11238 return -EFAULT; 11239 11240 head_type_name = btf_field_type_name(head_field_type); 11241 if (!tnum_is_const(reg->var_off)) { 11242 verbose(env, 11243 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11244 regno, head_type_name); 11245 return -EINVAL; 11246 } 11247 11248 rec = reg_btf_record(reg); 11249 head_off = reg->off + reg->var_off.value; 11250 field = btf_record_find(rec, head_off, head_field_type); 11251 if (!field) { 11252 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11253 return -EINVAL; 11254 } 11255 11256 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11257 if (check_reg_allocation_locked(env, reg)) { 11258 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11259 rec->spin_lock_off, head_type_name); 11260 return -EINVAL; 11261 } 11262 11263 if (*head_field) { 11264 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 11265 return -EFAULT; 11266 } 11267 *head_field = field; 11268 return 0; 11269 } 11270 11271 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11272 struct bpf_reg_state *reg, u32 regno, 11273 struct bpf_kfunc_call_arg_meta *meta) 11274 { 11275 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 11276 &meta->arg_list_head.field); 11277 } 11278 11279 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11280 struct bpf_reg_state *reg, u32 regno, 11281 struct bpf_kfunc_call_arg_meta *meta) 11282 { 11283 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 11284 &meta->arg_rbtree_root.field); 11285 } 11286 11287 static int 11288 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11289 struct bpf_reg_state *reg, u32 regno, 11290 struct bpf_kfunc_call_arg_meta *meta, 11291 enum btf_field_type head_field_type, 11292 enum btf_field_type node_field_type, 11293 struct btf_field **node_field) 11294 { 11295 const char *node_type_name; 11296 const struct btf_type *et, *t; 11297 struct btf_field *field; 11298 u32 node_off; 11299 11300 if (meta->btf != btf_vmlinux) { 11301 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11302 return -EFAULT; 11303 } 11304 11305 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11306 return -EFAULT; 11307 11308 node_type_name = btf_field_type_name(node_field_type); 11309 if (!tnum_is_const(reg->var_off)) { 11310 verbose(env, 11311 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11312 regno, node_type_name); 11313 return -EINVAL; 11314 } 11315 11316 node_off = reg->off + reg->var_off.value; 11317 field = reg_find_field_offset(reg, node_off, node_field_type); 11318 if (!field || field->offset != node_off) { 11319 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11320 return -EINVAL; 11321 } 11322 11323 field = *node_field; 11324 11325 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11326 t = btf_type_by_id(reg->btf, reg->btf_id); 11327 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11328 field->graph_root.value_btf_id, true)) { 11329 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11330 "in struct %s, but arg is at offset=%d in struct %s\n", 11331 btf_field_type_name(head_field_type), 11332 btf_field_type_name(node_field_type), 11333 field->graph_root.node_offset, 11334 btf_name_by_offset(field->graph_root.btf, et->name_off), 11335 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11336 return -EINVAL; 11337 } 11338 meta->arg_btf = reg->btf; 11339 meta->arg_btf_id = reg->btf_id; 11340 11341 if (node_off != field->graph_root.node_offset) { 11342 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11343 node_off, btf_field_type_name(node_field_type), 11344 field->graph_root.node_offset, 11345 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11346 return -EINVAL; 11347 } 11348 11349 return 0; 11350 } 11351 11352 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11353 struct bpf_reg_state *reg, u32 regno, 11354 struct bpf_kfunc_call_arg_meta *meta) 11355 { 11356 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11357 BPF_LIST_HEAD, BPF_LIST_NODE, 11358 &meta->arg_list_head.field); 11359 } 11360 11361 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11362 struct bpf_reg_state *reg, u32 regno, 11363 struct bpf_kfunc_call_arg_meta *meta) 11364 { 11365 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11366 BPF_RB_ROOT, BPF_RB_NODE, 11367 &meta->arg_rbtree_root.field); 11368 } 11369 11370 /* 11371 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 11372 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 11373 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 11374 * them can only be attached to some specific hook points. 11375 */ 11376 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 11377 { 11378 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11379 11380 switch (prog_type) { 11381 case BPF_PROG_TYPE_LSM: 11382 return true; 11383 case BPF_PROG_TYPE_TRACING: 11384 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 11385 return true; 11386 fallthrough; 11387 default: 11388 return env->prog->aux->sleepable; 11389 } 11390 } 11391 11392 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11393 int insn_idx) 11394 { 11395 const char *func_name = meta->func_name, *ref_tname; 11396 const struct btf *btf = meta->btf; 11397 const struct btf_param *args; 11398 struct btf_record *rec; 11399 u32 i, nargs; 11400 int ret; 11401 11402 args = (const struct btf_param *)(meta->func_proto + 1); 11403 nargs = btf_type_vlen(meta->func_proto); 11404 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 11405 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11406 MAX_BPF_FUNC_REG_ARGS); 11407 return -EINVAL; 11408 } 11409 11410 /* Check that BTF function arguments match actual types that the 11411 * verifier sees. 11412 */ 11413 for (i = 0; i < nargs; i++) { 11414 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 11415 const struct btf_type *t, *ref_t, *resolve_ret; 11416 enum bpf_arg_type arg_type = ARG_DONTCARE; 11417 u32 regno = i + 1, ref_id, type_size; 11418 bool is_ret_buf_sz = false; 11419 int kf_arg_type; 11420 11421 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11422 11423 if (is_kfunc_arg_ignore(btf, &args[i])) 11424 continue; 11425 11426 if (btf_type_is_scalar(t)) { 11427 if (reg->type != SCALAR_VALUE) { 11428 verbose(env, "R%d is not a scalar\n", regno); 11429 return -EINVAL; 11430 } 11431 11432 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11433 if (meta->arg_constant.found) { 11434 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11435 return -EFAULT; 11436 } 11437 if (!tnum_is_const(reg->var_off)) { 11438 verbose(env, "R%d must be a known constant\n", regno); 11439 return -EINVAL; 11440 } 11441 ret = mark_chain_precision(env, regno); 11442 if (ret < 0) 11443 return ret; 11444 meta->arg_constant.found = true; 11445 meta->arg_constant.value = reg->var_off.value; 11446 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 11447 meta->r0_rdonly = true; 11448 is_ret_buf_sz = true; 11449 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 11450 is_ret_buf_sz = true; 11451 } 11452 11453 if (is_ret_buf_sz) { 11454 if (meta->r0_size) { 11455 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 11456 return -EINVAL; 11457 } 11458 11459 if (!tnum_is_const(reg->var_off)) { 11460 verbose(env, "R%d is not a const\n", regno); 11461 return -EINVAL; 11462 } 11463 11464 meta->r0_size = reg->var_off.value; 11465 ret = mark_chain_precision(env, regno); 11466 if (ret) 11467 return ret; 11468 } 11469 continue; 11470 } 11471 11472 if (!btf_type_is_ptr(t)) { 11473 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 11474 return -EINVAL; 11475 } 11476 11477 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 11478 (register_is_null(reg) || type_may_be_null(reg->type)) && 11479 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 11480 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 11481 return -EACCES; 11482 } 11483 11484 if (reg->ref_obj_id) { 11485 if (is_kfunc_release(meta) && meta->ref_obj_id) { 11486 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 11487 regno, reg->ref_obj_id, 11488 meta->ref_obj_id); 11489 return -EFAULT; 11490 } 11491 meta->ref_obj_id = reg->ref_obj_id; 11492 if (is_kfunc_release(meta)) 11493 meta->release_regno = regno; 11494 } 11495 11496 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 11497 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 11498 11499 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 11500 if (kf_arg_type < 0) 11501 return kf_arg_type; 11502 11503 switch (kf_arg_type) { 11504 case KF_ARG_PTR_TO_NULL: 11505 continue; 11506 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11507 case KF_ARG_PTR_TO_BTF_ID: 11508 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 11509 break; 11510 11511 if (!is_trusted_reg(reg)) { 11512 if (!is_kfunc_rcu(meta)) { 11513 verbose(env, "R%d must be referenced or trusted\n", regno); 11514 return -EINVAL; 11515 } 11516 if (!is_rcu_reg(reg)) { 11517 verbose(env, "R%d must be a rcu pointer\n", regno); 11518 return -EINVAL; 11519 } 11520 } 11521 11522 fallthrough; 11523 case KF_ARG_PTR_TO_CTX: 11524 /* Trusted arguments have the same offset checks as release arguments */ 11525 arg_type |= OBJ_RELEASE; 11526 break; 11527 case KF_ARG_PTR_TO_DYNPTR: 11528 case KF_ARG_PTR_TO_ITER: 11529 case KF_ARG_PTR_TO_LIST_HEAD: 11530 case KF_ARG_PTR_TO_LIST_NODE: 11531 case KF_ARG_PTR_TO_RB_ROOT: 11532 case KF_ARG_PTR_TO_RB_NODE: 11533 case KF_ARG_PTR_TO_MEM: 11534 case KF_ARG_PTR_TO_MEM_SIZE: 11535 case KF_ARG_PTR_TO_CALLBACK: 11536 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11537 case KF_ARG_PTR_TO_CONST_STR: 11538 /* Trusted by default */ 11539 break; 11540 default: 11541 WARN_ON_ONCE(1); 11542 return -EFAULT; 11543 } 11544 11545 if (is_kfunc_release(meta) && reg->ref_obj_id) 11546 arg_type |= OBJ_RELEASE; 11547 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 11548 if (ret < 0) 11549 return ret; 11550 11551 switch (kf_arg_type) { 11552 case KF_ARG_PTR_TO_CTX: 11553 if (reg->type != PTR_TO_CTX) { 11554 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 11555 return -EINVAL; 11556 } 11557 11558 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11559 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 11560 if (ret < 0) 11561 return -EINVAL; 11562 meta->ret_btf_id = ret; 11563 } 11564 break; 11565 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11566 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 11567 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) { 11568 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i); 11569 return -EINVAL; 11570 } 11571 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 11572 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 11573 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i); 11574 return -EINVAL; 11575 } 11576 } else { 11577 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11578 return -EINVAL; 11579 } 11580 if (!reg->ref_obj_id) { 11581 verbose(env, "allocated object must be referenced\n"); 11582 return -EINVAL; 11583 } 11584 if (meta->btf == btf_vmlinux) { 11585 meta->arg_btf = reg->btf; 11586 meta->arg_btf_id = reg->btf_id; 11587 } 11588 break; 11589 case KF_ARG_PTR_TO_DYNPTR: 11590 { 11591 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 11592 int clone_ref_obj_id = 0; 11593 11594 if (reg->type != PTR_TO_STACK && 11595 reg->type != CONST_PTR_TO_DYNPTR) { 11596 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 11597 return -EINVAL; 11598 } 11599 11600 if (reg->type == CONST_PTR_TO_DYNPTR) 11601 dynptr_arg_type |= MEM_RDONLY; 11602 11603 if (is_kfunc_arg_uninit(btf, &args[i])) 11604 dynptr_arg_type |= MEM_UNINIT; 11605 11606 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 11607 dynptr_arg_type |= DYNPTR_TYPE_SKB; 11608 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 11609 dynptr_arg_type |= DYNPTR_TYPE_XDP; 11610 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 11611 (dynptr_arg_type & MEM_UNINIT)) { 11612 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 11613 11614 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 11615 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 11616 return -EFAULT; 11617 } 11618 11619 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 11620 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 11621 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 11622 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 11623 return -EFAULT; 11624 } 11625 } 11626 11627 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 11628 if (ret < 0) 11629 return ret; 11630 11631 if (!(dynptr_arg_type & MEM_UNINIT)) { 11632 int id = dynptr_id(env, reg); 11633 11634 if (id < 0) { 11635 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 11636 return id; 11637 } 11638 meta->initialized_dynptr.id = id; 11639 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 11640 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 11641 } 11642 11643 break; 11644 } 11645 case KF_ARG_PTR_TO_ITER: 11646 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 11647 if (!check_css_task_iter_allowlist(env)) { 11648 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 11649 return -EINVAL; 11650 } 11651 } 11652 ret = process_iter_arg(env, regno, insn_idx, meta); 11653 if (ret < 0) 11654 return ret; 11655 break; 11656 case KF_ARG_PTR_TO_LIST_HEAD: 11657 if (reg->type != PTR_TO_MAP_VALUE && 11658 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11659 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11660 return -EINVAL; 11661 } 11662 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11663 verbose(env, "allocated object must be referenced\n"); 11664 return -EINVAL; 11665 } 11666 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 11667 if (ret < 0) 11668 return ret; 11669 break; 11670 case KF_ARG_PTR_TO_RB_ROOT: 11671 if (reg->type != PTR_TO_MAP_VALUE && 11672 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11673 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11674 return -EINVAL; 11675 } 11676 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11677 verbose(env, "allocated object must be referenced\n"); 11678 return -EINVAL; 11679 } 11680 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 11681 if (ret < 0) 11682 return ret; 11683 break; 11684 case KF_ARG_PTR_TO_LIST_NODE: 11685 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11686 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11687 return -EINVAL; 11688 } 11689 if (!reg->ref_obj_id) { 11690 verbose(env, "allocated object must be referenced\n"); 11691 return -EINVAL; 11692 } 11693 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 11694 if (ret < 0) 11695 return ret; 11696 break; 11697 case KF_ARG_PTR_TO_RB_NODE: 11698 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 11699 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 11700 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 11701 return -EINVAL; 11702 } 11703 if (in_rbtree_lock_required_cb(env)) { 11704 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 11705 return -EINVAL; 11706 } 11707 } else { 11708 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11709 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11710 return -EINVAL; 11711 } 11712 if (!reg->ref_obj_id) { 11713 verbose(env, "allocated object must be referenced\n"); 11714 return -EINVAL; 11715 } 11716 } 11717 11718 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 11719 if (ret < 0) 11720 return ret; 11721 break; 11722 case KF_ARG_PTR_TO_BTF_ID: 11723 /* Only base_type is checked, further checks are done here */ 11724 if ((base_type(reg->type) != PTR_TO_BTF_ID || 11725 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 11726 !reg2btf_ids[base_type(reg->type)]) { 11727 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 11728 verbose(env, "expected %s or socket\n", 11729 reg_type_str(env, base_type(reg->type) | 11730 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 11731 return -EINVAL; 11732 } 11733 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 11734 if (ret < 0) 11735 return ret; 11736 break; 11737 case KF_ARG_PTR_TO_MEM: 11738 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 11739 if (IS_ERR(resolve_ret)) { 11740 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 11741 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 11742 return -EINVAL; 11743 } 11744 ret = check_mem_reg(env, reg, regno, type_size); 11745 if (ret < 0) 11746 return ret; 11747 break; 11748 case KF_ARG_PTR_TO_MEM_SIZE: 11749 { 11750 struct bpf_reg_state *buff_reg = ®s[regno]; 11751 const struct btf_param *buff_arg = &args[i]; 11752 struct bpf_reg_state *size_reg = ®s[regno + 1]; 11753 const struct btf_param *size_arg = &args[i + 1]; 11754 11755 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 11756 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 11757 if (ret < 0) { 11758 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 11759 return ret; 11760 } 11761 } 11762 11763 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 11764 if (meta->arg_constant.found) { 11765 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11766 return -EFAULT; 11767 } 11768 if (!tnum_is_const(size_reg->var_off)) { 11769 verbose(env, "R%d must be a known constant\n", regno + 1); 11770 return -EINVAL; 11771 } 11772 meta->arg_constant.found = true; 11773 meta->arg_constant.value = size_reg->var_off.value; 11774 } 11775 11776 /* Skip next '__sz' or '__szk' argument */ 11777 i++; 11778 break; 11779 } 11780 case KF_ARG_PTR_TO_CALLBACK: 11781 if (reg->type != PTR_TO_FUNC) { 11782 verbose(env, "arg%d expected pointer to func\n", i); 11783 return -EINVAL; 11784 } 11785 meta->subprogno = reg->subprogno; 11786 break; 11787 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11788 if (!type_is_ptr_alloc_obj(reg->type)) { 11789 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 11790 return -EINVAL; 11791 } 11792 if (!type_is_non_owning_ref(reg->type)) 11793 meta->arg_owning_ref = true; 11794 11795 rec = reg_btf_record(reg); 11796 if (!rec) { 11797 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 11798 return -EFAULT; 11799 } 11800 11801 if (rec->refcount_off < 0) { 11802 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 11803 return -EINVAL; 11804 } 11805 11806 meta->arg_btf = reg->btf; 11807 meta->arg_btf_id = reg->btf_id; 11808 break; 11809 case KF_ARG_PTR_TO_CONST_STR: 11810 if (reg->type != PTR_TO_MAP_VALUE) { 11811 verbose(env, "arg#%d doesn't point to a const string\n", i); 11812 return -EINVAL; 11813 } 11814 ret = check_reg_const_str(env, reg, regno); 11815 if (ret) 11816 return ret; 11817 break; 11818 } 11819 } 11820 11821 if (is_kfunc_release(meta) && !meta->release_regno) { 11822 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 11823 func_name); 11824 return -EINVAL; 11825 } 11826 11827 return 0; 11828 } 11829 11830 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 11831 struct bpf_insn *insn, 11832 struct bpf_kfunc_call_arg_meta *meta, 11833 const char **kfunc_name) 11834 { 11835 const struct btf_type *func, *func_proto; 11836 u32 func_id, *kfunc_flags; 11837 const char *func_name; 11838 struct btf *desc_btf; 11839 11840 if (kfunc_name) 11841 *kfunc_name = NULL; 11842 11843 if (!insn->imm) 11844 return -EINVAL; 11845 11846 desc_btf = find_kfunc_desc_btf(env, insn->off); 11847 if (IS_ERR(desc_btf)) 11848 return PTR_ERR(desc_btf); 11849 11850 func_id = insn->imm; 11851 func = btf_type_by_id(desc_btf, func_id); 11852 func_name = btf_name_by_offset(desc_btf, func->name_off); 11853 if (kfunc_name) 11854 *kfunc_name = func_name; 11855 func_proto = btf_type_by_id(desc_btf, func->type); 11856 11857 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 11858 if (!kfunc_flags) { 11859 return -EACCES; 11860 } 11861 11862 memset(meta, 0, sizeof(*meta)); 11863 meta->btf = desc_btf; 11864 meta->func_id = func_id; 11865 meta->kfunc_flags = *kfunc_flags; 11866 meta->func_proto = func_proto; 11867 meta->func_name = func_name; 11868 11869 return 0; 11870 } 11871 11872 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 11873 11874 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 11875 int *insn_idx_p) 11876 { 11877 const struct btf_type *t, *ptr_type; 11878 u32 i, nargs, ptr_type_id, release_ref_obj_id; 11879 struct bpf_reg_state *regs = cur_regs(env); 11880 const char *func_name, *ptr_type_name; 11881 bool sleepable, rcu_lock, rcu_unlock; 11882 struct bpf_kfunc_call_arg_meta meta; 11883 struct bpf_insn_aux_data *insn_aux; 11884 int err, insn_idx = *insn_idx_p; 11885 const struct btf_param *args; 11886 const struct btf_type *ret_t; 11887 struct btf *desc_btf; 11888 11889 /* skip for now, but return error when we find this in fixup_kfunc_call */ 11890 if (!insn->imm) 11891 return 0; 11892 11893 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 11894 if (err == -EACCES && func_name) 11895 verbose(env, "calling kernel function %s is not allowed\n", func_name); 11896 if (err) 11897 return err; 11898 desc_btf = meta.btf; 11899 insn_aux = &env->insn_aux_data[insn_idx]; 11900 11901 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 11902 11903 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 11904 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 11905 return -EACCES; 11906 } 11907 11908 sleepable = is_kfunc_sleepable(&meta); 11909 if (sleepable && !env->prog->aux->sleepable) { 11910 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 11911 return -EACCES; 11912 } 11913 11914 /* Check the arguments */ 11915 err = check_kfunc_args(env, &meta, insn_idx); 11916 if (err < 0) 11917 return err; 11918 11919 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 11920 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 11921 set_rbtree_add_callback_state); 11922 if (err) { 11923 verbose(env, "kfunc %s#%d failed callback verification\n", 11924 func_name, meta.func_id); 11925 return err; 11926 } 11927 } 11928 11929 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 11930 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 11931 11932 if (env->cur_state->active_rcu_lock) { 11933 struct bpf_func_state *state; 11934 struct bpf_reg_state *reg; 11935 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 11936 11937 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 11938 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 11939 return -EACCES; 11940 } 11941 11942 if (rcu_lock) { 11943 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 11944 return -EINVAL; 11945 } else if (rcu_unlock) { 11946 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({ 11947 if (reg->type & MEM_RCU) { 11948 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 11949 reg->type |= PTR_UNTRUSTED; 11950 } 11951 })); 11952 env->cur_state->active_rcu_lock = false; 11953 } else if (sleepable) { 11954 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 11955 return -EACCES; 11956 } 11957 } else if (rcu_lock) { 11958 env->cur_state->active_rcu_lock = true; 11959 } else if (rcu_unlock) { 11960 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 11961 return -EINVAL; 11962 } 11963 11964 /* In case of release function, we get register number of refcounted 11965 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 11966 */ 11967 if (meta.release_regno) { 11968 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 11969 if (err) { 11970 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 11971 func_name, meta.func_id); 11972 return err; 11973 } 11974 } 11975 11976 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11977 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11978 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 11979 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 11980 insn_aux->insert_off = regs[BPF_REG_2].off; 11981 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 11982 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 11983 if (err) { 11984 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 11985 func_name, meta.func_id); 11986 return err; 11987 } 11988 11989 err = release_reference(env, release_ref_obj_id); 11990 if (err) { 11991 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 11992 func_name, meta.func_id); 11993 return err; 11994 } 11995 } 11996 11997 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 11998 if (!bpf_jit_supports_exceptions()) { 11999 verbose(env, "JIT does not support calling kfunc %s#%d\n", 12000 func_name, meta.func_id); 12001 return -ENOTSUPP; 12002 } 12003 env->seen_exception = true; 12004 12005 /* In the case of the default callback, the cookie value passed 12006 * to bpf_throw becomes the return value of the program. 12007 */ 12008 if (!env->exception_callback_subprog) { 12009 err = check_return_code(env, BPF_REG_1, "R1"); 12010 if (err < 0) 12011 return err; 12012 } 12013 } 12014 12015 for (i = 0; i < CALLER_SAVED_REGS; i++) 12016 mark_reg_not_init(env, regs, caller_saved[i]); 12017 12018 /* Check return type */ 12019 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 12020 12021 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 12022 /* Only exception is bpf_obj_new_impl */ 12023 if (meta.btf != btf_vmlinux || 12024 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 12025 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] && 12026 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 12027 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 12028 return -EINVAL; 12029 } 12030 } 12031 12032 if (btf_type_is_scalar(t)) { 12033 mark_reg_unknown(env, regs, BPF_REG_0); 12034 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 12035 } else if (btf_type_is_ptr(t)) { 12036 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 12037 12038 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12039 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 12040 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12041 struct btf_struct_meta *struct_meta; 12042 struct btf *ret_btf; 12043 u32 ret_btf_id; 12044 12045 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set) 12046 return -ENOMEM; 12047 12048 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12049 if (!bpf_global_percpu_ma_set) { 12050 mutex_lock(&bpf_percpu_ma_lock); 12051 if (!bpf_global_percpu_ma_set) { 12052 err = bpf_mem_alloc_init(&bpf_global_percpu_ma, 0, true); 12053 if (!err) 12054 bpf_global_percpu_ma_set = true; 12055 } 12056 mutex_unlock(&bpf_percpu_ma_lock); 12057 if (err) 12058 return err; 12059 } 12060 } 12061 12062 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 12063 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 12064 return -EINVAL; 12065 } 12066 12067 ret_btf = env->prog->aux->btf; 12068 ret_btf_id = meta.arg_constant.value; 12069 12070 /* This may be NULL due to user not supplying a BTF */ 12071 if (!ret_btf) { 12072 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 12073 return -EINVAL; 12074 } 12075 12076 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 12077 if (!ret_t || !__btf_type_is_struct(ret_t)) { 12078 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 12079 return -EINVAL; 12080 } 12081 12082 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 12083 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12084 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 12085 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 12086 return -EINVAL; 12087 } 12088 12089 if (struct_meta) { 12090 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 12091 return -EINVAL; 12092 } 12093 } 12094 12095 mark_reg_known_zero(env, regs, BPF_REG_0); 12096 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12097 regs[BPF_REG_0].btf = ret_btf; 12098 regs[BPF_REG_0].btf_id = ret_btf_id; 12099 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) 12100 regs[BPF_REG_0].type |= MEM_PERCPU; 12101 12102 insn_aux->obj_new_size = ret_t->size; 12103 insn_aux->kptr_struct_meta = struct_meta; 12104 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 12105 mark_reg_known_zero(env, regs, BPF_REG_0); 12106 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12107 regs[BPF_REG_0].btf = meta.arg_btf; 12108 regs[BPF_REG_0].btf_id = meta.arg_btf_id; 12109 12110 insn_aux->kptr_struct_meta = 12111 btf_find_struct_meta(meta.arg_btf, 12112 meta.arg_btf_id); 12113 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 12114 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 12115 struct btf_field *field = meta.arg_list_head.field; 12116 12117 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12118 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12119 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12120 struct btf_field *field = meta.arg_rbtree_root.field; 12121 12122 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12123 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12124 mark_reg_known_zero(env, regs, BPF_REG_0); 12125 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 12126 regs[BPF_REG_0].btf = desc_btf; 12127 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 12128 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 12129 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 12130 if (!ret_t || !btf_type_is_struct(ret_t)) { 12131 verbose(env, 12132 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 12133 return -EINVAL; 12134 } 12135 12136 mark_reg_known_zero(env, regs, BPF_REG_0); 12137 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 12138 regs[BPF_REG_0].btf = desc_btf; 12139 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 12140 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 12141 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 12142 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 12143 12144 mark_reg_known_zero(env, regs, BPF_REG_0); 12145 12146 if (!meta.arg_constant.found) { 12147 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 12148 return -EFAULT; 12149 } 12150 12151 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 12152 12153 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 12154 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 12155 12156 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 12157 regs[BPF_REG_0].type |= MEM_RDONLY; 12158 } else { 12159 /* this will set env->seen_direct_write to true */ 12160 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 12161 verbose(env, "the prog does not allow writes to packet data\n"); 12162 return -EINVAL; 12163 } 12164 } 12165 12166 if (!meta.initialized_dynptr.id) { 12167 verbose(env, "verifier internal error: no dynptr id\n"); 12168 return -EFAULT; 12169 } 12170 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 12171 12172 /* we don't need to set BPF_REG_0's ref obj id 12173 * because packet slices are not refcounted (see 12174 * dynptr_type_refcounted) 12175 */ 12176 } else { 12177 verbose(env, "kernel function %s unhandled dynamic return type\n", 12178 meta.func_name); 12179 return -EFAULT; 12180 } 12181 } else if (!__btf_type_is_struct(ptr_type)) { 12182 if (!meta.r0_size) { 12183 __u32 sz; 12184 12185 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 12186 meta.r0_size = sz; 12187 meta.r0_rdonly = true; 12188 } 12189 } 12190 if (!meta.r0_size) { 12191 ptr_type_name = btf_name_by_offset(desc_btf, 12192 ptr_type->name_off); 12193 verbose(env, 12194 "kernel function %s returns pointer type %s %s is not supported\n", 12195 func_name, 12196 btf_type_str(ptr_type), 12197 ptr_type_name); 12198 return -EINVAL; 12199 } 12200 12201 mark_reg_known_zero(env, regs, BPF_REG_0); 12202 regs[BPF_REG_0].type = PTR_TO_MEM; 12203 regs[BPF_REG_0].mem_size = meta.r0_size; 12204 12205 if (meta.r0_rdonly) 12206 regs[BPF_REG_0].type |= MEM_RDONLY; 12207 12208 /* Ensures we don't access the memory after a release_reference() */ 12209 if (meta.ref_obj_id) 12210 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 12211 } else { 12212 mark_reg_known_zero(env, regs, BPF_REG_0); 12213 regs[BPF_REG_0].btf = desc_btf; 12214 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 12215 regs[BPF_REG_0].btf_id = ptr_type_id; 12216 } 12217 12218 if (is_kfunc_ret_null(&meta)) { 12219 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 12220 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 12221 regs[BPF_REG_0].id = ++env->id_gen; 12222 } 12223 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 12224 if (is_kfunc_acquire(&meta)) { 12225 int id = acquire_reference_state(env, insn_idx); 12226 12227 if (id < 0) 12228 return id; 12229 if (is_kfunc_ret_null(&meta)) 12230 regs[BPF_REG_0].id = id; 12231 regs[BPF_REG_0].ref_obj_id = id; 12232 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12233 ref_set_non_owning(env, ®s[BPF_REG_0]); 12234 } 12235 12236 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 12237 regs[BPF_REG_0].id = ++env->id_gen; 12238 } else if (btf_type_is_void(t)) { 12239 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12240 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 12241 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 12242 insn_aux->kptr_struct_meta = 12243 btf_find_struct_meta(meta.arg_btf, 12244 meta.arg_btf_id); 12245 } 12246 } 12247 } 12248 12249 nargs = btf_type_vlen(meta.func_proto); 12250 args = (const struct btf_param *)(meta.func_proto + 1); 12251 for (i = 0; i < nargs; i++) { 12252 u32 regno = i + 1; 12253 12254 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 12255 if (btf_type_is_ptr(t)) 12256 mark_btf_func_reg_size(env, regno, sizeof(void *)); 12257 else 12258 /* scalar. ensured by btf_check_kfunc_arg_match() */ 12259 mark_btf_func_reg_size(env, regno, t->size); 12260 } 12261 12262 if (is_iter_next_kfunc(&meta)) { 12263 err = process_iter_next_call(env, insn_idx, &meta); 12264 if (err) 12265 return err; 12266 } 12267 12268 return 0; 12269 } 12270 12271 static bool signed_add_overflows(s64 a, s64 b) 12272 { 12273 /* Do the add in u64, where overflow is well-defined */ 12274 s64 res = (s64)((u64)a + (u64)b); 12275 12276 if (b < 0) 12277 return res > a; 12278 return res < a; 12279 } 12280 12281 static bool signed_add32_overflows(s32 a, s32 b) 12282 { 12283 /* Do the add in u32, where overflow is well-defined */ 12284 s32 res = (s32)((u32)a + (u32)b); 12285 12286 if (b < 0) 12287 return res > a; 12288 return res < a; 12289 } 12290 12291 static bool signed_sub_overflows(s64 a, s64 b) 12292 { 12293 /* Do the sub in u64, where overflow is well-defined */ 12294 s64 res = (s64)((u64)a - (u64)b); 12295 12296 if (b < 0) 12297 return res < a; 12298 return res > a; 12299 } 12300 12301 static bool signed_sub32_overflows(s32 a, s32 b) 12302 { 12303 /* Do the sub in u32, where overflow is well-defined */ 12304 s32 res = (s32)((u32)a - (u32)b); 12305 12306 if (b < 0) 12307 return res < a; 12308 return res > a; 12309 } 12310 12311 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 12312 const struct bpf_reg_state *reg, 12313 enum bpf_reg_type type) 12314 { 12315 bool known = tnum_is_const(reg->var_off); 12316 s64 val = reg->var_off.value; 12317 s64 smin = reg->smin_value; 12318 12319 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 12320 verbose(env, "math between %s pointer and %lld is not allowed\n", 12321 reg_type_str(env, type), val); 12322 return false; 12323 } 12324 12325 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 12326 verbose(env, "%s pointer offset %d is not allowed\n", 12327 reg_type_str(env, type), reg->off); 12328 return false; 12329 } 12330 12331 if (smin == S64_MIN) { 12332 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 12333 reg_type_str(env, type)); 12334 return false; 12335 } 12336 12337 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 12338 verbose(env, "value %lld makes %s pointer be out of bounds\n", 12339 smin, reg_type_str(env, type)); 12340 return false; 12341 } 12342 12343 return true; 12344 } 12345 12346 enum { 12347 REASON_BOUNDS = -1, 12348 REASON_TYPE = -2, 12349 REASON_PATHS = -3, 12350 REASON_LIMIT = -4, 12351 REASON_STACK = -5, 12352 }; 12353 12354 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 12355 u32 *alu_limit, bool mask_to_left) 12356 { 12357 u32 max = 0, ptr_limit = 0; 12358 12359 switch (ptr_reg->type) { 12360 case PTR_TO_STACK: 12361 /* Offset 0 is out-of-bounds, but acceptable start for the 12362 * left direction, see BPF_REG_FP. Also, unknown scalar 12363 * offset where we would need to deal with min/max bounds is 12364 * currently prohibited for unprivileged. 12365 */ 12366 max = MAX_BPF_STACK + mask_to_left; 12367 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 12368 break; 12369 case PTR_TO_MAP_VALUE: 12370 max = ptr_reg->map_ptr->value_size; 12371 ptr_limit = (mask_to_left ? 12372 ptr_reg->smin_value : 12373 ptr_reg->umax_value) + ptr_reg->off; 12374 break; 12375 default: 12376 return REASON_TYPE; 12377 } 12378 12379 if (ptr_limit >= max) 12380 return REASON_LIMIT; 12381 *alu_limit = ptr_limit; 12382 return 0; 12383 } 12384 12385 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 12386 const struct bpf_insn *insn) 12387 { 12388 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 12389 } 12390 12391 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 12392 u32 alu_state, u32 alu_limit) 12393 { 12394 /* If we arrived here from different branches with different 12395 * state or limits to sanitize, then this won't work. 12396 */ 12397 if (aux->alu_state && 12398 (aux->alu_state != alu_state || 12399 aux->alu_limit != alu_limit)) 12400 return REASON_PATHS; 12401 12402 /* Corresponding fixup done in do_misc_fixups(). */ 12403 aux->alu_state = alu_state; 12404 aux->alu_limit = alu_limit; 12405 return 0; 12406 } 12407 12408 static int sanitize_val_alu(struct bpf_verifier_env *env, 12409 struct bpf_insn *insn) 12410 { 12411 struct bpf_insn_aux_data *aux = cur_aux(env); 12412 12413 if (can_skip_alu_sanitation(env, insn)) 12414 return 0; 12415 12416 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 12417 } 12418 12419 static bool sanitize_needed(u8 opcode) 12420 { 12421 return opcode == BPF_ADD || opcode == BPF_SUB; 12422 } 12423 12424 struct bpf_sanitize_info { 12425 struct bpf_insn_aux_data aux; 12426 bool mask_to_left; 12427 }; 12428 12429 static struct bpf_verifier_state * 12430 sanitize_speculative_path(struct bpf_verifier_env *env, 12431 const struct bpf_insn *insn, 12432 u32 next_idx, u32 curr_idx) 12433 { 12434 struct bpf_verifier_state *branch; 12435 struct bpf_reg_state *regs; 12436 12437 branch = push_stack(env, next_idx, curr_idx, true); 12438 if (branch && insn) { 12439 regs = branch->frame[branch->curframe]->regs; 12440 if (BPF_SRC(insn->code) == BPF_K) { 12441 mark_reg_unknown(env, regs, insn->dst_reg); 12442 } else if (BPF_SRC(insn->code) == BPF_X) { 12443 mark_reg_unknown(env, regs, insn->dst_reg); 12444 mark_reg_unknown(env, regs, insn->src_reg); 12445 } 12446 } 12447 return branch; 12448 } 12449 12450 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 12451 struct bpf_insn *insn, 12452 const struct bpf_reg_state *ptr_reg, 12453 const struct bpf_reg_state *off_reg, 12454 struct bpf_reg_state *dst_reg, 12455 struct bpf_sanitize_info *info, 12456 const bool commit_window) 12457 { 12458 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 12459 struct bpf_verifier_state *vstate = env->cur_state; 12460 bool off_is_imm = tnum_is_const(off_reg->var_off); 12461 bool off_is_neg = off_reg->smin_value < 0; 12462 bool ptr_is_dst_reg = ptr_reg == dst_reg; 12463 u8 opcode = BPF_OP(insn->code); 12464 u32 alu_state, alu_limit; 12465 struct bpf_reg_state tmp; 12466 bool ret; 12467 int err; 12468 12469 if (can_skip_alu_sanitation(env, insn)) 12470 return 0; 12471 12472 /* We already marked aux for masking from non-speculative 12473 * paths, thus we got here in the first place. We only care 12474 * to explore bad access from here. 12475 */ 12476 if (vstate->speculative) 12477 goto do_sim; 12478 12479 if (!commit_window) { 12480 if (!tnum_is_const(off_reg->var_off) && 12481 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 12482 return REASON_BOUNDS; 12483 12484 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 12485 (opcode == BPF_SUB && !off_is_neg); 12486 } 12487 12488 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 12489 if (err < 0) 12490 return err; 12491 12492 if (commit_window) { 12493 /* In commit phase we narrow the masking window based on 12494 * the observed pointer move after the simulated operation. 12495 */ 12496 alu_state = info->aux.alu_state; 12497 alu_limit = abs(info->aux.alu_limit - alu_limit); 12498 } else { 12499 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 12500 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 12501 alu_state |= ptr_is_dst_reg ? 12502 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 12503 12504 /* Limit pruning on unknown scalars to enable deep search for 12505 * potential masking differences from other program paths. 12506 */ 12507 if (!off_is_imm) 12508 env->explore_alu_limits = true; 12509 } 12510 12511 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 12512 if (err < 0) 12513 return err; 12514 do_sim: 12515 /* If we're in commit phase, we're done here given we already 12516 * pushed the truncated dst_reg into the speculative verification 12517 * stack. 12518 * 12519 * Also, when register is a known constant, we rewrite register-based 12520 * operation to immediate-based, and thus do not need masking (and as 12521 * a consequence, do not need to simulate the zero-truncation either). 12522 */ 12523 if (commit_window || off_is_imm) 12524 return 0; 12525 12526 /* Simulate and find potential out-of-bounds access under 12527 * speculative execution from truncation as a result of 12528 * masking when off was not within expected range. If off 12529 * sits in dst, then we temporarily need to move ptr there 12530 * to simulate dst (== 0) +/-= ptr. Needed, for example, 12531 * for cases where we use K-based arithmetic in one direction 12532 * and truncated reg-based in the other in order to explore 12533 * bad access. 12534 */ 12535 if (!ptr_is_dst_reg) { 12536 tmp = *dst_reg; 12537 copy_register_state(dst_reg, ptr_reg); 12538 } 12539 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 12540 env->insn_idx); 12541 if (!ptr_is_dst_reg && ret) 12542 *dst_reg = tmp; 12543 return !ret ? REASON_STACK : 0; 12544 } 12545 12546 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 12547 { 12548 struct bpf_verifier_state *vstate = env->cur_state; 12549 12550 /* If we simulate paths under speculation, we don't update the 12551 * insn as 'seen' such that when we verify unreachable paths in 12552 * the non-speculative domain, sanitize_dead_code() can still 12553 * rewrite/sanitize them. 12554 */ 12555 if (!vstate->speculative) 12556 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 12557 } 12558 12559 static int sanitize_err(struct bpf_verifier_env *env, 12560 const struct bpf_insn *insn, int reason, 12561 const struct bpf_reg_state *off_reg, 12562 const struct bpf_reg_state *dst_reg) 12563 { 12564 static const char *err = "pointer arithmetic with it prohibited for !root"; 12565 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 12566 u32 dst = insn->dst_reg, src = insn->src_reg; 12567 12568 switch (reason) { 12569 case REASON_BOUNDS: 12570 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 12571 off_reg == dst_reg ? dst : src, err); 12572 break; 12573 case REASON_TYPE: 12574 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 12575 off_reg == dst_reg ? src : dst, err); 12576 break; 12577 case REASON_PATHS: 12578 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 12579 dst, op, err); 12580 break; 12581 case REASON_LIMIT: 12582 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 12583 dst, op, err); 12584 break; 12585 case REASON_STACK: 12586 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 12587 dst, err); 12588 break; 12589 default: 12590 verbose(env, "verifier internal error: unknown reason (%d)\n", 12591 reason); 12592 break; 12593 } 12594 12595 return -EACCES; 12596 } 12597 12598 /* check that stack access falls within stack limits and that 'reg' doesn't 12599 * have a variable offset. 12600 * 12601 * Variable offset is prohibited for unprivileged mode for simplicity since it 12602 * requires corresponding support in Spectre masking for stack ALU. See also 12603 * retrieve_ptr_limit(). 12604 * 12605 * 12606 * 'off' includes 'reg->off'. 12607 */ 12608 static int check_stack_access_for_ptr_arithmetic( 12609 struct bpf_verifier_env *env, 12610 int regno, 12611 const struct bpf_reg_state *reg, 12612 int off) 12613 { 12614 if (!tnum_is_const(reg->var_off)) { 12615 char tn_buf[48]; 12616 12617 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 12618 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 12619 regno, tn_buf, off); 12620 return -EACCES; 12621 } 12622 12623 if (off >= 0 || off < -MAX_BPF_STACK) { 12624 verbose(env, "R%d stack pointer arithmetic goes out of range, " 12625 "prohibited for !root; off=%d\n", regno, off); 12626 return -EACCES; 12627 } 12628 12629 return 0; 12630 } 12631 12632 static int sanitize_check_bounds(struct bpf_verifier_env *env, 12633 const struct bpf_insn *insn, 12634 const struct bpf_reg_state *dst_reg) 12635 { 12636 u32 dst = insn->dst_reg; 12637 12638 /* For unprivileged we require that resulting offset must be in bounds 12639 * in order to be able to sanitize access later on. 12640 */ 12641 if (env->bypass_spec_v1) 12642 return 0; 12643 12644 switch (dst_reg->type) { 12645 case PTR_TO_STACK: 12646 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 12647 dst_reg->off + dst_reg->var_off.value)) 12648 return -EACCES; 12649 break; 12650 case PTR_TO_MAP_VALUE: 12651 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 12652 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 12653 "prohibited for !root\n", dst); 12654 return -EACCES; 12655 } 12656 break; 12657 default: 12658 break; 12659 } 12660 12661 return 0; 12662 } 12663 12664 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 12665 * Caller should also handle BPF_MOV case separately. 12666 * If we return -EACCES, caller may want to try again treating pointer as a 12667 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 12668 */ 12669 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 12670 struct bpf_insn *insn, 12671 const struct bpf_reg_state *ptr_reg, 12672 const struct bpf_reg_state *off_reg) 12673 { 12674 struct bpf_verifier_state *vstate = env->cur_state; 12675 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 12676 struct bpf_reg_state *regs = state->regs, *dst_reg; 12677 bool known = tnum_is_const(off_reg->var_off); 12678 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 12679 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 12680 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 12681 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 12682 struct bpf_sanitize_info info = {}; 12683 u8 opcode = BPF_OP(insn->code); 12684 u32 dst = insn->dst_reg; 12685 int ret; 12686 12687 dst_reg = ®s[dst]; 12688 12689 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 12690 smin_val > smax_val || umin_val > umax_val) { 12691 /* Taint dst register if offset had invalid bounds derived from 12692 * e.g. dead branches. 12693 */ 12694 __mark_reg_unknown(env, dst_reg); 12695 return 0; 12696 } 12697 12698 if (BPF_CLASS(insn->code) != BPF_ALU64) { 12699 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 12700 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 12701 __mark_reg_unknown(env, dst_reg); 12702 return 0; 12703 } 12704 12705 verbose(env, 12706 "R%d 32-bit pointer arithmetic prohibited\n", 12707 dst); 12708 return -EACCES; 12709 } 12710 12711 if (ptr_reg->type & PTR_MAYBE_NULL) { 12712 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 12713 dst, reg_type_str(env, ptr_reg->type)); 12714 return -EACCES; 12715 } 12716 12717 switch (base_type(ptr_reg->type)) { 12718 case CONST_PTR_TO_MAP: 12719 /* smin_val represents the known value */ 12720 if (known && smin_val == 0 && opcode == BPF_ADD) 12721 break; 12722 fallthrough; 12723 case PTR_TO_PACKET_END: 12724 case PTR_TO_SOCKET: 12725 case PTR_TO_SOCK_COMMON: 12726 case PTR_TO_TCP_SOCK: 12727 case PTR_TO_XDP_SOCK: 12728 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 12729 dst, reg_type_str(env, ptr_reg->type)); 12730 return -EACCES; 12731 default: 12732 break; 12733 } 12734 12735 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 12736 * The id may be overwritten later if we create a new variable offset. 12737 */ 12738 dst_reg->type = ptr_reg->type; 12739 dst_reg->id = ptr_reg->id; 12740 12741 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 12742 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 12743 return -EINVAL; 12744 12745 /* pointer types do not carry 32-bit bounds at the moment. */ 12746 __mark_reg32_unbounded(dst_reg); 12747 12748 if (sanitize_needed(opcode)) { 12749 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 12750 &info, false); 12751 if (ret < 0) 12752 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12753 } 12754 12755 switch (opcode) { 12756 case BPF_ADD: 12757 /* We can take a fixed offset as long as it doesn't overflow 12758 * the s32 'off' field 12759 */ 12760 if (known && (ptr_reg->off + smin_val == 12761 (s64)(s32)(ptr_reg->off + smin_val))) { 12762 /* pointer += K. Accumulate it into fixed offset */ 12763 dst_reg->smin_value = smin_ptr; 12764 dst_reg->smax_value = smax_ptr; 12765 dst_reg->umin_value = umin_ptr; 12766 dst_reg->umax_value = umax_ptr; 12767 dst_reg->var_off = ptr_reg->var_off; 12768 dst_reg->off = ptr_reg->off + smin_val; 12769 dst_reg->raw = ptr_reg->raw; 12770 break; 12771 } 12772 /* A new variable offset is created. Note that off_reg->off 12773 * == 0, since it's a scalar. 12774 * dst_reg gets the pointer type and since some positive 12775 * integer value was added to the pointer, give it a new 'id' 12776 * if it's a PTR_TO_PACKET. 12777 * this creates a new 'base' pointer, off_reg (variable) gets 12778 * added into the variable offset, and we copy the fixed offset 12779 * from ptr_reg. 12780 */ 12781 if (signed_add_overflows(smin_ptr, smin_val) || 12782 signed_add_overflows(smax_ptr, smax_val)) { 12783 dst_reg->smin_value = S64_MIN; 12784 dst_reg->smax_value = S64_MAX; 12785 } else { 12786 dst_reg->smin_value = smin_ptr + smin_val; 12787 dst_reg->smax_value = smax_ptr + smax_val; 12788 } 12789 if (umin_ptr + umin_val < umin_ptr || 12790 umax_ptr + umax_val < umax_ptr) { 12791 dst_reg->umin_value = 0; 12792 dst_reg->umax_value = U64_MAX; 12793 } else { 12794 dst_reg->umin_value = umin_ptr + umin_val; 12795 dst_reg->umax_value = umax_ptr + umax_val; 12796 } 12797 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 12798 dst_reg->off = ptr_reg->off; 12799 dst_reg->raw = ptr_reg->raw; 12800 if (reg_is_pkt_pointer(ptr_reg)) { 12801 dst_reg->id = ++env->id_gen; 12802 /* something was added to pkt_ptr, set range to zero */ 12803 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12804 } 12805 break; 12806 case BPF_SUB: 12807 if (dst_reg == off_reg) { 12808 /* scalar -= pointer. Creates an unknown scalar */ 12809 verbose(env, "R%d tried to subtract pointer from scalar\n", 12810 dst); 12811 return -EACCES; 12812 } 12813 /* We don't allow subtraction from FP, because (according to 12814 * test_verifier.c test "invalid fp arithmetic", JITs might not 12815 * be able to deal with it. 12816 */ 12817 if (ptr_reg->type == PTR_TO_STACK) { 12818 verbose(env, "R%d subtraction from stack pointer prohibited\n", 12819 dst); 12820 return -EACCES; 12821 } 12822 if (known && (ptr_reg->off - smin_val == 12823 (s64)(s32)(ptr_reg->off - smin_val))) { 12824 /* pointer -= K. Subtract it from fixed offset */ 12825 dst_reg->smin_value = smin_ptr; 12826 dst_reg->smax_value = smax_ptr; 12827 dst_reg->umin_value = umin_ptr; 12828 dst_reg->umax_value = umax_ptr; 12829 dst_reg->var_off = ptr_reg->var_off; 12830 dst_reg->id = ptr_reg->id; 12831 dst_reg->off = ptr_reg->off - smin_val; 12832 dst_reg->raw = ptr_reg->raw; 12833 break; 12834 } 12835 /* A new variable offset is created. If the subtrahend is known 12836 * nonnegative, then any reg->range we had before is still good. 12837 */ 12838 if (signed_sub_overflows(smin_ptr, smax_val) || 12839 signed_sub_overflows(smax_ptr, smin_val)) { 12840 /* Overflow possible, we know nothing */ 12841 dst_reg->smin_value = S64_MIN; 12842 dst_reg->smax_value = S64_MAX; 12843 } else { 12844 dst_reg->smin_value = smin_ptr - smax_val; 12845 dst_reg->smax_value = smax_ptr - smin_val; 12846 } 12847 if (umin_ptr < umax_val) { 12848 /* Overflow possible, we know nothing */ 12849 dst_reg->umin_value = 0; 12850 dst_reg->umax_value = U64_MAX; 12851 } else { 12852 /* Cannot overflow (as long as bounds are consistent) */ 12853 dst_reg->umin_value = umin_ptr - umax_val; 12854 dst_reg->umax_value = umax_ptr - umin_val; 12855 } 12856 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 12857 dst_reg->off = ptr_reg->off; 12858 dst_reg->raw = ptr_reg->raw; 12859 if (reg_is_pkt_pointer(ptr_reg)) { 12860 dst_reg->id = ++env->id_gen; 12861 /* something was added to pkt_ptr, set range to zero */ 12862 if (smin_val < 0) 12863 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 12864 } 12865 break; 12866 case BPF_AND: 12867 case BPF_OR: 12868 case BPF_XOR: 12869 /* bitwise ops on pointers are troublesome, prohibit. */ 12870 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 12871 dst, bpf_alu_string[opcode >> 4]); 12872 return -EACCES; 12873 default: 12874 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 12875 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 12876 dst, bpf_alu_string[opcode >> 4]); 12877 return -EACCES; 12878 } 12879 12880 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 12881 return -EINVAL; 12882 reg_bounds_sync(dst_reg); 12883 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 12884 return -EACCES; 12885 if (sanitize_needed(opcode)) { 12886 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 12887 &info, true); 12888 if (ret < 0) 12889 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12890 } 12891 12892 return 0; 12893 } 12894 12895 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 12896 struct bpf_reg_state *src_reg) 12897 { 12898 s32 smin_val = src_reg->s32_min_value; 12899 s32 smax_val = src_reg->s32_max_value; 12900 u32 umin_val = src_reg->u32_min_value; 12901 u32 umax_val = src_reg->u32_max_value; 12902 12903 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 12904 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 12905 dst_reg->s32_min_value = S32_MIN; 12906 dst_reg->s32_max_value = S32_MAX; 12907 } else { 12908 dst_reg->s32_min_value += smin_val; 12909 dst_reg->s32_max_value += smax_val; 12910 } 12911 if (dst_reg->u32_min_value + umin_val < umin_val || 12912 dst_reg->u32_max_value + umax_val < umax_val) { 12913 dst_reg->u32_min_value = 0; 12914 dst_reg->u32_max_value = U32_MAX; 12915 } else { 12916 dst_reg->u32_min_value += umin_val; 12917 dst_reg->u32_max_value += umax_val; 12918 } 12919 } 12920 12921 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 12922 struct bpf_reg_state *src_reg) 12923 { 12924 s64 smin_val = src_reg->smin_value; 12925 s64 smax_val = src_reg->smax_value; 12926 u64 umin_val = src_reg->umin_value; 12927 u64 umax_val = src_reg->umax_value; 12928 12929 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 12930 signed_add_overflows(dst_reg->smax_value, smax_val)) { 12931 dst_reg->smin_value = S64_MIN; 12932 dst_reg->smax_value = S64_MAX; 12933 } else { 12934 dst_reg->smin_value += smin_val; 12935 dst_reg->smax_value += smax_val; 12936 } 12937 if (dst_reg->umin_value + umin_val < umin_val || 12938 dst_reg->umax_value + umax_val < umax_val) { 12939 dst_reg->umin_value = 0; 12940 dst_reg->umax_value = U64_MAX; 12941 } else { 12942 dst_reg->umin_value += umin_val; 12943 dst_reg->umax_value += umax_val; 12944 } 12945 } 12946 12947 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 12948 struct bpf_reg_state *src_reg) 12949 { 12950 s32 smin_val = src_reg->s32_min_value; 12951 s32 smax_val = src_reg->s32_max_value; 12952 u32 umin_val = src_reg->u32_min_value; 12953 u32 umax_val = src_reg->u32_max_value; 12954 12955 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 12956 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 12957 /* Overflow possible, we know nothing */ 12958 dst_reg->s32_min_value = S32_MIN; 12959 dst_reg->s32_max_value = S32_MAX; 12960 } else { 12961 dst_reg->s32_min_value -= smax_val; 12962 dst_reg->s32_max_value -= smin_val; 12963 } 12964 if (dst_reg->u32_min_value < umax_val) { 12965 /* Overflow possible, we know nothing */ 12966 dst_reg->u32_min_value = 0; 12967 dst_reg->u32_max_value = U32_MAX; 12968 } else { 12969 /* Cannot overflow (as long as bounds are consistent) */ 12970 dst_reg->u32_min_value -= umax_val; 12971 dst_reg->u32_max_value -= umin_val; 12972 } 12973 } 12974 12975 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 12976 struct bpf_reg_state *src_reg) 12977 { 12978 s64 smin_val = src_reg->smin_value; 12979 s64 smax_val = src_reg->smax_value; 12980 u64 umin_val = src_reg->umin_value; 12981 u64 umax_val = src_reg->umax_value; 12982 12983 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 12984 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 12985 /* Overflow possible, we know nothing */ 12986 dst_reg->smin_value = S64_MIN; 12987 dst_reg->smax_value = S64_MAX; 12988 } else { 12989 dst_reg->smin_value -= smax_val; 12990 dst_reg->smax_value -= smin_val; 12991 } 12992 if (dst_reg->umin_value < umax_val) { 12993 /* Overflow possible, we know nothing */ 12994 dst_reg->umin_value = 0; 12995 dst_reg->umax_value = U64_MAX; 12996 } else { 12997 /* Cannot overflow (as long as bounds are consistent) */ 12998 dst_reg->umin_value -= umax_val; 12999 dst_reg->umax_value -= umin_val; 13000 } 13001 } 13002 13003 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 13004 struct bpf_reg_state *src_reg) 13005 { 13006 s32 smin_val = src_reg->s32_min_value; 13007 u32 umin_val = src_reg->u32_min_value; 13008 u32 umax_val = src_reg->u32_max_value; 13009 13010 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 13011 /* Ain't nobody got time to multiply that sign */ 13012 __mark_reg32_unbounded(dst_reg); 13013 return; 13014 } 13015 /* Both values are positive, so we can work with unsigned and 13016 * copy the result to signed (unless it exceeds S32_MAX). 13017 */ 13018 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 13019 /* Potential overflow, we know nothing */ 13020 __mark_reg32_unbounded(dst_reg); 13021 return; 13022 } 13023 dst_reg->u32_min_value *= umin_val; 13024 dst_reg->u32_max_value *= umax_val; 13025 if (dst_reg->u32_max_value > S32_MAX) { 13026 /* Overflow possible, we know nothing */ 13027 dst_reg->s32_min_value = S32_MIN; 13028 dst_reg->s32_max_value = S32_MAX; 13029 } else { 13030 dst_reg->s32_min_value = dst_reg->u32_min_value; 13031 dst_reg->s32_max_value = dst_reg->u32_max_value; 13032 } 13033 } 13034 13035 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 13036 struct bpf_reg_state *src_reg) 13037 { 13038 s64 smin_val = src_reg->smin_value; 13039 u64 umin_val = src_reg->umin_value; 13040 u64 umax_val = src_reg->umax_value; 13041 13042 if (smin_val < 0 || dst_reg->smin_value < 0) { 13043 /* Ain't nobody got time to multiply that sign */ 13044 __mark_reg64_unbounded(dst_reg); 13045 return; 13046 } 13047 /* Both values are positive, so we can work with unsigned and 13048 * copy the result to signed (unless it exceeds S64_MAX). 13049 */ 13050 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 13051 /* Potential overflow, we know nothing */ 13052 __mark_reg64_unbounded(dst_reg); 13053 return; 13054 } 13055 dst_reg->umin_value *= umin_val; 13056 dst_reg->umax_value *= umax_val; 13057 if (dst_reg->umax_value > S64_MAX) { 13058 /* Overflow possible, we know nothing */ 13059 dst_reg->smin_value = S64_MIN; 13060 dst_reg->smax_value = S64_MAX; 13061 } else { 13062 dst_reg->smin_value = dst_reg->umin_value; 13063 dst_reg->smax_value = dst_reg->umax_value; 13064 } 13065 } 13066 13067 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 13068 struct bpf_reg_state *src_reg) 13069 { 13070 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13071 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13072 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13073 s32 smin_val = src_reg->s32_min_value; 13074 u32 umax_val = src_reg->u32_max_value; 13075 13076 if (src_known && dst_known) { 13077 __mark_reg32_known(dst_reg, var32_off.value); 13078 return; 13079 } 13080 13081 /* We get our minimum from the var_off, since that's inherently 13082 * bitwise. Our maximum is the minimum of the operands' maxima. 13083 */ 13084 dst_reg->u32_min_value = var32_off.value; 13085 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 13086 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 13087 /* Lose signed bounds when ANDing negative numbers, 13088 * ain't nobody got time for that. 13089 */ 13090 dst_reg->s32_min_value = S32_MIN; 13091 dst_reg->s32_max_value = S32_MAX; 13092 } else { 13093 /* ANDing two positives gives a positive, so safe to 13094 * cast result into s64. 13095 */ 13096 dst_reg->s32_min_value = dst_reg->u32_min_value; 13097 dst_reg->s32_max_value = dst_reg->u32_max_value; 13098 } 13099 } 13100 13101 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 13102 struct bpf_reg_state *src_reg) 13103 { 13104 bool src_known = tnum_is_const(src_reg->var_off); 13105 bool dst_known = tnum_is_const(dst_reg->var_off); 13106 s64 smin_val = src_reg->smin_value; 13107 u64 umax_val = src_reg->umax_value; 13108 13109 if (src_known && dst_known) { 13110 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13111 return; 13112 } 13113 13114 /* We get our minimum from the var_off, since that's inherently 13115 * bitwise. Our maximum is the minimum of the operands' maxima. 13116 */ 13117 dst_reg->umin_value = dst_reg->var_off.value; 13118 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 13119 if (dst_reg->smin_value < 0 || smin_val < 0) { 13120 /* Lose signed bounds when ANDing negative numbers, 13121 * ain't nobody got time for that. 13122 */ 13123 dst_reg->smin_value = S64_MIN; 13124 dst_reg->smax_value = S64_MAX; 13125 } else { 13126 /* ANDing two positives gives a positive, so safe to 13127 * cast result into s64. 13128 */ 13129 dst_reg->smin_value = dst_reg->umin_value; 13130 dst_reg->smax_value = dst_reg->umax_value; 13131 } 13132 /* We may learn something more from the var_off */ 13133 __update_reg_bounds(dst_reg); 13134 } 13135 13136 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 13137 struct bpf_reg_state *src_reg) 13138 { 13139 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13140 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13141 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13142 s32 smin_val = src_reg->s32_min_value; 13143 u32 umin_val = src_reg->u32_min_value; 13144 13145 if (src_known && dst_known) { 13146 __mark_reg32_known(dst_reg, var32_off.value); 13147 return; 13148 } 13149 13150 /* We get our maximum from the var_off, and our minimum is the 13151 * maximum of the operands' minima 13152 */ 13153 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 13154 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13155 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 13156 /* Lose signed bounds when ORing negative numbers, 13157 * ain't nobody got time for that. 13158 */ 13159 dst_reg->s32_min_value = S32_MIN; 13160 dst_reg->s32_max_value = S32_MAX; 13161 } else { 13162 /* ORing two positives gives a positive, so safe to 13163 * cast result into s64. 13164 */ 13165 dst_reg->s32_min_value = dst_reg->u32_min_value; 13166 dst_reg->s32_max_value = dst_reg->u32_max_value; 13167 } 13168 } 13169 13170 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 13171 struct bpf_reg_state *src_reg) 13172 { 13173 bool src_known = tnum_is_const(src_reg->var_off); 13174 bool dst_known = tnum_is_const(dst_reg->var_off); 13175 s64 smin_val = src_reg->smin_value; 13176 u64 umin_val = src_reg->umin_value; 13177 13178 if (src_known && dst_known) { 13179 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13180 return; 13181 } 13182 13183 /* We get our maximum from the var_off, and our minimum is the 13184 * maximum of the operands' minima 13185 */ 13186 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 13187 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13188 if (dst_reg->smin_value < 0 || smin_val < 0) { 13189 /* Lose signed bounds when ORing negative numbers, 13190 * ain't nobody got time for that. 13191 */ 13192 dst_reg->smin_value = S64_MIN; 13193 dst_reg->smax_value = S64_MAX; 13194 } else { 13195 /* ORing two positives gives a positive, so safe to 13196 * cast result into s64. 13197 */ 13198 dst_reg->smin_value = dst_reg->umin_value; 13199 dst_reg->smax_value = dst_reg->umax_value; 13200 } 13201 /* We may learn something more from the var_off */ 13202 __update_reg_bounds(dst_reg); 13203 } 13204 13205 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 13206 struct bpf_reg_state *src_reg) 13207 { 13208 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13209 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13210 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13211 s32 smin_val = src_reg->s32_min_value; 13212 13213 if (src_known && dst_known) { 13214 __mark_reg32_known(dst_reg, var32_off.value); 13215 return; 13216 } 13217 13218 /* We get both minimum and maximum from the var32_off. */ 13219 dst_reg->u32_min_value = var32_off.value; 13220 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13221 13222 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 13223 /* XORing two positive sign numbers gives a positive, 13224 * so safe to cast u32 result into s32. 13225 */ 13226 dst_reg->s32_min_value = dst_reg->u32_min_value; 13227 dst_reg->s32_max_value = dst_reg->u32_max_value; 13228 } else { 13229 dst_reg->s32_min_value = S32_MIN; 13230 dst_reg->s32_max_value = S32_MAX; 13231 } 13232 } 13233 13234 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 13235 struct bpf_reg_state *src_reg) 13236 { 13237 bool src_known = tnum_is_const(src_reg->var_off); 13238 bool dst_known = tnum_is_const(dst_reg->var_off); 13239 s64 smin_val = src_reg->smin_value; 13240 13241 if (src_known && dst_known) { 13242 /* dst_reg->var_off.value has been updated earlier */ 13243 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13244 return; 13245 } 13246 13247 /* We get both minimum and maximum from the var_off. */ 13248 dst_reg->umin_value = dst_reg->var_off.value; 13249 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13250 13251 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 13252 /* XORing two positive sign numbers gives a positive, 13253 * so safe to cast u64 result into s64. 13254 */ 13255 dst_reg->smin_value = dst_reg->umin_value; 13256 dst_reg->smax_value = dst_reg->umax_value; 13257 } else { 13258 dst_reg->smin_value = S64_MIN; 13259 dst_reg->smax_value = S64_MAX; 13260 } 13261 13262 __update_reg_bounds(dst_reg); 13263 } 13264 13265 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13266 u64 umin_val, u64 umax_val) 13267 { 13268 /* We lose all sign bit information (except what we can pick 13269 * up from var_off) 13270 */ 13271 dst_reg->s32_min_value = S32_MIN; 13272 dst_reg->s32_max_value = S32_MAX; 13273 /* If we might shift our top bit out, then we know nothing */ 13274 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 13275 dst_reg->u32_min_value = 0; 13276 dst_reg->u32_max_value = U32_MAX; 13277 } else { 13278 dst_reg->u32_min_value <<= umin_val; 13279 dst_reg->u32_max_value <<= umax_val; 13280 } 13281 } 13282 13283 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13284 struct bpf_reg_state *src_reg) 13285 { 13286 u32 umax_val = src_reg->u32_max_value; 13287 u32 umin_val = src_reg->u32_min_value; 13288 /* u32 alu operation will zext upper bits */ 13289 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13290 13291 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13292 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 13293 /* Not required but being careful mark reg64 bounds as unknown so 13294 * that we are forced to pick them up from tnum and zext later and 13295 * if some path skips this step we are still safe. 13296 */ 13297 __mark_reg64_unbounded(dst_reg); 13298 __update_reg32_bounds(dst_reg); 13299 } 13300 13301 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 13302 u64 umin_val, u64 umax_val) 13303 { 13304 /* Special case <<32 because it is a common compiler pattern to sign 13305 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 13306 * positive we know this shift will also be positive so we can track 13307 * bounds correctly. Otherwise we lose all sign bit information except 13308 * what we can pick up from var_off. Perhaps we can generalize this 13309 * later to shifts of any length. 13310 */ 13311 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 13312 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 13313 else 13314 dst_reg->smax_value = S64_MAX; 13315 13316 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 13317 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 13318 else 13319 dst_reg->smin_value = S64_MIN; 13320 13321 /* If we might shift our top bit out, then we know nothing */ 13322 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 13323 dst_reg->umin_value = 0; 13324 dst_reg->umax_value = U64_MAX; 13325 } else { 13326 dst_reg->umin_value <<= umin_val; 13327 dst_reg->umax_value <<= umax_val; 13328 } 13329 } 13330 13331 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 13332 struct bpf_reg_state *src_reg) 13333 { 13334 u64 umax_val = src_reg->umax_value; 13335 u64 umin_val = src_reg->umin_value; 13336 13337 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 13338 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 13339 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13340 13341 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 13342 /* We may learn something more from the var_off */ 13343 __update_reg_bounds(dst_reg); 13344 } 13345 13346 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 13347 struct bpf_reg_state *src_reg) 13348 { 13349 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13350 u32 umax_val = src_reg->u32_max_value; 13351 u32 umin_val = src_reg->u32_min_value; 13352 13353 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13354 * be negative, then either: 13355 * 1) src_reg might be zero, so the sign bit of the result is 13356 * unknown, so we lose our signed bounds 13357 * 2) it's known negative, thus the unsigned bounds capture the 13358 * signed bounds 13359 * 3) the signed bounds cross zero, so they tell us nothing 13360 * about the result 13361 * If the value in dst_reg is known nonnegative, then again the 13362 * unsigned bounds capture the signed bounds. 13363 * Thus, in all cases it suffices to blow away our signed bounds 13364 * and rely on inferring new ones from the unsigned bounds and 13365 * var_off of the result. 13366 */ 13367 dst_reg->s32_min_value = S32_MIN; 13368 dst_reg->s32_max_value = S32_MAX; 13369 13370 dst_reg->var_off = tnum_rshift(subreg, umin_val); 13371 dst_reg->u32_min_value >>= umax_val; 13372 dst_reg->u32_max_value >>= umin_val; 13373 13374 __mark_reg64_unbounded(dst_reg); 13375 __update_reg32_bounds(dst_reg); 13376 } 13377 13378 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 13379 struct bpf_reg_state *src_reg) 13380 { 13381 u64 umax_val = src_reg->umax_value; 13382 u64 umin_val = src_reg->umin_value; 13383 13384 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13385 * be negative, then either: 13386 * 1) src_reg might be zero, so the sign bit of the result is 13387 * unknown, so we lose our signed bounds 13388 * 2) it's known negative, thus the unsigned bounds capture the 13389 * signed bounds 13390 * 3) the signed bounds cross zero, so they tell us nothing 13391 * about the result 13392 * If the value in dst_reg is known nonnegative, then again the 13393 * unsigned bounds capture the signed bounds. 13394 * Thus, in all cases it suffices to blow away our signed bounds 13395 * and rely on inferring new ones from the unsigned bounds and 13396 * var_off of the result. 13397 */ 13398 dst_reg->smin_value = S64_MIN; 13399 dst_reg->smax_value = S64_MAX; 13400 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 13401 dst_reg->umin_value >>= umax_val; 13402 dst_reg->umax_value >>= umin_val; 13403 13404 /* Its not easy to operate on alu32 bounds here because it depends 13405 * on bits being shifted in. Take easy way out and mark unbounded 13406 * so we can recalculate later from tnum. 13407 */ 13408 __mark_reg32_unbounded(dst_reg); 13409 __update_reg_bounds(dst_reg); 13410 } 13411 13412 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 13413 struct bpf_reg_state *src_reg) 13414 { 13415 u64 umin_val = src_reg->u32_min_value; 13416 13417 /* Upon reaching here, src_known is true and 13418 * umax_val is equal to umin_val. 13419 */ 13420 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 13421 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 13422 13423 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 13424 13425 /* blow away the dst_reg umin_value/umax_value and rely on 13426 * dst_reg var_off to refine the result. 13427 */ 13428 dst_reg->u32_min_value = 0; 13429 dst_reg->u32_max_value = U32_MAX; 13430 13431 __mark_reg64_unbounded(dst_reg); 13432 __update_reg32_bounds(dst_reg); 13433 } 13434 13435 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 13436 struct bpf_reg_state *src_reg) 13437 { 13438 u64 umin_val = src_reg->umin_value; 13439 13440 /* Upon reaching here, src_known is true and umax_val is equal 13441 * to umin_val. 13442 */ 13443 dst_reg->smin_value >>= umin_val; 13444 dst_reg->smax_value >>= umin_val; 13445 13446 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 13447 13448 /* blow away the dst_reg umin_value/umax_value and rely on 13449 * dst_reg var_off to refine the result. 13450 */ 13451 dst_reg->umin_value = 0; 13452 dst_reg->umax_value = U64_MAX; 13453 13454 /* Its not easy to operate on alu32 bounds here because it depends 13455 * on bits being shifted in from upper 32-bits. Take easy way out 13456 * and mark unbounded so we can recalculate later from tnum. 13457 */ 13458 __mark_reg32_unbounded(dst_reg); 13459 __update_reg_bounds(dst_reg); 13460 } 13461 13462 /* WARNING: This function does calculations on 64-bit values, but the actual 13463 * execution may occur on 32-bit values. Therefore, things like bitshifts 13464 * need extra checks in the 32-bit case. 13465 */ 13466 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 13467 struct bpf_insn *insn, 13468 struct bpf_reg_state *dst_reg, 13469 struct bpf_reg_state src_reg) 13470 { 13471 struct bpf_reg_state *regs = cur_regs(env); 13472 u8 opcode = BPF_OP(insn->code); 13473 bool src_known; 13474 s64 smin_val, smax_val; 13475 u64 umin_val, umax_val; 13476 s32 s32_min_val, s32_max_val; 13477 u32 u32_min_val, u32_max_val; 13478 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 13479 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 13480 int ret; 13481 13482 smin_val = src_reg.smin_value; 13483 smax_val = src_reg.smax_value; 13484 umin_val = src_reg.umin_value; 13485 umax_val = src_reg.umax_value; 13486 13487 s32_min_val = src_reg.s32_min_value; 13488 s32_max_val = src_reg.s32_max_value; 13489 u32_min_val = src_reg.u32_min_value; 13490 u32_max_val = src_reg.u32_max_value; 13491 13492 if (alu32) { 13493 src_known = tnum_subreg_is_const(src_reg.var_off); 13494 if ((src_known && 13495 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 13496 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 13497 /* Taint dst register if offset had invalid bounds 13498 * derived from e.g. dead branches. 13499 */ 13500 __mark_reg_unknown(env, dst_reg); 13501 return 0; 13502 } 13503 } else { 13504 src_known = tnum_is_const(src_reg.var_off); 13505 if ((src_known && 13506 (smin_val != smax_val || umin_val != umax_val)) || 13507 smin_val > smax_val || umin_val > umax_val) { 13508 /* Taint dst register if offset had invalid bounds 13509 * derived from e.g. dead branches. 13510 */ 13511 __mark_reg_unknown(env, dst_reg); 13512 return 0; 13513 } 13514 } 13515 13516 if (!src_known && 13517 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 13518 __mark_reg_unknown(env, dst_reg); 13519 return 0; 13520 } 13521 13522 if (sanitize_needed(opcode)) { 13523 ret = sanitize_val_alu(env, insn); 13524 if (ret < 0) 13525 return sanitize_err(env, insn, ret, NULL, NULL); 13526 } 13527 13528 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 13529 * There are two classes of instructions: The first class we track both 13530 * alu32 and alu64 sign/unsigned bounds independently this provides the 13531 * greatest amount of precision when alu operations are mixed with jmp32 13532 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 13533 * and BPF_OR. This is possible because these ops have fairly easy to 13534 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 13535 * See alu32 verifier tests for examples. The second class of 13536 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 13537 * with regards to tracking sign/unsigned bounds because the bits may 13538 * cross subreg boundaries in the alu64 case. When this happens we mark 13539 * the reg unbounded in the subreg bound space and use the resulting 13540 * tnum to calculate an approximation of the sign/unsigned bounds. 13541 */ 13542 switch (opcode) { 13543 case BPF_ADD: 13544 scalar32_min_max_add(dst_reg, &src_reg); 13545 scalar_min_max_add(dst_reg, &src_reg); 13546 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 13547 break; 13548 case BPF_SUB: 13549 scalar32_min_max_sub(dst_reg, &src_reg); 13550 scalar_min_max_sub(dst_reg, &src_reg); 13551 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 13552 break; 13553 case BPF_MUL: 13554 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 13555 scalar32_min_max_mul(dst_reg, &src_reg); 13556 scalar_min_max_mul(dst_reg, &src_reg); 13557 break; 13558 case BPF_AND: 13559 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 13560 scalar32_min_max_and(dst_reg, &src_reg); 13561 scalar_min_max_and(dst_reg, &src_reg); 13562 break; 13563 case BPF_OR: 13564 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 13565 scalar32_min_max_or(dst_reg, &src_reg); 13566 scalar_min_max_or(dst_reg, &src_reg); 13567 break; 13568 case BPF_XOR: 13569 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 13570 scalar32_min_max_xor(dst_reg, &src_reg); 13571 scalar_min_max_xor(dst_reg, &src_reg); 13572 break; 13573 case BPF_LSH: 13574 if (umax_val >= insn_bitness) { 13575 /* Shifts greater than 31 or 63 are undefined. 13576 * This includes shifts by a negative number. 13577 */ 13578 mark_reg_unknown(env, regs, insn->dst_reg); 13579 break; 13580 } 13581 if (alu32) 13582 scalar32_min_max_lsh(dst_reg, &src_reg); 13583 else 13584 scalar_min_max_lsh(dst_reg, &src_reg); 13585 break; 13586 case BPF_RSH: 13587 if (umax_val >= insn_bitness) { 13588 /* Shifts greater than 31 or 63 are undefined. 13589 * This includes shifts by a negative number. 13590 */ 13591 mark_reg_unknown(env, regs, insn->dst_reg); 13592 break; 13593 } 13594 if (alu32) 13595 scalar32_min_max_rsh(dst_reg, &src_reg); 13596 else 13597 scalar_min_max_rsh(dst_reg, &src_reg); 13598 break; 13599 case BPF_ARSH: 13600 if (umax_val >= insn_bitness) { 13601 /* Shifts greater than 31 or 63 are undefined. 13602 * This includes shifts by a negative number. 13603 */ 13604 mark_reg_unknown(env, regs, insn->dst_reg); 13605 break; 13606 } 13607 if (alu32) 13608 scalar32_min_max_arsh(dst_reg, &src_reg); 13609 else 13610 scalar_min_max_arsh(dst_reg, &src_reg); 13611 break; 13612 default: 13613 mark_reg_unknown(env, regs, insn->dst_reg); 13614 break; 13615 } 13616 13617 /* ALU32 ops are zero extended into 64bit register */ 13618 if (alu32) 13619 zext_32_to_64(dst_reg); 13620 reg_bounds_sync(dst_reg); 13621 return 0; 13622 } 13623 13624 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 13625 * and var_off. 13626 */ 13627 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 13628 struct bpf_insn *insn) 13629 { 13630 struct bpf_verifier_state *vstate = env->cur_state; 13631 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13632 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 13633 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 13634 u8 opcode = BPF_OP(insn->code); 13635 int err; 13636 13637 dst_reg = ®s[insn->dst_reg]; 13638 src_reg = NULL; 13639 if (dst_reg->type != SCALAR_VALUE) 13640 ptr_reg = dst_reg; 13641 else 13642 /* Make sure ID is cleared otherwise dst_reg min/max could be 13643 * incorrectly propagated into other registers by find_equal_scalars() 13644 */ 13645 dst_reg->id = 0; 13646 if (BPF_SRC(insn->code) == BPF_X) { 13647 src_reg = ®s[insn->src_reg]; 13648 if (src_reg->type != SCALAR_VALUE) { 13649 if (dst_reg->type != SCALAR_VALUE) { 13650 /* Combining two pointers by any ALU op yields 13651 * an arbitrary scalar. Disallow all math except 13652 * pointer subtraction 13653 */ 13654 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13655 mark_reg_unknown(env, regs, insn->dst_reg); 13656 return 0; 13657 } 13658 verbose(env, "R%d pointer %s pointer prohibited\n", 13659 insn->dst_reg, 13660 bpf_alu_string[opcode >> 4]); 13661 return -EACCES; 13662 } else { 13663 /* scalar += pointer 13664 * This is legal, but we have to reverse our 13665 * src/dest handling in computing the range 13666 */ 13667 err = mark_chain_precision(env, insn->dst_reg); 13668 if (err) 13669 return err; 13670 return adjust_ptr_min_max_vals(env, insn, 13671 src_reg, dst_reg); 13672 } 13673 } else if (ptr_reg) { 13674 /* pointer += scalar */ 13675 err = mark_chain_precision(env, insn->src_reg); 13676 if (err) 13677 return err; 13678 return adjust_ptr_min_max_vals(env, insn, 13679 dst_reg, src_reg); 13680 } else if (dst_reg->precise) { 13681 /* if dst_reg is precise, src_reg should be precise as well */ 13682 err = mark_chain_precision(env, insn->src_reg); 13683 if (err) 13684 return err; 13685 } 13686 } else { 13687 /* Pretend the src is a reg with a known value, since we only 13688 * need to be able to read from this state. 13689 */ 13690 off_reg.type = SCALAR_VALUE; 13691 __mark_reg_known(&off_reg, insn->imm); 13692 src_reg = &off_reg; 13693 if (ptr_reg) /* pointer += K */ 13694 return adjust_ptr_min_max_vals(env, insn, 13695 ptr_reg, src_reg); 13696 } 13697 13698 /* Got here implies adding two SCALAR_VALUEs */ 13699 if (WARN_ON_ONCE(ptr_reg)) { 13700 print_verifier_state(env, state, true); 13701 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 13702 return -EINVAL; 13703 } 13704 if (WARN_ON(!src_reg)) { 13705 print_verifier_state(env, state, true); 13706 verbose(env, "verifier internal error: no src_reg\n"); 13707 return -EINVAL; 13708 } 13709 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 13710 } 13711 13712 /* check validity of 32-bit and 64-bit arithmetic operations */ 13713 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 13714 { 13715 struct bpf_reg_state *regs = cur_regs(env); 13716 u8 opcode = BPF_OP(insn->code); 13717 int err; 13718 13719 if (opcode == BPF_END || opcode == BPF_NEG) { 13720 if (opcode == BPF_NEG) { 13721 if (BPF_SRC(insn->code) != BPF_K || 13722 insn->src_reg != BPF_REG_0 || 13723 insn->off != 0 || insn->imm != 0) { 13724 verbose(env, "BPF_NEG uses reserved fields\n"); 13725 return -EINVAL; 13726 } 13727 } else { 13728 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 13729 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 13730 (BPF_CLASS(insn->code) == BPF_ALU64 && 13731 BPF_SRC(insn->code) != BPF_TO_LE)) { 13732 verbose(env, "BPF_END uses reserved fields\n"); 13733 return -EINVAL; 13734 } 13735 } 13736 13737 /* check src operand */ 13738 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13739 if (err) 13740 return err; 13741 13742 if (is_pointer_value(env, insn->dst_reg)) { 13743 verbose(env, "R%d pointer arithmetic prohibited\n", 13744 insn->dst_reg); 13745 return -EACCES; 13746 } 13747 13748 /* check dest operand */ 13749 err = check_reg_arg(env, insn->dst_reg, DST_OP); 13750 if (err) 13751 return err; 13752 13753 } else if (opcode == BPF_MOV) { 13754 13755 if (BPF_SRC(insn->code) == BPF_X) { 13756 if (insn->imm != 0) { 13757 verbose(env, "BPF_MOV uses reserved fields\n"); 13758 return -EINVAL; 13759 } 13760 13761 if (BPF_CLASS(insn->code) == BPF_ALU) { 13762 if (insn->off != 0 && insn->off != 8 && insn->off != 16) { 13763 verbose(env, "BPF_MOV uses reserved fields\n"); 13764 return -EINVAL; 13765 } 13766 } else { 13767 if (insn->off != 0 && insn->off != 8 && insn->off != 16 && 13768 insn->off != 32) { 13769 verbose(env, "BPF_MOV uses reserved fields\n"); 13770 return -EINVAL; 13771 } 13772 } 13773 13774 /* check src operand */ 13775 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13776 if (err) 13777 return err; 13778 } else { 13779 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 13780 verbose(env, "BPF_MOV uses reserved fields\n"); 13781 return -EINVAL; 13782 } 13783 } 13784 13785 /* check dest operand, mark as required later */ 13786 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13787 if (err) 13788 return err; 13789 13790 if (BPF_SRC(insn->code) == BPF_X) { 13791 struct bpf_reg_state *src_reg = regs + insn->src_reg; 13792 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 13793 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id && 13794 !tnum_is_const(src_reg->var_off); 13795 13796 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13797 if (insn->off == 0) { 13798 /* case: R1 = R2 13799 * copy register state to dest reg 13800 */ 13801 if (need_id) 13802 /* Assign src and dst registers the same ID 13803 * that will be used by find_equal_scalars() 13804 * to propagate min/max range. 13805 */ 13806 src_reg->id = ++env->id_gen; 13807 copy_register_state(dst_reg, src_reg); 13808 dst_reg->live |= REG_LIVE_WRITTEN; 13809 dst_reg->subreg_def = DEF_NOT_SUBREG; 13810 } else { 13811 /* case: R1 = (s8, s16 s32)R2 */ 13812 if (is_pointer_value(env, insn->src_reg)) { 13813 verbose(env, 13814 "R%d sign-extension part of pointer\n", 13815 insn->src_reg); 13816 return -EACCES; 13817 } else if (src_reg->type == SCALAR_VALUE) { 13818 bool no_sext; 13819 13820 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13821 if (no_sext && need_id) 13822 src_reg->id = ++env->id_gen; 13823 copy_register_state(dst_reg, src_reg); 13824 if (!no_sext) 13825 dst_reg->id = 0; 13826 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 13827 dst_reg->live |= REG_LIVE_WRITTEN; 13828 dst_reg->subreg_def = DEF_NOT_SUBREG; 13829 } else { 13830 mark_reg_unknown(env, regs, insn->dst_reg); 13831 } 13832 } 13833 } else { 13834 /* R1 = (u32) R2 */ 13835 if (is_pointer_value(env, insn->src_reg)) { 13836 verbose(env, 13837 "R%d partial copy of pointer\n", 13838 insn->src_reg); 13839 return -EACCES; 13840 } else if (src_reg->type == SCALAR_VALUE) { 13841 if (insn->off == 0) { 13842 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX; 13843 13844 if (is_src_reg_u32 && need_id) 13845 src_reg->id = ++env->id_gen; 13846 copy_register_state(dst_reg, src_reg); 13847 /* Make sure ID is cleared if src_reg is not in u32 13848 * range otherwise dst_reg min/max could be incorrectly 13849 * propagated into src_reg by find_equal_scalars() 13850 */ 13851 if (!is_src_reg_u32) 13852 dst_reg->id = 0; 13853 dst_reg->live |= REG_LIVE_WRITTEN; 13854 dst_reg->subreg_def = env->insn_idx + 1; 13855 } else { 13856 /* case: W1 = (s8, s16)W2 */ 13857 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 13858 13859 if (no_sext && need_id) 13860 src_reg->id = ++env->id_gen; 13861 copy_register_state(dst_reg, src_reg); 13862 if (!no_sext) 13863 dst_reg->id = 0; 13864 dst_reg->live |= REG_LIVE_WRITTEN; 13865 dst_reg->subreg_def = env->insn_idx + 1; 13866 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 13867 } 13868 } else { 13869 mark_reg_unknown(env, regs, 13870 insn->dst_reg); 13871 } 13872 zext_32_to_64(dst_reg); 13873 reg_bounds_sync(dst_reg); 13874 } 13875 } else { 13876 /* case: R = imm 13877 * remember the value we stored into this reg 13878 */ 13879 /* clear any state __mark_reg_known doesn't set */ 13880 mark_reg_unknown(env, regs, insn->dst_reg); 13881 regs[insn->dst_reg].type = SCALAR_VALUE; 13882 if (BPF_CLASS(insn->code) == BPF_ALU64) { 13883 __mark_reg_known(regs + insn->dst_reg, 13884 insn->imm); 13885 } else { 13886 __mark_reg_known(regs + insn->dst_reg, 13887 (u32)insn->imm); 13888 } 13889 } 13890 13891 } else if (opcode > BPF_END) { 13892 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 13893 return -EINVAL; 13894 13895 } else { /* all other ALU ops: and, sub, xor, add, ... */ 13896 13897 if (BPF_SRC(insn->code) == BPF_X) { 13898 if (insn->imm != 0 || insn->off > 1 || 13899 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 13900 verbose(env, "BPF_ALU uses reserved fields\n"); 13901 return -EINVAL; 13902 } 13903 /* check src1 operand */ 13904 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13905 if (err) 13906 return err; 13907 } else { 13908 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 13909 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 13910 verbose(env, "BPF_ALU uses reserved fields\n"); 13911 return -EINVAL; 13912 } 13913 } 13914 13915 /* check src2 operand */ 13916 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13917 if (err) 13918 return err; 13919 13920 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 13921 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 13922 verbose(env, "div by zero\n"); 13923 return -EINVAL; 13924 } 13925 13926 if ((opcode == BPF_LSH || opcode == BPF_RSH || 13927 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 13928 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 13929 13930 if (insn->imm < 0 || insn->imm >= size) { 13931 verbose(env, "invalid shift %d\n", insn->imm); 13932 return -EINVAL; 13933 } 13934 } 13935 13936 /* check dest operand */ 13937 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13938 err = err ?: adjust_reg_min_max_vals(env, insn); 13939 if (err) 13940 return err; 13941 } 13942 13943 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 13944 } 13945 13946 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 13947 struct bpf_reg_state *dst_reg, 13948 enum bpf_reg_type type, 13949 bool range_right_open) 13950 { 13951 struct bpf_func_state *state; 13952 struct bpf_reg_state *reg; 13953 int new_range; 13954 13955 if (dst_reg->off < 0 || 13956 (dst_reg->off == 0 && range_right_open)) 13957 /* This doesn't give us any range */ 13958 return; 13959 13960 if (dst_reg->umax_value > MAX_PACKET_OFF || 13961 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 13962 /* Risk of overflow. For instance, ptr + (1<<63) may be less 13963 * than pkt_end, but that's because it's also less than pkt. 13964 */ 13965 return; 13966 13967 new_range = dst_reg->off; 13968 if (range_right_open) 13969 new_range++; 13970 13971 /* Examples for register markings: 13972 * 13973 * pkt_data in dst register: 13974 * 13975 * r2 = r3; 13976 * r2 += 8; 13977 * if (r2 > pkt_end) goto <handle exception> 13978 * <access okay> 13979 * 13980 * r2 = r3; 13981 * r2 += 8; 13982 * if (r2 < pkt_end) goto <access okay> 13983 * <handle exception> 13984 * 13985 * Where: 13986 * r2 == dst_reg, pkt_end == src_reg 13987 * r2=pkt(id=n,off=8,r=0) 13988 * r3=pkt(id=n,off=0,r=0) 13989 * 13990 * pkt_data in src register: 13991 * 13992 * r2 = r3; 13993 * r2 += 8; 13994 * if (pkt_end >= r2) goto <access okay> 13995 * <handle exception> 13996 * 13997 * r2 = r3; 13998 * r2 += 8; 13999 * if (pkt_end <= r2) goto <handle exception> 14000 * <access okay> 14001 * 14002 * Where: 14003 * pkt_end == dst_reg, r2 == src_reg 14004 * r2=pkt(id=n,off=8,r=0) 14005 * r3=pkt(id=n,off=0,r=0) 14006 * 14007 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 14008 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 14009 * and [r3, r3 + 8-1) respectively is safe to access depending on 14010 * the check. 14011 */ 14012 14013 /* If our ids match, then we must have the same max_value. And we 14014 * don't care about the other reg's fixed offset, since if it's too big 14015 * the range won't allow anything. 14016 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 14017 */ 14018 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14019 if (reg->type == type && reg->id == dst_reg->id) 14020 /* keep the maximum range already checked */ 14021 reg->range = max(reg->range, new_range); 14022 })); 14023 } 14024 14025 /* 14026 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 14027 */ 14028 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14029 u8 opcode, bool is_jmp32) 14030 { 14031 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 14032 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 14033 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value; 14034 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value; 14035 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value; 14036 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value; 14037 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value; 14038 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value; 14039 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value; 14040 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value; 14041 14042 switch (opcode) { 14043 case BPF_JEQ: 14044 /* constants, umin/umax and smin/smax checks would be 14045 * redundant in this case because they all should match 14046 */ 14047 if (tnum_is_const(t1) && tnum_is_const(t2)) 14048 return t1.value == t2.value; 14049 /* non-overlapping ranges */ 14050 if (umin1 > umax2 || umax1 < umin2) 14051 return 0; 14052 if (smin1 > smax2 || smax1 < smin2) 14053 return 0; 14054 if (!is_jmp32) { 14055 /* if 64-bit ranges are inconclusive, see if we can 14056 * utilize 32-bit subrange knowledge to eliminate 14057 * branches that can't be taken a priori 14058 */ 14059 if (reg1->u32_min_value > reg2->u32_max_value || 14060 reg1->u32_max_value < reg2->u32_min_value) 14061 return 0; 14062 if (reg1->s32_min_value > reg2->s32_max_value || 14063 reg1->s32_max_value < reg2->s32_min_value) 14064 return 0; 14065 } 14066 break; 14067 case BPF_JNE: 14068 /* constants, umin/umax and smin/smax checks would be 14069 * redundant in this case because they all should match 14070 */ 14071 if (tnum_is_const(t1) && tnum_is_const(t2)) 14072 return t1.value != t2.value; 14073 /* non-overlapping ranges */ 14074 if (umin1 > umax2 || umax1 < umin2) 14075 return 1; 14076 if (smin1 > smax2 || smax1 < smin2) 14077 return 1; 14078 if (!is_jmp32) { 14079 /* if 64-bit ranges are inconclusive, see if we can 14080 * utilize 32-bit subrange knowledge to eliminate 14081 * branches that can't be taken a priori 14082 */ 14083 if (reg1->u32_min_value > reg2->u32_max_value || 14084 reg1->u32_max_value < reg2->u32_min_value) 14085 return 1; 14086 if (reg1->s32_min_value > reg2->s32_max_value || 14087 reg1->s32_max_value < reg2->s32_min_value) 14088 return 1; 14089 } 14090 break; 14091 case BPF_JSET: 14092 if (!is_reg_const(reg2, is_jmp32)) { 14093 swap(reg1, reg2); 14094 swap(t1, t2); 14095 } 14096 if (!is_reg_const(reg2, is_jmp32)) 14097 return -1; 14098 if ((~t1.mask & t1.value) & t2.value) 14099 return 1; 14100 if (!((t1.mask | t1.value) & t2.value)) 14101 return 0; 14102 break; 14103 case BPF_JGT: 14104 if (umin1 > umax2) 14105 return 1; 14106 else if (umax1 <= umin2) 14107 return 0; 14108 break; 14109 case BPF_JSGT: 14110 if (smin1 > smax2) 14111 return 1; 14112 else if (smax1 <= smin2) 14113 return 0; 14114 break; 14115 case BPF_JLT: 14116 if (umax1 < umin2) 14117 return 1; 14118 else if (umin1 >= umax2) 14119 return 0; 14120 break; 14121 case BPF_JSLT: 14122 if (smax1 < smin2) 14123 return 1; 14124 else if (smin1 >= smax2) 14125 return 0; 14126 break; 14127 case BPF_JGE: 14128 if (umin1 >= umax2) 14129 return 1; 14130 else if (umax1 < umin2) 14131 return 0; 14132 break; 14133 case BPF_JSGE: 14134 if (smin1 >= smax2) 14135 return 1; 14136 else if (smax1 < smin2) 14137 return 0; 14138 break; 14139 case BPF_JLE: 14140 if (umax1 <= umin2) 14141 return 1; 14142 else if (umin1 > umax2) 14143 return 0; 14144 break; 14145 case BPF_JSLE: 14146 if (smax1 <= smin2) 14147 return 1; 14148 else if (smin1 > smax2) 14149 return 0; 14150 break; 14151 } 14152 14153 return -1; 14154 } 14155 14156 static int flip_opcode(u32 opcode) 14157 { 14158 /* How can we transform "a <op> b" into "b <op> a"? */ 14159 static const u8 opcode_flip[16] = { 14160 /* these stay the same */ 14161 [BPF_JEQ >> 4] = BPF_JEQ, 14162 [BPF_JNE >> 4] = BPF_JNE, 14163 [BPF_JSET >> 4] = BPF_JSET, 14164 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 14165 [BPF_JGE >> 4] = BPF_JLE, 14166 [BPF_JGT >> 4] = BPF_JLT, 14167 [BPF_JLE >> 4] = BPF_JGE, 14168 [BPF_JLT >> 4] = BPF_JGT, 14169 [BPF_JSGE >> 4] = BPF_JSLE, 14170 [BPF_JSGT >> 4] = BPF_JSLT, 14171 [BPF_JSLE >> 4] = BPF_JSGE, 14172 [BPF_JSLT >> 4] = BPF_JSGT 14173 }; 14174 return opcode_flip[opcode >> 4]; 14175 } 14176 14177 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 14178 struct bpf_reg_state *src_reg, 14179 u8 opcode) 14180 { 14181 struct bpf_reg_state *pkt; 14182 14183 if (src_reg->type == PTR_TO_PACKET_END) { 14184 pkt = dst_reg; 14185 } else if (dst_reg->type == PTR_TO_PACKET_END) { 14186 pkt = src_reg; 14187 opcode = flip_opcode(opcode); 14188 } else { 14189 return -1; 14190 } 14191 14192 if (pkt->range >= 0) 14193 return -1; 14194 14195 switch (opcode) { 14196 case BPF_JLE: 14197 /* pkt <= pkt_end */ 14198 fallthrough; 14199 case BPF_JGT: 14200 /* pkt > pkt_end */ 14201 if (pkt->range == BEYOND_PKT_END) 14202 /* pkt has at last one extra byte beyond pkt_end */ 14203 return opcode == BPF_JGT; 14204 break; 14205 case BPF_JLT: 14206 /* pkt < pkt_end */ 14207 fallthrough; 14208 case BPF_JGE: 14209 /* pkt >= pkt_end */ 14210 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 14211 return opcode == BPF_JGE; 14212 break; 14213 } 14214 return -1; 14215 } 14216 14217 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 14218 * and return: 14219 * 1 - branch will be taken and "goto target" will be executed 14220 * 0 - branch will not be taken and fall-through to next insn 14221 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 14222 * range [0,10] 14223 */ 14224 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14225 u8 opcode, bool is_jmp32) 14226 { 14227 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 14228 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 14229 14230 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 14231 u64 val; 14232 14233 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 14234 if (!is_reg_const(reg2, is_jmp32)) { 14235 opcode = flip_opcode(opcode); 14236 swap(reg1, reg2); 14237 } 14238 /* and ensure that reg2 is a constant */ 14239 if (!is_reg_const(reg2, is_jmp32)) 14240 return -1; 14241 14242 if (!reg_not_null(reg1)) 14243 return -1; 14244 14245 /* If pointer is valid tests against zero will fail so we can 14246 * use this to direct branch taken. 14247 */ 14248 val = reg_const_value(reg2, is_jmp32); 14249 if (val != 0) 14250 return -1; 14251 14252 switch (opcode) { 14253 case BPF_JEQ: 14254 return 0; 14255 case BPF_JNE: 14256 return 1; 14257 default: 14258 return -1; 14259 } 14260 } 14261 14262 /* now deal with two scalars, but not necessarily constants */ 14263 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32); 14264 } 14265 14266 /* Opcode that corresponds to a *false* branch condition. 14267 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 14268 */ 14269 static u8 rev_opcode(u8 opcode) 14270 { 14271 switch (opcode) { 14272 case BPF_JEQ: return BPF_JNE; 14273 case BPF_JNE: return BPF_JEQ; 14274 /* JSET doesn't have it's reverse opcode in BPF, so add 14275 * BPF_X flag to denote the reverse of that operation 14276 */ 14277 case BPF_JSET: return BPF_JSET | BPF_X; 14278 case BPF_JSET | BPF_X: return BPF_JSET; 14279 case BPF_JGE: return BPF_JLT; 14280 case BPF_JGT: return BPF_JLE; 14281 case BPF_JLE: return BPF_JGT; 14282 case BPF_JLT: return BPF_JGE; 14283 case BPF_JSGE: return BPF_JSLT; 14284 case BPF_JSGT: return BPF_JSLE; 14285 case BPF_JSLE: return BPF_JSGT; 14286 case BPF_JSLT: return BPF_JSGE; 14287 default: return 0; 14288 } 14289 } 14290 14291 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 14292 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14293 u8 opcode, bool is_jmp32) 14294 { 14295 struct tnum t; 14296 u64 val; 14297 14298 again: 14299 switch (opcode) { 14300 case BPF_JEQ: 14301 if (is_jmp32) { 14302 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14303 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14304 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14305 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14306 reg2->u32_min_value = reg1->u32_min_value; 14307 reg2->u32_max_value = reg1->u32_max_value; 14308 reg2->s32_min_value = reg1->s32_min_value; 14309 reg2->s32_max_value = reg1->s32_max_value; 14310 14311 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 14312 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14313 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 14314 } else { 14315 reg1->umin_value = max(reg1->umin_value, reg2->umin_value); 14316 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14317 reg1->smin_value = max(reg1->smin_value, reg2->smin_value); 14318 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14319 reg2->umin_value = reg1->umin_value; 14320 reg2->umax_value = reg1->umax_value; 14321 reg2->smin_value = reg1->smin_value; 14322 reg2->smax_value = reg1->smax_value; 14323 14324 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 14325 reg2->var_off = reg1->var_off; 14326 } 14327 break; 14328 case BPF_JNE: 14329 /* we don't derive any new information for inequality yet */ 14330 break; 14331 case BPF_JSET: 14332 if (!is_reg_const(reg2, is_jmp32)) 14333 swap(reg1, reg2); 14334 if (!is_reg_const(reg2, is_jmp32)) 14335 break; 14336 val = reg_const_value(reg2, is_jmp32); 14337 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 14338 * requires single bit to learn something useful. E.g., if we 14339 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 14340 * are actually set? We can learn something definite only if 14341 * it's a single-bit value to begin with. 14342 * 14343 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 14344 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 14345 * bit 1 is set, which we can readily use in adjustments. 14346 */ 14347 if (!is_power_of_2(val)) 14348 break; 14349 if (is_jmp32) { 14350 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 14351 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14352 } else { 14353 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 14354 } 14355 break; 14356 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 14357 if (!is_reg_const(reg2, is_jmp32)) 14358 swap(reg1, reg2); 14359 if (!is_reg_const(reg2, is_jmp32)) 14360 break; 14361 val = reg_const_value(reg2, is_jmp32); 14362 if (is_jmp32) { 14363 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 14364 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14365 } else { 14366 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 14367 } 14368 break; 14369 case BPF_JLE: 14370 if (is_jmp32) { 14371 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14372 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14373 } else { 14374 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14375 reg2->umin_value = max(reg1->umin_value, reg2->umin_value); 14376 } 14377 break; 14378 case BPF_JLT: 14379 if (is_jmp32) { 14380 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1); 14381 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value); 14382 } else { 14383 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1); 14384 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value); 14385 } 14386 break; 14387 case BPF_JSLE: 14388 if (is_jmp32) { 14389 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14390 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14391 } else { 14392 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14393 reg2->smin_value = max(reg1->smin_value, reg2->smin_value); 14394 } 14395 break; 14396 case BPF_JSLT: 14397 if (is_jmp32) { 14398 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1); 14399 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value); 14400 } else { 14401 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1); 14402 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value); 14403 } 14404 break; 14405 case BPF_JGE: 14406 case BPF_JGT: 14407 case BPF_JSGE: 14408 case BPF_JSGT: 14409 /* just reuse LE/LT logic above */ 14410 opcode = flip_opcode(opcode); 14411 swap(reg1, reg2); 14412 goto again; 14413 default: 14414 return; 14415 } 14416 } 14417 14418 /* Adjusts the register min/max values in the case that the dst_reg and 14419 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K 14420 * check, in which case we havea fake SCALAR_VALUE representing insn->imm). 14421 * Technically we can do similar adjustments for pointers to the same object, 14422 * but we don't support that right now. 14423 */ 14424 static int reg_set_min_max(struct bpf_verifier_env *env, 14425 struct bpf_reg_state *true_reg1, 14426 struct bpf_reg_state *true_reg2, 14427 struct bpf_reg_state *false_reg1, 14428 struct bpf_reg_state *false_reg2, 14429 u8 opcode, bool is_jmp32) 14430 { 14431 int err; 14432 14433 /* If either register is a pointer, we can't learn anything about its 14434 * variable offset from the compare (unless they were a pointer into 14435 * the same object, but we don't bother with that). 14436 */ 14437 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE) 14438 return 0; 14439 14440 /* fallthrough (FALSE) branch */ 14441 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32); 14442 reg_bounds_sync(false_reg1); 14443 reg_bounds_sync(false_reg2); 14444 14445 /* jump (TRUE) branch */ 14446 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32); 14447 reg_bounds_sync(true_reg1); 14448 reg_bounds_sync(true_reg2); 14449 14450 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1"); 14451 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2"); 14452 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1"); 14453 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2"); 14454 return err; 14455 } 14456 14457 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 14458 struct bpf_reg_state *reg, u32 id, 14459 bool is_null) 14460 { 14461 if (type_may_be_null(reg->type) && reg->id == id && 14462 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 14463 /* Old offset (both fixed and variable parts) should have been 14464 * known-zero, because we don't allow pointer arithmetic on 14465 * pointers that might be NULL. If we see this happening, don't 14466 * convert the register. 14467 * 14468 * But in some cases, some helpers that return local kptrs 14469 * advance offset for the returned pointer. In those cases, it 14470 * is fine to expect to see reg->off. 14471 */ 14472 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 14473 return; 14474 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 14475 WARN_ON_ONCE(reg->off)) 14476 return; 14477 14478 if (is_null) { 14479 reg->type = SCALAR_VALUE; 14480 /* We don't need id and ref_obj_id from this point 14481 * onwards anymore, thus we should better reset it, 14482 * so that state pruning has chances to take effect. 14483 */ 14484 reg->id = 0; 14485 reg->ref_obj_id = 0; 14486 14487 return; 14488 } 14489 14490 mark_ptr_not_null_reg(reg); 14491 14492 if (!reg_may_point_to_spin_lock(reg)) { 14493 /* For not-NULL ptr, reg->ref_obj_id will be reset 14494 * in release_reference(). 14495 * 14496 * reg->id is still used by spin_lock ptr. Other 14497 * than spin_lock ptr type, reg->id can be reset. 14498 */ 14499 reg->id = 0; 14500 } 14501 } 14502 } 14503 14504 /* The logic is similar to find_good_pkt_pointers(), both could eventually 14505 * be folded together at some point. 14506 */ 14507 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 14508 bool is_null) 14509 { 14510 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14511 struct bpf_reg_state *regs = state->regs, *reg; 14512 u32 ref_obj_id = regs[regno].ref_obj_id; 14513 u32 id = regs[regno].id; 14514 14515 if (ref_obj_id && ref_obj_id == id && is_null) 14516 /* regs[regno] is in the " == NULL" branch. 14517 * No one could have freed the reference state before 14518 * doing the NULL check. 14519 */ 14520 WARN_ON_ONCE(release_reference_state(state, id)); 14521 14522 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14523 mark_ptr_or_null_reg(state, reg, id, is_null); 14524 })); 14525 } 14526 14527 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 14528 struct bpf_reg_state *dst_reg, 14529 struct bpf_reg_state *src_reg, 14530 struct bpf_verifier_state *this_branch, 14531 struct bpf_verifier_state *other_branch) 14532 { 14533 if (BPF_SRC(insn->code) != BPF_X) 14534 return false; 14535 14536 /* Pointers are always 64-bit. */ 14537 if (BPF_CLASS(insn->code) == BPF_JMP32) 14538 return false; 14539 14540 switch (BPF_OP(insn->code)) { 14541 case BPF_JGT: 14542 if ((dst_reg->type == PTR_TO_PACKET && 14543 src_reg->type == PTR_TO_PACKET_END) || 14544 (dst_reg->type == PTR_TO_PACKET_META && 14545 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14546 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 14547 find_good_pkt_pointers(this_branch, dst_reg, 14548 dst_reg->type, false); 14549 mark_pkt_end(other_branch, insn->dst_reg, true); 14550 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14551 src_reg->type == PTR_TO_PACKET) || 14552 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14553 src_reg->type == PTR_TO_PACKET_META)) { 14554 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 14555 find_good_pkt_pointers(other_branch, src_reg, 14556 src_reg->type, true); 14557 mark_pkt_end(this_branch, insn->src_reg, false); 14558 } else { 14559 return false; 14560 } 14561 break; 14562 case BPF_JLT: 14563 if ((dst_reg->type == PTR_TO_PACKET && 14564 src_reg->type == PTR_TO_PACKET_END) || 14565 (dst_reg->type == PTR_TO_PACKET_META && 14566 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14567 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 14568 find_good_pkt_pointers(other_branch, dst_reg, 14569 dst_reg->type, true); 14570 mark_pkt_end(this_branch, insn->dst_reg, false); 14571 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14572 src_reg->type == PTR_TO_PACKET) || 14573 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14574 src_reg->type == PTR_TO_PACKET_META)) { 14575 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 14576 find_good_pkt_pointers(this_branch, src_reg, 14577 src_reg->type, false); 14578 mark_pkt_end(other_branch, insn->src_reg, true); 14579 } else { 14580 return false; 14581 } 14582 break; 14583 case BPF_JGE: 14584 if ((dst_reg->type == PTR_TO_PACKET && 14585 src_reg->type == PTR_TO_PACKET_END) || 14586 (dst_reg->type == PTR_TO_PACKET_META && 14587 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14588 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 14589 find_good_pkt_pointers(this_branch, dst_reg, 14590 dst_reg->type, true); 14591 mark_pkt_end(other_branch, insn->dst_reg, false); 14592 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14593 src_reg->type == PTR_TO_PACKET) || 14594 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14595 src_reg->type == PTR_TO_PACKET_META)) { 14596 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 14597 find_good_pkt_pointers(other_branch, src_reg, 14598 src_reg->type, false); 14599 mark_pkt_end(this_branch, insn->src_reg, true); 14600 } else { 14601 return false; 14602 } 14603 break; 14604 case BPF_JLE: 14605 if ((dst_reg->type == PTR_TO_PACKET && 14606 src_reg->type == PTR_TO_PACKET_END) || 14607 (dst_reg->type == PTR_TO_PACKET_META && 14608 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14609 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 14610 find_good_pkt_pointers(other_branch, dst_reg, 14611 dst_reg->type, false); 14612 mark_pkt_end(this_branch, insn->dst_reg, true); 14613 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14614 src_reg->type == PTR_TO_PACKET) || 14615 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14616 src_reg->type == PTR_TO_PACKET_META)) { 14617 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 14618 find_good_pkt_pointers(this_branch, src_reg, 14619 src_reg->type, true); 14620 mark_pkt_end(other_branch, insn->src_reg, false); 14621 } else { 14622 return false; 14623 } 14624 break; 14625 default: 14626 return false; 14627 } 14628 14629 return true; 14630 } 14631 14632 static void find_equal_scalars(struct bpf_verifier_state *vstate, 14633 struct bpf_reg_state *known_reg) 14634 { 14635 struct bpf_func_state *state; 14636 struct bpf_reg_state *reg; 14637 14638 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14639 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 14640 copy_register_state(reg, known_reg); 14641 })); 14642 } 14643 14644 static int check_cond_jmp_op(struct bpf_verifier_env *env, 14645 struct bpf_insn *insn, int *insn_idx) 14646 { 14647 struct bpf_verifier_state *this_branch = env->cur_state; 14648 struct bpf_verifier_state *other_branch; 14649 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 14650 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 14651 struct bpf_reg_state *eq_branch_regs; 14652 struct bpf_reg_state fake_reg = {}; 14653 u8 opcode = BPF_OP(insn->code); 14654 bool is_jmp32; 14655 int pred = -1; 14656 int err; 14657 14658 /* Only conditional jumps are expected to reach here. */ 14659 if (opcode == BPF_JA || opcode > BPF_JSLE) { 14660 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 14661 return -EINVAL; 14662 } 14663 14664 /* check src2 operand */ 14665 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14666 if (err) 14667 return err; 14668 14669 dst_reg = ®s[insn->dst_reg]; 14670 if (BPF_SRC(insn->code) == BPF_X) { 14671 if (insn->imm != 0) { 14672 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14673 return -EINVAL; 14674 } 14675 14676 /* check src1 operand */ 14677 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14678 if (err) 14679 return err; 14680 14681 src_reg = ®s[insn->src_reg]; 14682 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 14683 is_pointer_value(env, insn->src_reg)) { 14684 verbose(env, "R%d pointer comparison prohibited\n", 14685 insn->src_reg); 14686 return -EACCES; 14687 } 14688 } else { 14689 if (insn->src_reg != BPF_REG_0) { 14690 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14691 return -EINVAL; 14692 } 14693 src_reg = &fake_reg; 14694 src_reg->type = SCALAR_VALUE; 14695 __mark_reg_known(src_reg, insn->imm); 14696 } 14697 14698 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 14699 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32); 14700 if (pred >= 0) { 14701 /* If we get here with a dst_reg pointer type it is because 14702 * above is_branch_taken() special cased the 0 comparison. 14703 */ 14704 if (!__is_pointer_value(false, dst_reg)) 14705 err = mark_chain_precision(env, insn->dst_reg); 14706 if (BPF_SRC(insn->code) == BPF_X && !err && 14707 !__is_pointer_value(false, src_reg)) 14708 err = mark_chain_precision(env, insn->src_reg); 14709 if (err) 14710 return err; 14711 } 14712 14713 if (pred == 1) { 14714 /* Only follow the goto, ignore fall-through. If needed, push 14715 * the fall-through branch for simulation under speculative 14716 * execution. 14717 */ 14718 if (!env->bypass_spec_v1 && 14719 !sanitize_speculative_path(env, insn, *insn_idx + 1, 14720 *insn_idx)) 14721 return -EFAULT; 14722 if (env->log.level & BPF_LOG_LEVEL) 14723 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14724 *insn_idx += insn->off; 14725 return 0; 14726 } else if (pred == 0) { 14727 /* Only follow the fall-through branch, since that's where the 14728 * program will go. If needed, push the goto branch for 14729 * simulation under speculative execution. 14730 */ 14731 if (!env->bypass_spec_v1 && 14732 !sanitize_speculative_path(env, insn, 14733 *insn_idx + insn->off + 1, 14734 *insn_idx)) 14735 return -EFAULT; 14736 if (env->log.level & BPF_LOG_LEVEL) 14737 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14738 return 0; 14739 } 14740 14741 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 14742 false); 14743 if (!other_branch) 14744 return -EFAULT; 14745 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 14746 14747 if (BPF_SRC(insn->code) == BPF_X) { 14748 err = reg_set_min_max(env, 14749 &other_branch_regs[insn->dst_reg], 14750 &other_branch_regs[insn->src_reg], 14751 dst_reg, src_reg, opcode, is_jmp32); 14752 } else /* BPF_SRC(insn->code) == BPF_K */ { 14753 err = reg_set_min_max(env, 14754 &other_branch_regs[insn->dst_reg], 14755 src_reg /* fake one */, 14756 dst_reg, src_reg /* same fake one */, 14757 opcode, is_jmp32); 14758 } 14759 if (err) 14760 return err; 14761 14762 if (BPF_SRC(insn->code) == BPF_X && 14763 src_reg->type == SCALAR_VALUE && src_reg->id && 14764 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 14765 find_equal_scalars(this_branch, src_reg); 14766 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 14767 } 14768 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 14769 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 14770 find_equal_scalars(this_branch, dst_reg); 14771 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 14772 } 14773 14774 /* if one pointer register is compared to another pointer 14775 * register check if PTR_MAYBE_NULL could be lifted. 14776 * E.g. register A - maybe null 14777 * register B - not null 14778 * for JNE A, B, ... - A is not null in the false branch; 14779 * for JEQ A, B, ... - A is not null in the true branch. 14780 * 14781 * Since PTR_TO_BTF_ID points to a kernel struct that does 14782 * not need to be null checked by the BPF program, i.e., 14783 * could be null even without PTR_MAYBE_NULL marking, so 14784 * only propagate nullness when neither reg is that type. 14785 */ 14786 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 14787 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 14788 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 14789 base_type(src_reg->type) != PTR_TO_BTF_ID && 14790 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 14791 eq_branch_regs = NULL; 14792 switch (opcode) { 14793 case BPF_JEQ: 14794 eq_branch_regs = other_branch_regs; 14795 break; 14796 case BPF_JNE: 14797 eq_branch_regs = regs; 14798 break; 14799 default: 14800 /* do nothing */ 14801 break; 14802 } 14803 if (eq_branch_regs) { 14804 if (type_may_be_null(src_reg->type)) 14805 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 14806 else 14807 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 14808 } 14809 } 14810 14811 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 14812 * NOTE: these optimizations below are related with pointer comparison 14813 * which will never be JMP32. 14814 */ 14815 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 14816 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 14817 type_may_be_null(dst_reg->type)) { 14818 /* Mark all identical registers in each branch as either 14819 * safe or unknown depending R == 0 or R != 0 conditional. 14820 */ 14821 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 14822 opcode == BPF_JNE); 14823 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 14824 opcode == BPF_JEQ); 14825 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 14826 this_branch, other_branch) && 14827 is_pointer_value(env, insn->dst_reg)) { 14828 verbose(env, "R%d pointer comparison prohibited\n", 14829 insn->dst_reg); 14830 return -EACCES; 14831 } 14832 if (env->log.level & BPF_LOG_LEVEL) 14833 print_insn_state(env, this_branch->frame[this_branch->curframe]); 14834 return 0; 14835 } 14836 14837 /* verify BPF_LD_IMM64 instruction */ 14838 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 14839 { 14840 struct bpf_insn_aux_data *aux = cur_aux(env); 14841 struct bpf_reg_state *regs = cur_regs(env); 14842 struct bpf_reg_state *dst_reg; 14843 struct bpf_map *map; 14844 int err; 14845 14846 if (BPF_SIZE(insn->code) != BPF_DW) { 14847 verbose(env, "invalid BPF_LD_IMM insn\n"); 14848 return -EINVAL; 14849 } 14850 if (insn->off != 0) { 14851 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 14852 return -EINVAL; 14853 } 14854 14855 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14856 if (err) 14857 return err; 14858 14859 dst_reg = ®s[insn->dst_reg]; 14860 if (insn->src_reg == 0) { 14861 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 14862 14863 dst_reg->type = SCALAR_VALUE; 14864 __mark_reg_known(®s[insn->dst_reg], imm); 14865 return 0; 14866 } 14867 14868 /* All special src_reg cases are listed below. From this point onwards 14869 * we either succeed and assign a corresponding dst_reg->type after 14870 * zeroing the offset, or fail and reject the program. 14871 */ 14872 mark_reg_known_zero(env, regs, insn->dst_reg); 14873 14874 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 14875 dst_reg->type = aux->btf_var.reg_type; 14876 switch (base_type(dst_reg->type)) { 14877 case PTR_TO_MEM: 14878 dst_reg->mem_size = aux->btf_var.mem_size; 14879 break; 14880 case PTR_TO_BTF_ID: 14881 dst_reg->btf = aux->btf_var.btf; 14882 dst_reg->btf_id = aux->btf_var.btf_id; 14883 break; 14884 default: 14885 verbose(env, "bpf verifier is misconfigured\n"); 14886 return -EFAULT; 14887 } 14888 return 0; 14889 } 14890 14891 if (insn->src_reg == BPF_PSEUDO_FUNC) { 14892 struct bpf_prog_aux *aux = env->prog->aux; 14893 u32 subprogno = find_subprog(env, 14894 env->insn_idx + insn->imm + 1); 14895 14896 if (!aux->func_info) { 14897 verbose(env, "missing btf func_info\n"); 14898 return -EINVAL; 14899 } 14900 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 14901 verbose(env, "callback function not static\n"); 14902 return -EINVAL; 14903 } 14904 14905 dst_reg->type = PTR_TO_FUNC; 14906 dst_reg->subprogno = subprogno; 14907 return 0; 14908 } 14909 14910 map = env->used_maps[aux->map_index]; 14911 dst_reg->map_ptr = map; 14912 14913 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 14914 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 14915 dst_reg->type = PTR_TO_MAP_VALUE; 14916 dst_reg->off = aux->map_off; 14917 WARN_ON_ONCE(map->max_entries != 1); 14918 /* We want reg->id to be same (0) as map_value is not distinct */ 14919 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 14920 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 14921 dst_reg->type = CONST_PTR_TO_MAP; 14922 } else { 14923 verbose(env, "bpf verifier is misconfigured\n"); 14924 return -EINVAL; 14925 } 14926 14927 return 0; 14928 } 14929 14930 static bool may_access_skb(enum bpf_prog_type type) 14931 { 14932 switch (type) { 14933 case BPF_PROG_TYPE_SOCKET_FILTER: 14934 case BPF_PROG_TYPE_SCHED_CLS: 14935 case BPF_PROG_TYPE_SCHED_ACT: 14936 return true; 14937 default: 14938 return false; 14939 } 14940 } 14941 14942 /* verify safety of LD_ABS|LD_IND instructions: 14943 * - they can only appear in the programs where ctx == skb 14944 * - since they are wrappers of function calls, they scratch R1-R5 registers, 14945 * preserve R6-R9, and store return value into R0 14946 * 14947 * Implicit input: 14948 * ctx == skb == R6 == CTX 14949 * 14950 * Explicit input: 14951 * SRC == any register 14952 * IMM == 32-bit immediate 14953 * 14954 * Output: 14955 * R0 - 8/16/32-bit skb data converted to cpu endianness 14956 */ 14957 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 14958 { 14959 struct bpf_reg_state *regs = cur_regs(env); 14960 static const int ctx_reg = BPF_REG_6; 14961 u8 mode = BPF_MODE(insn->code); 14962 int i, err; 14963 14964 if (!may_access_skb(resolve_prog_type(env->prog))) { 14965 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 14966 return -EINVAL; 14967 } 14968 14969 if (!env->ops->gen_ld_abs) { 14970 verbose(env, "bpf verifier is misconfigured\n"); 14971 return -EINVAL; 14972 } 14973 14974 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 14975 BPF_SIZE(insn->code) == BPF_DW || 14976 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 14977 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 14978 return -EINVAL; 14979 } 14980 14981 /* check whether implicit source operand (register R6) is readable */ 14982 err = check_reg_arg(env, ctx_reg, SRC_OP); 14983 if (err) 14984 return err; 14985 14986 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 14987 * gen_ld_abs() may terminate the program at runtime, leading to 14988 * reference leak. 14989 */ 14990 err = check_reference_leak(env, false); 14991 if (err) { 14992 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 14993 return err; 14994 } 14995 14996 if (env->cur_state->active_lock.ptr) { 14997 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 14998 return -EINVAL; 14999 } 15000 15001 if (env->cur_state->active_rcu_lock) { 15002 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 15003 return -EINVAL; 15004 } 15005 15006 if (regs[ctx_reg].type != PTR_TO_CTX) { 15007 verbose(env, 15008 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 15009 return -EINVAL; 15010 } 15011 15012 if (mode == BPF_IND) { 15013 /* check explicit source operand */ 15014 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15015 if (err) 15016 return err; 15017 } 15018 15019 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 15020 if (err < 0) 15021 return err; 15022 15023 /* reset caller saved regs to unreadable */ 15024 for (i = 0; i < CALLER_SAVED_REGS; i++) { 15025 mark_reg_not_init(env, regs, caller_saved[i]); 15026 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 15027 } 15028 15029 /* mark destination R0 register as readable, since it contains 15030 * the value fetched from the packet. 15031 * Already marked as written above. 15032 */ 15033 mark_reg_unknown(env, regs, BPF_REG_0); 15034 /* ld_abs load up to 32-bit skb data. */ 15035 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 15036 return 0; 15037 } 15038 15039 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 15040 { 15041 const char *exit_ctx = "At program exit"; 15042 struct tnum enforce_attach_type_range = tnum_unknown; 15043 const struct bpf_prog *prog = env->prog; 15044 struct bpf_reg_state *reg; 15045 struct bpf_retval_range range = retval_range(0, 1); 15046 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 15047 int err; 15048 struct bpf_func_state *frame = env->cur_state->frame[0]; 15049 const bool is_subprog = frame->subprogno; 15050 15051 /* LSM and struct_ops func-ptr's return type could be "void" */ 15052 if (!is_subprog || frame->in_exception_callback_fn) { 15053 switch (prog_type) { 15054 case BPF_PROG_TYPE_LSM: 15055 if (prog->expected_attach_type == BPF_LSM_CGROUP) 15056 /* See below, can be 0 or 0-1 depending on hook. */ 15057 break; 15058 fallthrough; 15059 case BPF_PROG_TYPE_STRUCT_OPS: 15060 if (!prog->aux->attach_func_proto->type) 15061 return 0; 15062 break; 15063 default: 15064 break; 15065 } 15066 } 15067 15068 /* eBPF calling convention is such that R0 is used 15069 * to return the value from eBPF program. 15070 * Make sure that it's readable at this time 15071 * of bpf_exit, which means that program wrote 15072 * something into it earlier 15073 */ 15074 err = check_reg_arg(env, regno, SRC_OP); 15075 if (err) 15076 return err; 15077 15078 if (is_pointer_value(env, regno)) { 15079 verbose(env, "R%d leaks addr as return value\n", regno); 15080 return -EACCES; 15081 } 15082 15083 reg = cur_regs(env) + regno; 15084 15085 if (frame->in_async_callback_fn) { 15086 /* enforce return zero from async callbacks like timer */ 15087 exit_ctx = "At async callback return"; 15088 range = retval_range(0, 0); 15089 goto enforce_retval; 15090 } 15091 15092 if (is_subprog && !frame->in_exception_callback_fn) { 15093 if (reg->type != SCALAR_VALUE) { 15094 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 15095 regno, reg_type_str(env, reg->type)); 15096 return -EINVAL; 15097 } 15098 return 0; 15099 } 15100 15101 switch (prog_type) { 15102 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 15103 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 15104 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 15105 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG || 15106 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 15107 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 15108 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME || 15109 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 15110 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME || 15111 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME) 15112 range = retval_range(1, 1); 15113 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 15114 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 15115 range = retval_range(0, 3); 15116 break; 15117 case BPF_PROG_TYPE_CGROUP_SKB: 15118 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 15119 range = retval_range(0, 3); 15120 enforce_attach_type_range = tnum_range(2, 3); 15121 } 15122 break; 15123 case BPF_PROG_TYPE_CGROUP_SOCK: 15124 case BPF_PROG_TYPE_SOCK_OPS: 15125 case BPF_PROG_TYPE_CGROUP_DEVICE: 15126 case BPF_PROG_TYPE_CGROUP_SYSCTL: 15127 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 15128 break; 15129 case BPF_PROG_TYPE_RAW_TRACEPOINT: 15130 if (!env->prog->aux->attach_btf_id) 15131 return 0; 15132 range = retval_range(0, 0); 15133 break; 15134 case BPF_PROG_TYPE_TRACING: 15135 switch (env->prog->expected_attach_type) { 15136 case BPF_TRACE_FENTRY: 15137 case BPF_TRACE_FEXIT: 15138 range = retval_range(0, 0); 15139 break; 15140 case BPF_TRACE_RAW_TP: 15141 case BPF_MODIFY_RETURN: 15142 return 0; 15143 case BPF_TRACE_ITER: 15144 break; 15145 default: 15146 return -ENOTSUPP; 15147 } 15148 break; 15149 case BPF_PROG_TYPE_SK_LOOKUP: 15150 range = retval_range(SK_DROP, SK_PASS); 15151 break; 15152 15153 case BPF_PROG_TYPE_LSM: 15154 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 15155 /* Regular BPF_PROG_TYPE_LSM programs can return 15156 * any value. 15157 */ 15158 return 0; 15159 } 15160 if (!env->prog->aux->attach_func_proto->type) { 15161 /* Make sure programs that attach to void 15162 * hooks don't try to modify return value. 15163 */ 15164 range = retval_range(1, 1); 15165 } 15166 break; 15167 15168 case BPF_PROG_TYPE_NETFILTER: 15169 range = retval_range(NF_DROP, NF_ACCEPT); 15170 break; 15171 case BPF_PROG_TYPE_EXT: 15172 /* freplace program can return anything as its return value 15173 * depends on the to-be-replaced kernel func or bpf program. 15174 */ 15175 default: 15176 return 0; 15177 } 15178 15179 enforce_retval: 15180 if (reg->type != SCALAR_VALUE) { 15181 verbose(env, "%s the register R%d is not a known value (%s)\n", 15182 exit_ctx, regno, reg_type_str(env, reg->type)); 15183 return -EINVAL; 15184 } 15185 15186 err = mark_chain_precision(env, regno); 15187 if (err) 15188 return err; 15189 15190 if (!retval_range_within(range, reg)) { 15191 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 15192 if (!is_subprog && 15193 prog->expected_attach_type == BPF_LSM_CGROUP && 15194 prog_type == BPF_PROG_TYPE_LSM && 15195 !prog->aux->attach_func_proto->type) 15196 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 15197 return -EINVAL; 15198 } 15199 15200 if (!tnum_is_unknown(enforce_attach_type_range) && 15201 tnum_in(enforce_attach_type_range, reg->var_off)) 15202 env->prog->enforce_expected_attach_type = 1; 15203 return 0; 15204 } 15205 15206 /* non-recursive DFS pseudo code 15207 * 1 procedure DFS-iterative(G,v): 15208 * 2 label v as discovered 15209 * 3 let S be a stack 15210 * 4 S.push(v) 15211 * 5 while S is not empty 15212 * 6 t <- S.peek() 15213 * 7 if t is what we're looking for: 15214 * 8 return t 15215 * 9 for all edges e in G.adjacentEdges(t) do 15216 * 10 if edge e is already labelled 15217 * 11 continue with the next edge 15218 * 12 w <- G.adjacentVertex(t,e) 15219 * 13 if vertex w is not discovered and not explored 15220 * 14 label e as tree-edge 15221 * 15 label w as discovered 15222 * 16 S.push(w) 15223 * 17 continue at 5 15224 * 18 else if vertex w is discovered 15225 * 19 label e as back-edge 15226 * 20 else 15227 * 21 // vertex w is explored 15228 * 22 label e as forward- or cross-edge 15229 * 23 label t as explored 15230 * 24 S.pop() 15231 * 15232 * convention: 15233 * 0x10 - discovered 15234 * 0x11 - discovered and fall-through edge labelled 15235 * 0x12 - discovered and fall-through and branch edges labelled 15236 * 0x20 - explored 15237 */ 15238 15239 enum { 15240 DISCOVERED = 0x10, 15241 EXPLORED = 0x20, 15242 FALLTHROUGH = 1, 15243 BRANCH = 2, 15244 }; 15245 15246 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 15247 { 15248 env->insn_aux_data[idx].prune_point = true; 15249 } 15250 15251 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 15252 { 15253 return env->insn_aux_data[insn_idx].prune_point; 15254 } 15255 15256 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 15257 { 15258 env->insn_aux_data[idx].force_checkpoint = true; 15259 } 15260 15261 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 15262 { 15263 return env->insn_aux_data[insn_idx].force_checkpoint; 15264 } 15265 15266 static void mark_calls_callback(struct bpf_verifier_env *env, int idx) 15267 { 15268 env->insn_aux_data[idx].calls_callback = true; 15269 } 15270 15271 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx) 15272 { 15273 return env->insn_aux_data[insn_idx].calls_callback; 15274 } 15275 15276 enum { 15277 DONE_EXPLORING = 0, 15278 KEEP_EXPLORING = 1, 15279 }; 15280 15281 /* t, w, e - match pseudo-code above: 15282 * t - index of current instruction 15283 * w - next instruction 15284 * e - edge 15285 */ 15286 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 15287 { 15288 int *insn_stack = env->cfg.insn_stack; 15289 int *insn_state = env->cfg.insn_state; 15290 15291 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 15292 return DONE_EXPLORING; 15293 15294 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 15295 return DONE_EXPLORING; 15296 15297 if (w < 0 || w >= env->prog->len) { 15298 verbose_linfo(env, t, "%d: ", t); 15299 verbose(env, "jump out of range from insn %d to %d\n", t, w); 15300 return -EINVAL; 15301 } 15302 15303 if (e == BRANCH) { 15304 /* mark branch target for state pruning */ 15305 mark_prune_point(env, w); 15306 mark_jmp_point(env, w); 15307 } 15308 15309 if (insn_state[w] == 0) { 15310 /* tree-edge */ 15311 insn_state[t] = DISCOVERED | e; 15312 insn_state[w] = DISCOVERED; 15313 if (env->cfg.cur_stack >= env->prog->len) 15314 return -E2BIG; 15315 insn_stack[env->cfg.cur_stack++] = w; 15316 return KEEP_EXPLORING; 15317 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 15318 if (env->bpf_capable) 15319 return DONE_EXPLORING; 15320 verbose_linfo(env, t, "%d: ", t); 15321 verbose_linfo(env, w, "%d: ", w); 15322 verbose(env, "back-edge from insn %d to %d\n", t, w); 15323 return -EINVAL; 15324 } else if (insn_state[w] == EXPLORED) { 15325 /* forward- or cross-edge */ 15326 insn_state[t] = DISCOVERED | e; 15327 } else { 15328 verbose(env, "insn state internal bug\n"); 15329 return -EFAULT; 15330 } 15331 return DONE_EXPLORING; 15332 } 15333 15334 static int visit_func_call_insn(int t, struct bpf_insn *insns, 15335 struct bpf_verifier_env *env, 15336 bool visit_callee) 15337 { 15338 int ret, insn_sz; 15339 15340 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 15341 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 15342 if (ret) 15343 return ret; 15344 15345 mark_prune_point(env, t + insn_sz); 15346 /* when we exit from subprog, we need to record non-linear history */ 15347 mark_jmp_point(env, t + insn_sz); 15348 15349 if (visit_callee) { 15350 mark_prune_point(env, t); 15351 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env); 15352 } 15353 return ret; 15354 } 15355 15356 /* Visits the instruction at index t and returns one of the following: 15357 * < 0 - an error occurred 15358 * DONE_EXPLORING - the instruction was fully explored 15359 * KEEP_EXPLORING - there is still work to be done before it is fully explored 15360 */ 15361 static int visit_insn(int t, struct bpf_verifier_env *env) 15362 { 15363 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 15364 int ret, off, insn_sz; 15365 15366 if (bpf_pseudo_func(insn)) 15367 return visit_func_call_insn(t, insns, env, true); 15368 15369 /* All non-branch instructions have a single fall-through edge. */ 15370 if (BPF_CLASS(insn->code) != BPF_JMP && 15371 BPF_CLASS(insn->code) != BPF_JMP32) { 15372 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 15373 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 15374 } 15375 15376 switch (BPF_OP(insn->code)) { 15377 case BPF_EXIT: 15378 return DONE_EXPLORING; 15379 15380 case BPF_CALL: 15381 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback) 15382 /* Mark this call insn as a prune point to trigger 15383 * is_state_visited() check before call itself is 15384 * processed by __check_func_call(). Otherwise new 15385 * async state will be pushed for further exploration. 15386 */ 15387 mark_prune_point(env, t); 15388 /* For functions that invoke callbacks it is not known how many times 15389 * callback would be called. Verifier models callback calling functions 15390 * by repeatedly visiting callback bodies and returning to origin call 15391 * instruction. 15392 * In order to stop such iteration verifier needs to identify when a 15393 * state identical some state from a previous iteration is reached. 15394 * Check below forces creation of checkpoint before callback calling 15395 * instruction to allow search for such identical states. 15396 */ 15397 if (is_sync_callback_calling_insn(insn)) { 15398 mark_calls_callback(env, t); 15399 mark_force_checkpoint(env, t); 15400 mark_prune_point(env, t); 15401 mark_jmp_point(env, t); 15402 } 15403 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 15404 struct bpf_kfunc_call_arg_meta meta; 15405 15406 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 15407 if (ret == 0 && is_iter_next_kfunc(&meta)) { 15408 mark_prune_point(env, t); 15409 /* Checking and saving state checkpoints at iter_next() call 15410 * is crucial for fast convergence of open-coded iterator loop 15411 * logic, so we need to force it. If we don't do that, 15412 * is_state_visited() might skip saving a checkpoint, causing 15413 * unnecessarily long sequence of not checkpointed 15414 * instructions and jumps, leading to exhaustion of jump 15415 * history buffer, and potentially other undesired outcomes. 15416 * It is expected that with correct open-coded iterators 15417 * convergence will happen quickly, so we don't run a risk of 15418 * exhausting memory. 15419 */ 15420 mark_force_checkpoint(env, t); 15421 } 15422 } 15423 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 15424 15425 case BPF_JA: 15426 if (BPF_SRC(insn->code) != BPF_K) 15427 return -EINVAL; 15428 15429 if (BPF_CLASS(insn->code) == BPF_JMP) 15430 off = insn->off; 15431 else 15432 off = insn->imm; 15433 15434 /* unconditional jump with single edge */ 15435 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 15436 if (ret) 15437 return ret; 15438 15439 mark_prune_point(env, t + off + 1); 15440 mark_jmp_point(env, t + off + 1); 15441 15442 return ret; 15443 15444 default: 15445 /* conditional jump with two edges */ 15446 mark_prune_point(env, t); 15447 15448 ret = push_insn(t, t + 1, FALLTHROUGH, env); 15449 if (ret) 15450 return ret; 15451 15452 return push_insn(t, t + insn->off + 1, BRANCH, env); 15453 } 15454 } 15455 15456 /* non-recursive depth-first-search to detect loops in BPF program 15457 * loop == back-edge in directed graph 15458 */ 15459 static int check_cfg(struct bpf_verifier_env *env) 15460 { 15461 int insn_cnt = env->prog->len; 15462 int *insn_stack, *insn_state; 15463 int ex_insn_beg, i, ret = 0; 15464 bool ex_done = false; 15465 15466 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15467 if (!insn_state) 15468 return -ENOMEM; 15469 15470 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15471 if (!insn_stack) { 15472 kvfree(insn_state); 15473 return -ENOMEM; 15474 } 15475 15476 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 15477 insn_stack[0] = 0; /* 0 is the first instruction */ 15478 env->cfg.cur_stack = 1; 15479 15480 walk_cfg: 15481 while (env->cfg.cur_stack > 0) { 15482 int t = insn_stack[env->cfg.cur_stack - 1]; 15483 15484 ret = visit_insn(t, env); 15485 switch (ret) { 15486 case DONE_EXPLORING: 15487 insn_state[t] = EXPLORED; 15488 env->cfg.cur_stack--; 15489 break; 15490 case KEEP_EXPLORING: 15491 break; 15492 default: 15493 if (ret > 0) { 15494 verbose(env, "visit_insn internal bug\n"); 15495 ret = -EFAULT; 15496 } 15497 goto err_free; 15498 } 15499 } 15500 15501 if (env->cfg.cur_stack < 0) { 15502 verbose(env, "pop stack internal bug\n"); 15503 ret = -EFAULT; 15504 goto err_free; 15505 } 15506 15507 if (env->exception_callback_subprog && !ex_done) { 15508 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start; 15509 15510 insn_state[ex_insn_beg] = DISCOVERED; 15511 insn_stack[0] = ex_insn_beg; 15512 env->cfg.cur_stack = 1; 15513 ex_done = true; 15514 goto walk_cfg; 15515 } 15516 15517 for (i = 0; i < insn_cnt; i++) { 15518 struct bpf_insn *insn = &env->prog->insnsi[i]; 15519 15520 if (insn_state[i] != EXPLORED) { 15521 verbose(env, "unreachable insn %d\n", i); 15522 ret = -EINVAL; 15523 goto err_free; 15524 } 15525 if (bpf_is_ldimm64(insn)) { 15526 if (insn_state[i + 1] != 0) { 15527 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 15528 ret = -EINVAL; 15529 goto err_free; 15530 } 15531 i++; /* skip second half of ldimm64 */ 15532 } 15533 } 15534 ret = 0; /* cfg looks good */ 15535 15536 err_free: 15537 kvfree(insn_state); 15538 kvfree(insn_stack); 15539 env->cfg.insn_state = env->cfg.insn_stack = NULL; 15540 return ret; 15541 } 15542 15543 static int check_abnormal_return(struct bpf_verifier_env *env) 15544 { 15545 int i; 15546 15547 for (i = 1; i < env->subprog_cnt; i++) { 15548 if (env->subprog_info[i].has_ld_abs) { 15549 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 15550 return -EINVAL; 15551 } 15552 if (env->subprog_info[i].has_tail_call) { 15553 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 15554 return -EINVAL; 15555 } 15556 } 15557 return 0; 15558 } 15559 15560 /* The minimum supported BTF func info size */ 15561 #define MIN_BPF_FUNCINFO_SIZE 8 15562 #define MAX_FUNCINFO_REC_SIZE 252 15563 15564 static int check_btf_func_early(struct bpf_verifier_env *env, 15565 const union bpf_attr *attr, 15566 bpfptr_t uattr) 15567 { 15568 u32 krec_size = sizeof(struct bpf_func_info); 15569 const struct btf_type *type, *func_proto; 15570 u32 i, nfuncs, urec_size, min_size; 15571 struct bpf_func_info *krecord; 15572 struct bpf_prog *prog; 15573 const struct btf *btf; 15574 u32 prev_offset = 0; 15575 bpfptr_t urecord; 15576 int ret = -ENOMEM; 15577 15578 nfuncs = attr->func_info_cnt; 15579 if (!nfuncs) { 15580 if (check_abnormal_return(env)) 15581 return -EINVAL; 15582 return 0; 15583 } 15584 15585 urec_size = attr->func_info_rec_size; 15586 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 15587 urec_size > MAX_FUNCINFO_REC_SIZE || 15588 urec_size % sizeof(u32)) { 15589 verbose(env, "invalid func info rec size %u\n", urec_size); 15590 return -EINVAL; 15591 } 15592 15593 prog = env->prog; 15594 btf = prog->aux->btf; 15595 15596 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15597 min_size = min_t(u32, krec_size, urec_size); 15598 15599 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 15600 if (!krecord) 15601 return -ENOMEM; 15602 15603 for (i = 0; i < nfuncs; i++) { 15604 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 15605 if (ret) { 15606 if (ret == -E2BIG) { 15607 verbose(env, "nonzero tailing record in func info"); 15608 /* set the size kernel expects so loader can zero 15609 * out the rest of the record. 15610 */ 15611 if (copy_to_bpfptr_offset(uattr, 15612 offsetof(union bpf_attr, func_info_rec_size), 15613 &min_size, sizeof(min_size))) 15614 ret = -EFAULT; 15615 } 15616 goto err_free; 15617 } 15618 15619 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 15620 ret = -EFAULT; 15621 goto err_free; 15622 } 15623 15624 /* check insn_off */ 15625 ret = -EINVAL; 15626 if (i == 0) { 15627 if (krecord[i].insn_off) { 15628 verbose(env, 15629 "nonzero insn_off %u for the first func info record", 15630 krecord[i].insn_off); 15631 goto err_free; 15632 } 15633 } else if (krecord[i].insn_off <= prev_offset) { 15634 verbose(env, 15635 "same or smaller insn offset (%u) than previous func info record (%u)", 15636 krecord[i].insn_off, prev_offset); 15637 goto err_free; 15638 } 15639 15640 /* check type_id */ 15641 type = btf_type_by_id(btf, krecord[i].type_id); 15642 if (!type || !btf_type_is_func(type)) { 15643 verbose(env, "invalid type id %d in func info", 15644 krecord[i].type_id); 15645 goto err_free; 15646 } 15647 15648 func_proto = btf_type_by_id(btf, type->type); 15649 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 15650 /* btf_func_check() already verified it during BTF load */ 15651 goto err_free; 15652 15653 prev_offset = krecord[i].insn_off; 15654 bpfptr_add(&urecord, urec_size); 15655 } 15656 15657 prog->aux->func_info = krecord; 15658 prog->aux->func_info_cnt = nfuncs; 15659 return 0; 15660 15661 err_free: 15662 kvfree(krecord); 15663 return ret; 15664 } 15665 15666 static int check_btf_func(struct bpf_verifier_env *env, 15667 const union bpf_attr *attr, 15668 bpfptr_t uattr) 15669 { 15670 const struct btf_type *type, *func_proto, *ret_type; 15671 u32 i, nfuncs, urec_size; 15672 struct bpf_func_info *krecord; 15673 struct bpf_func_info_aux *info_aux = NULL; 15674 struct bpf_prog *prog; 15675 const struct btf *btf; 15676 bpfptr_t urecord; 15677 bool scalar_return; 15678 int ret = -ENOMEM; 15679 15680 nfuncs = attr->func_info_cnt; 15681 if (!nfuncs) { 15682 if (check_abnormal_return(env)) 15683 return -EINVAL; 15684 return 0; 15685 } 15686 if (nfuncs != env->subprog_cnt) { 15687 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 15688 return -EINVAL; 15689 } 15690 15691 urec_size = attr->func_info_rec_size; 15692 15693 prog = env->prog; 15694 btf = prog->aux->btf; 15695 15696 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15697 15698 krecord = prog->aux->func_info; 15699 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 15700 if (!info_aux) 15701 return -ENOMEM; 15702 15703 for (i = 0; i < nfuncs; i++) { 15704 /* check insn_off */ 15705 ret = -EINVAL; 15706 15707 if (env->subprog_info[i].start != krecord[i].insn_off) { 15708 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 15709 goto err_free; 15710 } 15711 15712 /* Already checked type_id */ 15713 type = btf_type_by_id(btf, krecord[i].type_id); 15714 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 15715 /* Already checked func_proto */ 15716 func_proto = btf_type_by_id(btf, type->type); 15717 15718 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 15719 scalar_return = 15720 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 15721 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 15722 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 15723 goto err_free; 15724 } 15725 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 15726 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 15727 goto err_free; 15728 } 15729 15730 bpfptr_add(&urecord, urec_size); 15731 } 15732 15733 prog->aux->func_info_aux = info_aux; 15734 return 0; 15735 15736 err_free: 15737 kfree(info_aux); 15738 return ret; 15739 } 15740 15741 static void adjust_btf_func(struct bpf_verifier_env *env) 15742 { 15743 struct bpf_prog_aux *aux = env->prog->aux; 15744 int i; 15745 15746 if (!aux->func_info) 15747 return; 15748 15749 /* func_info is not available for hidden subprogs */ 15750 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 15751 aux->func_info[i].insn_off = env->subprog_info[i].start; 15752 } 15753 15754 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 15755 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 15756 15757 static int check_btf_line(struct bpf_verifier_env *env, 15758 const union bpf_attr *attr, 15759 bpfptr_t uattr) 15760 { 15761 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 15762 struct bpf_subprog_info *sub; 15763 struct bpf_line_info *linfo; 15764 struct bpf_prog *prog; 15765 const struct btf *btf; 15766 bpfptr_t ulinfo; 15767 int err; 15768 15769 nr_linfo = attr->line_info_cnt; 15770 if (!nr_linfo) 15771 return 0; 15772 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 15773 return -EINVAL; 15774 15775 rec_size = attr->line_info_rec_size; 15776 if (rec_size < MIN_BPF_LINEINFO_SIZE || 15777 rec_size > MAX_LINEINFO_REC_SIZE || 15778 rec_size & (sizeof(u32) - 1)) 15779 return -EINVAL; 15780 15781 /* Need to zero it in case the userspace may 15782 * pass in a smaller bpf_line_info object. 15783 */ 15784 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 15785 GFP_KERNEL | __GFP_NOWARN); 15786 if (!linfo) 15787 return -ENOMEM; 15788 15789 prog = env->prog; 15790 btf = prog->aux->btf; 15791 15792 s = 0; 15793 sub = env->subprog_info; 15794 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 15795 expected_size = sizeof(struct bpf_line_info); 15796 ncopy = min_t(u32, expected_size, rec_size); 15797 for (i = 0; i < nr_linfo; i++) { 15798 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 15799 if (err) { 15800 if (err == -E2BIG) { 15801 verbose(env, "nonzero tailing record in line_info"); 15802 if (copy_to_bpfptr_offset(uattr, 15803 offsetof(union bpf_attr, line_info_rec_size), 15804 &expected_size, sizeof(expected_size))) 15805 err = -EFAULT; 15806 } 15807 goto err_free; 15808 } 15809 15810 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 15811 err = -EFAULT; 15812 goto err_free; 15813 } 15814 15815 /* 15816 * Check insn_off to ensure 15817 * 1) strictly increasing AND 15818 * 2) bounded by prog->len 15819 * 15820 * The linfo[0].insn_off == 0 check logically falls into 15821 * the later "missing bpf_line_info for func..." case 15822 * because the first linfo[0].insn_off must be the 15823 * first sub also and the first sub must have 15824 * subprog_info[0].start == 0. 15825 */ 15826 if ((i && linfo[i].insn_off <= prev_offset) || 15827 linfo[i].insn_off >= prog->len) { 15828 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 15829 i, linfo[i].insn_off, prev_offset, 15830 prog->len); 15831 err = -EINVAL; 15832 goto err_free; 15833 } 15834 15835 if (!prog->insnsi[linfo[i].insn_off].code) { 15836 verbose(env, 15837 "Invalid insn code at line_info[%u].insn_off\n", 15838 i); 15839 err = -EINVAL; 15840 goto err_free; 15841 } 15842 15843 if (!btf_name_by_offset(btf, linfo[i].line_off) || 15844 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 15845 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 15846 err = -EINVAL; 15847 goto err_free; 15848 } 15849 15850 if (s != env->subprog_cnt) { 15851 if (linfo[i].insn_off == sub[s].start) { 15852 sub[s].linfo_idx = i; 15853 s++; 15854 } else if (sub[s].start < linfo[i].insn_off) { 15855 verbose(env, "missing bpf_line_info for func#%u\n", s); 15856 err = -EINVAL; 15857 goto err_free; 15858 } 15859 } 15860 15861 prev_offset = linfo[i].insn_off; 15862 bpfptr_add(&ulinfo, rec_size); 15863 } 15864 15865 if (s != env->subprog_cnt) { 15866 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 15867 env->subprog_cnt - s, s); 15868 err = -EINVAL; 15869 goto err_free; 15870 } 15871 15872 prog->aux->linfo = linfo; 15873 prog->aux->nr_linfo = nr_linfo; 15874 15875 return 0; 15876 15877 err_free: 15878 kvfree(linfo); 15879 return err; 15880 } 15881 15882 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 15883 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 15884 15885 static int check_core_relo(struct bpf_verifier_env *env, 15886 const union bpf_attr *attr, 15887 bpfptr_t uattr) 15888 { 15889 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 15890 struct bpf_core_relo core_relo = {}; 15891 struct bpf_prog *prog = env->prog; 15892 const struct btf *btf = prog->aux->btf; 15893 struct bpf_core_ctx ctx = { 15894 .log = &env->log, 15895 .btf = btf, 15896 }; 15897 bpfptr_t u_core_relo; 15898 int err; 15899 15900 nr_core_relo = attr->core_relo_cnt; 15901 if (!nr_core_relo) 15902 return 0; 15903 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 15904 return -EINVAL; 15905 15906 rec_size = attr->core_relo_rec_size; 15907 if (rec_size < MIN_CORE_RELO_SIZE || 15908 rec_size > MAX_CORE_RELO_SIZE || 15909 rec_size % sizeof(u32)) 15910 return -EINVAL; 15911 15912 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 15913 expected_size = sizeof(struct bpf_core_relo); 15914 ncopy = min_t(u32, expected_size, rec_size); 15915 15916 /* Unlike func_info and line_info, copy and apply each CO-RE 15917 * relocation record one at a time. 15918 */ 15919 for (i = 0; i < nr_core_relo; i++) { 15920 /* future proofing when sizeof(bpf_core_relo) changes */ 15921 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 15922 if (err) { 15923 if (err == -E2BIG) { 15924 verbose(env, "nonzero tailing record in core_relo"); 15925 if (copy_to_bpfptr_offset(uattr, 15926 offsetof(union bpf_attr, core_relo_rec_size), 15927 &expected_size, sizeof(expected_size))) 15928 err = -EFAULT; 15929 } 15930 break; 15931 } 15932 15933 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 15934 err = -EFAULT; 15935 break; 15936 } 15937 15938 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 15939 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 15940 i, core_relo.insn_off, prog->len); 15941 err = -EINVAL; 15942 break; 15943 } 15944 15945 err = bpf_core_apply(&ctx, &core_relo, i, 15946 &prog->insnsi[core_relo.insn_off / 8]); 15947 if (err) 15948 break; 15949 bpfptr_add(&u_core_relo, rec_size); 15950 } 15951 return err; 15952 } 15953 15954 static int check_btf_info_early(struct bpf_verifier_env *env, 15955 const union bpf_attr *attr, 15956 bpfptr_t uattr) 15957 { 15958 struct btf *btf; 15959 int err; 15960 15961 if (!attr->func_info_cnt && !attr->line_info_cnt) { 15962 if (check_abnormal_return(env)) 15963 return -EINVAL; 15964 return 0; 15965 } 15966 15967 btf = btf_get_by_fd(attr->prog_btf_fd); 15968 if (IS_ERR(btf)) 15969 return PTR_ERR(btf); 15970 if (btf_is_kernel(btf)) { 15971 btf_put(btf); 15972 return -EACCES; 15973 } 15974 env->prog->aux->btf = btf; 15975 15976 err = check_btf_func_early(env, attr, uattr); 15977 if (err) 15978 return err; 15979 return 0; 15980 } 15981 15982 static int check_btf_info(struct bpf_verifier_env *env, 15983 const union bpf_attr *attr, 15984 bpfptr_t uattr) 15985 { 15986 int err; 15987 15988 if (!attr->func_info_cnt && !attr->line_info_cnt) { 15989 if (check_abnormal_return(env)) 15990 return -EINVAL; 15991 return 0; 15992 } 15993 15994 err = check_btf_func(env, attr, uattr); 15995 if (err) 15996 return err; 15997 15998 err = check_btf_line(env, attr, uattr); 15999 if (err) 16000 return err; 16001 16002 err = check_core_relo(env, attr, uattr); 16003 if (err) 16004 return err; 16005 16006 return 0; 16007 } 16008 16009 /* check %cur's range satisfies %old's */ 16010 static bool range_within(struct bpf_reg_state *old, 16011 struct bpf_reg_state *cur) 16012 { 16013 return old->umin_value <= cur->umin_value && 16014 old->umax_value >= cur->umax_value && 16015 old->smin_value <= cur->smin_value && 16016 old->smax_value >= cur->smax_value && 16017 old->u32_min_value <= cur->u32_min_value && 16018 old->u32_max_value >= cur->u32_max_value && 16019 old->s32_min_value <= cur->s32_min_value && 16020 old->s32_max_value >= cur->s32_max_value; 16021 } 16022 16023 /* If in the old state two registers had the same id, then they need to have 16024 * the same id in the new state as well. But that id could be different from 16025 * the old state, so we need to track the mapping from old to new ids. 16026 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 16027 * regs with old id 5 must also have new id 9 for the new state to be safe. But 16028 * regs with a different old id could still have new id 9, we don't care about 16029 * that. 16030 * So we look through our idmap to see if this old id has been seen before. If 16031 * so, we require the new id to match; otherwise, we add the id pair to the map. 16032 */ 16033 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 16034 { 16035 struct bpf_id_pair *map = idmap->map; 16036 unsigned int i; 16037 16038 /* either both IDs should be set or both should be zero */ 16039 if (!!old_id != !!cur_id) 16040 return false; 16041 16042 if (old_id == 0) /* cur_id == 0 as well */ 16043 return true; 16044 16045 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 16046 if (!map[i].old) { 16047 /* Reached an empty slot; haven't seen this id before */ 16048 map[i].old = old_id; 16049 map[i].cur = cur_id; 16050 return true; 16051 } 16052 if (map[i].old == old_id) 16053 return map[i].cur == cur_id; 16054 if (map[i].cur == cur_id) 16055 return false; 16056 } 16057 /* We ran out of idmap slots, which should be impossible */ 16058 WARN_ON_ONCE(1); 16059 return false; 16060 } 16061 16062 /* Similar to check_ids(), but allocate a unique temporary ID 16063 * for 'old_id' or 'cur_id' of zero. 16064 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 16065 */ 16066 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 16067 { 16068 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 16069 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 16070 16071 return check_ids(old_id, cur_id, idmap); 16072 } 16073 16074 static void clean_func_state(struct bpf_verifier_env *env, 16075 struct bpf_func_state *st) 16076 { 16077 enum bpf_reg_liveness live; 16078 int i, j; 16079 16080 for (i = 0; i < BPF_REG_FP; i++) { 16081 live = st->regs[i].live; 16082 /* liveness must not touch this register anymore */ 16083 st->regs[i].live |= REG_LIVE_DONE; 16084 if (!(live & REG_LIVE_READ)) 16085 /* since the register is unused, clear its state 16086 * to make further comparison simpler 16087 */ 16088 __mark_reg_not_init(env, &st->regs[i]); 16089 } 16090 16091 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 16092 live = st->stack[i].spilled_ptr.live; 16093 /* liveness must not touch this stack slot anymore */ 16094 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 16095 if (!(live & REG_LIVE_READ)) { 16096 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 16097 for (j = 0; j < BPF_REG_SIZE; j++) 16098 st->stack[i].slot_type[j] = STACK_INVALID; 16099 } 16100 } 16101 } 16102 16103 static void clean_verifier_state(struct bpf_verifier_env *env, 16104 struct bpf_verifier_state *st) 16105 { 16106 int i; 16107 16108 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 16109 /* all regs in this state in all frames were already marked */ 16110 return; 16111 16112 for (i = 0; i <= st->curframe; i++) 16113 clean_func_state(env, st->frame[i]); 16114 } 16115 16116 /* the parentage chains form a tree. 16117 * the verifier states are added to state lists at given insn and 16118 * pushed into state stack for future exploration. 16119 * when the verifier reaches bpf_exit insn some of the verifer states 16120 * stored in the state lists have their final liveness state already, 16121 * but a lot of states will get revised from liveness point of view when 16122 * the verifier explores other branches. 16123 * Example: 16124 * 1: r0 = 1 16125 * 2: if r1 == 100 goto pc+1 16126 * 3: r0 = 2 16127 * 4: exit 16128 * when the verifier reaches exit insn the register r0 in the state list of 16129 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 16130 * of insn 2 and goes exploring further. At the insn 4 it will walk the 16131 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 16132 * 16133 * Since the verifier pushes the branch states as it sees them while exploring 16134 * the program the condition of walking the branch instruction for the second 16135 * time means that all states below this branch were already explored and 16136 * their final liveness marks are already propagated. 16137 * Hence when the verifier completes the search of state list in is_state_visited() 16138 * we can call this clean_live_states() function to mark all liveness states 16139 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 16140 * will not be used. 16141 * This function also clears the registers and stack for states that !READ 16142 * to simplify state merging. 16143 * 16144 * Important note here that walking the same branch instruction in the callee 16145 * doesn't meant that the states are DONE. The verifier has to compare 16146 * the callsites 16147 */ 16148 static void clean_live_states(struct bpf_verifier_env *env, int insn, 16149 struct bpf_verifier_state *cur) 16150 { 16151 struct bpf_verifier_state_list *sl; 16152 16153 sl = *explored_state(env, insn); 16154 while (sl) { 16155 if (sl->state.branches) 16156 goto next; 16157 if (sl->state.insn_idx != insn || 16158 !same_callsites(&sl->state, cur)) 16159 goto next; 16160 clean_verifier_state(env, &sl->state); 16161 next: 16162 sl = sl->next; 16163 } 16164 } 16165 16166 static bool regs_exact(const struct bpf_reg_state *rold, 16167 const struct bpf_reg_state *rcur, 16168 struct bpf_idmap *idmap) 16169 { 16170 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16171 check_ids(rold->id, rcur->id, idmap) && 16172 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16173 } 16174 16175 /* Returns true if (rold safe implies rcur safe) */ 16176 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 16177 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact) 16178 { 16179 if (exact) 16180 return regs_exact(rold, rcur, idmap); 16181 16182 if (!(rold->live & REG_LIVE_READ)) 16183 /* explored state didn't use this */ 16184 return true; 16185 if (rold->type == NOT_INIT) 16186 /* explored state can't have used this */ 16187 return true; 16188 if (rcur->type == NOT_INIT) 16189 return false; 16190 16191 /* Enforce that register types have to match exactly, including their 16192 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 16193 * rule. 16194 * 16195 * One can make a point that using a pointer register as unbounded 16196 * SCALAR would be technically acceptable, but this could lead to 16197 * pointer leaks because scalars are allowed to leak while pointers 16198 * are not. We could make this safe in special cases if root is 16199 * calling us, but it's probably not worth the hassle. 16200 * 16201 * Also, register types that are *not* MAYBE_NULL could technically be 16202 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 16203 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 16204 * to the same map). 16205 * However, if the old MAYBE_NULL register then got NULL checked, 16206 * doing so could have affected others with the same id, and we can't 16207 * check for that because we lost the id when we converted to 16208 * a non-MAYBE_NULL variant. 16209 * So, as a general rule we don't allow mixing MAYBE_NULL and 16210 * non-MAYBE_NULL registers as well. 16211 */ 16212 if (rold->type != rcur->type) 16213 return false; 16214 16215 switch (base_type(rold->type)) { 16216 case SCALAR_VALUE: 16217 if (env->explore_alu_limits) { 16218 /* explore_alu_limits disables tnum_in() and range_within() 16219 * logic and requires everything to be strict 16220 */ 16221 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16222 check_scalar_ids(rold->id, rcur->id, idmap); 16223 } 16224 if (!rold->precise) 16225 return true; 16226 /* Why check_ids() for scalar registers? 16227 * 16228 * Consider the following BPF code: 16229 * 1: r6 = ... unbound scalar, ID=a ... 16230 * 2: r7 = ... unbound scalar, ID=b ... 16231 * 3: if (r6 > r7) goto +1 16232 * 4: r6 = r7 16233 * 5: if (r6 > X) goto ... 16234 * 6: ... memory operation using r7 ... 16235 * 16236 * First verification path is [1-6]: 16237 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 16238 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark 16239 * r7 <= X, because r6 and r7 share same id. 16240 * Next verification path is [1-4, 6]. 16241 * 16242 * Instruction (6) would be reached in two states: 16243 * I. r6{.id=b}, r7{.id=b} via path 1-6; 16244 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 16245 * 16246 * Use check_ids() to distinguish these states. 16247 * --- 16248 * Also verify that new value satisfies old value range knowledge. 16249 */ 16250 return range_within(rold, rcur) && 16251 tnum_in(rold->var_off, rcur->var_off) && 16252 check_scalar_ids(rold->id, rcur->id, idmap); 16253 case PTR_TO_MAP_KEY: 16254 case PTR_TO_MAP_VALUE: 16255 case PTR_TO_MEM: 16256 case PTR_TO_BUF: 16257 case PTR_TO_TP_BUFFER: 16258 /* If the new min/max/var_off satisfy the old ones and 16259 * everything else matches, we are OK. 16260 */ 16261 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 16262 range_within(rold, rcur) && 16263 tnum_in(rold->var_off, rcur->var_off) && 16264 check_ids(rold->id, rcur->id, idmap) && 16265 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16266 case PTR_TO_PACKET_META: 16267 case PTR_TO_PACKET: 16268 /* We must have at least as much range as the old ptr 16269 * did, so that any accesses which were safe before are 16270 * still safe. This is true even if old range < old off, 16271 * since someone could have accessed through (ptr - k), or 16272 * even done ptr -= k in a register, to get a safe access. 16273 */ 16274 if (rold->range > rcur->range) 16275 return false; 16276 /* If the offsets don't match, we can't trust our alignment; 16277 * nor can we be sure that we won't fall out of range. 16278 */ 16279 if (rold->off != rcur->off) 16280 return false; 16281 /* id relations must be preserved */ 16282 if (!check_ids(rold->id, rcur->id, idmap)) 16283 return false; 16284 /* new val must satisfy old val knowledge */ 16285 return range_within(rold, rcur) && 16286 tnum_in(rold->var_off, rcur->var_off); 16287 case PTR_TO_STACK: 16288 /* two stack pointers are equal only if they're pointing to 16289 * the same stack frame, since fp-8 in foo != fp-8 in bar 16290 */ 16291 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 16292 default: 16293 return regs_exact(rold, rcur, idmap); 16294 } 16295 } 16296 16297 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 16298 struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact) 16299 { 16300 int i, spi; 16301 16302 /* walk slots of the explored stack and ignore any additional 16303 * slots in the current stack, since explored(safe) state 16304 * didn't use them 16305 */ 16306 for (i = 0; i < old->allocated_stack; i++) { 16307 struct bpf_reg_state *old_reg, *cur_reg; 16308 16309 spi = i / BPF_REG_SIZE; 16310 16311 if (exact && 16312 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16313 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16314 return false; 16315 16316 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) { 16317 i += BPF_REG_SIZE - 1; 16318 /* explored state didn't use this */ 16319 continue; 16320 } 16321 16322 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 16323 continue; 16324 16325 if (env->allow_uninit_stack && 16326 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 16327 continue; 16328 16329 /* explored stack has more populated slots than current stack 16330 * and these slots were used 16331 */ 16332 if (i >= cur->allocated_stack) 16333 return false; 16334 16335 /* if old state was safe with misc data in the stack 16336 * it will be safe with zero-initialized stack. 16337 * The opposite is not true 16338 */ 16339 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 16340 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 16341 continue; 16342 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16343 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16344 /* Ex: old explored (safe) state has STACK_SPILL in 16345 * this stack slot, but current has STACK_MISC -> 16346 * this verifier states are not equivalent, 16347 * return false to continue verification of this path 16348 */ 16349 return false; 16350 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 16351 continue; 16352 /* Both old and cur are having same slot_type */ 16353 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 16354 case STACK_SPILL: 16355 /* when explored and current stack slot are both storing 16356 * spilled registers, check that stored pointers types 16357 * are the same as well. 16358 * Ex: explored safe path could have stored 16359 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 16360 * but current path has stored: 16361 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 16362 * such verifier states are not equivalent. 16363 * return false to continue verification of this path 16364 */ 16365 if (!regsafe(env, &old->stack[spi].spilled_ptr, 16366 &cur->stack[spi].spilled_ptr, idmap, exact)) 16367 return false; 16368 break; 16369 case STACK_DYNPTR: 16370 old_reg = &old->stack[spi].spilled_ptr; 16371 cur_reg = &cur->stack[spi].spilled_ptr; 16372 if (old_reg->dynptr.type != cur_reg->dynptr.type || 16373 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 16374 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16375 return false; 16376 break; 16377 case STACK_ITER: 16378 old_reg = &old->stack[spi].spilled_ptr; 16379 cur_reg = &cur->stack[spi].spilled_ptr; 16380 /* iter.depth is not compared between states as it 16381 * doesn't matter for correctness and would otherwise 16382 * prevent convergence; we maintain it only to prevent 16383 * infinite loop check triggering, see 16384 * iter_active_depths_differ() 16385 */ 16386 if (old_reg->iter.btf != cur_reg->iter.btf || 16387 old_reg->iter.btf_id != cur_reg->iter.btf_id || 16388 old_reg->iter.state != cur_reg->iter.state || 16389 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 16390 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16391 return false; 16392 break; 16393 case STACK_MISC: 16394 case STACK_ZERO: 16395 case STACK_INVALID: 16396 continue; 16397 /* Ensure that new unhandled slot types return false by default */ 16398 default: 16399 return false; 16400 } 16401 } 16402 return true; 16403 } 16404 16405 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 16406 struct bpf_idmap *idmap) 16407 { 16408 int i; 16409 16410 if (old->acquired_refs != cur->acquired_refs) 16411 return false; 16412 16413 for (i = 0; i < old->acquired_refs; i++) { 16414 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 16415 return false; 16416 } 16417 16418 return true; 16419 } 16420 16421 /* compare two verifier states 16422 * 16423 * all states stored in state_list are known to be valid, since 16424 * verifier reached 'bpf_exit' instruction through them 16425 * 16426 * this function is called when verifier exploring different branches of 16427 * execution popped from the state stack. If it sees an old state that has 16428 * more strict register state and more strict stack state then this execution 16429 * branch doesn't need to be explored further, since verifier already 16430 * concluded that more strict state leads to valid finish. 16431 * 16432 * Therefore two states are equivalent if register state is more conservative 16433 * and explored stack state is more conservative than the current one. 16434 * Example: 16435 * explored current 16436 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 16437 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 16438 * 16439 * In other words if current stack state (one being explored) has more 16440 * valid slots than old one that already passed validation, it means 16441 * the verifier can stop exploring and conclude that current state is valid too 16442 * 16443 * Similarly with registers. If explored state has register type as invalid 16444 * whereas register type in current state is meaningful, it means that 16445 * the current state will reach 'bpf_exit' instruction safely 16446 */ 16447 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 16448 struct bpf_func_state *cur, bool exact) 16449 { 16450 int i; 16451 16452 for (i = 0; i < MAX_BPF_REG; i++) 16453 if (!regsafe(env, &old->regs[i], &cur->regs[i], 16454 &env->idmap_scratch, exact)) 16455 return false; 16456 16457 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 16458 return false; 16459 16460 if (!refsafe(old, cur, &env->idmap_scratch)) 16461 return false; 16462 16463 return true; 16464 } 16465 16466 static void reset_idmap_scratch(struct bpf_verifier_env *env) 16467 { 16468 env->idmap_scratch.tmp_id_gen = env->id_gen; 16469 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 16470 } 16471 16472 static bool states_equal(struct bpf_verifier_env *env, 16473 struct bpf_verifier_state *old, 16474 struct bpf_verifier_state *cur, 16475 bool exact) 16476 { 16477 int i; 16478 16479 if (old->curframe != cur->curframe) 16480 return false; 16481 16482 reset_idmap_scratch(env); 16483 16484 /* Verification state from speculative execution simulation 16485 * must never prune a non-speculative execution one. 16486 */ 16487 if (old->speculative && !cur->speculative) 16488 return false; 16489 16490 if (old->active_lock.ptr != cur->active_lock.ptr) 16491 return false; 16492 16493 /* Old and cur active_lock's have to be either both present 16494 * or both absent. 16495 */ 16496 if (!!old->active_lock.id != !!cur->active_lock.id) 16497 return false; 16498 16499 if (old->active_lock.id && 16500 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch)) 16501 return false; 16502 16503 if (old->active_rcu_lock != cur->active_rcu_lock) 16504 return false; 16505 16506 /* for states to be equal callsites have to be the same 16507 * and all frame states need to be equivalent 16508 */ 16509 for (i = 0; i <= old->curframe; i++) { 16510 if (old->frame[i]->callsite != cur->frame[i]->callsite) 16511 return false; 16512 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact)) 16513 return false; 16514 } 16515 return true; 16516 } 16517 16518 /* Return 0 if no propagation happened. Return negative error code if error 16519 * happened. Otherwise, return the propagated bit. 16520 */ 16521 static int propagate_liveness_reg(struct bpf_verifier_env *env, 16522 struct bpf_reg_state *reg, 16523 struct bpf_reg_state *parent_reg) 16524 { 16525 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 16526 u8 flag = reg->live & REG_LIVE_READ; 16527 int err; 16528 16529 /* When comes here, read flags of PARENT_REG or REG could be any of 16530 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 16531 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 16532 */ 16533 if (parent_flag == REG_LIVE_READ64 || 16534 /* Or if there is no read flag from REG. */ 16535 !flag || 16536 /* Or if the read flag from REG is the same as PARENT_REG. */ 16537 parent_flag == flag) 16538 return 0; 16539 16540 err = mark_reg_read(env, reg, parent_reg, flag); 16541 if (err) 16542 return err; 16543 16544 return flag; 16545 } 16546 16547 /* A write screens off any subsequent reads; but write marks come from the 16548 * straight-line code between a state and its parent. When we arrive at an 16549 * equivalent state (jump target or such) we didn't arrive by the straight-line 16550 * code, so read marks in the state must propagate to the parent regardless 16551 * of the state's write marks. That's what 'parent == state->parent' comparison 16552 * in mark_reg_read() is for. 16553 */ 16554 static int propagate_liveness(struct bpf_verifier_env *env, 16555 const struct bpf_verifier_state *vstate, 16556 struct bpf_verifier_state *vparent) 16557 { 16558 struct bpf_reg_state *state_reg, *parent_reg; 16559 struct bpf_func_state *state, *parent; 16560 int i, frame, err = 0; 16561 16562 if (vparent->curframe != vstate->curframe) { 16563 WARN(1, "propagate_live: parent frame %d current frame %d\n", 16564 vparent->curframe, vstate->curframe); 16565 return -EFAULT; 16566 } 16567 /* Propagate read liveness of registers... */ 16568 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 16569 for (frame = 0; frame <= vstate->curframe; frame++) { 16570 parent = vparent->frame[frame]; 16571 state = vstate->frame[frame]; 16572 parent_reg = parent->regs; 16573 state_reg = state->regs; 16574 /* We don't need to worry about FP liveness, it's read-only */ 16575 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 16576 err = propagate_liveness_reg(env, &state_reg[i], 16577 &parent_reg[i]); 16578 if (err < 0) 16579 return err; 16580 if (err == REG_LIVE_READ64) 16581 mark_insn_zext(env, &parent_reg[i]); 16582 } 16583 16584 /* Propagate stack slots. */ 16585 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 16586 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 16587 parent_reg = &parent->stack[i].spilled_ptr; 16588 state_reg = &state->stack[i].spilled_ptr; 16589 err = propagate_liveness_reg(env, state_reg, 16590 parent_reg); 16591 if (err < 0) 16592 return err; 16593 } 16594 } 16595 return 0; 16596 } 16597 16598 /* find precise scalars in the previous equivalent state and 16599 * propagate them into the current state 16600 */ 16601 static int propagate_precision(struct bpf_verifier_env *env, 16602 const struct bpf_verifier_state *old) 16603 { 16604 struct bpf_reg_state *state_reg; 16605 struct bpf_func_state *state; 16606 int i, err = 0, fr; 16607 bool first; 16608 16609 for (fr = old->curframe; fr >= 0; fr--) { 16610 state = old->frame[fr]; 16611 state_reg = state->regs; 16612 first = true; 16613 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 16614 if (state_reg->type != SCALAR_VALUE || 16615 !state_reg->precise || 16616 !(state_reg->live & REG_LIVE_READ)) 16617 continue; 16618 if (env->log.level & BPF_LOG_LEVEL2) { 16619 if (first) 16620 verbose(env, "frame %d: propagating r%d", fr, i); 16621 else 16622 verbose(env, ",r%d", i); 16623 } 16624 bt_set_frame_reg(&env->bt, fr, i); 16625 first = false; 16626 } 16627 16628 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16629 if (!is_spilled_reg(&state->stack[i])) 16630 continue; 16631 state_reg = &state->stack[i].spilled_ptr; 16632 if (state_reg->type != SCALAR_VALUE || 16633 !state_reg->precise || 16634 !(state_reg->live & REG_LIVE_READ)) 16635 continue; 16636 if (env->log.level & BPF_LOG_LEVEL2) { 16637 if (first) 16638 verbose(env, "frame %d: propagating fp%d", 16639 fr, (-i - 1) * BPF_REG_SIZE); 16640 else 16641 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 16642 } 16643 bt_set_frame_slot(&env->bt, fr, i); 16644 first = false; 16645 } 16646 if (!first) 16647 verbose(env, "\n"); 16648 } 16649 16650 err = mark_chain_precision_batch(env); 16651 if (err < 0) 16652 return err; 16653 16654 return 0; 16655 } 16656 16657 static bool states_maybe_looping(struct bpf_verifier_state *old, 16658 struct bpf_verifier_state *cur) 16659 { 16660 struct bpf_func_state *fold, *fcur; 16661 int i, fr = cur->curframe; 16662 16663 if (old->curframe != fr) 16664 return false; 16665 16666 fold = old->frame[fr]; 16667 fcur = cur->frame[fr]; 16668 for (i = 0; i < MAX_BPF_REG; i++) 16669 if (memcmp(&fold->regs[i], &fcur->regs[i], 16670 offsetof(struct bpf_reg_state, parent))) 16671 return false; 16672 return true; 16673 } 16674 16675 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 16676 { 16677 return env->insn_aux_data[insn_idx].is_iter_next; 16678 } 16679 16680 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 16681 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 16682 * states to match, which otherwise would look like an infinite loop. So while 16683 * iter_next() calls are taken care of, we still need to be careful and 16684 * prevent erroneous and too eager declaration of "ininite loop", when 16685 * iterators are involved. 16686 * 16687 * Here's a situation in pseudo-BPF assembly form: 16688 * 16689 * 0: again: ; set up iter_next() call args 16690 * 1: r1 = &it ; <CHECKPOINT HERE> 16691 * 2: call bpf_iter_num_next ; this is iter_next() call 16692 * 3: if r0 == 0 goto done 16693 * 4: ... something useful here ... 16694 * 5: goto again ; another iteration 16695 * 6: done: 16696 * 7: r1 = &it 16697 * 8: call bpf_iter_num_destroy ; clean up iter state 16698 * 9: exit 16699 * 16700 * This is a typical loop. Let's assume that we have a prune point at 1:, 16701 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 16702 * again`, assuming other heuristics don't get in a way). 16703 * 16704 * When we first time come to 1:, let's say we have some state X. We proceed 16705 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 16706 * Now we come back to validate that forked ACTIVE state. We proceed through 16707 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 16708 * are converging. But the problem is that we don't know that yet, as this 16709 * convergence has to happen at iter_next() call site only. So if nothing is 16710 * done, at 1: verifier will use bounded loop logic and declare infinite 16711 * looping (and would be *technically* correct, if not for iterator's 16712 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 16713 * don't want that. So what we do in process_iter_next_call() when we go on 16714 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 16715 * a different iteration. So when we suspect an infinite loop, we additionally 16716 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 16717 * pretend we are not looping and wait for next iter_next() call. 16718 * 16719 * This only applies to ACTIVE state. In DRAINED state we don't expect to 16720 * loop, because that would actually mean infinite loop, as DRAINED state is 16721 * "sticky", and so we'll keep returning into the same instruction with the 16722 * same state (at least in one of possible code paths). 16723 * 16724 * This approach allows to keep infinite loop heuristic even in the face of 16725 * active iterator. E.g., C snippet below is and will be detected as 16726 * inifintely looping: 16727 * 16728 * struct bpf_iter_num it; 16729 * int *p, x; 16730 * 16731 * bpf_iter_num_new(&it, 0, 10); 16732 * while ((p = bpf_iter_num_next(&t))) { 16733 * x = p; 16734 * while (x--) {} // <<-- infinite loop here 16735 * } 16736 * 16737 */ 16738 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 16739 { 16740 struct bpf_reg_state *slot, *cur_slot; 16741 struct bpf_func_state *state; 16742 int i, fr; 16743 16744 for (fr = old->curframe; fr >= 0; fr--) { 16745 state = old->frame[fr]; 16746 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 16747 if (state->stack[i].slot_type[0] != STACK_ITER) 16748 continue; 16749 16750 slot = &state->stack[i].spilled_ptr; 16751 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 16752 continue; 16753 16754 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 16755 if (cur_slot->iter.depth != slot->iter.depth) 16756 return true; 16757 } 16758 } 16759 return false; 16760 } 16761 16762 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 16763 { 16764 struct bpf_verifier_state_list *new_sl; 16765 struct bpf_verifier_state_list *sl, **pprev; 16766 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry; 16767 int i, j, n, err, states_cnt = 0; 16768 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx); 16769 bool add_new_state = force_new_state; 16770 bool force_exact; 16771 16772 /* bpf progs typically have pruning point every 4 instructions 16773 * http://vger.kernel.org/bpfconf2019.html#session-1 16774 * Do not add new state for future pruning if the verifier hasn't seen 16775 * at least 2 jumps and at least 8 instructions. 16776 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 16777 * In tests that amounts to up to 50% reduction into total verifier 16778 * memory consumption and 20% verifier time speedup. 16779 */ 16780 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 16781 env->insn_processed - env->prev_insn_processed >= 8) 16782 add_new_state = true; 16783 16784 pprev = explored_state(env, insn_idx); 16785 sl = *pprev; 16786 16787 clean_live_states(env, insn_idx, cur); 16788 16789 while (sl) { 16790 states_cnt++; 16791 if (sl->state.insn_idx != insn_idx) 16792 goto next; 16793 16794 if (sl->state.branches) { 16795 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 16796 16797 if (frame->in_async_callback_fn && 16798 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 16799 /* Different async_entry_cnt means that the verifier is 16800 * processing another entry into async callback. 16801 * Seeing the same state is not an indication of infinite 16802 * loop or infinite recursion. 16803 * But finding the same state doesn't mean that it's safe 16804 * to stop processing the current state. The previous state 16805 * hasn't yet reached bpf_exit, since state.branches > 0. 16806 * Checking in_async_callback_fn alone is not enough either. 16807 * Since the verifier still needs to catch infinite loops 16808 * inside async callbacks. 16809 */ 16810 goto skip_inf_loop_check; 16811 } 16812 /* BPF open-coded iterators loop detection is special. 16813 * states_maybe_looping() logic is too simplistic in detecting 16814 * states that *might* be equivalent, because it doesn't know 16815 * about ID remapping, so don't even perform it. 16816 * See process_iter_next_call() and iter_active_depths_differ() 16817 * for overview of the logic. When current and one of parent 16818 * states are detected as equivalent, it's a good thing: we prove 16819 * convergence and can stop simulating further iterations. 16820 * It's safe to assume that iterator loop will finish, taking into 16821 * account iter_next() contract of eventually returning 16822 * sticky NULL result. 16823 * 16824 * Note, that states have to be compared exactly in this case because 16825 * read and precision marks might not be finalized inside the loop. 16826 * E.g. as in the program below: 16827 * 16828 * 1. r7 = -16 16829 * 2. r6 = bpf_get_prandom_u32() 16830 * 3. while (bpf_iter_num_next(&fp[-8])) { 16831 * 4. if (r6 != 42) { 16832 * 5. r7 = -32 16833 * 6. r6 = bpf_get_prandom_u32() 16834 * 7. continue 16835 * 8. } 16836 * 9. r0 = r10 16837 * 10. r0 += r7 16838 * 11. r8 = *(u64 *)(r0 + 0) 16839 * 12. r6 = bpf_get_prandom_u32() 16840 * 13. } 16841 * 16842 * Here verifier would first visit path 1-3, create a checkpoint at 3 16843 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 16844 * not have read or precision mark for r7 yet, thus inexact states 16845 * comparison would discard current state with r7=-32 16846 * => unsafe memory access at 11 would not be caught. 16847 */ 16848 if (is_iter_next_insn(env, insn_idx)) { 16849 if (states_equal(env, &sl->state, cur, true)) { 16850 struct bpf_func_state *cur_frame; 16851 struct bpf_reg_state *iter_state, *iter_reg; 16852 int spi; 16853 16854 cur_frame = cur->frame[cur->curframe]; 16855 /* btf_check_iter_kfuncs() enforces that 16856 * iter state pointer is always the first arg 16857 */ 16858 iter_reg = &cur_frame->regs[BPF_REG_1]; 16859 /* current state is valid due to states_equal(), 16860 * so we can assume valid iter and reg state, 16861 * no need for extra (re-)validations 16862 */ 16863 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 16864 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 16865 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 16866 update_loop_entry(cur, &sl->state); 16867 goto hit; 16868 } 16869 } 16870 goto skip_inf_loop_check; 16871 } 16872 if (calls_callback(env, insn_idx)) { 16873 if (states_equal(env, &sl->state, cur, true)) 16874 goto hit; 16875 goto skip_inf_loop_check; 16876 } 16877 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 16878 if (states_maybe_looping(&sl->state, cur) && 16879 states_equal(env, &sl->state, cur, false) && 16880 !iter_active_depths_differ(&sl->state, cur) && 16881 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 16882 verbose_linfo(env, insn_idx, "; "); 16883 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 16884 verbose(env, "cur state:"); 16885 print_verifier_state(env, cur->frame[cur->curframe], true); 16886 verbose(env, "old state:"); 16887 print_verifier_state(env, sl->state.frame[cur->curframe], true); 16888 return -EINVAL; 16889 } 16890 /* if the verifier is processing a loop, avoid adding new state 16891 * too often, since different loop iterations have distinct 16892 * states and may not help future pruning. 16893 * This threshold shouldn't be too low to make sure that 16894 * a loop with large bound will be rejected quickly. 16895 * The most abusive loop will be: 16896 * r1 += 1 16897 * if r1 < 1000000 goto pc-2 16898 * 1M insn_procssed limit / 100 == 10k peak states. 16899 * This threshold shouldn't be too high either, since states 16900 * at the end of the loop are likely to be useful in pruning. 16901 */ 16902 skip_inf_loop_check: 16903 if (!force_new_state && 16904 env->jmps_processed - env->prev_jmps_processed < 20 && 16905 env->insn_processed - env->prev_insn_processed < 100) 16906 add_new_state = false; 16907 goto miss; 16908 } 16909 /* If sl->state is a part of a loop and this loop's entry is a part of 16910 * current verification path then states have to be compared exactly. 16911 * 'force_exact' is needed to catch the following case: 16912 * 16913 * initial Here state 'succ' was processed first, 16914 * | it was eventually tracked to produce a 16915 * V state identical to 'hdr'. 16916 * .---------> hdr All branches from 'succ' had been explored 16917 * | | and thus 'succ' has its .branches == 0. 16918 * | V 16919 * | .------... Suppose states 'cur' and 'succ' correspond 16920 * | | | to the same instruction + callsites. 16921 * | V V In such case it is necessary to check 16922 * | ... ... if 'succ' and 'cur' are states_equal(). 16923 * | | | If 'succ' and 'cur' are a part of the 16924 * | V V same loop exact flag has to be set. 16925 * | succ <- cur To check if that is the case, verify 16926 * | | if loop entry of 'succ' is in current 16927 * | V DFS path. 16928 * | ... 16929 * | | 16930 * '----' 16931 * 16932 * Additional details are in the comment before get_loop_entry(). 16933 */ 16934 loop_entry = get_loop_entry(&sl->state); 16935 force_exact = loop_entry && loop_entry->branches > 0; 16936 if (states_equal(env, &sl->state, cur, force_exact)) { 16937 if (force_exact) 16938 update_loop_entry(cur, loop_entry); 16939 hit: 16940 sl->hit_cnt++; 16941 /* reached equivalent register/stack state, 16942 * prune the search. 16943 * Registers read by the continuation are read by us. 16944 * If we have any write marks in env->cur_state, they 16945 * will prevent corresponding reads in the continuation 16946 * from reaching our parent (an explored_state). Our 16947 * own state will get the read marks recorded, but 16948 * they'll be immediately forgotten as we're pruning 16949 * this state and will pop a new one. 16950 */ 16951 err = propagate_liveness(env, &sl->state, cur); 16952 16953 /* if previous state reached the exit with precision and 16954 * current state is equivalent to it (except precsion marks) 16955 * the precision needs to be propagated back in 16956 * the current state. 16957 */ 16958 if (is_jmp_point(env, env->insn_idx)) 16959 err = err ? : push_jmp_history(env, cur, 0); 16960 err = err ? : propagate_precision(env, &sl->state); 16961 if (err) 16962 return err; 16963 return 1; 16964 } 16965 miss: 16966 /* when new state is not going to be added do not increase miss count. 16967 * Otherwise several loop iterations will remove the state 16968 * recorded earlier. The goal of these heuristics is to have 16969 * states from some iterations of the loop (some in the beginning 16970 * and some at the end) to help pruning. 16971 */ 16972 if (add_new_state) 16973 sl->miss_cnt++; 16974 /* heuristic to determine whether this state is beneficial 16975 * to keep checking from state equivalence point of view. 16976 * Higher numbers increase max_states_per_insn and verification time, 16977 * but do not meaningfully decrease insn_processed. 16978 * 'n' controls how many times state could miss before eviction. 16979 * Use bigger 'n' for checkpoints because evicting checkpoint states 16980 * too early would hinder iterator convergence. 16981 */ 16982 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 16983 if (sl->miss_cnt > sl->hit_cnt * n + n) { 16984 /* the state is unlikely to be useful. Remove it to 16985 * speed up verification 16986 */ 16987 *pprev = sl->next; 16988 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE && 16989 !sl->state.used_as_loop_entry) { 16990 u32 br = sl->state.branches; 16991 16992 WARN_ONCE(br, 16993 "BUG live_done but branches_to_explore %d\n", 16994 br); 16995 free_verifier_state(&sl->state, false); 16996 kfree(sl); 16997 env->peak_states--; 16998 } else { 16999 /* cannot free this state, since parentage chain may 17000 * walk it later. Add it for free_list instead to 17001 * be freed at the end of verification 17002 */ 17003 sl->next = env->free_list; 17004 env->free_list = sl; 17005 } 17006 sl = *pprev; 17007 continue; 17008 } 17009 next: 17010 pprev = &sl->next; 17011 sl = *pprev; 17012 } 17013 17014 if (env->max_states_per_insn < states_cnt) 17015 env->max_states_per_insn = states_cnt; 17016 17017 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 17018 return 0; 17019 17020 if (!add_new_state) 17021 return 0; 17022 17023 /* There were no equivalent states, remember the current one. 17024 * Technically the current state is not proven to be safe yet, 17025 * but it will either reach outer most bpf_exit (which means it's safe) 17026 * or it will be rejected. When there are no loops the verifier won't be 17027 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 17028 * again on the way to bpf_exit. 17029 * When looping the sl->state.branches will be > 0 and this state 17030 * will not be considered for equivalence until branches == 0. 17031 */ 17032 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 17033 if (!new_sl) 17034 return -ENOMEM; 17035 env->total_states++; 17036 env->peak_states++; 17037 env->prev_jmps_processed = env->jmps_processed; 17038 env->prev_insn_processed = env->insn_processed; 17039 17040 /* forget precise markings we inherited, see __mark_chain_precision */ 17041 if (env->bpf_capable) 17042 mark_all_scalars_imprecise(env, cur); 17043 17044 /* add new state to the head of linked list */ 17045 new = &new_sl->state; 17046 err = copy_verifier_state(new, cur); 17047 if (err) { 17048 free_verifier_state(new, false); 17049 kfree(new_sl); 17050 return err; 17051 } 17052 new->insn_idx = insn_idx; 17053 WARN_ONCE(new->branches != 1, 17054 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 17055 17056 cur->parent = new; 17057 cur->first_insn_idx = insn_idx; 17058 cur->dfs_depth = new->dfs_depth + 1; 17059 clear_jmp_history(cur); 17060 new_sl->next = *explored_state(env, insn_idx); 17061 *explored_state(env, insn_idx) = new_sl; 17062 /* connect new state to parentage chain. Current frame needs all 17063 * registers connected. Only r6 - r9 of the callers are alive (pushed 17064 * to the stack implicitly by JITs) so in callers' frames connect just 17065 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 17066 * the state of the call instruction (with WRITTEN set), and r0 comes 17067 * from callee with its full parentage chain, anyway. 17068 */ 17069 /* clear write marks in current state: the writes we did are not writes 17070 * our child did, so they don't screen off its reads from us. 17071 * (There are no read marks in current state, because reads always mark 17072 * their parent and current state never has children yet. Only 17073 * explored_states can get read marks.) 17074 */ 17075 for (j = 0; j <= cur->curframe; j++) { 17076 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 17077 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 17078 for (i = 0; i < BPF_REG_FP; i++) 17079 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 17080 } 17081 17082 /* all stack frames are accessible from callee, clear them all */ 17083 for (j = 0; j <= cur->curframe; j++) { 17084 struct bpf_func_state *frame = cur->frame[j]; 17085 struct bpf_func_state *newframe = new->frame[j]; 17086 17087 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 17088 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 17089 frame->stack[i].spilled_ptr.parent = 17090 &newframe->stack[i].spilled_ptr; 17091 } 17092 } 17093 return 0; 17094 } 17095 17096 /* Return true if it's OK to have the same insn return a different type. */ 17097 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 17098 { 17099 switch (base_type(type)) { 17100 case PTR_TO_CTX: 17101 case PTR_TO_SOCKET: 17102 case PTR_TO_SOCK_COMMON: 17103 case PTR_TO_TCP_SOCK: 17104 case PTR_TO_XDP_SOCK: 17105 case PTR_TO_BTF_ID: 17106 return false; 17107 default: 17108 return true; 17109 } 17110 } 17111 17112 /* If an instruction was previously used with particular pointer types, then we 17113 * need to be careful to avoid cases such as the below, where it may be ok 17114 * for one branch accessing the pointer, but not ok for the other branch: 17115 * 17116 * R1 = sock_ptr 17117 * goto X; 17118 * ... 17119 * R1 = some_other_valid_ptr; 17120 * goto X; 17121 * ... 17122 * R2 = *(u32 *)(R1 + 0); 17123 */ 17124 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 17125 { 17126 return src != prev && (!reg_type_mismatch_ok(src) || 17127 !reg_type_mismatch_ok(prev)); 17128 } 17129 17130 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 17131 bool allow_trust_missmatch) 17132 { 17133 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 17134 17135 if (*prev_type == NOT_INIT) { 17136 /* Saw a valid insn 17137 * dst_reg = *(u32 *)(src_reg + off) 17138 * save type to validate intersecting paths 17139 */ 17140 *prev_type = type; 17141 } else if (reg_type_mismatch(type, *prev_type)) { 17142 /* Abuser program is trying to use the same insn 17143 * dst_reg = *(u32*) (src_reg + off) 17144 * with different pointer types: 17145 * src_reg == ctx in one branch and 17146 * src_reg == stack|map in some other branch. 17147 * Reject it. 17148 */ 17149 if (allow_trust_missmatch && 17150 base_type(type) == PTR_TO_BTF_ID && 17151 base_type(*prev_type) == PTR_TO_BTF_ID) { 17152 /* 17153 * Have to support a use case when one path through 17154 * the program yields TRUSTED pointer while another 17155 * is UNTRUSTED. Fallback to UNTRUSTED to generate 17156 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 17157 */ 17158 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 17159 } else { 17160 verbose(env, "same insn cannot be used with different pointers\n"); 17161 return -EINVAL; 17162 } 17163 } 17164 17165 return 0; 17166 } 17167 17168 static int do_check(struct bpf_verifier_env *env) 17169 { 17170 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17171 struct bpf_verifier_state *state = env->cur_state; 17172 struct bpf_insn *insns = env->prog->insnsi; 17173 struct bpf_reg_state *regs; 17174 int insn_cnt = env->prog->len; 17175 bool do_print_state = false; 17176 int prev_insn_idx = -1; 17177 17178 for (;;) { 17179 bool exception_exit = false; 17180 struct bpf_insn *insn; 17181 u8 class; 17182 int err; 17183 17184 /* reset current history entry on each new instruction */ 17185 env->cur_hist_ent = NULL; 17186 17187 env->prev_insn_idx = prev_insn_idx; 17188 if (env->insn_idx >= insn_cnt) { 17189 verbose(env, "invalid insn idx %d insn_cnt %d\n", 17190 env->insn_idx, insn_cnt); 17191 return -EFAULT; 17192 } 17193 17194 insn = &insns[env->insn_idx]; 17195 class = BPF_CLASS(insn->code); 17196 17197 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 17198 verbose(env, 17199 "BPF program is too large. Processed %d insn\n", 17200 env->insn_processed); 17201 return -E2BIG; 17202 } 17203 17204 state->last_insn_idx = env->prev_insn_idx; 17205 17206 if (is_prune_point(env, env->insn_idx)) { 17207 err = is_state_visited(env, env->insn_idx); 17208 if (err < 0) 17209 return err; 17210 if (err == 1) { 17211 /* found equivalent state, can prune the search */ 17212 if (env->log.level & BPF_LOG_LEVEL) { 17213 if (do_print_state) 17214 verbose(env, "\nfrom %d to %d%s: safe\n", 17215 env->prev_insn_idx, env->insn_idx, 17216 env->cur_state->speculative ? 17217 " (speculative execution)" : ""); 17218 else 17219 verbose(env, "%d: safe\n", env->insn_idx); 17220 } 17221 goto process_bpf_exit; 17222 } 17223 } 17224 17225 if (is_jmp_point(env, env->insn_idx)) { 17226 err = push_jmp_history(env, state, 0); 17227 if (err) 17228 return err; 17229 } 17230 17231 if (signal_pending(current)) 17232 return -EAGAIN; 17233 17234 if (need_resched()) 17235 cond_resched(); 17236 17237 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17238 verbose(env, "\nfrom %d to %d%s:", 17239 env->prev_insn_idx, env->insn_idx, 17240 env->cur_state->speculative ? 17241 " (speculative execution)" : ""); 17242 print_verifier_state(env, state->frame[state->curframe], true); 17243 do_print_state = false; 17244 } 17245 17246 if (env->log.level & BPF_LOG_LEVEL) { 17247 const struct bpf_insn_cbs cbs = { 17248 .cb_call = disasm_kfunc_name, 17249 .cb_print = verbose, 17250 .private_data = env, 17251 }; 17252 17253 if (verifier_state_scratched(env)) 17254 print_insn_state(env, state->frame[state->curframe]); 17255 17256 verbose_linfo(env, env->insn_idx, "; "); 17257 env->prev_log_pos = env->log.end_pos; 17258 verbose(env, "%d: ", env->insn_idx); 17259 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 17260 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17261 env->prev_log_pos = env->log.end_pos; 17262 } 17263 17264 if (bpf_prog_is_offloaded(env->prog->aux)) { 17265 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17266 env->prev_insn_idx); 17267 if (err) 17268 return err; 17269 } 17270 17271 regs = cur_regs(env); 17272 sanitize_mark_insn_seen(env); 17273 prev_insn_idx = env->insn_idx; 17274 17275 if (class == BPF_ALU || class == BPF_ALU64) { 17276 err = check_alu_op(env, insn); 17277 if (err) 17278 return err; 17279 17280 } else if (class == BPF_LDX) { 17281 enum bpf_reg_type src_reg_type; 17282 17283 /* check for reserved fields is already done */ 17284 17285 /* check src operand */ 17286 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17287 if (err) 17288 return err; 17289 17290 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 17291 if (err) 17292 return err; 17293 17294 src_reg_type = regs[insn->src_reg].type; 17295 17296 /* check that memory (src_reg + off) is readable, 17297 * the state of dst_reg will be updated by this func 17298 */ 17299 err = check_mem_access(env, env->insn_idx, insn->src_reg, 17300 insn->off, BPF_SIZE(insn->code), 17301 BPF_READ, insn->dst_reg, false, 17302 BPF_MODE(insn->code) == BPF_MEMSX); 17303 err = err ?: save_aux_ptr_type(env, src_reg_type, true); 17304 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], "ldx"); 17305 if (err) 17306 return err; 17307 } else if (class == BPF_STX) { 17308 enum bpf_reg_type dst_reg_type; 17309 17310 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 17311 err = check_atomic(env, env->insn_idx, insn); 17312 if (err) 17313 return err; 17314 env->insn_idx++; 17315 continue; 17316 } 17317 17318 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 17319 verbose(env, "BPF_STX uses reserved fields\n"); 17320 return -EINVAL; 17321 } 17322 17323 /* check src1 operand */ 17324 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17325 if (err) 17326 return err; 17327 /* check src2 operand */ 17328 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17329 if (err) 17330 return err; 17331 17332 dst_reg_type = regs[insn->dst_reg].type; 17333 17334 /* check that memory (dst_reg + off) is writeable */ 17335 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17336 insn->off, BPF_SIZE(insn->code), 17337 BPF_WRITE, insn->src_reg, false, false); 17338 if (err) 17339 return err; 17340 17341 err = save_aux_ptr_type(env, dst_reg_type, false); 17342 if (err) 17343 return err; 17344 } else if (class == BPF_ST) { 17345 enum bpf_reg_type dst_reg_type; 17346 17347 if (BPF_MODE(insn->code) != BPF_MEM || 17348 insn->src_reg != BPF_REG_0) { 17349 verbose(env, "BPF_ST uses reserved fields\n"); 17350 return -EINVAL; 17351 } 17352 /* check src operand */ 17353 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17354 if (err) 17355 return err; 17356 17357 dst_reg_type = regs[insn->dst_reg].type; 17358 17359 /* check that memory (dst_reg + off) is writeable */ 17360 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17361 insn->off, BPF_SIZE(insn->code), 17362 BPF_WRITE, -1, false, false); 17363 if (err) 17364 return err; 17365 17366 err = save_aux_ptr_type(env, dst_reg_type, false); 17367 if (err) 17368 return err; 17369 } else if (class == BPF_JMP || class == BPF_JMP32) { 17370 u8 opcode = BPF_OP(insn->code); 17371 17372 env->jmps_processed++; 17373 if (opcode == BPF_CALL) { 17374 if (BPF_SRC(insn->code) != BPF_K || 17375 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 17376 && insn->off != 0) || 17377 (insn->src_reg != BPF_REG_0 && 17378 insn->src_reg != BPF_PSEUDO_CALL && 17379 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 17380 insn->dst_reg != BPF_REG_0 || 17381 class == BPF_JMP32) { 17382 verbose(env, "BPF_CALL uses reserved fields\n"); 17383 return -EINVAL; 17384 } 17385 17386 if (env->cur_state->active_lock.ptr) { 17387 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 17388 (insn->src_reg == BPF_PSEUDO_CALL) || 17389 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17390 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 17391 verbose(env, "function calls are not allowed while holding a lock\n"); 17392 return -EINVAL; 17393 } 17394 } 17395 if (insn->src_reg == BPF_PSEUDO_CALL) { 17396 err = check_func_call(env, insn, &env->insn_idx); 17397 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 17398 err = check_kfunc_call(env, insn, &env->insn_idx); 17399 if (!err && is_bpf_throw_kfunc(insn)) { 17400 exception_exit = true; 17401 goto process_bpf_exit_full; 17402 } 17403 } else { 17404 err = check_helper_call(env, insn, &env->insn_idx); 17405 } 17406 if (err) 17407 return err; 17408 17409 mark_reg_scratched(env, BPF_REG_0); 17410 } else if (opcode == BPF_JA) { 17411 if (BPF_SRC(insn->code) != BPF_K || 17412 insn->src_reg != BPF_REG_0 || 17413 insn->dst_reg != BPF_REG_0 || 17414 (class == BPF_JMP && insn->imm != 0) || 17415 (class == BPF_JMP32 && insn->off != 0)) { 17416 verbose(env, "BPF_JA uses reserved fields\n"); 17417 return -EINVAL; 17418 } 17419 17420 if (class == BPF_JMP) 17421 env->insn_idx += insn->off + 1; 17422 else 17423 env->insn_idx += insn->imm + 1; 17424 continue; 17425 17426 } else if (opcode == BPF_EXIT) { 17427 if (BPF_SRC(insn->code) != BPF_K || 17428 insn->imm != 0 || 17429 insn->src_reg != BPF_REG_0 || 17430 insn->dst_reg != BPF_REG_0 || 17431 class == BPF_JMP32) { 17432 verbose(env, "BPF_EXIT uses reserved fields\n"); 17433 return -EINVAL; 17434 } 17435 process_bpf_exit_full: 17436 if (env->cur_state->active_lock.ptr && 17437 !in_rbtree_lock_required_cb(env)) { 17438 verbose(env, "bpf_spin_unlock is missing\n"); 17439 return -EINVAL; 17440 } 17441 17442 if (env->cur_state->active_rcu_lock && 17443 !in_rbtree_lock_required_cb(env)) { 17444 verbose(env, "bpf_rcu_read_unlock is missing\n"); 17445 return -EINVAL; 17446 } 17447 17448 /* We must do check_reference_leak here before 17449 * prepare_func_exit to handle the case when 17450 * state->curframe > 0, it may be a callback 17451 * function, for which reference_state must 17452 * match caller reference state when it exits. 17453 */ 17454 err = check_reference_leak(env, exception_exit); 17455 if (err) 17456 return err; 17457 17458 /* The side effect of the prepare_func_exit 17459 * which is being skipped is that it frees 17460 * bpf_func_state. Typically, process_bpf_exit 17461 * will only be hit with outermost exit. 17462 * copy_verifier_state in pop_stack will handle 17463 * freeing of any extra bpf_func_state left over 17464 * from not processing all nested function 17465 * exits. We also skip return code checks as 17466 * they are not needed for exceptional exits. 17467 */ 17468 if (exception_exit) 17469 goto process_bpf_exit; 17470 17471 if (state->curframe) { 17472 /* exit from nested function */ 17473 err = prepare_func_exit(env, &env->insn_idx); 17474 if (err) 17475 return err; 17476 do_print_state = true; 17477 continue; 17478 } 17479 17480 err = check_return_code(env, BPF_REG_0, "R0"); 17481 if (err) 17482 return err; 17483 process_bpf_exit: 17484 mark_verifier_state_scratched(env); 17485 update_branch_counts(env, env->cur_state); 17486 err = pop_stack(env, &prev_insn_idx, 17487 &env->insn_idx, pop_log); 17488 if (err < 0) { 17489 if (err != -ENOENT) 17490 return err; 17491 break; 17492 } else { 17493 do_print_state = true; 17494 continue; 17495 } 17496 } else { 17497 err = check_cond_jmp_op(env, insn, &env->insn_idx); 17498 if (err) 17499 return err; 17500 } 17501 } else if (class == BPF_LD) { 17502 u8 mode = BPF_MODE(insn->code); 17503 17504 if (mode == BPF_ABS || mode == BPF_IND) { 17505 err = check_ld_abs(env, insn); 17506 if (err) 17507 return err; 17508 17509 } else if (mode == BPF_IMM) { 17510 err = check_ld_imm(env, insn); 17511 if (err) 17512 return err; 17513 17514 env->insn_idx++; 17515 sanitize_mark_insn_seen(env); 17516 } else { 17517 verbose(env, "invalid BPF_LD mode\n"); 17518 return -EINVAL; 17519 } 17520 } else { 17521 verbose(env, "unknown insn class %d\n", class); 17522 return -EINVAL; 17523 } 17524 17525 env->insn_idx++; 17526 } 17527 17528 return 0; 17529 } 17530 17531 static int find_btf_percpu_datasec(struct btf *btf) 17532 { 17533 const struct btf_type *t; 17534 const char *tname; 17535 int i, n; 17536 17537 /* 17538 * Both vmlinux and module each have their own ".data..percpu" 17539 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17540 * types to look at only module's own BTF types. 17541 */ 17542 n = btf_nr_types(btf); 17543 if (btf_is_module(btf)) 17544 i = btf_nr_types(btf_vmlinux); 17545 else 17546 i = 1; 17547 17548 for(; i < n; i++) { 17549 t = btf_type_by_id(btf, i); 17550 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17551 continue; 17552 17553 tname = btf_name_by_offset(btf, t->name_off); 17554 if (!strcmp(tname, ".data..percpu")) 17555 return i; 17556 } 17557 17558 return -ENOENT; 17559 } 17560 17561 /* replace pseudo btf_id with kernel symbol address */ 17562 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 17563 struct bpf_insn *insn, 17564 struct bpf_insn_aux_data *aux) 17565 { 17566 const struct btf_var_secinfo *vsi; 17567 const struct btf_type *datasec; 17568 struct btf_mod_pair *btf_mod; 17569 const struct btf_type *t; 17570 const char *sym_name; 17571 bool percpu = false; 17572 u32 type, id = insn->imm; 17573 struct btf *btf; 17574 s32 datasec_id; 17575 u64 addr; 17576 int i, btf_fd, err; 17577 17578 btf_fd = insn[1].imm; 17579 if (btf_fd) { 17580 btf = btf_get_by_fd(btf_fd); 17581 if (IS_ERR(btf)) { 17582 verbose(env, "invalid module BTF object FD specified.\n"); 17583 return -EINVAL; 17584 } 17585 } else { 17586 if (!btf_vmlinux) { 17587 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 17588 return -EINVAL; 17589 } 17590 btf = btf_vmlinux; 17591 btf_get(btf); 17592 } 17593 17594 t = btf_type_by_id(btf, id); 17595 if (!t) { 17596 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17597 err = -ENOENT; 17598 goto err_put; 17599 } 17600 17601 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 17602 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 17603 err = -EINVAL; 17604 goto err_put; 17605 } 17606 17607 sym_name = btf_name_by_offset(btf, t->name_off); 17608 addr = kallsyms_lookup_name(sym_name); 17609 if (!addr) { 17610 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 17611 sym_name); 17612 err = -ENOENT; 17613 goto err_put; 17614 } 17615 insn[0].imm = (u32)addr; 17616 insn[1].imm = addr >> 32; 17617 17618 if (btf_type_is_func(t)) { 17619 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17620 aux->btf_var.mem_size = 0; 17621 goto check_btf; 17622 } 17623 17624 datasec_id = find_btf_percpu_datasec(btf); 17625 if (datasec_id > 0) { 17626 datasec = btf_type_by_id(btf, datasec_id); 17627 for_each_vsi(i, datasec, vsi) { 17628 if (vsi->type == id) { 17629 percpu = true; 17630 break; 17631 } 17632 } 17633 } 17634 17635 type = t->type; 17636 t = btf_type_skip_modifiers(btf, type, NULL); 17637 if (percpu) { 17638 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 17639 aux->btf_var.btf = btf; 17640 aux->btf_var.btf_id = type; 17641 } else if (!btf_type_is_struct(t)) { 17642 const struct btf_type *ret; 17643 const char *tname; 17644 u32 tsize; 17645 17646 /* resolve the type size of ksym. */ 17647 ret = btf_resolve_size(btf, t, &tsize); 17648 if (IS_ERR(ret)) { 17649 tname = btf_name_by_offset(btf, t->name_off); 17650 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 17651 tname, PTR_ERR(ret)); 17652 err = -EINVAL; 17653 goto err_put; 17654 } 17655 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17656 aux->btf_var.mem_size = tsize; 17657 } else { 17658 aux->btf_var.reg_type = PTR_TO_BTF_ID; 17659 aux->btf_var.btf = btf; 17660 aux->btf_var.btf_id = type; 17661 } 17662 check_btf: 17663 /* check whether we recorded this BTF (and maybe module) already */ 17664 for (i = 0; i < env->used_btf_cnt; i++) { 17665 if (env->used_btfs[i].btf == btf) { 17666 btf_put(btf); 17667 return 0; 17668 } 17669 } 17670 17671 if (env->used_btf_cnt >= MAX_USED_BTFS) { 17672 err = -E2BIG; 17673 goto err_put; 17674 } 17675 17676 btf_mod = &env->used_btfs[env->used_btf_cnt]; 17677 btf_mod->btf = btf; 17678 btf_mod->module = NULL; 17679 17680 /* if we reference variables from kernel module, bump its refcount */ 17681 if (btf_is_module(btf)) { 17682 btf_mod->module = btf_try_get_module(btf); 17683 if (!btf_mod->module) { 17684 err = -ENXIO; 17685 goto err_put; 17686 } 17687 } 17688 17689 env->used_btf_cnt++; 17690 17691 return 0; 17692 err_put: 17693 btf_put(btf); 17694 return err; 17695 } 17696 17697 static bool is_tracing_prog_type(enum bpf_prog_type type) 17698 { 17699 switch (type) { 17700 case BPF_PROG_TYPE_KPROBE: 17701 case BPF_PROG_TYPE_TRACEPOINT: 17702 case BPF_PROG_TYPE_PERF_EVENT: 17703 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17704 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 17705 return true; 17706 default: 17707 return false; 17708 } 17709 } 17710 17711 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 17712 struct bpf_map *map, 17713 struct bpf_prog *prog) 17714 17715 { 17716 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17717 17718 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 17719 btf_record_has_field(map->record, BPF_RB_ROOT)) { 17720 if (is_tracing_prog_type(prog_type)) { 17721 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 17722 return -EINVAL; 17723 } 17724 } 17725 17726 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 17727 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 17728 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 17729 return -EINVAL; 17730 } 17731 17732 if (is_tracing_prog_type(prog_type)) { 17733 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 17734 return -EINVAL; 17735 } 17736 } 17737 17738 if (btf_record_has_field(map->record, BPF_TIMER)) { 17739 if (is_tracing_prog_type(prog_type)) { 17740 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 17741 return -EINVAL; 17742 } 17743 } 17744 17745 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 17746 !bpf_offload_prog_map_match(prog, map)) { 17747 verbose(env, "offload device mismatch between prog and map\n"); 17748 return -EINVAL; 17749 } 17750 17751 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 17752 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 17753 return -EINVAL; 17754 } 17755 17756 if (prog->aux->sleepable) 17757 switch (map->map_type) { 17758 case BPF_MAP_TYPE_HASH: 17759 case BPF_MAP_TYPE_LRU_HASH: 17760 case BPF_MAP_TYPE_ARRAY: 17761 case BPF_MAP_TYPE_PERCPU_HASH: 17762 case BPF_MAP_TYPE_PERCPU_ARRAY: 17763 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 17764 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 17765 case BPF_MAP_TYPE_HASH_OF_MAPS: 17766 case BPF_MAP_TYPE_RINGBUF: 17767 case BPF_MAP_TYPE_USER_RINGBUF: 17768 case BPF_MAP_TYPE_INODE_STORAGE: 17769 case BPF_MAP_TYPE_SK_STORAGE: 17770 case BPF_MAP_TYPE_TASK_STORAGE: 17771 case BPF_MAP_TYPE_CGRP_STORAGE: 17772 break; 17773 default: 17774 verbose(env, 17775 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 17776 return -EINVAL; 17777 } 17778 17779 return 0; 17780 } 17781 17782 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 17783 { 17784 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 17785 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 17786 } 17787 17788 /* find and rewrite pseudo imm in ld_imm64 instructions: 17789 * 17790 * 1. if it accesses map FD, replace it with actual map pointer. 17791 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 17792 * 17793 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 17794 */ 17795 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 17796 { 17797 struct bpf_insn *insn = env->prog->insnsi; 17798 int insn_cnt = env->prog->len; 17799 int i, j, err; 17800 17801 err = bpf_prog_calc_tag(env->prog); 17802 if (err) 17803 return err; 17804 17805 for (i = 0; i < insn_cnt; i++, insn++) { 17806 if (BPF_CLASS(insn->code) == BPF_LDX && 17807 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 17808 insn->imm != 0)) { 17809 verbose(env, "BPF_LDX uses reserved fields\n"); 17810 return -EINVAL; 17811 } 17812 17813 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 17814 struct bpf_insn_aux_data *aux; 17815 struct bpf_map *map; 17816 struct fd f; 17817 u64 addr; 17818 u32 fd; 17819 17820 if (i == insn_cnt - 1 || insn[1].code != 0 || 17821 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 17822 insn[1].off != 0) { 17823 verbose(env, "invalid bpf_ld_imm64 insn\n"); 17824 return -EINVAL; 17825 } 17826 17827 if (insn[0].src_reg == 0) 17828 /* valid generic load 64-bit imm */ 17829 goto next_insn; 17830 17831 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 17832 aux = &env->insn_aux_data[i]; 17833 err = check_pseudo_btf_id(env, insn, aux); 17834 if (err) 17835 return err; 17836 goto next_insn; 17837 } 17838 17839 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 17840 aux = &env->insn_aux_data[i]; 17841 aux->ptr_type = PTR_TO_FUNC; 17842 goto next_insn; 17843 } 17844 17845 /* In final convert_pseudo_ld_imm64() step, this is 17846 * converted into regular 64-bit imm load insn. 17847 */ 17848 switch (insn[0].src_reg) { 17849 case BPF_PSEUDO_MAP_VALUE: 17850 case BPF_PSEUDO_MAP_IDX_VALUE: 17851 break; 17852 case BPF_PSEUDO_MAP_FD: 17853 case BPF_PSEUDO_MAP_IDX: 17854 if (insn[1].imm == 0) 17855 break; 17856 fallthrough; 17857 default: 17858 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 17859 return -EINVAL; 17860 } 17861 17862 switch (insn[0].src_reg) { 17863 case BPF_PSEUDO_MAP_IDX_VALUE: 17864 case BPF_PSEUDO_MAP_IDX: 17865 if (bpfptr_is_null(env->fd_array)) { 17866 verbose(env, "fd_idx without fd_array is invalid\n"); 17867 return -EPROTO; 17868 } 17869 if (copy_from_bpfptr_offset(&fd, env->fd_array, 17870 insn[0].imm * sizeof(fd), 17871 sizeof(fd))) 17872 return -EFAULT; 17873 break; 17874 default: 17875 fd = insn[0].imm; 17876 break; 17877 } 17878 17879 f = fdget(fd); 17880 map = __bpf_map_get(f); 17881 if (IS_ERR(map)) { 17882 verbose(env, "fd %d is not pointing to valid bpf_map\n", 17883 insn[0].imm); 17884 return PTR_ERR(map); 17885 } 17886 17887 err = check_map_prog_compatibility(env, map, env->prog); 17888 if (err) { 17889 fdput(f); 17890 return err; 17891 } 17892 17893 aux = &env->insn_aux_data[i]; 17894 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 17895 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 17896 addr = (unsigned long)map; 17897 } else { 17898 u32 off = insn[1].imm; 17899 17900 if (off >= BPF_MAX_VAR_OFF) { 17901 verbose(env, "direct value offset of %u is not allowed\n", off); 17902 fdput(f); 17903 return -EINVAL; 17904 } 17905 17906 if (!map->ops->map_direct_value_addr) { 17907 verbose(env, "no direct value access support for this map type\n"); 17908 fdput(f); 17909 return -EINVAL; 17910 } 17911 17912 err = map->ops->map_direct_value_addr(map, &addr, off); 17913 if (err) { 17914 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 17915 map->value_size, off); 17916 fdput(f); 17917 return err; 17918 } 17919 17920 aux->map_off = off; 17921 addr += off; 17922 } 17923 17924 insn[0].imm = (u32)addr; 17925 insn[1].imm = addr >> 32; 17926 17927 /* check whether we recorded this map already */ 17928 for (j = 0; j < env->used_map_cnt; j++) { 17929 if (env->used_maps[j] == map) { 17930 aux->map_index = j; 17931 fdput(f); 17932 goto next_insn; 17933 } 17934 } 17935 17936 if (env->used_map_cnt >= MAX_USED_MAPS) { 17937 fdput(f); 17938 return -E2BIG; 17939 } 17940 17941 if (env->prog->aux->sleepable) 17942 atomic64_inc(&map->sleepable_refcnt); 17943 /* hold the map. If the program is rejected by verifier, 17944 * the map will be released by release_maps() or it 17945 * will be used by the valid program until it's unloaded 17946 * and all maps are released in bpf_free_used_maps() 17947 */ 17948 bpf_map_inc(map); 17949 17950 aux->map_index = env->used_map_cnt; 17951 env->used_maps[env->used_map_cnt++] = map; 17952 17953 if (bpf_map_is_cgroup_storage(map) && 17954 bpf_cgroup_storage_assign(env->prog->aux, map)) { 17955 verbose(env, "only one cgroup storage of each type is allowed\n"); 17956 fdput(f); 17957 return -EBUSY; 17958 } 17959 17960 fdput(f); 17961 next_insn: 17962 insn++; 17963 i++; 17964 continue; 17965 } 17966 17967 /* Basic sanity check before we invest more work here. */ 17968 if (!bpf_opcode_in_insntable(insn->code)) { 17969 verbose(env, "unknown opcode %02x\n", insn->code); 17970 return -EINVAL; 17971 } 17972 } 17973 17974 /* now all pseudo BPF_LD_IMM64 instructions load valid 17975 * 'struct bpf_map *' into a register instead of user map_fd. 17976 * These pointers will be used later by verifier to validate map access. 17977 */ 17978 return 0; 17979 } 17980 17981 /* drop refcnt of maps used by the rejected program */ 17982 static void release_maps(struct bpf_verifier_env *env) 17983 { 17984 __bpf_free_used_maps(env->prog->aux, env->used_maps, 17985 env->used_map_cnt); 17986 } 17987 17988 /* drop refcnt of maps used by the rejected program */ 17989 static void release_btfs(struct bpf_verifier_env *env) 17990 { 17991 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 17992 env->used_btf_cnt); 17993 } 17994 17995 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 17996 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 17997 { 17998 struct bpf_insn *insn = env->prog->insnsi; 17999 int insn_cnt = env->prog->len; 18000 int i; 18001 18002 for (i = 0; i < insn_cnt; i++, insn++) { 18003 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 18004 continue; 18005 if (insn->src_reg == BPF_PSEUDO_FUNC) 18006 continue; 18007 insn->src_reg = 0; 18008 } 18009 } 18010 18011 /* single env->prog->insni[off] instruction was replaced with the range 18012 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 18013 * [0, off) and [off, end) to new locations, so the patched range stays zero 18014 */ 18015 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 18016 struct bpf_insn_aux_data *new_data, 18017 struct bpf_prog *new_prog, u32 off, u32 cnt) 18018 { 18019 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 18020 struct bpf_insn *insn = new_prog->insnsi; 18021 u32 old_seen = old_data[off].seen; 18022 u32 prog_len; 18023 int i; 18024 18025 /* aux info at OFF always needs adjustment, no matter fast path 18026 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 18027 * original insn at old prog. 18028 */ 18029 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 18030 18031 if (cnt == 1) 18032 return; 18033 prog_len = new_prog->len; 18034 18035 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 18036 memcpy(new_data + off + cnt - 1, old_data + off, 18037 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 18038 for (i = off; i < off + cnt - 1; i++) { 18039 /* Expand insni[off]'s seen count to the patched range. */ 18040 new_data[i].seen = old_seen; 18041 new_data[i].zext_dst = insn_has_def32(env, insn + i); 18042 } 18043 env->insn_aux_data = new_data; 18044 vfree(old_data); 18045 } 18046 18047 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 18048 { 18049 int i; 18050 18051 if (len == 1) 18052 return; 18053 /* NOTE: fake 'exit' subprog should be updated as well. */ 18054 for (i = 0; i <= env->subprog_cnt; i++) { 18055 if (env->subprog_info[i].start <= off) 18056 continue; 18057 env->subprog_info[i].start += len - 1; 18058 } 18059 } 18060 18061 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 18062 { 18063 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 18064 int i, sz = prog->aux->size_poke_tab; 18065 struct bpf_jit_poke_descriptor *desc; 18066 18067 for (i = 0; i < sz; i++) { 18068 desc = &tab[i]; 18069 if (desc->insn_idx <= off) 18070 continue; 18071 desc->insn_idx += len - 1; 18072 } 18073 } 18074 18075 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 18076 const struct bpf_insn *patch, u32 len) 18077 { 18078 struct bpf_prog *new_prog; 18079 struct bpf_insn_aux_data *new_data = NULL; 18080 18081 if (len > 1) { 18082 new_data = vzalloc(array_size(env->prog->len + len - 1, 18083 sizeof(struct bpf_insn_aux_data))); 18084 if (!new_data) 18085 return NULL; 18086 } 18087 18088 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 18089 if (IS_ERR(new_prog)) { 18090 if (PTR_ERR(new_prog) == -ERANGE) 18091 verbose(env, 18092 "insn %d cannot be patched due to 16-bit range\n", 18093 env->insn_aux_data[off].orig_idx); 18094 vfree(new_data); 18095 return NULL; 18096 } 18097 adjust_insn_aux_data(env, new_data, new_prog, off, len); 18098 adjust_subprog_starts(env, off, len); 18099 adjust_poke_descs(new_prog, off, len); 18100 return new_prog; 18101 } 18102 18103 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 18104 u32 off, u32 cnt) 18105 { 18106 int i, j; 18107 18108 /* find first prog starting at or after off (first to remove) */ 18109 for (i = 0; i < env->subprog_cnt; i++) 18110 if (env->subprog_info[i].start >= off) 18111 break; 18112 /* find first prog starting at or after off + cnt (first to stay) */ 18113 for (j = i; j < env->subprog_cnt; j++) 18114 if (env->subprog_info[j].start >= off + cnt) 18115 break; 18116 /* if j doesn't start exactly at off + cnt, we are just removing 18117 * the front of previous prog 18118 */ 18119 if (env->subprog_info[j].start != off + cnt) 18120 j--; 18121 18122 if (j > i) { 18123 struct bpf_prog_aux *aux = env->prog->aux; 18124 int move; 18125 18126 /* move fake 'exit' subprog as well */ 18127 move = env->subprog_cnt + 1 - j; 18128 18129 memmove(env->subprog_info + i, 18130 env->subprog_info + j, 18131 sizeof(*env->subprog_info) * move); 18132 env->subprog_cnt -= j - i; 18133 18134 /* remove func_info */ 18135 if (aux->func_info) { 18136 move = aux->func_info_cnt - j; 18137 18138 memmove(aux->func_info + i, 18139 aux->func_info + j, 18140 sizeof(*aux->func_info) * move); 18141 aux->func_info_cnt -= j - i; 18142 /* func_info->insn_off is set after all code rewrites, 18143 * in adjust_btf_func() - no need to adjust 18144 */ 18145 } 18146 } else { 18147 /* convert i from "first prog to remove" to "first to adjust" */ 18148 if (env->subprog_info[i].start == off) 18149 i++; 18150 } 18151 18152 /* update fake 'exit' subprog as well */ 18153 for (; i <= env->subprog_cnt; i++) 18154 env->subprog_info[i].start -= cnt; 18155 18156 return 0; 18157 } 18158 18159 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 18160 u32 cnt) 18161 { 18162 struct bpf_prog *prog = env->prog; 18163 u32 i, l_off, l_cnt, nr_linfo; 18164 struct bpf_line_info *linfo; 18165 18166 nr_linfo = prog->aux->nr_linfo; 18167 if (!nr_linfo) 18168 return 0; 18169 18170 linfo = prog->aux->linfo; 18171 18172 /* find first line info to remove, count lines to be removed */ 18173 for (i = 0; i < nr_linfo; i++) 18174 if (linfo[i].insn_off >= off) 18175 break; 18176 18177 l_off = i; 18178 l_cnt = 0; 18179 for (; i < nr_linfo; i++) 18180 if (linfo[i].insn_off < off + cnt) 18181 l_cnt++; 18182 else 18183 break; 18184 18185 /* First live insn doesn't match first live linfo, it needs to "inherit" 18186 * last removed linfo. prog is already modified, so prog->len == off 18187 * means no live instructions after (tail of the program was removed). 18188 */ 18189 if (prog->len != off && l_cnt && 18190 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 18191 l_cnt--; 18192 linfo[--i].insn_off = off + cnt; 18193 } 18194 18195 /* remove the line info which refer to the removed instructions */ 18196 if (l_cnt) { 18197 memmove(linfo + l_off, linfo + i, 18198 sizeof(*linfo) * (nr_linfo - i)); 18199 18200 prog->aux->nr_linfo -= l_cnt; 18201 nr_linfo = prog->aux->nr_linfo; 18202 } 18203 18204 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 18205 for (i = l_off; i < nr_linfo; i++) 18206 linfo[i].insn_off -= cnt; 18207 18208 /* fix up all subprogs (incl. 'exit') which start >= off */ 18209 for (i = 0; i <= env->subprog_cnt; i++) 18210 if (env->subprog_info[i].linfo_idx > l_off) { 18211 /* program may have started in the removed region but 18212 * may not be fully removed 18213 */ 18214 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 18215 env->subprog_info[i].linfo_idx -= l_cnt; 18216 else 18217 env->subprog_info[i].linfo_idx = l_off; 18218 } 18219 18220 return 0; 18221 } 18222 18223 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 18224 { 18225 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18226 unsigned int orig_prog_len = env->prog->len; 18227 int err; 18228 18229 if (bpf_prog_is_offloaded(env->prog->aux)) 18230 bpf_prog_offload_remove_insns(env, off, cnt); 18231 18232 err = bpf_remove_insns(env->prog, off, cnt); 18233 if (err) 18234 return err; 18235 18236 err = adjust_subprog_starts_after_remove(env, off, cnt); 18237 if (err) 18238 return err; 18239 18240 err = bpf_adj_linfo_after_remove(env, off, cnt); 18241 if (err) 18242 return err; 18243 18244 memmove(aux_data + off, aux_data + off + cnt, 18245 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 18246 18247 return 0; 18248 } 18249 18250 /* The verifier does more data flow analysis than llvm and will not 18251 * explore branches that are dead at run time. Malicious programs can 18252 * have dead code too. Therefore replace all dead at-run-time code 18253 * with 'ja -1'. 18254 * 18255 * Just nops are not optimal, e.g. if they would sit at the end of the 18256 * program and through another bug we would manage to jump there, then 18257 * we'd execute beyond program memory otherwise. Returning exception 18258 * code also wouldn't work since we can have subprogs where the dead 18259 * code could be located. 18260 */ 18261 static void sanitize_dead_code(struct bpf_verifier_env *env) 18262 { 18263 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18264 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18265 struct bpf_insn *insn = env->prog->insnsi; 18266 const int insn_cnt = env->prog->len; 18267 int i; 18268 18269 for (i = 0; i < insn_cnt; i++) { 18270 if (aux_data[i].seen) 18271 continue; 18272 memcpy(insn + i, &trap, sizeof(trap)); 18273 aux_data[i].zext_dst = false; 18274 } 18275 } 18276 18277 static bool insn_is_cond_jump(u8 code) 18278 { 18279 u8 op; 18280 18281 op = BPF_OP(code); 18282 if (BPF_CLASS(code) == BPF_JMP32) 18283 return op != BPF_JA; 18284 18285 if (BPF_CLASS(code) != BPF_JMP) 18286 return false; 18287 18288 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 18289 } 18290 18291 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 18292 { 18293 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18294 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18295 struct bpf_insn *insn = env->prog->insnsi; 18296 const int insn_cnt = env->prog->len; 18297 int i; 18298 18299 for (i = 0; i < insn_cnt; i++, insn++) { 18300 if (!insn_is_cond_jump(insn->code)) 18301 continue; 18302 18303 if (!aux_data[i + 1].seen) 18304 ja.off = insn->off; 18305 else if (!aux_data[i + 1 + insn->off].seen) 18306 ja.off = 0; 18307 else 18308 continue; 18309 18310 if (bpf_prog_is_offloaded(env->prog->aux)) 18311 bpf_prog_offload_replace_insn(env, i, &ja); 18312 18313 memcpy(insn, &ja, sizeof(ja)); 18314 } 18315 } 18316 18317 static int opt_remove_dead_code(struct bpf_verifier_env *env) 18318 { 18319 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18320 int insn_cnt = env->prog->len; 18321 int i, err; 18322 18323 for (i = 0; i < insn_cnt; i++) { 18324 int j; 18325 18326 j = 0; 18327 while (i + j < insn_cnt && !aux_data[i + j].seen) 18328 j++; 18329 if (!j) 18330 continue; 18331 18332 err = verifier_remove_insns(env, i, j); 18333 if (err) 18334 return err; 18335 insn_cnt = env->prog->len; 18336 } 18337 18338 return 0; 18339 } 18340 18341 static int opt_remove_nops(struct bpf_verifier_env *env) 18342 { 18343 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18344 struct bpf_insn *insn = env->prog->insnsi; 18345 int insn_cnt = env->prog->len; 18346 int i, err; 18347 18348 for (i = 0; i < insn_cnt; i++) { 18349 if (memcmp(&insn[i], &ja, sizeof(ja))) 18350 continue; 18351 18352 err = verifier_remove_insns(env, i, 1); 18353 if (err) 18354 return err; 18355 insn_cnt--; 18356 i--; 18357 } 18358 18359 return 0; 18360 } 18361 18362 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 18363 const union bpf_attr *attr) 18364 { 18365 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 18366 struct bpf_insn_aux_data *aux = env->insn_aux_data; 18367 int i, patch_len, delta = 0, len = env->prog->len; 18368 struct bpf_insn *insns = env->prog->insnsi; 18369 struct bpf_prog *new_prog; 18370 bool rnd_hi32; 18371 18372 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 18373 zext_patch[1] = BPF_ZEXT_REG(0); 18374 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 18375 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 18376 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 18377 for (i = 0; i < len; i++) { 18378 int adj_idx = i + delta; 18379 struct bpf_insn insn; 18380 int load_reg; 18381 18382 insn = insns[adj_idx]; 18383 load_reg = insn_def_regno(&insn); 18384 if (!aux[adj_idx].zext_dst) { 18385 u8 code, class; 18386 u32 imm_rnd; 18387 18388 if (!rnd_hi32) 18389 continue; 18390 18391 code = insn.code; 18392 class = BPF_CLASS(code); 18393 if (load_reg == -1) 18394 continue; 18395 18396 /* NOTE: arg "reg" (the fourth one) is only used for 18397 * BPF_STX + SRC_OP, so it is safe to pass NULL 18398 * here. 18399 */ 18400 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 18401 if (class == BPF_LD && 18402 BPF_MODE(code) == BPF_IMM) 18403 i++; 18404 continue; 18405 } 18406 18407 /* ctx load could be transformed into wider load. */ 18408 if (class == BPF_LDX && 18409 aux[adj_idx].ptr_type == PTR_TO_CTX) 18410 continue; 18411 18412 imm_rnd = get_random_u32(); 18413 rnd_hi32_patch[0] = insn; 18414 rnd_hi32_patch[1].imm = imm_rnd; 18415 rnd_hi32_patch[3].dst_reg = load_reg; 18416 patch = rnd_hi32_patch; 18417 patch_len = 4; 18418 goto apply_patch_buffer; 18419 } 18420 18421 /* Add in an zero-extend instruction if a) the JIT has requested 18422 * it or b) it's a CMPXCHG. 18423 * 18424 * The latter is because: BPF_CMPXCHG always loads a value into 18425 * R0, therefore always zero-extends. However some archs' 18426 * equivalent instruction only does this load when the 18427 * comparison is successful. This detail of CMPXCHG is 18428 * orthogonal to the general zero-extension behaviour of the 18429 * CPU, so it's treated independently of bpf_jit_needs_zext. 18430 */ 18431 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 18432 continue; 18433 18434 /* Zero-extension is done by the caller. */ 18435 if (bpf_pseudo_kfunc_call(&insn)) 18436 continue; 18437 18438 if (WARN_ON(load_reg == -1)) { 18439 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 18440 return -EFAULT; 18441 } 18442 18443 zext_patch[0] = insn; 18444 zext_patch[1].dst_reg = load_reg; 18445 zext_patch[1].src_reg = load_reg; 18446 patch = zext_patch; 18447 patch_len = 2; 18448 apply_patch_buffer: 18449 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 18450 if (!new_prog) 18451 return -ENOMEM; 18452 env->prog = new_prog; 18453 insns = new_prog->insnsi; 18454 aux = env->insn_aux_data; 18455 delta += patch_len - 1; 18456 } 18457 18458 return 0; 18459 } 18460 18461 /* convert load instructions that access fields of a context type into a 18462 * sequence of instructions that access fields of the underlying structure: 18463 * struct __sk_buff -> struct sk_buff 18464 * struct bpf_sock_ops -> struct sock 18465 */ 18466 static int convert_ctx_accesses(struct bpf_verifier_env *env) 18467 { 18468 const struct bpf_verifier_ops *ops = env->ops; 18469 int i, cnt, size, ctx_field_size, delta = 0; 18470 const int insn_cnt = env->prog->len; 18471 struct bpf_insn insn_buf[16], *insn; 18472 u32 target_size, size_default, off; 18473 struct bpf_prog *new_prog; 18474 enum bpf_access_type type; 18475 bool is_narrower_load; 18476 18477 if (ops->gen_prologue || env->seen_direct_write) { 18478 if (!ops->gen_prologue) { 18479 verbose(env, "bpf verifier is misconfigured\n"); 18480 return -EINVAL; 18481 } 18482 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 18483 env->prog); 18484 if (cnt >= ARRAY_SIZE(insn_buf)) { 18485 verbose(env, "bpf verifier is misconfigured\n"); 18486 return -EINVAL; 18487 } else if (cnt) { 18488 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 18489 if (!new_prog) 18490 return -ENOMEM; 18491 18492 env->prog = new_prog; 18493 delta += cnt - 1; 18494 } 18495 } 18496 18497 if (bpf_prog_is_offloaded(env->prog->aux)) 18498 return 0; 18499 18500 insn = env->prog->insnsi + delta; 18501 18502 for (i = 0; i < insn_cnt; i++, insn++) { 18503 bpf_convert_ctx_access_t convert_ctx_access; 18504 u8 mode; 18505 18506 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 18507 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 18508 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 18509 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 18510 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 18511 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 18512 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 18513 type = BPF_READ; 18514 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 18515 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 18516 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 18517 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 18518 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 18519 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 18520 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 18521 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 18522 type = BPF_WRITE; 18523 } else { 18524 continue; 18525 } 18526 18527 if (type == BPF_WRITE && 18528 env->insn_aux_data[i + delta].sanitize_stack_spill) { 18529 struct bpf_insn patch[] = { 18530 *insn, 18531 BPF_ST_NOSPEC(), 18532 }; 18533 18534 cnt = ARRAY_SIZE(patch); 18535 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 18536 if (!new_prog) 18537 return -ENOMEM; 18538 18539 delta += cnt - 1; 18540 env->prog = new_prog; 18541 insn = new_prog->insnsi + i + delta; 18542 continue; 18543 } 18544 18545 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 18546 case PTR_TO_CTX: 18547 if (!ops->convert_ctx_access) 18548 continue; 18549 convert_ctx_access = ops->convert_ctx_access; 18550 break; 18551 case PTR_TO_SOCKET: 18552 case PTR_TO_SOCK_COMMON: 18553 convert_ctx_access = bpf_sock_convert_ctx_access; 18554 break; 18555 case PTR_TO_TCP_SOCK: 18556 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 18557 break; 18558 case PTR_TO_XDP_SOCK: 18559 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 18560 break; 18561 case PTR_TO_BTF_ID: 18562 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 18563 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 18564 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 18565 * be said once it is marked PTR_UNTRUSTED, hence we must handle 18566 * any faults for loads into such types. BPF_WRITE is disallowed 18567 * for this case. 18568 */ 18569 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 18570 if (type == BPF_READ) { 18571 if (BPF_MODE(insn->code) == BPF_MEM) 18572 insn->code = BPF_LDX | BPF_PROBE_MEM | 18573 BPF_SIZE((insn)->code); 18574 else 18575 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 18576 BPF_SIZE((insn)->code); 18577 env->prog->aux->num_exentries++; 18578 } 18579 continue; 18580 default: 18581 continue; 18582 } 18583 18584 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 18585 size = BPF_LDST_BYTES(insn); 18586 mode = BPF_MODE(insn->code); 18587 18588 /* If the read access is a narrower load of the field, 18589 * convert to a 4/8-byte load, to minimum program type specific 18590 * convert_ctx_access changes. If conversion is successful, 18591 * we will apply proper mask to the result. 18592 */ 18593 is_narrower_load = size < ctx_field_size; 18594 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 18595 off = insn->off; 18596 if (is_narrower_load) { 18597 u8 size_code; 18598 18599 if (type == BPF_WRITE) { 18600 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 18601 return -EINVAL; 18602 } 18603 18604 size_code = BPF_H; 18605 if (ctx_field_size == 4) 18606 size_code = BPF_W; 18607 else if (ctx_field_size == 8) 18608 size_code = BPF_DW; 18609 18610 insn->off = off & ~(size_default - 1); 18611 insn->code = BPF_LDX | BPF_MEM | size_code; 18612 } 18613 18614 target_size = 0; 18615 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 18616 &target_size); 18617 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 18618 (ctx_field_size && !target_size)) { 18619 verbose(env, "bpf verifier is misconfigured\n"); 18620 return -EINVAL; 18621 } 18622 18623 if (is_narrower_load && size < target_size) { 18624 u8 shift = bpf_ctx_narrow_access_offset( 18625 off, size, size_default) * 8; 18626 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 18627 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 18628 return -EINVAL; 18629 } 18630 if (ctx_field_size <= 4) { 18631 if (shift) 18632 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 18633 insn->dst_reg, 18634 shift); 18635 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18636 (1 << size * 8) - 1); 18637 } else { 18638 if (shift) 18639 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 18640 insn->dst_reg, 18641 shift); 18642 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 18643 (1ULL << size * 8) - 1); 18644 } 18645 } 18646 if (mode == BPF_MEMSX) 18647 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 18648 insn->dst_reg, insn->dst_reg, 18649 size * 8, 0); 18650 18651 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18652 if (!new_prog) 18653 return -ENOMEM; 18654 18655 delta += cnt - 1; 18656 18657 /* keep walking new program and skip insns we just inserted */ 18658 env->prog = new_prog; 18659 insn = new_prog->insnsi + i + delta; 18660 } 18661 18662 return 0; 18663 } 18664 18665 static int jit_subprogs(struct bpf_verifier_env *env) 18666 { 18667 struct bpf_prog *prog = env->prog, **func, *tmp; 18668 int i, j, subprog_start, subprog_end = 0, len, subprog; 18669 struct bpf_map *map_ptr; 18670 struct bpf_insn *insn; 18671 void *old_bpf_func; 18672 int err, num_exentries; 18673 18674 if (env->subprog_cnt <= 1) 18675 return 0; 18676 18677 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18678 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 18679 continue; 18680 18681 /* Upon error here we cannot fall back to interpreter but 18682 * need a hard reject of the program. Thus -EFAULT is 18683 * propagated in any case. 18684 */ 18685 subprog = find_subprog(env, i + insn->imm + 1); 18686 if (subprog < 0) { 18687 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 18688 i + insn->imm + 1); 18689 return -EFAULT; 18690 } 18691 /* temporarily remember subprog id inside insn instead of 18692 * aux_data, since next loop will split up all insns into funcs 18693 */ 18694 insn->off = subprog; 18695 /* remember original imm in case JIT fails and fallback 18696 * to interpreter will be needed 18697 */ 18698 env->insn_aux_data[i].call_imm = insn->imm; 18699 /* point imm to __bpf_call_base+1 from JITs point of view */ 18700 insn->imm = 1; 18701 if (bpf_pseudo_func(insn)) 18702 /* jit (e.g. x86_64) may emit fewer instructions 18703 * if it learns a u32 imm is the same as a u64 imm. 18704 * Force a non zero here. 18705 */ 18706 insn[1].imm = 1; 18707 } 18708 18709 err = bpf_prog_alloc_jited_linfo(prog); 18710 if (err) 18711 goto out_undo_insn; 18712 18713 err = -ENOMEM; 18714 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 18715 if (!func) 18716 goto out_undo_insn; 18717 18718 for (i = 0; i < env->subprog_cnt; i++) { 18719 subprog_start = subprog_end; 18720 subprog_end = env->subprog_info[i + 1].start; 18721 18722 len = subprog_end - subprog_start; 18723 /* bpf_prog_run() doesn't call subprogs directly, 18724 * hence main prog stats include the runtime of subprogs. 18725 * subprogs don't have IDs and not reachable via prog_get_next_id 18726 * func[i]->stats will never be accessed and stays NULL 18727 */ 18728 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 18729 if (!func[i]) 18730 goto out_free; 18731 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 18732 len * sizeof(struct bpf_insn)); 18733 func[i]->type = prog->type; 18734 func[i]->len = len; 18735 if (bpf_prog_calc_tag(func[i])) 18736 goto out_free; 18737 func[i]->is_func = 1; 18738 func[i]->aux->func_idx = i; 18739 /* Below members will be freed only at prog->aux */ 18740 func[i]->aux->btf = prog->aux->btf; 18741 func[i]->aux->func_info = prog->aux->func_info; 18742 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 18743 func[i]->aux->poke_tab = prog->aux->poke_tab; 18744 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 18745 18746 for (j = 0; j < prog->aux->size_poke_tab; j++) { 18747 struct bpf_jit_poke_descriptor *poke; 18748 18749 poke = &prog->aux->poke_tab[j]; 18750 if (poke->insn_idx < subprog_end && 18751 poke->insn_idx >= subprog_start) 18752 poke->aux = func[i]->aux; 18753 } 18754 18755 func[i]->aux->name[0] = 'F'; 18756 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 18757 func[i]->jit_requested = 1; 18758 func[i]->blinding_requested = prog->blinding_requested; 18759 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 18760 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 18761 func[i]->aux->linfo = prog->aux->linfo; 18762 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 18763 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 18764 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 18765 num_exentries = 0; 18766 insn = func[i]->insnsi; 18767 for (j = 0; j < func[i]->len; j++, insn++) { 18768 if (BPF_CLASS(insn->code) == BPF_LDX && 18769 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 18770 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 18771 num_exentries++; 18772 } 18773 func[i]->aux->num_exentries = num_exentries; 18774 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 18775 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb; 18776 if (!i) 18777 func[i]->aux->exception_boundary = env->seen_exception; 18778 func[i] = bpf_int_jit_compile(func[i]); 18779 if (!func[i]->jited) { 18780 err = -ENOTSUPP; 18781 goto out_free; 18782 } 18783 cond_resched(); 18784 } 18785 18786 /* at this point all bpf functions were successfully JITed 18787 * now populate all bpf_calls with correct addresses and 18788 * run last pass of JIT 18789 */ 18790 for (i = 0; i < env->subprog_cnt; i++) { 18791 insn = func[i]->insnsi; 18792 for (j = 0; j < func[i]->len; j++, insn++) { 18793 if (bpf_pseudo_func(insn)) { 18794 subprog = insn->off; 18795 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 18796 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 18797 continue; 18798 } 18799 if (!bpf_pseudo_call(insn)) 18800 continue; 18801 subprog = insn->off; 18802 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 18803 } 18804 18805 /* we use the aux data to keep a list of the start addresses 18806 * of the JITed images for each function in the program 18807 * 18808 * for some architectures, such as powerpc64, the imm field 18809 * might not be large enough to hold the offset of the start 18810 * address of the callee's JITed image from __bpf_call_base 18811 * 18812 * in such cases, we can lookup the start address of a callee 18813 * by using its subprog id, available from the off field of 18814 * the call instruction, as an index for this list 18815 */ 18816 func[i]->aux->func = func; 18817 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 18818 func[i]->aux->real_func_cnt = env->subprog_cnt; 18819 } 18820 for (i = 0; i < env->subprog_cnt; i++) { 18821 old_bpf_func = func[i]->bpf_func; 18822 tmp = bpf_int_jit_compile(func[i]); 18823 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 18824 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 18825 err = -ENOTSUPP; 18826 goto out_free; 18827 } 18828 cond_resched(); 18829 } 18830 18831 /* finally lock prog and jit images for all functions and 18832 * populate kallsysm. Begin at the first subprogram, since 18833 * bpf_prog_load will add the kallsyms for the main program. 18834 */ 18835 for (i = 1; i < env->subprog_cnt; i++) { 18836 bpf_prog_lock_ro(func[i]); 18837 bpf_prog_kallsyms_add(func[i]); 18838 } 18839 18840 /* Last step: make now unused interpreter insns from main 18841 * prog consistent for later dump requests, so they can 18842 * later look the same as if they were interpreted only. 18843 */ 18844 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18845 if (bpf_pseudo_func(insn)) { 18846 insn[0].imm = env->insn_aux_data[i].call_imm; 18847 insn[1].imm = insn->off; 18848 insn->off = 0; 18849 continue; 18850 } 18851 if (!bpf_pseudo_call(insn)) 18852 continue; 18853 insn->off = env->insn_aux_data[i].call_imm; 18854 subprog = find_subprog(env, i + insn->off + 1); 18855 insn->imm = subprog; 18856 } 18857 18858 prog->jited = 1; 18859 prog->bpf_func = func[0]->bpf_func; 18860 prog->jited_len = func[0]->jited_len; 18861 prog->aux->extable = func[0]->aux->extable; 18862 prog->aux->num_exentries = func[0]->aux->num_exentries; 18863 prog->aux->func = func; 18864 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 18865 prog->aux->real_func_cnt = env->subprog_cnt; 18866 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func; 18867 prog->aux->exception_boundary = func[0]->aux->exception_boundary; 18868 bpf_prog_jit_attempt_done(prog); 18869 return 0; 18870 out_free: 18871 /* We failed JIT'ing, so at this point we need to unregister poke 18872 * descriptors from subprogs, so that kernel is not attempting to 18873 * patch it anymore as we're freeing the subprog JIT memory. 18874 */ 18875 for (i = 0; i < prog->aux->size_poke_tab; i++) { 18876 map_ptr = prog->aux->poke_tab[i].tail_call.map; 18877 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 18878 } 18879 /* At this point we're guaranteed that poke descriptors are not 18880 * live anymore. We can just unlink its descriptor table as it's 18881 * released with the main prog. 18882 */ 18883 for (i = 0; i < env->subprog_cnt; i++) { 18884 if (!func[i]) 18885 continue; 18886 func[i]->aux->poke_tab = NULL; 18887 bpf_jit_free(func[i]); 18888 } 18889 kfree(func); 18890 out_undo_insn: 18891 /* cleanup main prog to be interpreted */ 18892 prog->jit_requested = 0; 18893 prog->blinding_requested = 0; 18894 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 18895 if (!bpf_pseudo_call(insn)) 18896 continue; 18897 insn->off = 0; 18898 insn->imm = env->insn_aux_data[i].call_imm; 18899 } 18900 bpf_prog_jit_attempt_done(prog); 18901 return err; 18902 } 18903 18904 static int fixup_call_args(struct bpf_verifier_env *env) 18905 { 18906 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 18907 struct bpf_prog *prog = env->prog; 18908 struct bpf_insn *insn = prog->insnsi; 18909 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 18910 int i, depth; 18911 #endif 18912 int err = 0; 18913 18914 if (env->prog->jit_requested && 18915 !bpf_prog_is_offloaded(env->prog->aux)) { 18916 err = jit_subprogs(env); 18917 if (err == 0) 18918 return 0; 18919 if (err == -EFAULT) 18920 return err; 18921 } 18922 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 18923 if (has_kfunc_call) { 18924 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 18925 return -EINVAL; 18926 } 18927 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 18928 /* When JIT fails the progs with bpf2bpf calls and tail_calls 18929 * have to be rejected, since interpreter doesn't support them yet. 18930 */ 18931 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 18932 return -EINVAL; 18933 } 18934 for (i = 0; i < prog->len; i++, insn++) { 18935 if (bpf_pseudo_func(insn)) { 18936 /* When JIT fails the progs with callback calls 18937 * have to be rejected, since interpreter doesn't support them yet. 18938 */ 18939 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 18940 return -EINVAL; 18941 } 18942 18943 if (!bpf_pseudo_call(insn)) 18944 continue; 18945 depth = get_callee_stack_depth(env, insn, i); 18946 if (depth < 0) 18947 return depth; 18948 bpf_patch_call_args(insn, depth); 18949 } 18950 err = 0; 18951 #endif 18952 return err; 18953 } 18954 18955 /* replace a generic kfunc with a specialized version if necessary */ 18956 static void specialize_kfunc(struct bpf_verifier_env *env, 18957 u32 func_id, u16 offset, unsigned long *addr) 18958 { 18959 struct bpf_prog *prog = env->prog; 18960 bool seen_direct_write; 18961 void *xdp_kfunc; 18962 bool is_rdonly; 18963 18964 if (bpf_dev_bound_kfunc_id(func_id)) { 18965 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 18966 if (xdp_kfunc) { 18967 *addr = (unsigned long)xdp_kfunc; 18968 return; 18969 } 18970 /* fallback to default kfunc when not supported by netdev */ 18971 } 18972 18973 if (offset) 18974 return; 18975 18976 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 18977 seen_direct_write = env->seen_direct_write; 18978 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 18979 18980 if (is_rdonly) 18981 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 18982 18983 /* restore env->seen_direct_write to its original value, since 18984 * may_access_direct_pkt_data mutates it 18985 */ 18986 env->seen_direct_write = seen_direct_write; 18987 } 18988 } 18989 18990 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 18991 u16 struct_meta_reg, 18992 u16 node_offset_reg, 18993 struct bpf_insn *insn, 18994 struct bpf_insn *insn_buf, 18995 int *cnt) 18996 { 18997 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 18998 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 18999 19000 insn_buf[0] = addr[0]; 19001 insn_buf[1] = addr[1]; 19002 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 19003 insn_buf[3] = *insn; 19004 *cnt = 4; 19005 } 19006 19007 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 19008 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 19009 { 19010 const struct bpf_kfunc_desc *desc; 19011 19012 if (!insn->imm) { 19013 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 19014 return -EINVAL; 19015 } 19016 19017 *cnt = 0; 19018 19019 /* insn->imm has the btf func_id. Replace it with an offset relative to 19020 * __bpf_call_base, unless the JIT needs to call functions that are 19021 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 19022 */ 19023 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 19024 if (!desc) { 19025 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 19026 insn->imm); 19027 return -EFAULT; 19028 } 19029 19030 if (!bpf_jit_supports_far_kfunc_call()) 19031 insn->imm = BPF_CALL_IMM(desc->addr); 19032 if (insn->off) 19033 return 0; 19034 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 19035 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 19036 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19037 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19038 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 19039 19040 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) { 19041 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 19042 insn_idx); 19043 return -EFAULT; 19044 } 19045 19046 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 19047 insn_buf[1] = addr[0]; 19048 insn_buf[2] = addr[1]; 19049 insn_buf[3] = *insn; 19050 *cnt = 4; 19051 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 19052 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] || 19053 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 19054 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19055 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19056 19057 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) { 19058 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 19059 insn_idx); 19060 return -EFAULT; 19061 } 19062 19063 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 19064 !kptr_struct_meta) { 19065 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 19066 insn_idx); 19067 return -EFAULT; 19068 } 19069 19070 insn_buf[0] = addr[0]; 19071 insn_buf[1] = addr[1]; 19072 insn_buf[2] = *insn; 19073 *cnt = 3; 19074 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 19075 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 19076 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 19077 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19078 int struct_meta_reg = BPF_REG_3; 19079 int node_offset_reg = BPF_REG_4; 19080 19081 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 19082 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 19083 struct_meta_reg = BPF_REG_4; 19084 node_offset_reg = BPF_REG_5; 19085 } 19086 19087 if (!kptr_struct_meta) { 19088 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 19089 insn_idx); 19090 return -EFAULT; 19091 } 19092 19093 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 19094 node_offset_reg, insn, insn_buf, cnt); 19095 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 19096 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 19097 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 19098 *cnt = 1; 19099 } 19100 return 0; 19101 } 19102 19103 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */ 19104 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len) 19105 { 19106 struct bpf_subprog_info *info = env->subprog_info; 19107 int cnt = env->subprog_cnt; 19108 struct bpf_prog *prog; 19109 19110 /* We only reserve one slot for hidden subprogs in subprog_info. */ 19111 if (env->hidden_subprog_cnt) { 19112 verbose(env, "verifier internal error: only one hidden subprog supported\n"); 19113 return -EFAULT; 19114 } 19115 /* We're not patching any existing instruction, just appending the new 19116 * ones for the hidden subprog. Hence all of the adjustment operations 19117 * in bpf_patch_insn_data are no-ops. 19118 */ 19119 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len); 19120 if (!prog) 19121 return -ENOMEM; 19122 env->prog = prog; 19123 info[cnt + 1].start = info[cnt].start; 19124 info[cnt].start = prog->len - len + 1; 19125 env->subprog_cnt++; 19126 env->hidden_subprog_cnt++; 19127 return 0; 19128 } 19129 19130 /* Do various post-verification rewrites in a single program pass. 19131 * These rewrites simplify JIT and interpreter implementations. 19132 */ 19133 static int do_misc_fixups(struct bpf_verifier_env *env) 19134 { 19135 struct bpf_prog *prog = env->prog; 19136 enum bpf_attach_type eatype = prog->expected_attach_type; 19137 enum bpf_prog_type prog_type = resolve_prog_type(prog); 19138 struct bpf_insn *insn = prog->insnsi; 19139 const struct bpf_func_proto *fn; 19140 const int insn_cnt = prog->len; 19141 const struct bpf_map_ops *ops; 19142 struct bpf_insn_aux_data *aux; 19143 struct bpf_insn insn_buf[16]; 19144 struct bpf_prog *new_prog; 19145 struct bpf_map *map_ptr; 19146 int i, ret, cnt, delta = 0; 19147 19148 if (env->seen_exception && !env->exception_callback_subprog) { 19149 struct bpf_insn patch[] = { 19150 env->prog->insnsi[insn_cnt - 1], 19151 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1), 19152 BPF_EXIT_INSN(), 19153 }; 19154 19155 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch)); 19156 if (ret < 0) 19157 return ret; 19158 prog = env->prog; 19159 insn = prog->insnsi; 19160 19161 env->exception_callback_subprog = env->subprog_cnt - 1; 19162 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */ 19163 env->subprog_info[env->exception_callback_subprog].is_cb = true; 19164 env->subprog_info[env->exception_callback_subprog].is_async_cb = true; 19165 env->subprog_info[env->exception_callback_subprog].is_exception_cb = true; 19166 } 19167 19168 for (i = 0; i < insn_cnt; i++, insn++) { 19169 /* Make divide-by-zero exceptions impossible. */ 19170 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 19171 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 19172 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 19173 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 19174 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 19175 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 19176 struct bpf_insn *patchlet; 19177 struct bpf_insn chk_and_div[] = { 19178 /* [R,W]x div 0 -> 0 */ 19179 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 19180 BPF_JNE | BPF_K, insn->src_reg, 19181 0, 2, 0), 19182 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 19183 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 19184 *insn, 19185 }; 19186 struct bpf_insn chk_and_mod[] = { 19187 /* [R,W]x mod 0 -> [R,W]x */ 19188 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 19189 BPF_JEQ | BPF_K, insn->src_reg, 19190 0, 1 + (is64 ? 0 : 1), 0), 19191 *insn, 19192 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 19193 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 19194 }; 19195 19196 patchlet = isdiv ? chk_and_div : chk_and_mod; 19197 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 19198 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 19199 19200 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 19201 if (!new_prog) 19202 return -ENOMEM; 19203 19204 delta += cnt - 1; 19205 env->prog = prog = new_prog; 19206 insn = new_prog->insnsi + i + delta; 19207 continue; 19208 } 19209 19210 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 19211 if (BPF_CLASS(insn->code) == BPF_LD && 19212 (BPF_MODE(insn->code) == BPF_ABS || 19213 BPF_MODE(insn->code) == BPF_IND)) { 19214 cnt = env->ops->gen_ld_abs(insn, insn_buf); 19215 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19216 verbose(env, "bpf verifier is misconfigured\n"); 19217 return -EINVAL; 19218 } 19219 19220 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19221 if (!new_prog) 19222 return -ENOMEM; 19223 19224 delta += cnt - 1; 19225 env->prog = prog = new_prog; 19226 insn = new_prog->insnsi + i + delta; 19227 continue; 19228 } 19229 19230 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 19231 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 19232 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 19233 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 19234 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 19235 struct bpf_insn *patch = &insn_buf[0]; 19236 bool issrc, isneg, isimm; 19237 u32 off_reg; 19238 19239 aux = &env->insn_aux_data[i + delta]; 19240 if (!aux->alu_state || 19241 aux->alu_state == BPF_ALU_NON_POINTER) 19242 continue; 19243 19244 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 19245 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 19246 BPF_ALU_SANITIZE_SRC; 19247 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 19248 19249 off_reg = issrc ? insn->src_reg : insn->dst_reg; 19250 if (isimm) { 19251 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19252 } else { 19253 if (isneg) 19254 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19255 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19256 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 19257 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 19258 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 19259 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 19260 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 19261 } 19262 if (!issrc) 19263 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 19264 insn->src_reg = BPF_REG_AX; 19265 if (isneg) 19266 insn->code = insn->code == code_add ? 19267 code_sub : code_add; 19268 *patch++ = *insn; 19269 if (issrc && isneg && !isimm) 19270 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19271 cnt = patch - insn_buf; 19272 19273 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19274 if (!new_prog) 19275 return -ENOMEM; 19276 19277 delta += cnt - 1; 19278 env->prog = prog = new_prog; 19279 insn = new_prog->insnsi + i + delta; 19280 continue; 19281 } 19282 19283 if (insn->code != (BPF_JMP | BPF_CALL)) 19284 continue; 19285 if (insn->src_reg == BPF_PSEUDO_CALL) 19286 continue; 19287 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 19288 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 19289 if (ret) 19290 return ret; 19291 if (cnt == 0) 19292 continue; 19293 19294 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19295 if (!new_prog) 19296 return -ENOMEM; 19297 19298 delta += cnt - 1; 19299 env->prog = prog = new_prog; 19300 insn = new_prog->insnsi + i + delta; 19301 continue; 19302 } 19303 19304 if (insn->imm == BPF_FUNC_get_route_realm) 19305 prog->dst_needed = 1; 19306 if (insn->imm == BPF_FUNC_get_prandom_u32) 19307 bpf_user_rnd_init_once(); 19308 if (insn->imm == BPF_FUNC_override_return) 19309 prog->kprobe_override = 1; 19310 if (insn->imm == BPF_FUNC_tail_call) { 19311 /* If we tail call into other programs, we 19312 * cannot make any assumptions since they can 19313 * be replaced dynamically during runtime in 19314 * the program array. 19315 */ 19316 prog->cb_access = 1; 19317 if (!allow_tail_call_in_subprogs(env)) 19318 prog->aux->stack_depth = MAX_BPF_STACK; 19319 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 19320 19321 /* mark bpf_tail_call as different opcode to avoid 19322 * conditional branch in the interpreter for every normal 19323 * call and to prevent accidental JITing by JIT compiler 19324 * that doesn't support bpf_tail_call yet 19325 */ 19326 insn->imm = 0; 19327 insn->code = BPF_JMP | BPF_TAIL_CALL; 19328 19329 aux = &env->insn_aux_data[i + delta]; 19330 if (env->bpf_capable && !prog->blinding_requested && 19331 prog->jit_requested && 19332 !bpf_map_key_poisoned(aux) && 19333 !bpf_map_ptr_poisoned(aux) && 19334 !bpf_map_ptr_unpriv(aux)) { 19335 struct bpf_jit_poke_descriptor desc = { 19336 .reason = BPF_POKE_REASON_TAIL_CALL, 19337 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 19338 .tail_call.key = bpf_map_key_immediate(aux), 19339 .insn_idx = i + delta, 19340 }; 19341 19342 ret = bpf_jit_add_poke_descriptor(prog, &desc); 19343 if (ret < 0) { 19344 verbose(env, "adding tail call poke descriptor failed\n"); 19345 return ret; 19346 } 19347 19348 insn->imm = ret + 1; 19349 continue; 19350 } 19351 19352 if (!bpf_map_ptr_unpriv(aux)) 19353 continue; 19354 19355 /* instead of changing every JIT dealing with tail_call 19356 * emit two extra insns: 19357 * if (index >= max_entries) goto out; 19358 * index &= array->index_mask; 19359 * to avoid out-of-bounds cpu speculation 19360 */ 19361 if (bpf_map_ptr_poisoned(aux)) { 19362 verbose(env, "tail_call abusing map_ptr\n"); 19363 return -EINVAL; 19364 } 19365 19366 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19367 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 19368 map_ptr->max_entries, 2); 19369 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 19370 container_of(map_ptr, 19371 struct bpf_array, 19372 map)->index_mask); 19373 insn_buf[2] = *insn; 19374 cnt = 3; 19375 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19376 if (!new_prog) 19377 return -ENOMEM; 19378 19379 delta += cnt - 1; 19380 env->prog = prog = new_prog; 19381 insn = new_prog->insnsi + i + delta; 19382 continue; 19383 } 19384 19385 if (insn->imm == BPF_FUNC_timer_set_callback) { 19386 /* The verifier will process callback_fn as many times as necessary 19387 * with different maps and the register states prepared by 19388 * set_timer_callback_state will be accurate. 19389 * 19390 * The following use case is valid: 19391 * map1 is shared by prog1, prog2, prog3. 19392 * prog1 calls bpf_timer_init for some map1 elements 19393 * prog2 calls bpf_timer_set_callback for some map1 elements. 19394 * Those that were not bpf_timer_init-ed will return -EINVAL. 19395 * prog3 calls bpf_timer_start for some map1 elements. 19396 * Those that were not both bpf_timer_init-ed and 19397 * bpf_timer_set_callback-ed will return -EINVAL. 19398 */ 19399 struct bpf_insn ld_addrs[2] = { 19400 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 19401 }; 19402 19403 insn_buf[0] = ld_addrs[0]; 19404 insn_buf[1] = ld_addrs[1]; 19405 insn_buf[2] = *insn; 19406 cnt = 3; 19407 19408 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19409 if (!new_prog) 19410 return -ENOMEM; 19411 19412 delta += cnt - 1; 19413 env->prog = prog = new_prog; 19414 insn = new_prog->insnsi + i + delta; 19415 goto patch_call_imm; 19416 } 19417 19418 if (is_storage_get_function(insn->imm)) { 19419 if (!env->prog->aux->sleepable || 19420 env->insn_aux_data[i + delta].storage_get_func_atomic) 19421 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 19422 else 19423 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 19424 insn_buf[1] = *insn; 19425 cnt = 2; 19426 19427 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19428 if (!new_prog) 19429 return -ENOMEM; 19430 19431 delta += cnt - 1; 19432 env->prog = prog = new_prog; 19433 insn = new_prog->insnsi + i + delta; 19434 goto patch_call_imm; 19435 } 19436 19437 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */ 19438 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) { 19439 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data, 19440 * bpf_mem_alloc() returns a ptr to the percpu data ptr. 19441 */ 19442 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0); 19443 insn_buf[1] = *insn; 19444 cnt = 2; 19445 19446 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19447 if (!new_prog) 19448 return -ENOMEM; 19449 19450 delta += cnt - 1; 19451 env->prog = prog = new_prog; 19452 insn = new_prog->insnsi + i + delta; 19453 goto patch_call_imm; 19454 } 19455 19456 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 19457 * and other inlining handlers are currently limited to 64 bit 19458 * only. 19459 */ 19460 if (prog->jit_requested && BITS_PER_LONG == 64 && 19461 (insn->imm == BPF_FUNC_map_lookup_elem || 19462 insn->imm == BPF_FUNC_map_update_elem || 19463 insn->imm == BPF_FUNC_map_delete_elem || 19464 insn->imm == BPF_FUNC_map_push_elem || 19465 insn->imm == BPF_FUNC_map_pop_elem || 19466 insn->imm == BPF_FUNC_map_peek_elem || 19467 insn->imm == BPF_FUNC_redirect_map || 19468 insn->imm == BPF_FUNC_for_each_map_elem || 19469 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 19470 aux = &env->insn_aux_data[i + delta]; 19471 if (bpf_map_ptr_poisoned(aux)) 19472 goto patch_call_imm; 19473 19474 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19475 ops = map_ptr->ops; 19476 if (insn->imm == BPF_FUNC_map_lookup_elem && 19477 ops->map_gen_lookup) { 19478 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 19479 if (cnt == -EOPNOTSUPP) 19480 goto patch_map_ops_generic; 19481 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19482 verbose(env, "bpf verifier is misconfigured\n"); 19483 return -EINVAL; 19484 } 19485 19486 new_prog = bpf_patch_insn_data(env, i + delta, 19487 insn_buf, cnt); 19488 if (!new_prog) 19489 return -ENOMEM; 19490 19491 delta += cnt - 1; 19492 env->prog = prog = new_prog; 19493 insn = new_prog->insnsi + i + delta; 19494 continue; 19495 } 19496 19497 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 19498 (void *(*)(struct bpf_map *map, void *key))NULL)); 19499 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 19500 (long (*)(struct bpf_map *map, void *key))NULL)); 19501 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 19502 (long (*)(struct bpf_map *map, void *key, void *value, 19503 u64 flags))NULL)); 19504 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 19505 (long (*)(struct bpf_map *map, void *value, 19506 u64 flags))NULL)); 19507 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 19508 (long (*)(struct bpf_map *map, void *value))NULL)); 19509 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 19510 (long (*)(struct bpf_map *map, void *value))NULL)); 19511 BUILD_BUG_ON(!__same_type(ops->map_redirect, 19512 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 19513 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 19514 (long (*)(struct bpf_map *map, 19515 bpf_callback_t callback_fn, 19516 void *callback_ctx, 19517 u64 flags))NULL)); 19518 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 19519 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 19520 19521 patch_map_ops_generic: 19522 switch (insn->imm) { 19523 case BPF_FUNC_map_lookup_elem: 19524 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 19525 continue; 19526 case BPF_FUNC_map_update_elem: 19527 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 19528 continue; 19529 case BPF_FUNC_map_delete_elem: 19530 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 19531 continue; 19532 case BPF_FUNC_map_push_elem: 19533 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 19534 continue; 19535 case BPF_FUNC_map_pop_elem: 19536 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 19537 continue; 19538 case BPF_FUNC_map_peek_elem: 19539 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 19540 continue; 19541 case BPF_FUNC_redirect_map: 19542 insn->imm = BPF_CALL_IMM(ops->map_redirect); 19543 continue; 19544 case BPF_FUNC_for_each_map_elem: 19545 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 19546 continue; 19547 case BPF_FUNC_map_lookup_percpu_elem: 19548 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 19549 continue; 19550 } 19551 19552 goto patch_call_imm; 19553 } 19554 19555 /* Implement bpf_jiffies64 inline. */ 19556 if (prog->jit_requested && BITS_PER_LONG == 64 && 19557 insn->imm == BPF_FUNC_jiffies64) { 19558 struct bpf_insn ld_jiffies_addr[2] = { 19559 BPF_LD_IMM64(BPF_REG_0, 19560 (unsigned long)&jiffies), 19561 }; 19562 19563 insn_buf[0] = ld_jiffies_addr[0]; 19564 insn_buf[1] = ld_jiffies_addr[1]; 19565 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 19566 BPF_REG_0, 0); 19567 cnt = 3; 19568 19569 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 19570 cnt); 19571 if (!new_prog) 19572 return -ENOMEM; 19573 19574 delta += cnt - 1; 19575 env->prog = prog = new_prog; 19576 insn = new_prog->insnsi + i + delta; 19577 continue; 19578 } 19579 19580 /* Implement bpf_get_func_arg inline. */ 19581 if (prog_type == BPF_PROG_TYPE_TRACING && 19582 insn->imm == BPF_FUNC_get_func_arg) { 19583 /* Load nr_args from ctx - 8 */ 19584 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19585 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 19586 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 19587 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 19588 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 19589 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19590 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 19591 insn_buf[7] = BPF_JMP_A(1); 19592 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 19593 cnt = 9; 19594 19595 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19596 if (!new_prog) 19597 return -ENOMEM; 19598 19599 delta += cnt - 1; 19600 env->prog = prog = new_prog; 19601 insn = new_prog->insnsi + i + delta; 19602 continue; 19603 } 19604 19605 /* Implement bpf_get_func_ret inline. */ 19606 if (prog_type == BPF_PROG_TYPE_TRACING && 19607 insn->imm == BPF_FUNC_get_func_ret) { 19608 if (eatype == BPF_TRACE_FEXIT || 19609 eatype == BPF_MODIFY_RETURN) { 19610 /* Load nr_args from ctx - 8 */ 19611 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19612 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 19613 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 19614 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 19615 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 19616 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 19617 cnt = 6; 19618 } else { 19619 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 19620 cnt = 1; 19621 } 19622 19623 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19624 if (!new_prog) 19625 return -ENOMEM; 19626 19627 delta += cnt - 1; 19628 env->prog = prog = new_prog; 19629 insn = new_prog->insnsi + i + delta; 19630 continue; 19631 } 19632 19633 /* Implement get_func_arg_cnt inline. */ 19634 if (prog_type == BPF_PROG_TYPE_TRACING && 19635 insn->imm == BPF_FUNC_get_func_arg_cnt) { 19636 /* Load nr_args from ctx - 8 */ 19637 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19638 19639 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19640 if (!new_prog) 19641 return -ENOMEM; 19642 19643 env->prog = prog = new_prog; 19644 insn = new_prog->insnsi + i + delta; 19645 continue; 19646 } 19647 19648 /* Implement bpf_get_func_ip inline. */ 19649 if (prog_type == BPF_PROG_TYPE_TRACING && 19650 insn->imm == BPF_FUNC_get_func_ip) { 19651 /* Load IP address from ctx - 16 */ 19652 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 19653 19654 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 19655 if (!new_prog) 19656 return -ENOMEM; 19657 19658 env->prog = prog = new_prog; 19659 insn = new_prog->insnsi + i + delta; 19660 continue; 19661 } 19662 19663 patch_call_imm: 19664 fn = env->ops->get_func_proto(insn->imm, env->prog); 19665 /* all functions that have prototype and verifier allowed 19666 * programs to call them, must be real in-kernel functions 19667 */ 19668 if (!fn->func) { 19669 verbose(env, 19670 "kernel subsystem misconfigured func %s#%d\n", 19671 func_id_name(insn->imm), insn->imm); 19672 return -EFAULT; 19673 } 19674 insn->imm = fn->func - __bpf_call_base; 19675 } 19676 19677 /* Since poke tab is now finalized, publish aux to tracker. */ 19678 for (i = 0; i < prog->aux->size_poke_tab; i++) { 19679 map_ptr = prog->aux->poke_tab[i].tail_call.map; 19680 if (!map_ptr->ops->map_poke_track || 19681 !map_ptr->ops->map_poke_untrack || 19682 !map_ptr->ops->map_poke_run) { 19683 verbose(env, "bpf verifier is misconfigured\n"); 19684 return -EINVAL; 19685 } 19686 19687 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 19688 if (ret < 0) { 19689 verbose(env, "tracking tail call prog failed\n"); 19690 return ret; 19691 } 19692 } 19693 19694 sort_kfunc_descs_by_imm_off(env->prog); 19695 19696 return 0; 19697 } 19698 19699 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 19700 int position, 19701 s32 stack_base, 19702 u32 callback_subprogno, 19703 u32 *cnt) 19704 { 19705 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 19706 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 19707 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 19708 int reg_loop_max = BPF_REG_6; 19709 int reg_loop_cnt = BPF_REG_7; 19710 int reg_loop_ctx = BPF_REG_8; 19711 19712 struct bpf_prog *new_prog; 19713 u32 callback_start; 19714 u32 call_insn_offset; 19715 s32 callback_offset; 19716 19717 /* This represents an inlined version of bpf_iter.c:bpf_loop, 19718 * be careful to modify this code in sync. 19719 */ 19720 struct bpf_insn insn_buf[] = { 19721 /* Return error and jump to the end of the patch if 19722 * expected number of iterations is too big. 19723 */ 19724 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 19725 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 19726 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 19727 /* spill R6, R7, R8 to use these as loop vars */ 19728 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 19729 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 19730 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 19731 /* initialize loop vars */ 19732 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 19733 BPF_MOV32_IMM(reg_loop_cnt, 0), 19734 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 19735 /* loop header, 19736 * if reg_loop_cnt >= reg_loop_max skip the loop body 19737 */ 19738 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 19739 /* callback call, 19740 * correct callback offset would be set after patching 19741 */ 19742 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 19743 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 19744 BPF_CALL_REL(0), 19745 /* increment loop counter */ 19746 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 19747 /* jump to loop header if callback returned 0 */ 19748 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 19749 /* return value of bpf_loop, 19750 * set R0 to the number of iterations 19751 */ 19752 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 19753 /* restore original values of R6, R7, R8 */ 19754 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 19755 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 19756 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 19757 }; 19758 19759 *cnt = ARRAY_SIZE(insn_buf); 19760 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 19761 if (!new_prog) 19762 return new_prog; 19763 19764 /* callback start is known only after patching */ 19765 callback_start = env->subprog_info[callback_subprogno].start; 19766 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 19767 call_insn_offset = position + 12; 19768 callback_offset = callback_start - call_insn_offset - 1; 19769 new_prog->insnsi[call_insn_offset].imm = callback_offset; 19770 19771 return new_prog; 19772 } 19773 19774 static bool is_bpf_loop_call(struct bpf_insn *insn) 19775 { 19776 return insn->code == (BPF_JMP | BPF_CALL) && 19777 insn->src_reg == 0 && 19778 insn->imm == BPF_FUNC_loop; 19779 } 19780 19781 /* For all sub-programs in the program (including main) check 19782 * insn_aux_data to see if there are bpf_loop calls that require 19783 * inlining. If such calls are found the calls are replaced with a 19784 * sequence of instructions produced by `inline_bpf_loop` function and 19785 * subprog stack_depth is increased by the size of 3 registers. 19786 * This stack space is used to spill values of the R6, R7, R8. These 19787 * registers are used to store the loop bound, counter and context 19788 * variables. 19789 */ 19790 static int optimize_bpf_loop(struct bpf_verifier_env *env) 19791 { 19792 struct bpf_subprog_info *subprogs = env->subprog_info; 19793 int i, cur_subprog = 0, cnt, delta = 0; 19794 struct bpf_insn *insn = env->prog->insnsi; 19795 int insn_cnt = env->prog->len; 19796 u16 stack_depth = subprogs[cur_subprog].stack_depth; 19797 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19798 u16 stack_depth_extra = 0; 19799 19800 for (i = 0; i < insn_cnt; i++, insn++) { 19801 struct bpf_loop_inline_state *inline_state = 19802 &env->insn_aux_data[i + delta].loop_inline_state; 19803 19804 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 19805 struct bpf_prog *new_prog; 19806 19807 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 19808 new_prog = inline_bpf_loop(env, 19809 i + delta, 19810 -(stack_depth + stack_depth_extra), 19811 inline_state->callback_subprogno, 19812 &cnt); 19813 if (!new_prog) 19814 return -ENOMEM; 19815 19816 delta += cnt - 1; 19817 env->prog = new_prog; 19818 insn = new_prog->insnsi + i + delta; 19819 } 19820 19821 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 19822 subprogs[cur_subprog].stack_depth += stack_depth_extra; 19823 cur_subprog++; 19824 stack_depth = subprogs[cur_subprog].stack_depth; 19825 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 19826 stack_depth_extra = 0; 19827 } 19828 } 19829 19830 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 19831 19832 return 0; 19833 } 19834 19835 static void free_states(struct bpf_verifier_env *env) 19836 { 19837 struct bpf_verifier_state_list *sl, *sln; 19838 int i; 19839 19840 sl = env->free_list; 19841 while (sl) { 19842 sln = sl->next; 19843 free_verifier_state(&sl->state, false); 19844 kfree(sl); 19845 sl = sln; 19846 } 19847 env->free_list = NULL; 19848 19849 if (!env->explored_states) 19850 return; 19851 19852 for (i = 0; i < state_htab_size(env); i++) { 19853 sl = env->explored_states[i]; 19854 19855 while (sl) { 19856 sln = sl->next; 19857 free_verifier_state(&sl->state, false); 19858 kfree(sl); 19859 sl = sln; 19860 } 19861 env->explored_states[i] = NULL; 19862 } 19863 } 19864 19865 static int do_check_common(struct bpf_verifier_env *env, int subprog, bool is_ex_cb) 19866 { 19867 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 19868 struct bpf_verifier_state *state; 19869 struct bpf_reg_state *regs; 19870 int ret, i; 19871 19872 env->prev_linfo = NULL; 19873 env->pass_cnt++; 19874 19875 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 19876 if (!state) 19877 return -ENOMEM; 19878 state->curframe = 0; 19879 state->speculative = false; 19880 state->branches = 1; 19881 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 19882 if (!state->frame[0]) { 19883 kfree(state); 19884 return -ENOMEM; 19885 } 19886 env->cur_state = state; 19887 init_func_state(env, state->frame[0], 19888 BPF_MAIN_FUNC /* callsite */, 19889 0 /* frameno */, 19890 subprog); 19891 state->first_insn_idx = env->subprog_info[subprog].start; 19892 state->last_insn_idx = -1; 19893 19894 regs = state->frame[state->curframe]->regs; 19895 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 19896 ret = btf_prepare_func_args(env, subprog, regs, is_ex_cb); 19897 if (ret) 19898 goto out; 19899 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 19900 if (regs[i].type == PTR_TO_CTX) 19901 mark_reg_known_zero(env, regs, i); 19902 else if (regs[i].type == SCALAR_VALUE) 19903 mark_reg_unknown(env, regs, i); 19904 else if (base_type(regs[i].type) == PTR_TO_MEM) { 19905 const u32 mem_size = regs[i].mem_size; 19906 19907 mark_reg_known_zero(env, regs, i); 19908 regs[i].mem_size = mem_size; 19909 regs[i].id = ++env->id_gen; 19910 } 19911 } 19912 if (is_ex_cb) { 19913 state->frame[0]->in_exception_callback_fn = true; 19914 env->subprog_info[subprog].is_cb = true; 19915 env->subprog_info[subprog].is_async_cb = true; 19916 env->subprog_info[subprog].is_exception_cb = true; 19917 } 19918 } else { 19919 /* 1st arg to a function */ 19920 regs[BPF_REG_1].type = PTR_TO_CTX; 19921 mark_reg_known_zero(env, regs, BPF_REG_1); 19922 ret = btf_check_subprog_arg_match(env, subprog, regs); 19923 if (ret == -EFAULT) 19924 /* unlikely verifier bug. abort. 19925 * ret == 0 and ret < 0 are sadly acceptable for 19926 * main() function due to backward compatibility. 19927 * Like socket filter program may be written as: 19928 * int bpf_prog(struct pt_regs *ctx) 19929 * and never dereference that ctx in the program. 19930 * 'struct pt_regs' is a type mismatch for socket 19931 * filter that should be using 'struct __sk_buff'. 19932 */ 19933 goto out; 19934 } 19935 19936 ret = do_check(env); 19937 out: 19938 /* check for NULL is necessary, since cur_state can be freed inside 19939 * do_check() under memory pressure. 19940 */ 19941 if (env->cur_state) { 19942 free_verifier_state(env->cur_state, true); 19943 env->cur_state = NULL; 19944 } 19945 while (!pop_stack(env, NULL, NULL, false)); 19946 if (!ret && pop_log) 19947 bpf_vlog_reset(&env->log, 0); 19948 free_states(env); 19949 return ret; 19950 } 19951 19952 /* Lazily verify all global functions based on their BTF, if they are called 19953 * from main BPF program or any of subprograms transitively. 19954 * BPF global subprogs called from dead code are not validated. 19955 * All callable global functions must pass verification. 19956 * Otherwise the whole program is rejected. 19957 * Consider: 19958 * int bar(int); 19959 * int foo(int f) 19960 * { 19961 * return bar(f); 19962 * } 19963 * int bar(int b) 19964 * { 19965 * ... 19966 * } 19967 * foo() will be verified first for R1=any_scalar_value. During verification it 19968 * will be assumed that bar() already verified successfully and call to bar() 19969 * from foo() will be checked for type match only. Later bar() will be verified 19970 * independently to check that it's safe for R1=any_scalar_value. 19971 */ 19972 static int do_check_subprogs(struct bpf_verifier_env *env) 19973 { 19974 struct bpf_prog_aux *aux = env->prog->aux; 19975 struct bpf_func_info_aux *sub_aux; 19976 int i, ret, new_cnt; 19977 19978 if (!aux->func_info) 19979 return 0; 19980 19981 /* exception callback is presumed to be always called */ 19982 if (env->exception_callback_subprog) 19983 subprog_aux(env, env->exception_callback_subprog)->called = true; 19984 19985 again: 19986 new_cnt = 0; 19987 for (i = 1; i < env->subprog_cnt; i++) { 19988 if (!subprog_is_global(env, i)) 19989 continue; 19990 19991 sub_aux = subprog_aux(env, i); 19992 if (!sub_aux->called || sub_aux->verified) 19993 continue; 19994 19995 env->insn_idx = env->subprog_info[i].start; 19996 WARN_ON_ONCE(env->insn_idx == 0); 19997 ret = do_check_common(env, i, env->exception_callback_subprog == i); 19998 if (ret) { 19999 return ret; 20000 } else if (env->log.level & BPF_LOG_LEVEL) { 20001 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 20002 i, subprog_name(env, i)); 20003 } 20004 20005 /* We verified new global subprog, it might have called some 20006 * more global subprogs that we haven't verified yet, so we 20007 * need to do another pass over subprogs to verify those. 20008 */ 20009 sub_aux->verified = true; 20010 new_cnt++; 20011 } 20012 20013 /* We can't loop forever as we verify at least one global subprog on 20014 * each pass. 20015 */ 20016 if (new_cnt) 20017 goto again; 20018 20019 return 0; 20020 } 20021 20022 static int do_check_main(struct bpf_verifier_env *env) 20023 { 20024 int ret; 20025 20026 env->insn_idx = 0; 20027 ret = do_check_common(env, 0, false); 20028 if (!ret) 20029 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 20030 return ret; 20031 } 20032 20033 20034 static void print_verification_stats(struct bpf_verifier_env *env) 20035 { 20036 int i; 20037 20038 if (env->log.level & BPF_LOG_STATS) { 20039 verbose(env, "verification time %lld usec\n", 20040 div_u64(env->verification_time, 1000)); 20041 verbose(env, "stack depth "); 20042 for (i = 0; i < env->subprog_cnt; i++) { 20043 u32 depth = env->subprog_info[i].stack_depth; 20044 20045 verbose(env, "%d", depth); 20046 if (i + 1 < env->subprog_cnt) 20047 verbose(env, "+"); 20048 } 20049 verbose(env, "\n"); 20050 } 20051 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 20052 "total_states %d peak_states %d mark_read %d\n", 20053 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 20054 env->max_states_per_insn, env->total_states, 20055 env->peak_states, env->longest_mark_read_walk); 20056 } 20057 20058 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 20059 { 20060 const struct btf_type *t, *func_proto; 20061 const struct bpf_struct_ops *st_ops; 20062 const struct btf_member *member; 20063 struct bpf_prog *prog = env->prog; 20064 u32 btf_id, member_idx; 20065 const char *mname; 20066 20067 if (!prog->gpl_compatible) { 20068 verbose(env, "struct ops programs must have a GPL compatible license\n"); 20069 return -EINVAL; 20070 } 20071 20072 btf_id = prog->aux->attach_btf_id; 20073 st_ops = bpf_struct_ops_find(btf_id); 20074 if (!st_ops) { 20075 verbose(env, "attach_btf_id %u is not a supported struct\n", 20076 btf_id); 20077 return -ENOTSUPP; 20078 } 20079 20080 t = st_ops->type; 20081 member_idx = prog->expected_attach_type; 20082 if (member_idx >= btf_type_vlen(t)) { 20083 verbose(env, "attach to invalid member idx %u of struct %s\n", 20084 member_idx, st_ops->name); 20085 return -EINVAL; 20086 } 20087 20088 member = &btf_type_member(t)[member_idx]; 20089 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 20090 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 20091 NULL); 20092 if (!func_proto) { 20093 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 20094 mname, member_idx, st_ops->name); 20095 return -EINVAL; 20096 } 20097 20098 if (st_ops->check_member) { 20099 int err = st_ops->check_member(t, member, prog); 20100 20101 if (err) { 20102 verbose(env, "attach to unsupported member %s of struct %s\n", 20103 mname, st_ops->name); 20104 return err; 20105 } 20106 } 20107 20108 prog->aux->attach_func_proto = func_proto; 20109 prog->aux->attach_func_name = mname; 20110 env->ops = st_ops->verifier_ops; 20111 20112 return 0; 20113 } 20114 #define SECURITY_PREFIX "security_" 20115 20116 static int check_attach_modify_return(unsigned long addr, const char *func_name) 20117 { 20118 if (within_error_injection_list(addr) || 20119 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 20120 return 0; 20121 20122 return -EINVAL; 20123 } 20124 20125 /* list of non-sleepable functions that are otherwise on 20126 * ALLOW_ERROR_INJECTION list 20127 */ 20128 BTF_SET_START(btf_non_sleepable_error_inject) 20129 /* Three functions below can be called from sleepable and non-sleepable context. 20130 * Assume non-sleepable from bpf safety point of view. 20131 */ 20132 BTF_ID(func, __filemap_add_folio) 20133 BTF_ID(func, should_fail_alloc_page) 20134 BTF_ID(func, should_failslab) 20135 BTF_SET_END(btf_non_sleepable_error_inject) 20136 20137 static int check_non_sleepable_error_inject(u32 btf_id) 20138 { 20139 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 20140 } 20141 20142 int bpf_check_attach_target(struct bpf_verifier_log *log, 20143 const struct bpf_prog *prog, 20144 const struct bpf_prog *tgt_prog, 20145 u32 btf_id, 20146 struct bpf_attach_target_info *tgt_info) 20147 { 20148 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 20149 const char prefix[] = "btf_trace_"; 20150 int ret = 0, subprog = -1, i; 20151 const struct btf_type *t; 20152 bool conservative = true; 20153 const char *tname; 20154 struct btf *btf; 20155 long addr = 0; 20156 struct module *mod = NULL; 20157 20158 if (!btf_id) { 20159 bpf_log(log, "Tracing programs must provide btf_id\n"); 20160 return -EINVAL; 20161 } 20162 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 20163 if (!btf) { 20164 bpf_log(log, 20165 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 20166 return -EINVAL; 20167 } 20168 t = btf_type_by_id(btf, btf_id); 20169 if (!t) { 20170 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 20171 return -EINVAL; 20172 } 20173 tname = btf_name_by_offset(btf, t->name_off); 20174 if (!tname) { 20175 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 20176 return -EINVAL; 20177 } 20178 if (tgt_prog) { 20179 struct bpf_prog_aux *aux = tgt_prog->aux; 20180 20181 if (bpf_prog_is_dev_bound(prog->aux) && 20182 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 20183 bpf_log(log, "Target program bound device mismatch"); 20184 return -EINVAL; 20185 } 20186 20187 for (i = 0; i < aux->func_info_cnt; i++) 20188 if (aux->func_info[i].type_id == btf_id) { 20189 subprog = i; 20190 break; 20191 } 20192 if (subprog == -1) { 20193 bpf_log(log, "Subprog %s doesn't exist\n", tname); 20194 return -EINVAL; 20195 } 20196 if (aux->func && aux->func[subprog]->aux->exception_cb) { 20197 bpf_log(log, 20198 "%s programs cannot attach to exception callback\n", 20199 prog_extension ? "Extension" : "FENTRY/FEXIT"); 20200 return -EINVAL; 20201 } 20202 conservative = aux->func_info_aux[subprog].unreliable; 20203 if (prog_extension) { 20204 if (conservative) { 20205 bpf_log(log, 20206 "Cannot replace static functions\n"); 20207 return -EINVAL; 20208 } 20209 if (!prog->jit_requested) { 20210 bpf_log(log, 20211 "Extension programs should be JITed\n"); 20212 return -EINVAL; 20213 } 20214 } 20215 if (!tgt_prog->jited) { 20216 bpf_log(log, "Can attach to only JITed progs\n"); 20217 return -EINVAL; 20218 } 20219 if (tgt_prog->type == prog->type) { 20220 /* Cannot fentry/fexit another fentry/fexit program. 20221 * Cannot attach program extension to another extension. 20222 * It's ok to attach fentry/fexit to extension program. 20223 */ 20224 bpf_log(log, "Cannot recursively attach\n"); 20225 return -EINVAL; 20226 } 20227 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 20228 prog_extension && 20229 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 20230 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 20231 /* Program extensions can extend all program types 20232 * except fentry/fexit. The reason is the following. 20233 * The fentry/fexit programs are used for performance 20234 * analysis, stats and can be attached to any program 20235 * type except themselves. When extension program is 20236 * replacing XDP function it is necessary to allow 20237 * performance analysis of all functions. Both original 20238 * XDP program and its program extension. Hence 20239 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 20240 * allowed. If extending of fentry/fexit was allowed it 20241 * would be possible to create long call chain 20242 * fentry->extension->fentry->extension beyond 20243 * reasonable stack size. Hence extending fentry is not 20244 * allowed. 20245 */ 20246 bpf_log(log, "Cannot extend fentry/fexit\n"); 20247 return -EINVAL; 20248 } 20249 } else { 20250 if (prog_extension) { 20251 bpf_log(log, "Cannot replace kernel functions\n"); 20252 return -EINVAL; 20253 } 20254 } 20255 20256 switch (prog->expected_attach_type) { 20257 case BPF_TRACE_RAW_TP: 20258 if (tgt_prog) { 20259 bpf_log(log, 20260 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 20261 return -EINVAL; 20262 } 20263 if (!btf_type_is_typedef(t)) { 20264 bpf_log(log, "attach_btf_id %u is not a typedef\n", 20265 btf_id); 20266 return -EINVAL; 20267 } 20268 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 20269 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 20270 btf_id, tname); 20271 return -EINVAL; 20272 } 20273 tname += sizeof(prefix) - 1; 20274 t = btf_type_by_id(btf, t->type); 20275 if (!btf_type_is_ptr(t)) 20276 /* should never happen in valid vmlinux build */ 20277 return -EINVAL; 20278 t = btf_type_by_id(btf, t->type); 20279 if (!btf_type_is_func_proto(t)) 20280 /* should never happen in valid vmlinux build */ 20281 return -EINVAL; 20282 20283 break; 20284 case BPF_TRACE_ITER: 20285 if (!btf_type_is_func(t)) { 20286 bpf_log(log, "attach_btf_id %u is not a function\n", 20287 btf_id); 20288 return -EINVAL; 20289 } 20290 t = btf_type_by_id(btf, t->type); 20291 if (!btf_type_is_func_proto(t)) 20292 return -EINVAL; 20293 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 20294 if (ret) 20295 return ret; 20296 break; 20297 default: 20298 if (!prog_extension) 20299 return -EINVAL; 20300 fallthrough; 20301 case BPF_MODIFY_RETURN: 20302 case BPF_LSM_MAC: 20303 case BPF_LSM_CGROUP: 20304 case BPF_TRACE_FENTRY: 20305 case BPF_TRACE_FEXIT: 20306 if (!btf_type_is_func(t)) { 20307 bpf_log(log, "attach_btf_id %u is not a function\n", 20308 btf_id); 20309 return -EINVAL; 20310 } 20311 if (prog_extension && 20312 btf_check_type_match(log, prog, btf, t)) 20313 return -EINVAL; 20314 t = btf_type_by_id(btf, t->type); 20315 if (!btf_type_is_func_proto(t)) 20316 return -EINVAL; 20317 20318 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 20319 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 20320 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 20321 return -EINVAL; 20322 20323 if (tgt_prog && conservative) 20324 t = NULL; 20325 20326 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 20327 if (ret < 0) 20328 return ret; 20329 20330 if (tgt_prog) { 20331 if (subprog == 0) 20332 addr = (long) tgt_prog->bpf_func; 20333 else 20334 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 20335 } else { 20336 if (btf_is_module(btf)) { 20337 mod = btf_try_get_module(btf); 20338 if (mod) 20339 addr = find_kallsyms_symbol_value(mod, tname); 20340 else 20341 addr = 0; 20342 } else { 20343 addr = kallsyms_lookup_name(tname); 20344 } 20345 if (!addr) { 20346 module_put(mod); 20347 bpf_log(log, 20348 "The address of function %s cannot be found\n", 20349 tname); 20350 return -ENOENT; 20351 } 20352 } 20353 20354 if (prog->aux->sleepable) { 20355 ret = -EINVAL; 20356 switch (prog->type) { 20357 case BPF_PROG_TYPE_TRACING: 20358 20359 /* fentry/fexit/fmod_ret progs can be sleepable if they are 20360 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 20361 */ 20362 if (!check_non_sleepable_error_inject(btf_id) && 20363 within_error_injection_list(addr)) 20364 ret = 0; 20365 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 20366 * in the fmodret id set with the KF_SLEEPABLE flag. 20367 */ 20368 else { 20369 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 20370 prog); 20371 20372 if (flags && (*flags & KF_SLEEPABLE)) 20373 ret = 0; 20374 } 20375 break; 20376 case BPF_PROG_TYPE_LSM: 20377 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 20378 * Only some of them are sleepable. 20379 */ 20380 if (bpf_lsm_is_sleepable_hook(btf_id)) 20381 ret = 0; 20382 break; 20383 default: 20384 break; 20385 } 20386 if (ret) { 20387 module_put(mod); 20388 bpf_log(log, "%s is not sleepable\n", tname); 20389 return ret; 20390 } 20391 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 20392 if (tgt_prog) { 20393 module_put(mod); 20394 bpf_log(log, "can't modify return codes of BPF programs\n"); 20395 return -EINVAL; 20396 } 20397 ret = -EINVAL; 20398 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 20399 !check_attach_modify_return(addr, tname)) 20400 ret = 0; 20401 if (ret) { 20402 module_put(mod); 20403 bpf_log(log, "%s() is not modifiable\n", tname); 20404 return ret; 20405 } 20406 } 20407 20408 break; 20409 } 20410 tgt_info->tgt_addr = addr; 20411 tgt_info->tgt_name = tname; 20412 tgt_info->tgt_type = t; 20413 tgt_info->tgt_mod = mod; 20414 return 0; 20415 } 20416 20417 BTF_SET_START(btf_id_deny) 20418 BTF_ID_UNUSED 20419 #ifdef CONFIG_SMP 20420 BTF_ID(func, migrate_disable) 20421 BTF_ID(func, migrate_enable) 20422 #endif 20423 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 20424 BTF_ID(func, rcu_read_unlock_strict) 20425 #endif 20426 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 20427 BTF_ID(func, preempt_count_add) 20428 BTF_ID(func, preempt_count_sub) 20429 #endif 20430 #ifdef CONFIG_PREEMPT_RCU 20431 BTF_ID(func, __rcu_read_lock) 20432 BTF_ID(func, __rcu_read_unlock) 20433 #endif 20434 BTF_SET_END(btf_id_deny) 20435 20436 static bool can_be_sleepable(struct bpf_prog *prog) 20437 { 20438 if (prog->type == BPF_PROG_TYPE_TRACING) { 20439 switch (prog->expected_attach_type) { 20440 case BPF_TRACE_FENTRY: 20441 case BPF_TRACE_FEXIT: 20442 case BPF_MODIFY_RETURN: 20443 case BPF_TRACE_ITER: 20444 return true; 20445 default: 20446 return false; 20447 } 20448 } 20449 return prog->type == BPF_PROG_TYPE_LSM || 20450 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 20451 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 20452 } 20453 20454 static int check_attach_btf_id(struct bpf_verifier_env *env) 20455 { 20456 struct bpf_prog *prog = env->prog; 20457 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 20458 struct bpf_attach_target_info tgt_info = {}; 20459 u32 btf_id = prog->aux->attach_btf_id; 20460 struct bpf_trampoline *tr; 20461 int ret; 20462 u64 key; 20463 20464 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 20465 if (prog->aux->sleepable) 20466 /* attach_btf_id checked to be zero already */ 20467 return 0; 20468 verbose(env, "Syscall programs can only be sleepable\n"); 20469 return -EINVAL; 20470 } 20471 20472 if (prog->aux->sleepable && !can_be_sleepable(prog)) { 20473 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 20474 return -EINVAL; 20475 } 20476 20477 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 20478 return check_struct_ops_btf_id(env); 20479 20480 if (prog->type != BPF_PROG_TYPE_TRACING && 20481 prog->type != BPF_PROG_TYPE_LSM && 20482 prog->type != BPF_PROG_TYPE_EXT) 20483 return 0; 20484 20485 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 20486 if (ret) 20487 return ret; 20488 20489 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 20490 /* to make freplace equivalent to their targets, they need to 20491 * inherit env->ops and expected_attach_type for the rest of the 20492 * verification 20493 */ 20494 env->ops = bpf_verifier_ops[tgt_prog->type]; 20495 prog->expected_attach_type = tgt_prog->expected_attach_type; 20496 } 20497 20498 /* store info about the attachment target that will be used later */ 20499 prog->aux->attach_func_proto = tgt_info.tgt_type; 20500 prog->aux->attach_func_name = tgt_info.tgt_name; 20501 prog->aux->mod = tgt_info.tgt_mod; 20502 20503 if (tgt_prog) { 20504 prog->aux->saved_dst_prog_type = tgt_prog->type; 20505 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 20506 } 20507 20508 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 20509 prog->aux->attach_btf_trace = true; 20510 return 0; 20511 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 20512 if (!bpf_iter_prog_supported(prog)) 20513 return -EINVAL; 20514 return 0; 20515 } 20516 20517 if (prog->type == BPF_PROG_TYPE_LSM) { 20518 ret = bpf_lsm_verify_prog(&env->log, prog); 20519 if (ret < 0) 20520 return ret; 20521 } else if (prog->type == BPF_PROG_TYPE_TRACING && 20522 btf_id_set_contains(&btf_id_deny, btf_id)) { 20523 return -EINVAL; 20524 } 20525 20526 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 20527 tr = bpf_trampoline_get(key, &tgt_info); 20528 if (!tr) 20529 return -ENOMEM; 20530 20531 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 20532 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 20533 20534 prog->aux->dst_trampoline = tr; 20535 return 0; 20536 } 20537 20538 struct btf *bpf_get_btf_vmlinux(void) 20539 { 20540 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 20541 mutex_lock(&bpf_verifier_lock); 20542 if (!btf_vmlinux) 20543 btf_vmlinux = btf_parse_vmlinux(); 20544 mutex_unlock(&bpf_verifier_lock); 20545 } 20546 return btf_vmlinux; 20547 } 20548 20549 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 20550 { 20551 u64 start_time = ktime_get_ns(); 20552 struct bpf_verifier_env *env; 20553 int i, len, ret = -EINVAL, err; 20554 u32 log_true_size; 20555 bool is_priv; 20556 20557 /* no program is valid */ 20558 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 20559 return -EINVAL; 20560 20561 /* 'struct bpf_verifier_env' can be global, but since it's not small, 20562 * allocate/free it every time bpf_check() is called 20563 */ 20564 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 20565 if (!env) 20566 return -ENOMEM; 20567 20568 env->bt.env = env; 20569 20570 len = (*prog)->len; 20571 env->insn_aux_data = 20572 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 20573 ret = -ENOMEM; 20574 if (!env->insn_aux_data) 20575 goto err_free_env; 20576 for (i = 0; i < len; i++) 20577 env->insn_aux_data[i].orig_idx = i; 20578 env->prog = *prog; 20579 env->ops = bpf_verifier_ops[env->prog->type]; 20580 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 20581 20582 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 20583 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 20584 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 20585 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 20586 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 20587 20588 bpf_get_btf_vmlinux(); 20589 20590 /* grab the mutex to protect few globals used by verifier */ 20591 if (!is_priv) 20592 mutex_lock(&bpf_verifier_lock); 20593 20594 /* user could have requested verbose verifier output 20595 * and supplied buffer to store the verification trace 20596 */ 20597 ret = bpf_vlog_init(&env->log, attr->log_level, 20598 (char __user *) (unsigned long) attr->log_buf, 20599 attr->log_size); 20600 if (ret) 20601 goto err_unlock; 20602 20603 mark_verifier_state_clean(env); 20604 20605 if (IS_ERR(btf_vmlinux)) { 20606 /* Either gcc or pahole or kernel are broken. */ 20607 verbose(env, "in-kernel BTF is malformed\n"); 20608 ret = PTR_ERR(btf_vmlinux); 20609 goto skip_full_check; 20610 } 20611 20612 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 20613 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 20614 env->strict_alignment = true; 20615 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 20616 env->strict_alignment = false; 20617 20618 if (is_priv) 20619 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 20620 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 20621 20622 env->explored_states = kvcalloc(state_htab_size(env), 20623 sizeof(struct bpf_verifier_state_list *), 20624 GFP_USER); 20625 ret = -ENOMEM; 20626 if (!env->explored_states) 20627 goto skip_full_check; 20628 20629 ret = check_btf_info_early(env, attr, uattr); 20630 if (ret < 0) 20631 goto skip_full_check; 20632 20633 ret = add_subprog_and_kfunc(env); 20634 if (ret < 0) 20635 goto skip_full_check; 20636 20637 ret = check_subprogs(env); 20638 if (ret < 0) 20639 goto skip_full_check; 20640 20641 ret = check_btf_info(env, attr, uattr); 20642 if (ret < 0) 20643 goto skip_full_check; 20644 20645 ret = check_attach_btf_id(env); 20646 if (ret) 20647 goto skip_full_check; 20648 20649 ret = resolve_pseudo_ldimm64(env); 20650 if (ret < 0) 20651 goto skip_full_check; 20652 20653 if (bpf_prog_is_offloaded(env->prog->aux)) { 20654 ret = bpf_prog_offload_verifier_prep(env->prog); 20655 if (ret) 20656 goto skip_full_check; 20657 } 20658 20659 ret = check_cfg(env); 20660 if (ret < 0) 20661 goto skip_full_check; 20662 20663 ret = do_check_main(env); 20664 ret = ret ?: do_check_subprogs(env); 20665 20666 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 20667 ret = bpf_prog_offload_finalize(env); 20668 20669 skip_full_check: 20670 kvfree(env->explored_states); 20671 20672 if (ret == 0) 20673 ret = check_max_stack_depth(env); 20674 20675 /* instruction rewrites happen after this point */ 20676 if (ret == 0) 20677 ret = optimize_bpf_loop(env); 20678 20679 if (is_priv) { 20680 if (ret == 0) 20681 opt_hard_wire_dead_code_branches(env); 20682 if (ret == 0) 20683 ret = opt_remove_dead_code(env); 20684 if (ret == 0) 20685 ret = opt_remove_nops(env); 20686 } else { 20687 if (ret == 0) 20688 sanitize_dead_code(env); 20689 } 20690 20691 if (ret == 0) 20692 /* program is valid, convert *(u32*)(ctx + off) accesses */ 20693 ret = convert_ctx_accesses(env); 20694 20695 if (ret == 0) 20696 ret = do_misc_fixups(env); 20697 20698 /* do 32-bit optimization after insn patching has done so those patched 20699 * insns could be handled correctly. 20700 */ 20701 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 20702 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 20703 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 20704 : false; 20705 } 20706 20707 if (ret == 0) 20708 ret = fixup_call_args(env); 20709 20710 env->verification_time = ktime_get_ns() - start_time; 20711 print_verification_stats(env); 20712 env->prog->aux->verified_insns = env->insn_processed; 20713 20714 /* preserve original error even if log finalization is successful */ 20715 err = bpf_vlog_finalize(&env->log, &log_true_size); 20716 if (err) 20717 ret = err; 20718 20719 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 20720 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 20721 &log_true_size, sizeof(log_true_size))) { 20722 ret = -EFAULT; 20723 goto err_release_maps; 20724 } 20725 20726 if (ret) 20727 goto err_release_maps; 20728 20729 if (env->used_map_cnt) { 20730 /* if program passed verifier, update used_maps in bpf_prog_info */ 20731 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 20732 sizeof(env->used_maps[0]), 20733 GFP_KERNEL); 20734 20735 if (!env->prog->aux->used_maps) { 20736 ret = -ENOMEM; 20737 goto err_release_maps; 20738 } 20739 20740 memcpy(env->prog->aux->used_maps, env->used_maps, 20741 sizeof(env->used_maps[0]) * env->used_map_cnt); 20742 env->prog->aux->used_map_cnt = env->used_map_cnt; 20743 } 20744 if (env->used_btf_cnt) { 20745 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 20746 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 20747 sizeof(env->used_btfs[0]), 20748 GFP_KERNEL); 20749 if (!env->prog->aux->used_btfs) { 20750 ret = -ENOMEM; 20751 goto err_release_maps; 20752 } 20753 20754 memcpy(env->prog->aux->used_btfs, env->used_btfs, 20755 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 20756 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 20757 } 20758 if (env->used_map_cnt || env->used_btf_cnt) { 20759 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 20760 * bpf_ld_imm64 instructions 20761 */ 20762 convert_pseudo_ld_imm64(env); 20763 } 20764 20765 adjust_btf_func(env); 20766 20767 err_release_maps: 20768 if (!env->prog->aux->used_maps) 20769 /* if we didn't copy map pointers into bpf_prog_info, release 20770 * them now. Otherwise free_used_maps() will release them. 20771 */ 20772 release_maps(env); 20773 if (!env->prog->aux->used_btfs) 20774 release_btfs(env); 20775 20776 /* extension progs temporarily inherit the attach_type of their targets 20777 for verification purposes, so set it back to zero before returning 20778 */ 20779 if (env->prog->type == BPF_PROG_TYPE_EXT) 20780 env->prog->expected_attach_type = 0; 20781 20782 *prog = env->prog; 20783 err_unlock: 20784 if (!is_priv) 20785 mutex_unlock(&bpf_verifier_lock); 20786 vfree(env->insn_aux_data); 20787 err_free_env: 20788 kfree(env); 20789 return ret; 20790 } 20791