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 /* verifier 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_GLOBAL_PERCPU_MA_MAX_SIZE 512 194 195 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx); 196 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id); 197 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 198 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 199 static int ref_set_non_owning(struct bpf_verifier_env *env, 200 struct bpf_reg_state *reg); 201 static void specialize_kfunc(struct bpf_verifier_env *env, 202 u32 func_id, u16 offset, unsigned long *addr); 203 static bool is_trusted_reg(const struct bpf_reg_state *reg); 204 205 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 206 { 207 return aux->map_ptr_state.poison; 208 } 209 210 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 211 { 212 return aux->map_ptr_state.unpriv; 213 } 214 215 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 216 struct bpf_map *map, 217 bool unpriv, bool poison) 218 { 219 unpriv |= bpf_map_ptr_unpriv(aux); 220 aux->map_ptr_state.unpriv = unpriv; 221 aux->map_ptr_state.poison = poison; 222 aux->map_ptr_state.map_ptr = map; 223 } 224 225 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 226 { 227 return aux->map_key_state & BPF_MAP_KEY_POISON; 228 } 229 230 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 231 { 232 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 233 } 234 235 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 236 { 237 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 238 } 239 240 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 241 { 242 bool poisoned = bpf_map_key_poisoned(aux); 243 244 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 245 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 246 } 247 248 static bool bpf_helper_call(const struct bpf_insn *insn) 249 { 250 return insn->code == (BPF_JMP | BPF_CALL) && 251 insn->src_reg == 0; 252 } 253 254 static bool bpf_pseudo_call(const struct bpf_insn *insn) 255 { 256 return insn->code == (BPF_JMP | BPF_CALL) && 257 insn->src_reg == BPF_PSEUDO_CALL; 258 } 259 260 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 261 { 262 return insn->code == (BPF_JMP | BPF_CALL) && 263 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 264 } 265 266 struct bpf_call_arg_meta { 267 struct bpf_map *map_ptr; 268 bool raw_mode; 269 bool pkt_access; 270 u8 release_regno; 271 int regno; 272 int access_size; 273 int mem_size; 274 u64 msize_max_value; 275 int ref_obj_id; 276 int dynptr_id; 277 int map_uid; 278 int func_id; 279 struct btf *btf; 280 u32 btf_id; 281 struct btf *ret_btf; 282 u32 ret_btf_id; 283 u32 subprogno; 284 struct btf_field *kptr_field; 285 }; 286 287 struct bpf_kfunc_call_arg_meta { 288 /* In parameters */ 289 struct btf *btf; 290 u32 func_id; 291 u32 kfunc_flags; 292 const struct btf_type *func_proto; 293 const char *func_name; 294 /* Out parameters */ 295 u32 ref_obj_id; 296 u8 release_regno; 297 bool r0_rdonly; 298 u32 ret_btf_id; 299 u64 r0_size; 300 u32 subprogno; 301 struct { 302 u64 value; 303 bool found; 304 } arg_constant; 305 306 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling, 307 * generally to pass info about user-defined local kptr types to later 308 * verification logic 309 * bpf_obj_drop/bpf_percpu_obj_drop 310 * Record the local kptr type to be drop'd 311 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type) 312 * Record the local kptr type to be refcount_incr'd and use 313 * arg_owning_ref to determine whether refcount_acquire should be 314 * fallible 315 */ 316 struct btf *arg_btf; 317 u32 arg_btf_id; 318 bool arg_owning_ref; 319 320 struct { 321 struct btf_field *field; 322 } arg_list_head; 323 struct { 324 struct btf_field *field; 325 } arg_rbtree_root; 326 struct { 327 enum bpf_dynptr_type type; 328 u32 id; 329 u32 ref_obj_id; 330 } initialized_dynptr; 331 struct { 332 u8 spi; 333 u8 frameno; 334 } iter; 335 struct { 336 struct bpf_map *ptr; 337 int uid; 338 } map; 339 u64 mem_size; 340 }; 341 342 struct btf *btf_vmlinux; 343 344 static const char *btf_type_name(const struct btf *btf, u32 id) 345 { 346 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 347 } 348 349 static DEFINE_MUTEX(bpf_verifier_lock); 350 static DEFINE_MUTEX(bpf_percpu_ma_lock); 351 352 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 353 { 354 struct bpf_verifier_env *env = private_data; 355 va_list args; 356 357 if (!bpf_verifier_log_needed(&env->log)) 358 return; 359 360 va_start(args, fmt); 361 bpf_verifier_vlog(&env->log, fmt, args); 362 va_end(args); 363 } 364 365 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 366 struct bpf_reg_state *reg, 367 struct bpf_retval_range range, const char *ctx, 368 const char *reg_name) 369 { 370 bool unknown = true; 371 372 verbose(env, "%s the register %s has", ctx, reg_name); 373 if (reg->smin_value > S64_MIN) { 374 verbose(env, " smin=%lld", reg->smin_value); 375 unknown = false; 376 } 377 if (reg->smax_value < S64_MAX) { 378 verbose(env, " smax=%lld", reg->smax_value); 379 unknown = false; 380 } 381 if (unknown) 382 verbose(env, " unknown scalar value"); 383 verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval); 384 } 385 386 static bool type_may_be_null(u32 type) 387 { 388 return type & PTR_MAYBE_NULL; 389 } 390 391 static bool reg_not_null(const struct bpf_reg_state *reg) 392 { 393 enum bpf_reg_type type; 394 395 type = reg->type; 396 if (type_may_be_null(type)) 397 return false; 398 399 type = base_type(type); 400 return type == PTR_TO_SOCKET || 401 type == PTR_TO_TCP_SOCK || 402 type == PTR_TO_MAP_VALUE || 403 type == PTR_TO_MAP_KEY || 404 type == PTR_TO_SOCK_COMMON || 405 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) || 406 type == PTR_TO_MEM; 407 } 408 409 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 410 { 411 struct btf_record *rec = NULL; 412 struct btf_struct_meta *meta; 413 414 if (reg->type == PTR_TO_MAP_VALUE) { 415 rec = reg->map_ptr->record; 416 } else if (type_is_ptr_alloc_obj(reg->type)) { 417 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 418 if (meta) 419 rec = meta->record; 420 } 421 return rec; 422 } 423 424 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog) 425 { 426 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 427 428 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 429 } 430 431 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog) 432 { 433 struct bpf_func_info *info; 434 435 if (!env->prog->aux->func_info) 436 return ""; 437 438 info = &env->prog->aux->func_info[subprog]; 439 return btf_type_name(env->prog->aux->btf, info->type_id); 440 } 441 442 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog) 443 { 444 struct bpf_subprog_info *info = subprog_info(env, subprog); 445 446 info->is_cb = true; 447 info->is_async_cb = true; 448 info->is_exception_cb = true; 449 } 450 451 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog) 452 { 453 return subprog_info(env, subprog)->is_exception_cb; 454 } 455 456 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 457 { 458 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK); 459 } 460 461 static bool type_is_rdonly_mem(u32 type) 462 { 463 return type & MEM_RDONLY; 464 } 465 466 static bool is_acquire_function(enum bpf_func_id func_id, 467 const struct bpf_map *map) 468 { 469 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 470 471 if (func_id == BPF_FUNC_sk_lookup_tcp || 472 func_id == BPF_FUNC_sk_lookup_udp || 473 func_id == BPF_FUNC_skc_lookup_tcp || 474 func_id == BPF_FUNC_ringbuf_reserve || 475 func_id == BPF_FUNC_kptr_xchg) 476 return true; 477 478 if (func_id == BPF_FUNC_map_lookup_elem && 479 (map_type == BPF_MAP_TYPE_SOCKMAP || 480 map_type == BPF_MAP_TYPE_SOCKHASH)) 481 return true; 482 483 return false; 484 } 485 486 static bool is_ptr_cast_function(enum bpf_func_id func_id) 487 { 488 return func_id == BPF_FUNC_tcp_sock || 489 func_id == BPF_FUNC_sk_fullsock || 490 func_id == BPF_FUNC_skc_to_tcp_sock || 491 func_id == BPF_FUNC_skc_to_tcp6_sock || 492 func_id == BPF_FUNC_skc_to_udp6_sock || 493 func_id == BPF_FUNC_skc_to_mptcp_sock || 494 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 495 func_id == BPF_FUNC_skc_to_tcp_request_sock; 496 } 497 498 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 499 { 500 return func_id == BPF_FUNC_dynptr_data; 501 } 502 503 static bool is_sync_callback_calling_kfunc(u32 btf_id); 504 static bool is_async_callback_calling_kfunc(u32 btf_id); 505 static bool is_callback_calling_kfunc(u32 btf_id); 506 static bool is_bpf_throw_kfunc(struct bpf_insn *insn); 507 508 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id); 509 510 static bool is_sync_callback_calling_function(enum bpf_func_id func_id) 511 { 512 return func_id == BPF_FUNC_for_each_map_elem || 513 func_id == BPF_FUNC_find_vma || 514 func_id == BPF_FUNC_loop || 515 func_id == BPF_FUNC_user_ringbuf_drain; 516 } 517 518 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 519 { 520 return func_id == BPF_FUNC_timer_set_callback; 521 } 522 523 static bool is_callback_calling_function(enum bpf_func_id func_id) 524 { 525 return is_sync_callback_calling_function(func_id) || 526 is_async_callback_calling_function(func_id); 527 } 528 529 static bool is_sync_callback_calling_insn(struct bpf_insn *insn) 530 { 531 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) || 532 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm)); 533 } 534 535 static bool is_async_callback_calling_insn(struct bpf_insn *insn) 536 { 537 return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) || 538 (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm)); 539 } 540 541 static bool is_may_goto_insn(struct bpf_insn *insn) 542 { 543 return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO; 544 } 545 546 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx) 547 { 548 return is_may_goto_insn(&env->prog->insnsi[insn_idx]); 549 } 550 551 static bool is_storage_get_function(enum bpf_func_id func_id) 552 { 553 return func_id == BPF_FUNC_sk_storage_get || 554 func_id == BPF_FUNC_inode_storage_get || 555 func_id == BPF_FUNC_task_storage_get || 556 func_id == BPF_FUNC_cgrp_storage_get; 557 } 558 559 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 560 const struct bpf_map *map) 561 { 562 int ref_obj_uses = 0; 563 564 if (is_ptr_cast_function(func_id)) 565 ref_obj_uses++; 566 if (is_acquire_function(func_id, map)) 567 ref_obj_uses++; 568 if (is_dynptr_ref_function(func_id)) 569 ref_obj_uses++; 570 571 return ref_obj_uses > 1; 572 } 573 574 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 575 { 576 return BPF_CLASS(insn->code) == BPF_STX && 577 BPF_MODE(insn->code) == BPF_ATOMIC && 578 insn->imm == BPF_CMPXCHG; 579 } 580 581 static int __get_spi(s32 off) 582 { 583 return (-off - 1) / BPF_REG_SIZE; 584 } 585 586 static struct bpf_func_state *func(struct bpf_verifier_env *env, 587 const struct bpf_reg_state *reg) 588 { 589 struct bpf_verifier_state *cur = env->cur_state; 590 591 return cur->frame[reg->frameno]; 592 } 593 594 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 595 { 596 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 597 598 /* We need to check that slots between [spi - nr_slots + 1, spi] are 599 * within [0, allocated_stack). 600 * 601 * Please note that the spi grows downwards. For example, a dynptr 602 * takes the size of two stack slots; the first slot will be at 603 * spi and the second slot will be at spi - 1. 604 */ 605 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 606 } 607 608 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 609 const char *obj_kind, int nr_slots) 610 { 611 int off, spi; 612 613 if (!tnum_is_const(reg->var_off)) { 614 verbose(env, "%s has to be at a constant offset\n", obj_kind); 615 return -EINVAL; 616 } 617 618 off = reg->off + reg->var_off.value; 619 if (off % BPF_REG_SIZE) { 620 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 621 return -EINVAL; 622 } 623 624 spi = __get_spi(off); 625 if (spi + 1 < nr_slots) { 626 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 627 return -EINVAL; 628 } 629 630 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots)) 631 return -ERANGE; 632 return spi; 633 } 634 635 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 636 { 637 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 638 } 639 640 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 641 { 642 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 643 } 644 645 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 646 { 647 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 648 case DYNPTR_TYPE_LOCAL: 649 return BPF_DYNPTR_TYPE_LOCAL; 650 case DYNPTR_TYPE_RINGBUF: 651 return BPF_DYNPTR_TYPE_RINGBUF; 652 case DYNPTR_TYPE_SKB: 653 return BPF_DYNPTR_TYPE_SKB; 654 case DYNPTR_TYPE_XDP: 655 return BPF_DYNPTR_TYPE_XDP; 656 default: 657 return BPF_DYNPTR_TYPE_INVALID; 658 } 659 } 660 661 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 662 { 663 switch (type) { 664 case BPF_DYNPTR_TYPE_LOCAL: 665 return DYNPTR_TYPE_LOCAL; 666 case BPF_DYNPTR_TYPE_RINGBUF: 667 return DYNPTR_TYPE_RINGBUF; 668 case BPF_DYNPTR_TYPE_SKB: 669 return DYNPTR_TYPE_SKB; 670 case BPF_DYNPTR_TYPE_XDP: 671 return DYNPTR_TYPE_XDP; 672 default: 673 return 0; 674 } 675 } 676 677 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 678 { 679 return type == BPF_DYNPTR_TYPE_RINGBUF; 680 } 681 682 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 683 enum bpf_dynptr_type type, 684 bool first_slot, int dynptr_id); 685 686 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 687 struct bpf_reg_state *reg); 688 689 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 690 struct bpf_reg_state *sreg1, 691 struct bpf_reg_state *sreg2, 692 enum bpf_dynptr_type type) 693 { 694 int id = ++env->id_gen; 695 696 __mark_dynptr_reg(sreg1, type, true, id); 697 __mark_dynptr_reg(sreg2, type, false, id); 698 } 699 700 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 701 struct bpf_reg_state *reg, 702 enum bpf_dynptr_type type) 703 { 704 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 705 } 706 707 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 708 struct bpf_func_state *state, int spi); 709 710 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 711 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id) 712 { 713 struct bpf_func_state *state = func(env, reg); 714 enum bpf_dynptr_type type; 715 int spi, i, err; 716 717 spi = dynptr_get_spi(env, reg); 718 if (spi < 0) 719 return spi; 720 721 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 722 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 723 * to ensure that for the following example: 724 * [d1][d1][d2][d2] 725 * spi 3 2 1 0 726 * So marking spi = 2 should lead to destruction of both d1 and d2. In 727 * case they do belong to same dynptr, second call won't see slot_type 728 * as STACK_DYNPTR and will simply skip destruction. 729 */ 730 err = destroy_if_dynptr_stack_slot(env, state, spi); 731 if (err) 732 return err; 733 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 734 if (err) 735 return err; 736 737 for (i = 0; i < BPF_REG_SIZE; i++) { 738 state->stack[spi].slot_type[i] = STACK_DYNPTR; 739 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 740 } 741 742 type = arg_to_dynptr_type(arg_type); 743 if (type == BPF_DYNPTR_TYPE_INVALID) 744 return -EINVAL; 745 746 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 747 &state->stack[spi - 1].spilled_ptr, type); 748 749 if (dynptr_type_refcounted(type)) { 750 /* The id is used to track proper releasing */ 751 int id; 752 753 if (clone_ref_obj_id) 754 id = clone_ref_obj_id; 755 else 756 id = acquire_reference_state(env, insn_idx); 757 758 if (id < 0) 759 return id; 760 761 state->stack[spi].spilled_ptr.ref_obj_id = id; 762 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 763 } 764 765 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 766 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 767 768 return 0; 769 } 770 771 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi) 772 { 773 int i; 774 775 for (i = 0; i < BPF_REG_SIZE; i++) { 776 state->stack[spi].slot_type[i] = STACK_INVALID; 777 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 778 } 779 780 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 781 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 782 783 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot? 784 * 785 * While we don't allow reading STACK_INVALID, it is still possible to 786 * do <8 byte writes marking some but not all slots as STACK_MISC. Then, 787 * helpers or insns can do partial read of that part without failing, 788 * but check_stack_range_initialized, check_stack_read_var_off, and 789 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of 790 * the slot conservatively. Hence we need to prevent those liveness 791 * marking walks. 792 * 793 * This was not a problem before because STACK_INVALID is only set by 794 * default (where the default reg state has its reg->parent as NULL), or 795 * in clean_live_states after REG_LIVE_DONE (at which point 796 * mark_reg_read won't walk reg->parent chain), but not randomly during 797 * verifier state exploration (like we did above). Hence, for our case 798 * parentage chain will still be live (i.e. reg->parent may be 799 * non-NULL), while earlier reg->parent was NULL, so we need 800 * REG_LIVE_WRITTEN to screen off read marker propagation when it is 801 * done later on reads or by mark_dynptr_read as well to unnecessary 802 * mark registers in verifier state. 803 */ 804 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 805 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 806 } 807 808 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 809 { 810 struct bpf_func_state *state = func(env, reg); 811 int spi, ref_obj_id, i; 812 813 spi = dynptr_get_spi(env, reg); 814 if (spi < 0) 815 return spi; 816 817 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 818 invalidate_dynptr(env, state, spi); 819 return 0; 820 } 821 822 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 823 824 /* If the dynptr has a ref_obj_id, then we need to invalidate 825 * two things: 826 * 827 * 1) Any dynptrs with a matching ref_obj_id (clones) 828 * 2) Any slices derived from this dynptr. 829 */ 830 831 /* Invalidate any slices associated with this dynptr */ 832 WARN_ON_ONCE(release_reference(env, ref_obj_id)); 833 834 /* Invalidate any dynptr clones */ 835 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) { 836 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id) 837 continue; 838 839 /* it should always be the case that if the ref obj id 840 * matches then the stack slot also belongs to a 841 * dynptr 842 */ 843 if (state->stack[i].slot_type[0] != STACK_DYNPTR) { 844 verbose(env, "verifier internal error: misconfigured ref_obj_id\n"); 845 return -EFAULT; 846 } 847 if (state->stack[i].spilled_ptr.dynptr.first_slot) 848 invalidate_dynptr(env, state, i); 849 } 850 851 return 0; 852 } 853 854 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 855 struct bpf_reg_state *reg); 856 857 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 858 { 859 if (!env->allow_ptr_leaks) 860 __mark_reg_not_init(env, reg); 861 else 862 __mark_reg_unknown(env, reg); 863 } 864 865 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 866 struct bpf_func_state *state, int spi) 867 { 868 struct bpf_func_state *fstate; 869 struct bpf_reg_state *dreg; 870 int i, dynptr_id; 871 872 /* We always ensure that STACK_DYNPTR is never set partially, 873 * hence just checking for slot_type[0] is enough. This is 874 * different for STACK_SPILL, where it may be only set for 875 * 1 byte, so code has to use is_spilled_reg. 876 */ 877 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 878 return 0; 879 880 /* Reposition spi to first slot */ 881 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 882 spi = spi + 1; 883 884 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 885 verbose(env, "cannot overwrite referenced dynptr\n"); 886 return -EINVAL; 887 } 888 889 mark_stack_slot_scratched(env, spi); 890 mark_stack_slot_scratched(env, spi - 1); 891 892 /* Writing partially to one dynptr stack slot destroys both. */ 893 for (i = 0; i < BPF_REG_SIZE; i++) { 894 state->stack[spi].slot_type[i] = STACK_INVALID; 895 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 896 } 897 898 dynptr_id = state->stack[spi].spilled_ptr.id; 899 /* Invalidate any slices associated with this dynptr */ 900 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 901 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 902 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 903 continue; 904 if (dreg->dynptr_id == dynptr_id) 905 mark_reg_invalid(env, dreg); 906 })); 907 908 /* Do not release reference state, we are destroying dynptr on stack, 909 * not using some helper to release it. Just reset register. 910 */ 911 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 912 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 913 914 /* Same reason as unmark_stack_slots_dynptr above */ 915 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 916 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 917 918 return 0; 919 } 920 921 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 922 { 923 int spi; 924 925 if (reg->type == CONST_PTR_TO_DYNPTR) 926 return false; 927 928 spi = dynptr_get_spi(env, reg); 929 930 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 931 * error because this just means the stack state hasn't been updated yet. 932 * We will do check_mem_access to check and update stack bounds later. 933 */ 934 if (spi < 0 && spi != -ERANGE) 935 return false; 936 937 /* We don't need to check if the stack slots are marked by previous 938 * dynptr initializations because we allow overwriting existing unreferenced 939 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 940 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 941 * touching are completely destructed before we reinitialize them for a new 942 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 943 * instead of delaying it until the end where the user will get "Unreleased 944 * reference" error. 945 */ 946 return true; 947 } 948 949 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 950 { 951 struct bpf_func_state *state = func(env, reg); 952 int i, spi; 953 954 /* This already represents first slot of initialized bpf_dynptr. 955 * 956 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 957 * check_func_arg_reg_off's logic, so we don't need to check its 958 * offset and alignment. 959 */ 960 if (reg->type == CONST_PTR_TO_DYNPTR) 961 return true; 962 963 spi = dynptr_get_spi(env, reg); 964 if (spi < 0) 965 return false; 966 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 967 return false; 968 969 for (i = 0; i < BPF_REG_SIZE; i++) { 970 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 971 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 972 return false; 973 } 974 975 return true; 976 } 977 978 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 979 enum bpf_arg_type arg_type) 980 { 981 struct bpf_func_state *state = func(env, reg); 982 enum bpf_dynptr_type dynptr_type; 983 int spi; 984 985 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 986 if (arg_type == ARG_PTR_TO_DYNPTR) 987 return true; 988 989 dynptr_type = arg_to_dynptr_type(arg_type); 990 if (reg->type == CONST_PTR_TO_DYNPTR) { 991 return reg->dynptr.type == dynptr_type; 992 } else { 993 spi = dynptr_get_spi(env, reg); 994 if (spi < 0) 995 return false; 996 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 997 } 998 } 999 1000 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 1001 1002 static bool in_rcu_cs(struct bpf_verifier_env *env); 1003 1004 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta); 1005 1006 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 1007 struct bpf_kfunc_call_arg_meta *meta, 1008 struct bpf_reg_state *reg, int insn_idx, 1009 struct btf *btf, u32 btf_id, int nr_slots) 1010 { 1011 struct bpf_func_state *state = func(env, reg); 1012 int spi, i, j, id; 1013 1014 spi = iter_get_spi(env, reg, nr_slots); 1015 if (spi < 0) 1016 return spi; 1017 1018 id = acquire_reference_state(env, insn_idx); 1019 if (id < 0) 1020 return id; 1021 1022 for (i = 0; i < nr_slots; i++) { 1023 struct bpf_stack_state *slot = &state->stack[spi - i]; 1024 struct bpf_reg_state *st = &slot->spilled_ptr; 1025 1026 __mark_reg_known_zero(st); 1027 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1028 if (is_kfunc_rcu_protected(meta)) { 1029 if (in_rcu_cs(env)) 1030 st->type |= MEM_RCU; 1031 else 1032 st->type |= PTR_UNTRUSTED; 1033 } 1034 st->live |= REG_LIVE_WRITTEN; 1035 st->ref_obj_id = i == 0 ? id : 0; 1036 st->iter.btf = btf; 1037 st->iter.btf_id = btf_id; 1038 st->iter.state = BPF_ITER_STATE_ACTIVE; 1039 st->iter.depth = 0; 1040 1041 for (j = 0; j < BPF_REG_SIZE; j++) 1042 slot->slot_type[j] = STACK_ITER; 1043 1044 mark_stack_slot_scratched(env, spi - i); 1045 } 1046 1047 return 0; 1048 } 1049 1050 static int unmark_stack_slots_iter(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 spi = iter_get_spi(env, reg, nr_slots); 1057 if (spi < 0) 1058 return spi; 1059 1060 for (i = 0; i < nr_slots; i++) { 1061 struct bpf_stack_state *slot = &state->stack[spi - i]; 1062 struct bpf_reg_state *st = &slot->spilled_ptr; 1063 1064 if (i == 0) 1065 WARN_ON_ONCE(release_reference(env, st->ref_obj_id)); 1066 1067 __mark_reg_not_init(env, st); 1068 1069 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1070 st->live |= REG_LIVE_WRITTEN; 1071 1072 for (j = 0; j < BPF_REG_SIZE; j++) 1073 slot->slot_type[j] = STACK_INVALID; 1074 1075 mark_stack_slot_scratched(env, spi - i); 1076 } 1077 1078 return 0; 1079 } 1080 1081 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1082 struct bpf_reg_state *reg, int nr_slots) 1083 { 1084 struct bpf_func_state *state = func(env, reg); 1085 int spi, i, j; 1086 1087 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1088 * will do check_mem_access to check and update stack bounds later, so 1089 * return true for that case. 1090 */ 1091 spi = iter_get_spi(env, reg, nr_slots); 1092 if (spi == -ERANGE) 1093 return true; 1094 if (spi < 0) 1095 return false; 1096 1097 for (i = 0; i < nr_slots; i++) { 1098 struct bpf_stack_state *slot = &state->stack[spi - i]; 1099 1100 for (j = 0; j < BPF_REG_SIZE; j++) 1101 if (slot->slot_type[j] == STACK_ITER) 1102 return false; 1103 } 1104 1105 return true; 1106 } 1107 1108 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1109 struct btf *btf, u32 btf_id, int nr_slots) 1110 { 1111 struct bpf_func_state *state = func(env, reg); 1112 int spi, i, j; 1113 1114 spi = iter_get_spi(env, reg, nr_slots); 1115 if (spi < 0) 1116 return -EINVAL; 1117 1118 for (i = 0; i < nr_slots; i++) { 1119 struct bpf_stack_state *slot = &state->stack[spi - i]; 1120 struct bpf_reg_state *st = &slot->spilled_ptr; 1121 1122 if (st->type & PTR_UNTRUSTED) 1123 return -EPROTO; 1124 /* only main (first) slot has ref_obj_id set */ 1125 if (i == 0 && !st->ref_obj_id) 1126 return -EINVAL; 1127 if (i != 0 && st->ref_obj_id) 1128 return -EINVAL; 1129 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1130 return -EINVAL; 1131 1132 for (j = 0; j < BPF_REG_SIZE; j++) 1133 if (slot->slot_type[j] != STACK_ITER) 1134 return -EINVAL; 1135 } 1136 1137 return 0; 1138 } 1139 1140 /* Check if given stack slot is "special": 1141 * - spilled register state (STACK_SPILL); 1142 * - dynptr state (STACK_DYNPTR); 1143 * - iter state (STACK_ITER). 1144 */ 1145 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1146 { 1147 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1148 1149 switch (type) { 1150 case STACK_SPILL: 1151 case STACK_DYNPTR: 1152 case STACK_ITER: 1153 return true; 1154 case STACK_INVALID: 1155 case STACK_MISC: 1156 case STACK_ZERO: 1157 return false; 1158 default: 1159 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1160 return true; 1161 } 1162 } 1163 1164 /* The reg state of a pointer or a bounded scalar was saved when 1165 * it was spilled to the stack. 1166 */ 1167 static bool is_spilled_reg(const struct bpf_stack_state *stack) 1168 { 1169 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1170 } 1171 1172 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack) 1173 { 1174 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL && 1175 stack->spilled_ptr.type == SCALAR_VALUE; 1176 } 1177 1178 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack) 1179 { 1180 return stack->slot_type[0] == STACK_SPILL && 1181 stack->spilled_ptr.type == SCALAR_VALUE; 1182 } 1183 1184 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which 1185 * case they are equivalent, or it's STACK_ZERO, in which case we preserve 1186 * more precise STACK_ZERO. 1187 * Note, in uprivileged mode leaving STACK_INVALID is wrong, so we take 1188 * env->allow_ptr_leaks into account and force STACK_MISC, if necessary. 1189 */ 1190 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype) 1191 { 1192 if (*stype == STACK_ZERO) 1193 return; 1194 if (env->allow_ptr_leaks && *stype == STACK_INVALID) 1195 return; 1196 *stype = STACK_MISC; 1197 } 1198 1199 static void scrub_spilled_slot(u8 *stype) 1200 { 1201 if (*stype != STACK_INVALID) 1202 *stype = STACK_MISC; 1203 } 1204 1205 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1206 * small to hold src. This is different from krealloc since we don't want to preserve 1207 * the contents of dst. 1208 * 1209 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1210 * not be allocated. 1211 */ 1212 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1213 { 1214 size_t alloc_bytes; 1215 void *orig = dst; 1216 size_t bytes; 1217 1218 if (ZERO_OR_NULL_PTR(src)) 1219 goto out; 1220 1221 if (unlikely(check_mul_overflow(n, size, &bytes))) 1222 return NULL; 1223 1224 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1225 dst = krealloc(orig, alloc_bytes, flags); 1226 if (!dst) { 1227 kfree(orig); 1228 return NULL; 1229 } 1230 1231 memcpy(dst, src, bytes); 1232 out: 1233 return dst ? dst : ZERO_SIZE_PTR; 1234 } 1235 1236 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1237 * small to hold new_n items. new items are zeroed out if the array grows. 1238 * 1239 * Contrary to krealloc_array, does not free arr if new_n is zero. 1240 */ 1241 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1242 { 1243 size_t alloc_size; 1244 void *new_arr; 1245 1246 if (!new_n || old_n == new_n) 1247 goto out; 1248 1249 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1250 new_arr = krealloc(arr, alloc_size, GFP_KERNEL); 1251 if (!new_arr) { 1252 kfree(arr); 1253 return NULL; 1254 } 1255 arr = new_arr; 1256 1257 if (new_n > old_n) 1258 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1259 1260 out: 1261 return arr ? arr : ZERO_SIZE_PTR; 1262 } 1263 1264 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1265 { 1266 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1267 sizeof(struct bpf_reference_state), GFP_KERNEL); 1268 if (!dst->refs) 1269 return -ENOMEM; 1270 1271 dst->acquired_refs = src->acquired_refs; 1272 return 0; 1273 } 1274 1275 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1276 { 1277 size_t n = src->allocated_stack / BPF_REG_SIZE; 1278 1279 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1280 GFP_KERNEL); 1281 if (!dst->stack) 1282 return -ENOMEM; 1283 1284 dst->allocated_stack = src->allocated_stack; 1285 return 0; 1286 } 1287 1288 static int resize_reference_state(struct bpf_func_state *state, size_t n) 1289 { 1290 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1291 sizeof(struct bpf_reference_state)); 1292 if (!state->refs) 1293 return -ENOMEM; 1294 1295 state->acquired_refs = n; 1296 return 0; 1297 } 1298 1299 /* Possibly update state->allocated_stack to be at least size bytes. Also 1300 * possibly update the function's high-water mark in its bpf_subprog_info. 1301 */ 1302 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) 1303 { 1304 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n; 1305 1306 /* The stack size is always a multiple of BPF_REG_SIZE. */ 1307 size = round_up(size, BPF_REG_SIZE); 1308 n = size / BPF_REG_SIZE; 1309 1310 if (old_n >= n) 1311 return 0; 1312 1313 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1314 if (!state->stack) 1315 return -ENOMEM; 1316 1317 state->allocated_stack = size; 1318 1319 /* update known max for given subprogram */ 1320 if (env->subprog_info[state->subprogno].stack_depth < size) 1321 env->subprog_info[state->subprogno].stack_depth = size; 1322 1323 return 0; 1324 } 1325 1326 /* Acquire a pointer id from the env and update the state->refs to include 1327 * this new pointer reference. 1328 * On success, returns a valid pointer id to associate with the register 1329 * On failure, returns a negative errno. 1330 */ 1331 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1332 { 1333 struct bpf_func_state *state = cur_func(env); 1334 int new_ofs = state->acquired_refs; 1335 int id, err; 1336 1337 err = resize_reference_state(state, state->acquired_refs + 1); 1338 if (err) 1339 return err; 1340 id = ++env->id_gen; 1341 state->refs[new_ofs].id = id; 1342 state->refs[new_ofs].insn_idx = insn_idx; 1343 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0; 1344 1345 return id; 1346 } 1347 1348 /* release function corresponding to acquire_reference_state(). Idempotent. */ 1349 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 1350 { 1351 int i, last_idx; 1352 1353 last_idx = state->acquired_refs - 1; 1354 for (i = 0; i < state->acquired_refs; i++) { 1355 if (state->refs[i].id == ptr_id) { 1356 /* Cannot release caller references in callbacks */ 1357 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 1358 return -EINVAL; 1359 if (last_idx && i != last_idx) 1360 memcpy(&state->refs[i], &state->refs[last_idx], 1361 sizeof(*state->refs)); 1362 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1363 state->acquired_refs--; 1364 return 0; 1365 } 1366 } 1367 return -EINVAL; 1368 } 1369 1370 static void free_func_state(struct bpf_func_state *state) 1371 { 1372 if (!state) 1373 return; 1374 kfree(state->refs); 1375 kfree(state->stack); 1376 kfree(state); 1377 } 1378 1379 static void clear_jmp_history(struct bpf_verifier_state *state) 1380 { 1381 kfree(state->jmp_history); 1382 state->jmp_history = NULL; 1383 state->jmp_history_cnt = 0; 1384 } 1385 1386 static void free_verifier_state(struct bpf_verifier_state *state, 1387 bool free_self) 1388 { 1389 int i; 1390 1391 for (i = 0; i <= state->curframe; i++) { 1392 free_func_state(state->frame[i]); 1393 state->frame[i] = NULL; 1394 } 1395 clear_jmp_history(state); 1396 if (free_self) 1397 kfree(state); 1398 } 1399 1400 /* copy verifier state from src to dst growing dst stack space 1401 * when necessary to accommodate larger src stack 1402 */ 1403 static int copy_func_state(struct bpf_func_state *dst, 1404 const struct bpf_func_state *src) 1405 { 1406 int err; 1407 1408 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 1409 err = copy_reference_state(dst, src); 1410 if (err) 1411 return err; 1412 return copy_stack_state(dst, src); 1413 } 1414 1415 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1416 const struct bpf_verifier_state *src) 1417 { 1418 struct bpf_func_state *dst; 1419 int i, err; 1420 1421 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1422 src->jmp_history_cnt, sizeof(*dst_state->jmp_history), 1423 GFP_USER); 1424 if (!dst_state->jmp_history) 1425 return -ENOMEM; 1426 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1427 1428 /* if dst has more stack frames then src frame, free them, this is also 1429 * necessary in case of exceptional exits using bpf_throw. 1430 */ 1431 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1432 free_func_state(dst_state->frame[i]); 1433 dst_state->frame[i] = NULL; 1434 } 1435 dst_state->speculative = src->speculative; 1436 dst_state->active_rcu_lock = src->active_rcu_lock; 1437 dst_state->active_preempt_lock = src->active_preempt_lock; 1438 dst_state->in_sleepable = src->in_sleepable; 1439 dst_state->curframe = src->curframe; 1440 dst_state->active_lock.ptr = src->active_lock.ptr; 1441 dst_state->active_lock.id = src->active_lock.id; 1442 dst_state->branches = src->branches; 1443 dst_state->parent = src->parent; 1444 dst_state->first_insn_idx = src->first_insn_idx; 1445 dst_state->last_insn_idx = src->last_insn_idx; 1446 dst_state->dfs_depth = src->dfs_depth; 1447 dst_state->callback_unroll_depth = src->callback_unroll_depth; 1448 dst_state->used_as_loop_entry = src->used_as_loop_entry; 1449 dst_state->may_goto_depth = src->may_goto_depth; 1450 for (i = 0; i <= src->curframe; i++) { 1451 dst = dst_state->frame[i]; 1452 if (!dst) { 1453 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1454 if (!dst) 1455 return -ENOMEM; 1456 dst_state->frame[i] = dst; 1457 } 1458 err = copy_func_state(dst, src->frame[i]); 1459 if (err) 1460 return err; 1461 } 1462 return 0; 1463 } 1464 1465 static u32 state_htab_size(struct bpf_verifier_env *env) 1466 { 1467 return env->prog->len; 1468 } 1469 1470 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx) 1471 { 1472 struct bpf_verifier_state *cur = env->cur_state; 1473 struct bpf_func_state *state = cur->frame[cur->curframe]; 1474 1475 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 1476 } 1477 1478 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b) 1479 { 1480 int fr; 1481 1482 if (a->curframe != b->curframe) 1483 return false; 1484 1485 for (fr = a->curframe; fr >= 0; fr--) 1486 if (a->frame[fr]->callsite != b->frame[fr]->callsite) 1487 return false; 1488 1489 return true; 1490 } 1491 1492 /* Open coded iterators allow back-edges in the state graph in order to 1493 * check unbounded loops that iterators. 1494 * 1495 * In is_state_visited() it is necessary to know if explored states are 1496 * part of some loops in order to decide whether non-exact states 1497 * comparison could be used: 1498 * - non-exact states comparison establishes sub-state relation and uses 1499 * read and precision marks to do so, these marks are propagated from 1500 * children states and thus are not guaranteed to be final in a loop; 1501 * - exact states comparison just checks if current and explored states 1502 * are identical (and thus form a back-edge). 1503 * 1504 * Paper "A New Algorithm for Identifying Loops in Decompilation" 1505 * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient 1506 * algorithm for loop structure detection and gives an overview of 1507 * relevant terminology. It also has helpful illustrations. 1508 * 1509 * [1] https://api.semanticscholar.org/CorpusID:15784067 1510 * 1511 * We use a similar algorithm but because loop nested structure is 1512 * irrelevant for verifier ours is significantly simpler and resembles 1513 * strongly connected components algorithm from Sedgewick's textbook. 1514 * 1515 * Define topmost loop entry as a first node of the loop traversed in a 1516 * depth first search starting from initial state. The goal of the loop 1517 * tracking algorithm is to associate topmost loop entries with states 1518 * derived from these entries. 1519 * 1520 * For each step in the DFS states traversal algorithm needs to identify 1521 * the following situations: 1522 * 1523 * initial initial initial 1524 * | | | 1525 * V V V 1526 * ... ... .---------> hdr 1527 * | | | | 1528 * V V | V 1529 * cur .-> succ | .------... 1530 * | | | | | | 1531 * V | V | V V 1532 * succ '-- cur | ... ... 1533 * | | | 1534 * | V V 1535 * | succ <- cur 1536 * | | 1537 * | V 1538 * | ... 1539 * | | 1540 * '----' 1541 * 1542 * (A) successor state of cur (B) successor state of cur or it's entry 1543 * not yet traversed are in current DFS path, thus cur and succ 1544 * are members of the same outermost loop 1545 * 1546 * initial initial 1547 * | | 1548 * V V 1549 * ... ... 1550 * | | 1551 * V V 1552 * .------... .------... 1553 * | | | | 1554 * V V V V 1555 * .-> hdr ... ... ... 1556 * | | | | | 1557 * | V V V V 1558 * | succ <- cur succ <- cur 1559 * | | | 1560 * | V V 1561 * | ... ... 1562 * | | | 1563 * '----' exit 1564 * 1565 * (C) successor state of cur is a part of some loop but this loop 1566 * does not include cur or successor state is not in a loop at all. 1567 * 1568 * Algorithm could be described as the following python code: 1569 * 1570 * traversed = set() # Set of traversed nodes 1571 * entries = {} # Mapping from node to loop entry 1572 * depths = {} # Depth level assigned to graph node 1573 * path = set() # Current DFS path 1574 * 1575 * # Find outermost loop entry known for n 1576 * def get_loop_entry(n): 1577 * h = entries.get(n, None) 1578 * while h in entries and entries[h] != h: 1579 * h = entries[h] 1580 * return h 1581 * 1582 * # Update n's loop entry if h's outermost entry comes 1583 * # before n's outermost entry in current DFS path. 1584 * def update_loop_entry(n, h): 1585 * n1 = get_loop_entry(n) or n 1586 * h1 = get_loop_entry(h) or h 1587 * if h1 in path and depths[h1] <= depths[n1]: 1588 * entries[n] = h1 1589 * 1590 * def dfs(n, depth): 1591 * traversed.add(n) 1592 * path.add(n) 1593 * depths[n] = depth 1594 * for succ in G.successors(n): 1595 * if succ not in traversed: 1596 * # Case A: explore succ and update cur's loop entry 1597 * # only if succ's entry is in current DFS path. 1598 * dfs(succ, depth + 1) 1599 * h = get_loop_entry(succ) 1600 * update_loop_entry(n, h) 1601 * else: 1602 * # Case B or C depending on `h1 in path` check in update_loop_entry(). 1603 * update_loop_entry(n, succ) 1604 * path.remove(n) 1605 * 1606 * To adapt this algorithm for use with verifier: 1607 * - use st->branch == 0 as a signal that DFS of succ had been finished 1608 * and cur's loop entry has to be updated (case A), handle this in 1609 * update_branch_counts(); 1610 * - use st->branch > 0 as a signal that st is in the current DFS path; 1611 * - handle cases B and C in is_state_visited(); 1612 * - update topmost loop entry for intermediate states in get_loop_entry(). 1613 */ 1614 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st) 1615 { 1616 struct bpf_verifier_state *topmost = st->loop_entry, *old; 1617 1618 while (topmost && topmost->loop_entry && topmost != topmost->loop_entry) 1619 topmost = topmost->loop_entry; 1620 /* Update loop entries for intermediate states to avoid this 1621 * traversal in future get_loop_entry() calls. 1622 */ 1623 while (st && st->loop_entry != topmost) { 1624 old = st->loop_entry; 1625 st->loop_entry = topmost; 1626 st = old; 1627 } 1628 return topmost; 1629 } 1630 1631 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr) 1632 { 1633 struct bpf_verifier_state *cur1, *hdr1; 1634 1635 cur1 = get_loop_entry(cur) ?: cur; 1636 hdr1 = get_loop_entry(hdr) ?: hdr; 1637 /* The head1->branches check decides between cases B and C in 1638 * comment for get_loop_entry(). If hdr1->branches == 0 then 1639 * head's topmost loop entry is not in current DFS path, 1640 * hence 'cur' and 'hdr' are not in the same loop and there is 1641 * no need to update cur->loop_entry. 1642 */ 1643 if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) { 1644 cur->loop_entry = hdr; 1645 hdr->used_as_loop_entry = true; 1646 } 1647 } 1648 1649 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1650 { 1651 while (st) { 1652 u32 br = --st->branches; 1653 1654 /* br == 0 signals that DFS exploration for 'st' is finished, 1655 * thus it is necessary to update parent's loop entry if it 1656 * turned out that st is a part of some loop. 1657 * This is a part of 'case A' in get_loop_entry() comment. 1658 */ 1659 if (br == 0 && st->parent && st->loop_entry) 1660 update_loop_entry(st->parent, st->loop_entry); 1661 1662 /* WARN_ON(br > 1) technically makes sense here, 1663 * but see comment in push_stack(), hence: 1664 */ 1665 WARN_ONCE((int)br < 0, 1666 "BUG update_branch_counts:branches_to_explore=%d\n", 1667 br); 1668 if (br) 1669 break; 1670 st = st->parent; 1671 } 1672 } 1673 1674 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1675 int *insn_idx, bool pop_log) 1676 { 1677 struct bpf_verifier_state *cur = env->cur_state; 1678 struct bpf_verifier_stack_elem *elem, *head = env->head; 1679 int err; 1680 1681 if (env->head == NULL) 1682 return -ENOENT; 1683 1684 if (cur) { 1685 err = copy_verifier_state(cur, &head->st); 1686 if (err) 1687 return err; 1688 } 1689 if (pop_log) 1690 bpf_vlog_reset(&env->log, head->log_pos); 1691 if (insn_idx) 1692 *insn_idx = head->insn_idx; 1693 if (prev_insn_idx) 1694 *prev_insn_idx = head->prev_insn_idx; 1695 elem = head->next; 1696 free_verifier_state(&head->st, false); 1697 kfree(head); 1698 env->head = elem; 1699 env->stack_size--; 1700 return 0; 1701 } 1702 1703 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1704 int insn_idx, int prev_insn_idx, 1705 bool speculative) 1706 { 1707 struct bpf_verifier_state *cur = env->cur_state; 1708 struct bpf_verifier_stack_elem *elem; 1709 int err; 1710 1711 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1712 if (!elem) 1713 goto err; 1714 1715 elem->insn_idx = insn_idx; 1716 elem->prev_insn_idx = prev_insn_idx; 1717 elem->next = env->head; 1718 elem->log_pos = env->log.end_pos; 1719 env->head = elem; 1720 env->stack_size++; 1721 err = copy_verifier_state(&elem->st, cur); 1722 if (err) 1723 goto err; 1724 elem->st.speculative |= speculative; 1725 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1726 verbose(env, "The sequence of %d jumps is too complex.\n", 1727 env->stack_size); 1728 goto err; 1729 } 1730 if (elem->st.parent) { 1731 ++elem->st.parent->branches; 1732 /* WARN_ON(branches > 2) technically makes sense here, 1733 * but 1734 * 1. speculative states will bump 'branches' for non-branch 1735 * instructions 1736 * 2. is_state_visited() heuristics may decide not to create 1737 * a new state for a sequence of branches and all such current 1738 * and cloned states will be pointing to a single parent state 1739 * which might have large 'branches' count. 1740 */ 1741 } 1742 return &elem->st; 1743 err: 1744 free_verifier_state(env->cur_state, true); 1745 env->cur_state = NULL; 1746 /* pop all elements and return */ 1747 while (!pop_stack(env, NULL, NULL, false)); 1748 return NULL; 1749 } 1750 1751 #define CALLER_SAVED_REGS 6 1752 static const int caller_saved[CALLER_SAVED_REGS] = { 1753 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1754 }; 1755 1756 /* This helper doesn't clear reg->id */ 1757 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1758 { 1759 reg->var_off = tnum_const(imm); 1760 reg->smin_value = (s64)imm; 1761 reg->smax_value = (s64)imm; 1762 reg->umin_value = imm; 1763 reg->umax_value = imm; 1764 1765 reg->s32_min_value = (s32)imm; 1766 reg->s32_max_value = (s32)imm; 1767 reg->u32_min_value = (u32)imm; 1768 reg->u32_max_value = (u32)imm; 1769 } 1770 1771 /* Mark the unknown part of a register (variable offset or scalar value) as 1772 * known to have the value @imm. 1773 */ 1774 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1775 { 1776 /* Clear off and union(map_ptr, range) */ 1777 memset(((u8 *)reg) + sizeof(reg->type), 0, 1778 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1779 reg->id = 0; 1780 reg->ref_obj_id = 0; 1781 ___mark_reg_known(reg, imm); 1782 } 1783 1784 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1785 { 1786 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1787 reg->s32_min_value = (s32)imm; 1788 reg->s32_max_value = (s32)imm; 1789 reg->u32_min_value = (u32)imm; 1790 reg->u32_max_value = (u32)imm; 1791 } 1792 1793 /* Mark the 'variable offset' part of a register as zero. This should be 1794 * used only on registers holding a pointer type. 1795 */ 1796 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1797 { 1798 __mark_reg_known(reg, 0); 1799 } 1800 1801 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1802 { 1803 __mark_reg_known(reg, 0); 1804 reg->type = SCALAR_VALUE; 1805 /* all scalars are assumed imprecise initially (unless unprivileged, 1806 * in which case everything is forced to be precise) 1807 */ 1808 reg->precise = !env->bpf_capable; 1809 } 1810 1811 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1812 struct bpf_reg_state *regs, u32 regno) 1813 { 1814 if (WARN_ON(regno >= MAX_BPF_REG)) { 1815 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1816 /* Something bad happened, let's kill all regs */ 1817 for (regno = 0; regno < MAX_BPF_REG; regno++) 1818 __mark_reg_not_init(env, regs + regno); 1819 return; 1820 } 1821 __mark_reg_known_zero(regs + regno); 1822 } 1823 1824 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1825 bool first_slot, int dynptr_id) 1826 { 1827 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1828 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1829 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1830 */ 1831 __mark_reg_known_zero(reg); 1832 reg->type = CONST_PTR_TO_DYNPTR; 1833 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1834 reg->id = dynptr_id; 1835 reg->dynptr.type = type; 1836 reg->dynptr.first_slot = first_slot; 1837 } 1838 1839 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1840 { 1841 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1842 const struct bpf_map *map = reg->map_ptr; 1843 1844 if (map->inner_map_meta) { 1845 reg->type = CONST_PTR_TO_MAP; 1846 reg->map_ptr = map->inner_map_meta; 1847 /* transfer reg's id which is unique for every map_lookup_elem 1848 * as UID of the inner map. 1849 */ 1850 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 1851 reg->map_uid = reg->id; 1852 if (btf_record_has_field(map->inner_map_meta->record, BPF_WORKQUEUE)) 1853 reg->map_uid = reg->id; 1854 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1855 reg->type = PTR_TO_XDP_SOCK; 1856 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1857 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1858 reg->type = PTR_TO_SOCKET; 1859 } else { 1860 reg->type = PTR_TO_MAP_VALUE; 1861 } 1862 return; 1863 } 1864 1865 reg->type &= ~PTR_MAYBE_NULL; 1866 } 1867 1868 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 1869 struct btf_field_graph_root *ds_head) 1870 { 1871 __mark_reg_known_zero(®s[regno]); 1872 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 1873 regs[regno].btf = ds_head->btf; 1874 regs[regno].btf_id = ds_head->value_btf_id; 1875 regs[regno].off = ds_head->node_offset; 1876 } 1877 1878 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1879 { 1880 return type_is_pkt_pointer(reg->type); 1881 } 1882 1883 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1884 { 1885 return reg_is_pkt_pointer(reg) || 1886 reg->type == PTR_TO_PACKET_END; 1887 } 1888 1889 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 1890 { 1891 return base_type(reg->type) == PTR_TO_MEM && 1892 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP); 1893 } 1894 1895 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1896 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1897 enum bpf_reg_type which) 1898 { 1899 /* The register can already have a range from prior markings. 1900 * This is fine as long as it hasn't been advanced from its 1901 * origin. 1902 */ 1903 return reg->type == which && 1904 reg->id == 0 && 1905 reg->off == 0 && 1906 tnum_equals_const(reg->var_off, 0); 1907 } 1908 1909 /* Reset the min/max bounds of a register */ 1910 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1911 { 1912 reg->smin_value = S64_MIN; 1913 reg->smax_value = S64_MAX; 1914 reg->umin_value = 0; 1915 reg->umax_value = U64_MAX; 1916 1917 reg->s32_min_value = S32_MIN; 1918 reg->s32_max_value = S32_MAX; 1919 reg->u32_min_value = 0; 1920 reg->u32_max_value = U32_MAX; 1921 } 1922 1923 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1924 { 1925 reg->smin_value = S64_MIN; 1926 reg->smax_value = S64_MAX; 1927 reg->umin_value = 0; 1928 reg->umax_value = U64_MAX; 1929 } 1930 1931 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1932 { 1933 reg->s32_min_value = S32_MIN; 1934 reg->s32_max_value = S32_MAX; 1935 reg->u32_min_value = 0; 1936 reg->u32_max_value = U32_MAX; 1937 } 1938 1939 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1940 { 1941 struct tnum var32_off = tnum_subreg(reg->var_off); 1942 1943 /* min signed is max(sign bit) | min(other bits) */ 1944 reg->s32_min_value = max_t(s32, reg->s32_min_value, 1945 var32_off.value | (var32_off.mask & S32_MIN)); 1946 /* max signed is min(sign bit) | max(other bits) */ 1947 reg->s32_max_value = min_t(s32, reg->s32_max_value, 1948 var32_off.value | (var32_off.mask & S32_MAX)); 1949 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 1950 reg->u32_max_value = min(reg->u32_max_value, 1951 (u32)(var32_off.value | var32_off.mask)); 1952 } 1953 1954 static void __update_reg64_bounds(struct bpf_reg_state *reg) 1955 { 1956 /* min signed is max(sign bit) | min(other bits) */ 1957 reg->smin_value = max_t(s64, reg->smin_value, 1958 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 1959 /* max signed is min(sign bit) | max(other bits) */ 1960 reg->smax_value = min_t(s64, reg->smax_value, 1961 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 1962 reg->umin_value = max(reg->umin_value, reg->var_off.value); 1963 reg->umax_value = min(reg->umax_value, 1964 reg->var_off.value | reg->var_off.mask); 1965 } 1966 1967 static void __update_reg_bounds(struct bpf_reg_state *reg) 1968 { 1969 __update_reg32_bounds(reg); 1970 __update_reg64_bounds(reg); 1971 } 1972 1973 /* Uses signed min/max values to inform unsigned, and vice-versa */ 1974 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 1975 { 1976 /* If upper 32 bits of u64/s64 range don't change, we can use lower 32 1977 * bits to improve our u32/s32 boundaries. 1978 * 1979 * E.g., the case where we have upper 32 bits as zero ([10, 20] in 1980 * u64) is pretty trivial, it's obvious that in u32 we'll also have 1981 * [10, 20] range. But this property holds for any 64-bit range as 1982 * long as upper 32 bits in that entire range of values stay the same. 1983 * 1984 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311] 1985 * in decimal) has the same upper 32 bits throughout all the values in 1986 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15]) 1987 * range. 1988 * 1989 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32, 1990 * following the rules outlined below about u64/s64 correspondence 1991 * (which equally applies to u32 vs s32 correspondence). In general it 1992 * depends on actual hexadecimal values of 32-bit range. They can form 1993 * only valid u32, or only valid s32 ranges in some cases. 1994 * 1995 * So we use all these insights to derive bounds for subregisters here. 1996 */ 1997 if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) { 1998 /* u64 to u32 casting preserves validity of low 32 bits as 1999 * a range, if upper 32 bits are the same 2000 */ 2001 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value); 2002 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value); 2003 2004 if ((s32)reg->umin_value <= (s32)reg->umax_value) { 2005 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 2006 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 2007 } 2008 } 2009 if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) { 2010 /* low 32 bits should form a proper u32 range */ 2011 if ((u32)reg->smin_value <= (u32)reg->smax_value) { 2012 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value); 2013 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value); 2014 } 2015 /* low 32 bits should form a proper s32 range */ 2016 if ((s32)reg->smin_value <= (s32)reg->smax_value) { 2017 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 2018 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 2019 } 2020 } 2021 /* Special case where upper bits form a small sequence of two 2022 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to 2023 * 0x00000000 is also valid), while lower bits form a proper s32 range 2024 * going from negative numbers to positive numbers. E.g., let's say we 2025 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]). 2026 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff, 2027 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits, 2028 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]). 2029 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in 2030 * upper 32 bits. As a random example, s64 range 2031 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range 2032 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister. 2033 */ 2034 if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) && 2035 (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) { 2036 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 2037 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 2038 } 2039 if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) && 2040 (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) { 2041 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 2042 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 2043 } 2044 /* if u32 range forms a valid s32 range (due to matching sign bit), 2045 * try to learn from that 2046 */ 2047 if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) { 2048 reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value); 2049 reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value); 2050 } 2051 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2052 * are the same, so combine. This works even in the negative case, e.g. 2053 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2054 */ 2055 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2056 reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value); 2057 reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value); 2058 } 2059 } 2060 2061 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 2062 { 2063 /* If u64 range forms a valid s64 range (due to matching sign bit), 2064 * try to learn from that. Let's do a bit of ASCII art to see when 2065 * this is happening. Let's take u64 range first: 2066 * 2067 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2068 * |-------------------------------|--------------------------------| 2069 * 2070 * Valid u64 range is formed when umin and umax are anywhere in the 2071 * range [0, U64_MAX], and umin <= umax. u64 case is simple and 2072 * straightforward. Let's see how s64 range maps onto the same range 2073 * of values, annotated below the line for comparison: 2074 * 2075 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2076 * |-------------------------------|--------------------------------| 2077 * 0 S64_MAX S64_MIN -1 2078 * 2079 * So s64 values basically start in the middle and they are logically 2080 * contiguous to the right of it, wrapping around from -1 to 0, and 2081 * then finishing as S64_MAX (0x7fffffffffffffff) right before 2082 * S64_MIN. We can try drawing the continuity of u64 vs s64 values 2083 * more visually as mapped to sign-agnostic range of hex values. 2084 * 2085 * u64 start u64 end 2086 * _______________________________________________________________ 2087 * / \ 2088 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2089 * |-------------------------------|--------------------------------| 2090 * 0 S64_MAX S64_MIN -1 2091 * / \ 2092 * >------------------------------ -------------------------------> 2093 * s64 continues... s64 end s64 start s64 "midpoint" 2094 * 2095 * What this means is that, in general, we can't always derive 2096 * something new about u64 from any random s64 range, and vice versa. 2097 * 2098 * But we can do that in two particular cases. One is when entire 2099 * u64/s64 range is *entirely* contained within left half of the above 2100 * diagram or when it is *entirely* contained in the right half. I.e.: 2101 * 2102 * |-------------------------------|--------------------------------| 2103 * ^ ^ ^ ^ 2104 * A B C D 2105 * 2106 * [A, B] and [C, D] are contained entirely in their respective halves 2107 * and form valid contiguous ranges as both u64 and s64 values. [A, B] 2108 * will be non-negative both as u64 and s64 (and in fact it will be 2109 * identical ranges no matter the signedness). [C, D] treated as s64 2110 * will be a range of negative values, while in u64 it will be 2111 * non-negative range of values larger than 0x8000000000000000. 2112 * 2113 * Now, any other range here can't be represented in both u64 and s64 2114 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid 2115 * contiguous u64 ranges, but they are discontinuous in s64. [B, C] 2116 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX], 2117 * for example. Similarly, valid s64 range [D, A] (going from negative 2118 * to positive values), would be two separate [D, U64_MAX] and [0, A] 2119 * ranges as u64. Currently reg_state can't represent two segments per 2120 * numeric domain, so in such situations we can only derive maximal 2121 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64). 2122 * 2123 * So we use these facts to derive umin/umax from smin/smax and vice 2124 * versa only if they stay within the same "half". This is equivalent 2125 * to checking sign bit: lower half will have sign bit as zero, upper 2126 * half have sign bit 1. Below in code we simplify this by just 2127 * casting umin/umax as smin/smax and checking if they form valid 2128 * range, and vice versa. Those are equivalent checks. 2129 */ 2130 if ((s64)reg->umin_value <= (s64)reg->umax_value) { 2131 reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value); 2132 reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value); 2133 } 2134 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2135 * are the same, so combine. This works even in the negative case, e.g. 2136 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2137 */ 2138 if ((u64)reg->smin_value <= (u64)reg->smax_value) { 2139 reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); 2140 reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); 2141 } 2142 } 2143 2144 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg) 2145 { 2146 /* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit 2147 * values on both sides of 64-bit range in hope to have tighter range. 2148 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from 2149 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff]. 2150 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound 2151 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of 2152 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a 2153 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff]. 2154 * We just need to make sure that derived bounds we are intersecting 2155 * with are well-formed ranges in respective s64 or u64 domain, just 2156 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments. 2157 */ 2158 __u64 new_umin, new_umax; 2159 __s64 new_smin, new_smax; 2160 2161 /* u32 -> u64 tightening, it's always well-formed */ 2162 new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value; 2163 new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value; 2164 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2165 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2166 /* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */ 2167 new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value; 2168 new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value; 2169 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2170 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2171 2172 /* if s32 can be treated as valid u32 range, we can use it as well */ 2173 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2174 /* s32 -> u64 tightening */ 2175 new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value; 2176 new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value; 2177 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2178 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2179 /* s32 -> s64 tightening */ 2180 new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value; 2181 new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value; 2182 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2183 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2184 } 2185 2186 /* Here we would like to handle a special case after sign extending load, 2187 * when upper bits for a 64-bit range are all 1s or all 0s. 2188 * 2189 * Upper bits are all 1s when register is in a range: 2190 * [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff] 2191 * Upper bits are all 0s when register is in a range: 2192 * [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff] 2193 * Together this forms are continuous range: 2194 * [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff] 2195 * 2196 * Now, suppose that register range is in fact tighter: 2197 * [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R) 2198 * Also suppose that it's 32-bit range is positive, 2199 * meaning that lower 32-bits of the full 64-bit register 2200 * are in the range: 2201 * [0x0000_0000, 0x7fff_ffff] (W) 2202 * 2203 * If this happens, then any value in a range: 2204 * [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff] 2205 * is smaller than a lowest bound of the range (R): 2206 * 0xffff_ffff_8000_0000 2207 * which means that upper bits of the full 64-bit register 2208 * can't be all 1s, when lower bits are in range (W). 2209 * 2210 * Note that: 2211 * - 0xffff_ffff_8000_0000 == (s64)S32_MIN 2212 * - 0x0000_0000_7fff_ffff == (s64)S32_MAX 2213 * These relations are used in the conditions below. 2214 */ 2215 if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) { 2216 reg->smin_value = reg->s32_min_value; 2217 reg->smax_value = reg->s32_max_value; 2218 reg->umin_value = reg->s32_min_value; 2219 reg->umax_value = reg->s32_max_value; 2220 reg->var_off = tnum_intersect(reg->var_off, 2221 tnum_range(reg->smin_value, reg->smax_value)); 2222 } 2223 } 2224 2225 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2226 { 2227 __reg32_deduce_bounds(reg); 2228 __reg64_deduce_bounds(reg); 2229 __reg_deduce_mixed_bounds(reg); 2230 } 2231 2232 /* Attempts to improve var_off based on unsigned min/max information */ 2233 static void __reg_bound_offset(struct bpf_reg_state *reg) 2234 { 2235 struct tnum var64_off = tnum_intersect(reg->var_off, 2236 tnum_range(reg->umin_value, 2237 reg->umax_value)); 2238 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2239 tnum_range(reg->u32_min_value, 2240 reg->u32_max_value)); 2241 2242 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2243 } 2244 2245 static void reg_bounds_sync(struct bpf_reg_state *reg) 2246 { 2247 /* We might have learned new bounds from the var_off. */ 2248 __update_reg_bounds(reg); 2249 /* We might have learned something about the sign bit. */ 2250 __reg_deduce_bounds(reg); 2251 __reg_deduce_bounds(reg); 2252 /* We might have learned some bits from the bounds. */ 2253 __reg_bound_offset(reg); 2254 /* Intersecting with the old var_off might have improved our bounds 2255 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2256 * then new var_off is (0; 0x7f...fc) which improves our umax. 2257 */ 2258 __update_reg_bounds(reg); 2259 } 2260 2261 static int reg_bounds_sanity_check(struct bpf_verifier_env *env, 2262 struct bpf_reg_state *reg, const char *ctx) 2263 { 2264 const char *msg; 2265 2266 if (reg->umin_value > reg->umax_value || 2267 reg->smin_value > reg->smax_value || 2268 reg->u32_min_value > reg->u32_max_value || 2269 reg->s32_min_value > reg->s32_max_value) { 2270 msg = "range bounds violation"; 2271 goto out; 2272 } 2273 2274 if (tnum_is_const(reg->var_off)) { 2275 u64 uval = reg->var_off.value; 2276 s64 sval = (s64)uval; 2277 2278 if (reg->umin_value != uval || reg->umax_value != uval || 2279 reg->smin_value != sval || reg->smax_value != sval) { 2280 msg = "const tnum out of sync with range bounds"; 2281 goto out; 2282 } 2283 } 2284 2285 if (tnum_subreg_is_const(reg->var_off)) { 2286 u32 uval32 = tnum_subreg(reg->var_off).value; 2287 s32 sval32 = (s32)uval32; 2288 2289 if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 || 2290 reg->s32_min_value != sval32 || reg->s32_max_value != sval32) { 2291 msg = "const subreg tnum out of sync with range bounds"; 2292 goto out; 2293 } 2294 } 2295 2296 return 0; 2297 out: 2298 verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] " 2299 "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n", 2300 ctx, msg, reg->umin_value, reg->umax_value, 2301 reg->smin_value, reg->smax_value, 2302 reg->u32_min_value, reg->u32_max_value, 2303 reg->s32_min_value, reg->s32_max_value, 2304 reg->var_off.value, reg->var_off.mask); 2305 if (env->test_reg_invariants) 2306 return -EFAULT; 2307 __mark_reg_unbounded(reg); 2308 return 0; 2309 } 2310 2311 static bool __reg32_bound_s64(s32 a) 2312 { 2313 return a >= 0 && a <= S32_MAX; 2314 } 2315 2316 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 2317 { 2318 reg->umin_value = reg->u32_min_value; 2319 reg->umax_value = reg->u32_max_value; 2320 2321 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 2322 * be positive otherwise set to worse case bounds and refine later 2323 * from tnum. 2324 */ 2325 if (__reg32_bound_s64(reg->s32_min_value) && 2326 __reg32_bound_s64(reg->s32_max_value)) { 2327 reg->smin_value = reg->s32_min_value; 2328 reg->smax_value = reg->s32_max_value; 2329 } else { 2330 reg->smin_value = 0; 2331 reg->smax_value = U32_MAX; 2332 } 2333 } 2334 2335 /* Mark a register as having a completely unknown (scalar) value. */ 2336 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg) 2337 { 2338 /* 2339 * Clear type, off, and union(map_ptr, range) and 2340 * padding between 'type' and union 2341 */ 2342 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2343 reg->type = SCALAR_VALUE; 2344 reg->id = 0; 2345 reg->ref_obj_id = 0; 2346 reg->var_off = tnum_unknown; 2347 reg->frameno = 0; 2348 reg->precise = false; 2349 __mark_reg_unbounded(reg); 2350 } 2351 2352 /* Mark a register as having a completely unknown (scalar) value, 2353 * initialize .precise as true when not bpf capable. 2354 */ 2355 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2356 struct bpf_reg_state *reg) 2357 { 2358 __mark_reg_unknown_imprecise(reg); 2359 reg->precise = !env->bpf_capable; 2360 } 2361 2362 static void mark_reg_unknown(struct bpf_verifier_env *env, 2363 struct bpf_reg_state *regs, u32 regno) 2364 { 2365 if (WARN_ON(regno >= MAX_BPF_REG)) { 2366 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 2367 /* Something bad happened, let's kill all regs except FP */ 2368 for (regno = 0; regno < BPF_REG_FP; regno++) 2369 __mark_reg_not_init(env, regs + regno); 2370 return; 2371 } 2372 __mark_reg_unknown(env, regs + regno); 2373 } 2374 2375 static int __mark_reg_s32_range(struct bpf_verifier_env *env, 2376 struct bpf_reg_state *regs, 2377 u32 regno, 2378 s32 s32_min, 2379 s32 s32_max) 2380 { 2381 struct bpf_reg_state *reg = regs + regno; 2382 2383 reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min); 2384 reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max); 2385 2386 reg->smin_value = max_t(s64, reg->smin_value, s32_min); 2387 reg->smax_value = min_t(s64, reg->smax_value, s32_max); 2388 2389 reg_bounds_sync(reg); 2390 2391 return reg_bounds_sanity_check(env, reg, "s32_range"); 2392 } 2393 2394 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 2395 struct bpf_reg_state *reg) 2396 { 2397 __mark_reg_unknown(env, reg); 2398 reg->type = NOT_INIT; 2399 } 2400 2401 static void mark_reg_not_init(struct bpf_verifier_env *env, 2402 struct bpf_reg_state *regs, u32 regno) 2403 { 2404 if (WARN_ON(regno >= MAX_BPF_REG)) { 2405 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 2406 /* Something bad happened, let's kill all regs except FP */ 2407 for (regno = 0; regno < BPF_REG_FP; regno++) 2408 __mark_reg_not_init(env, regs + regno); 2409 return; 2410 } 2411 __mark_reg_not_init(env, regs + regno); 2412 } 2413 2414 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 2415 struct bpf_reg_state *regs, u32 regno, 2416 enum bpf_reg_type reg_type, 2417 struct btf *btf, u32 btf_id, 2418 enum bpf_type_flag flag) 2419 { 2420 if (reg_type == SCALAR_VALUE) { 2421 mark_reg_unknown(env, regs, regno); 2422 return; 2423 } 2424 mark_reg_known_zero(env, regs, regno); 2425 regs[regno].type = PTR_TO_BTF_ID | flag; 2426 regs[regno].btf = btf; 2427 regs[regno].btf_id = btf_id; 2428 if (type_may_be_null(flag)) 2429 regs[regno].id = ++env->id_gen; 2430 } 2431 2432 #define DEF_NOT_SUBREG (0) 2433 static void init_reg_state(struct bpf_verifier_env *env, 2434 struct bpf_func_state *state) 2435 { 2436 struct bpf_reg_state *regs = state->regs; 2437 int i; 2438 2439 for (i = 0; i < MAX_BPF_REG; i++) { 2440 mark_reg_not_init(env, regs, i); 2441 regs[i].live = REG_LIVE_NONE; 2442 regs[i].parent = NULL; 2443 regs[i].subreg_def = DEF_NOT_SUBREG; 2444 } 2445 2446 /* frame pointer */ 2447 regs[BPF_REG_FP].type = PTR_TO_STACK; 2448 mark_reg_known_zero(env, regs, BPF_REG_FP); 2449 regs[BPF_REG_FP].frameno = state->frameno; 2450 } 2451 2452 static struct bpf_retval_range retval_range(s32 minval, s32 maxval) 2453 { 2454 return (struct bpf_retval_range){ minval, maxval }; 2455 } 2456 2457 #define BPF_MAIN_FUNC (-1) 2458 static void init_func_state(struct bpf_verifier_env *env, 2459 struct bpf_func_state *state, 2460 int callsite, int frameno, int subprogno) 2461 { 2462 state->callsite = callsite; 2463 state->frameno = frameno; 2464 state->subprogno = subprogno; 2465 state->callback_ret_range = retval_range(0, 0); 2466 init_reg_state(env, state); 2467 mark_verifier_state_scratched(env); 2468 } 2469 2470 /* Similar to push_stack(), but for async callbacks */ 2471 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2472 int insn_idx, int prev_insn_idx, 2473 int subprog, bool is_sleepable) 2474 { 2475 struct bpf_verifier_stack_elem *elem; 2476 struct bpf_func_state *frame; 2477 2478 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2479 if (!elem) 2480 goto err; 2481 2482 elem->insn_idx = insn_idx; 2483 elem->prev_insn_idx = prev_insn_idx; 2484 elem->next = env->head; 2485 elem->log_pos = env->log.end_pos; 2486 env->head = elem; 2487 env->stack_size++; 2488 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2489 verbose(env, 2490 "The sequence of %d jumps is too complex for async cb.\n", 2491 env->stack_size); 2492 goto err; 2493 } 2494 /* Unlike push_stack() do not copy_verifier_state(). 2495 * The caller state doesn't matter. 2496 * This is async callback. It starts in a fresh stack. 2497 * Initialize it similar to do_check_common(). 2498 */ 2499 elem->st.branches = 1; 2500 elem->st.in_sleepable = is_sleepable; 2501 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 2502 if (!frame) 2503 goto err; 2504 init_func_state(env, frame, 2505 BPF_MAIN_FUNC /* callsite */, 2506 0 /* frameno within this callchain */, 2507 subprog /* subprog number within this prog */); 2508 elem->st.frame[0] = frame; 2509 return &elem->st; 2510 err: 2511 free_verifier_state(env->cur_state, true); 2512 env->cur_state = NULL; 2513 /* pop all elements and return */ 2514 while (!pop_stack(env, NULL, NULL, false)); 2515 return NULL; 2516 } 2517 2518 2519 enum reg_arg_type { 2520 SRC_OP, /* register is used as source operand */ 2521 DST_OP, /* register is used as destination operand */ 2522 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2523 }; 2524 2525 static int cmp_subprogs(const void *a, const void *b) 2526 { 2527 return ((struct bpf_subprog_info *)a)->start - 2528 ((struct bpf_subprog_info *)b)->start; 2529 } 2530 2531 static int find_subprog(struct bpf_verifier_env *env, int off) 2532 { 2533 struct bpf_subprog_info *p; 2534 2535 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 2536 sizeof(env->subprog_info[0]), cmp_subprogs); 2537 if (!p) 2538 return -ENOENT; 2539 return p - env->subprog_info; 2540 2541 } 2542 2543 static int add_subprog(struct bpf_verifier_env *env, int off) 2544 { 2545 int insn_cnt = env->prog->len; 2546 int ret; 2547 2548 if (off >= insn_cnt || off < 0) { 2549 verbose(env, "call to invalid destination\n"); 2550 return -EINVAL; 2551 } 2552 ret = find_subprog(env, off); 2553 if (ret >= 0) 2554 return ret; 2555 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2556 verbose(env, "too many subprograms\n"); 2557 return -E2BIG; 2558 } 2559 /* determine subprog starts. The end is one before the next starts */ 2560 env->subprog_info[env->subprog_cnt++].start = off; 2561 sort(env->subprog_info, env->subprog_cnt, 2562 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2563 return env->subprog_cnt - 1; 2564 } 2565 2566 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env) 2567 { 2568 struct bpf_prog_aux *aux = env->prog->aux; 2569 struct btf *btf = aux->btf; 2570 const struct btf_type *t; 2571 u32 main_btf_id, id; 2572 const char *name; 2573 int ret, i; 2574 2575 /* Non-zero func_info_cnt implies valid btf */ 2576 if (!aux->func_info_cnt) 2577 return 0; 2578 main_btf_id = aux->func_info[0].type_id; 2579 2580 t = btf_type_by_id(btf, main_btf_id); 2581 if (!t) { 2582 verbose(env, "invalid btf id for main subprog in func_info\n"); 2583 return -EINVAL; 2584 } 2585 2586 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:"); 2587 if (IS_ERR(name)) { 2588 ret = PTR_ERR(name); 2589 /* If there is no tag present, there is no exception callback */ 2590 if (ret == -ENOENT) 2591 ret = 0; 2592 else if (ret == -EEXIST) 2593 verbose(env, "multiple exception callback tags for main subprog\n"); 2594 return ret; 2595 } 2596 2597 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC); 2598 if (ret < 0) { 2599 verbose(env, "exception callback '%s' could not be found in BTF\n", name); 2600 return ret; 2601 } 2602 id = ret; 2603 t = btf_type_by_id(btf, id); 2604 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) { 2605 verbose(env, "exception callback '%s' must have global linkage\n", name); 2606 return -EINVAL; 2607 } 2608 ret = 0; 2609 for (i = 0; i < aux->func_info_cnt; i++) { 2610 if (aux->func_info[i].type_id != id) 2611 continue; 2612 ret = aux->func_info[i].insn_off; 2613 /* Further func_info and subprog checks will also happen 2614 * later, so assume this is the right insn_off for now. 2615 */ 2616 if (!ret) { 2617 verbose(env, "invalid exception callback insn_off in func_info: 0\n"); 2618 ret = -EINVAL; 2619 } 2620 } 2621 if (!ret) { 2622 verbose(env, "exception callback type id not found in func_info\n"); 2623 ret = -EINVAL; 2624 } 2625 return ret; 2626 } 2627 2628 #define MAX_KFUNC_DESCS 256 2629 #define MAX_KFUNC_BTFS 256 2630 2631 struct bpf_kfunc_desc { 2632 struct btf_func_model func_model; 2633 u32 func_id; 2634 s32 imm; 2635 u16 offset; 2636 unsigned long addr; 2637 }; 2638 2639 struct bpf_kfunc_btf { 2640 struct btf *btf; 2641 struct module *module; 2642 u16 offset; 2643 }; 2644 2645 struct bpf_kfunc_desc_tab { 2646 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during 2647 * verification. JITs do lookups by bpf_insn, where func_id may not be 2648 * available, therefore at the end of verification do_misc_fixups() 2649 * sorts this by imm and offset. 2650 */ 2651 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 2652 u32 nr_descs; 2653 }; 2654 2655 struct bpf_kfunc_btf_tab { 2656 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2657 u32 nr_descs; 2658 }; 2659 2660 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2661 { 2662 const struct bpf_kfunc_desc *d0 = a; 2663 const struct bpf_kfunc_desc *d1 = b; 2664 2665 /* func_id is not greater than BTF_MAX_TYPE */ 2666 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2667 } 2668 2669 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2670 { 2671 const struct bpf_kfunc_btf *d0 = a; 2672 const struct bpf_kfunc_btf *d1 = b; 2673 2674 return d0->offset - d1->offset; 2675 } 2676 2677 static const struct bpf_kfunc_desc * 2678 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2679 { 2680 struct bpf_kfunc_desc desc = { 2681 .func_id = func_id, 2682 .offset = offset, 2683 }; 2684 struct bpf_kfunc_desc_tab *tab; 2685 2686 tab = prog->aux->kfunc_tab; 2687 return bsearch(&desc, tab->descs, tab->nr_descs, 2688 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2689 } 2690 2691 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2692 u16 btf_fd_idx, u8 **func_addr) 2693 { 2694 const struct bpf_kfunc_desc *desc; 2695 2696 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2697 if (!desc) 2698 return -EFAULT; 2699 2700 *func_addr = (u8 *)desc->addr; 2701 return 0; 2702 } 2703 2704 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2705 s16 offset) 2706 { 2707 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2708 struct bpf_kfunc_btf_tab *tab; 2709 struct bpf_kfunc_btf *b; 2710 struct module *mod; 2711 struct btf *btf; 2712 int btf_fd; 2713 2714 tab = env->prog->aux->kfunc_btf_tab; 2715 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2716 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2717 if (!b) { 2718 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2719 verbose(env, "too many different module BTFs\n"); 2720 return ERR_PTR(-E2BIG); 2721 } 2722 2723 if (bpfptr_is_null(env->fd_array)) { 2724 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2725 return ERR_PTR(-EPROTO); 2726 } 2727 2728 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2729 offset * sizeof(btf_fd), 2730 sizeof(btf_fd))) 2731 return ERR_PTR(-EFAULT); 2732 2733 btf = btf_get_by_fd(btf_fd); 2734 if (IS_ERR(btf)) { 2735 verbose(env, "invalid module BTF fd specified\n"); 2736 return btf; 2737 } 2738 2739 if (!btf_is_module(btf)) { 2740 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2741 btf_put(btf); 2742 return ERR_PTR(-EINVAL); 2743 } 2744 2745 mod = btf_try_get_module(btf); 2746 if (!mod) { 2747 btf_put(btf); 2748 return ERR_PTR(-ENXIO); 2749 } 2750 2751 b = &tab->descs[tab->nr_descs++]; 2752 b->btf = btf; 2753 b->module = mod; 2754 b->offset = offset; 2755 2756 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2757 kfunc_btf_cmp_by_off, NULL); 2758 } 2759 return b->btf; 2760 } 2761 2762 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2763 { 2764 if (!tab) 2765 return; 2766 2767 while (tab->nr_descs--) { 2768 module_put(tab->descs[tab->nr_descs].module); 2769 btf_put(tab->descs[tab->nr_descs].btf); 2770 } 2771 kfree(tab); 2772 } 2773 2774 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2775 { 2776 if (offset) { 2777 if (offset < 0) { 2778 /* In the future, this can be allowed to increase limit 2779 * of fd index into fd_array, interpreted as u16. 2780 */ 2781 verbose(env, "negative offset disallowed for kernel module function call\n"); 2782 return ERR_PTR(-EINVAL); 2783 } 2784 2785 return __find_kfunc_desc_btf(env, offset); 2786 } 2787 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2788 } 2789 2790 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 2791 { 2792 const struct btf_type *func, *func_proto; 2793 struct bpf_kfunc_btf_tab *btf_tab; 2794 struct bpf_kfunc_desc_tab *tab; 2795 struct bpf_prog_aux *prog_aux; 2796 struct bpf_kfunc_desc *desc; 2797 const char *func_name; 2798 struct btf *desc_btf; 2799 unsigned long call_imm; 2800 unsigned long addr; 2801 int err; 2802 2803 prog_aux = env->prog->aux; 2804 tab = prog_aux->kfunc_tab; 2805 btf_tab = prog_aux->kfunc_btf_tab; 2806 if (!tab) { 2807 if (!btf_vmlinux) { 2808 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2809 return -ENOTSUPP; 2810 } 2811 2812 if (!env->prog->jit_requested) { 2813 verbose(env, "JIT is required for calling kernel function\n"); 2814 return -ENOTSUPP; 2815 } 2816 2817 if (!bpf_jit_supports_kfunc_call()) { 2818 verbose(env, "JIT does not support calling kernel function\n"); 2819 return -ENOTSUPP; 2820 } 2821 2822 if (!env->prog->gpl_compatible) { 2823 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2824 return -EINVAL; 2825 } 2826 2827 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 2828 if (!tab) 2829 return -ENOMEM; 2830 prog_aux->kfunc_tab = tab; 2831 } 2832 2833 /* func_id == 0 is always invalid, but instead of returning an error, be 2834 * conservative and wait until the code elimination pass before returning 2835 * error, so that invalid calls that get pruned out can be in BPF programs 2836 * loaded from userspace. It is also required that offset be untouched 2837 * for such calls. 2838 */ 2839 if (!func_id && !offset) 2840 return 0; 2841 2842 if (!btf_tab && offset) { 2843 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 2844 if (!btf_tab) 2845 return -ENOMEM; 2846 prog_aux->kfunc_btf_tab = btf_tab; 2847 } 2848 2849 desc_btf = find_kfunc_desc_btf(env, offset); 2850 if (IS_ERR(desc_btf)) { 2851 verbose(env, "failed to find BTF for kernel function\n"); 2852 return PTR_ERR(desc_btf); 2853 } 2854 2855 if (find_kfunc_desc(env->prog, func_id, offset)) 2856 return 0; 2857 2858 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2859 verbose(env, "too many different kernel function calls\n"); 2860 return -E2BIG; 2861 } 2862 2863 func = btf_type_by_id(desc_btf, func_id); 2864 if (!func || !btf_type_is_func(func)) { 2865 verbose(env, "kernel btf_id %u is not a function\n", 2866 func_id); 2867 return -EINVAL; 2868 } 2869 func_proto = btf_type_by_id(desc_btf, func->type); 2870 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2871 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 2872 func_id); 2873 return -EINVAL; 2874 } 2875 2876 func_name = btf_name_by_offset(desc_btf, func->name_off); 2877 addr = kallsyms_lookup_name(func_name); 2878 if (!addr) { 2879 verbose(env, "cannot find address for kernel function %s\n", 2880 func_name); 2881 return -EINVAL; 2882 } 2883 specialize_kfunc(env, func_id, offset, &addr); 2884 2885 if (bpf_jit_supports_far_kfunc_call()) { 2886 call_imm = func_id; 2887 } else { 2888 call_imm = BPF_CALL_IMM(addr); 2889 /* Check whether the relative offset overflows desc->imm */ 2890 if ((unsigned long)(s32)call_imm != call_imm) { 2891 verbose(env, "address of kernel function %s is out of range\n", 2892 func_name); 2893 return -EINVAL; 2894 } 2895 } 2896 2897 if (bpf_dev_bound_kfunc_id(func_id)) { 2898 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2899 if (err) 2900 return err; 2901 } 2902 2903 desc = &tab->descs[tab->nr_descs++]; 2904 desc->func_id = func_id; 2905 desc->imm = call_imm; 2906 desc->offset = offset; 2907 desc->addr = addr; 2908 err = btf_distill_func_proto(&env->log, desc_btf, 2909 func_proto, func_name, 2910 &desc->func_model); 2911 if (!err) 2912 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2913 kfunc_desc_cmp_by_id_off, NULL); 2914 return err; 2915 } 2916 2917 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b) 2918 { 2919 const struct bpf_kfunc_desc *d0 = a; 2920 const struct bpf_kfunc_desc *d1 = b; 2921 2922 if (d0->imm != d1->imm) 2923 return d0->imm < d1->imm ? -1 : 1; 2924 if (d0->offset != d1->offset) 2925 return d0->offset < d1->offset ? -1 : 1; 2926 return 0; 2927 } 2928 2929 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog) 2930 { 2931 struct bpf_kfunc_desc_tab *tab; 2932 2933 tab = prog->aux->kfunc_tab; 2934 if (!tab) 2935 return; 2936 2937 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2938 kfunc_desc_cmp_by_imm_off, NULL); 2939 } 2940 2941 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2942 { 2943 return !!prog->aux->kfunc_tab; 2944 } 2945 2946 const struct btf_func_model * 2947 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 2948 const struct bpf_insn *insn) 2949 { 2950 const struct bpf_kfunc_desc desc = { 2951 .imm = insn->imm, 2952 .offset = insn->off, 2953 }; 2954 const struct bpf_kfunc_desc *res; 2955 struct bpf_kfunc_desc_tab *tab; 2956 2957 tab = prog->aux->kfunc_tab; 2958 res = bsearch(&desc, tab->descs, tab->nr_descs, 2959 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off); 2960 2961 return res ? &res->func_model : NULL; 2962 } 2963 2964 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 2965 { 2966 struct bpf_subprog_info *subprog = env->subprog_info; 2967 int i, ret, insn_cnt = env->prog->len, ex_cb_insn; 2968 struct bpf_insn *insn = env->prog->insnsi; 2969 2970 /* Add entry function. */ 2971 ret = add_subprog(env, 0); 2972 if (ret) 2973 return ret; 2974 2975 for (i = 0; i < insn_cnt; i++, insn++) { 2976 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 2977 !bpf_pseudo_kfunc_call(insn)) 2978 continue; 2979 2980 if (!env->bpf_capable) { 2981 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2982 return -EPERM; 2983 } 2984 2985 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 2986 ret = add_subprog(env, i + insn->imm + 1); 2987 else 2988 ret = add_kfunc_call(env, insn->imm, insn->off); 2989 2990 if (ret < 0) 2991 return ret; 2992 } 2993 2994 ret = bpf_find_exception_callback_insn_off(env); 2995 if (ret < 0) 2996 return ret; 2997 ex_cb_insn = ret; 2998 2999 /* If ex_cb_insn > 0, this means that the main program has a subprog 3000 * marked using BTF decl tag to serve as the exception callback. 3001 */ 3002 if (ex_cb_insn) { 3003 ret = add_subprog(env, ex_cb_insn); 3004 if (ret < 0) 3005 return ret; 3006 for (i = 1; i < env->subprog_cnt; i++) { 3007 if (env->subprog_info[i].start != ex_cb_insn) 3008 continue; 3009 env->exception_callback_subprog = i; 3010 mark_subprog_exc_cb(env, i); 3011 break; 3012 } 3013 } 3014 3015 /* Add a fake 'exit' subprog which could simplify subprog iteration 3016 * logic. 'subprog_cnt' should not be increased. 3017 */ 3018 subprog[env->subprog_cnt].start = insn_cnt; 3019 3020 if (env->log.level & BPF_LOG_LEVEL2) 3021 for (i = 0; i < env->subprog_cnt; i++) 3022 verbose(env, "func#%d @%d\n", i, subprog[i].start); 3023 3024 return 0; 3025 } 3026 3027 static int check_subprogs(struct bpf_verifier_env *env) 3028 { 3029 int i, subprog_start, subprog_end, off, cur_subprog = 0; 3030 struct bpf_subprog_info *subprog = env->subprog_info; 3031 struct bpf_insn *insn = env->prog->insnsi; 3032 int insn_cnt = env->prog->len; 3033 3034 /* now check that all jumps are within the same subprog */ 3035 subprog_start = subprog[cur_subprog].start; 3036 subprog_end = subprog[cur_subprog + 1].start; 3037 for (i = 0; i < insn_cnt; i++) { 3038 u8 code = insn[i].code; 3039 3040 if (code == (BPF_JMP | BPF_CALL) && 3041 insn[i].src_reg == 0 && 3042 insn[i].imm == BPF_FUNC_tail_call) { 3043 subprog[cur_subprog].has_tail_call = true; 3044 subprog[cur_subprog].tail_call_reachable = true; 3045 } 3046 if (BPF_CLASS(code) == BPF_LD && 3047 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 3048 subprog[cur_subprog].has_ld_abs = true; 3049 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 3050 goto next; 3051 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 3052 goto next; 3053 if (code == (BPF_JMP32 | BPF_JA)) 3054 off = i + insn[i].imm + 1; 3055 else 3056 off = i + insn[i].off + 1; 3057 if (off < subprog_start || off >= subprog_end) { 3058 verbose(env, "jump out of range from insn %d to %d\n", i, off); 3059 return -EINVAL; 3060 } 3061 next: 3062 if (i == subprog_end - 1) { 3063 /* to avoid fall-through from one subprog into another 3064 * the last insn of the subprog should be either exit 3065 * or unconditional jump back or bpf_throw call 3066 */ 3067 if (code != (BPF_JMP | BPF_EXIT) && 3068 code != (BPF_JMP32 | BPF_JA) && 3069 code != (BPF_JMP | BPF_JA)) { 3070 verbose(env, "last insn is not an exit or jmp\n"); 3071 return -EINVAL; 3072 } 3073 subprog_start = subprog_end; 3074 cur_subprog++; 3075 if (cur_subprog < env->subprog_cnt) 3076 subprog_end = subprog[cur_subprog + 1].start; 3077 } 3078 } 3079 return 0; 3080 } 3081 3082 /* Parentage chain of this register (or stack slot) should take care of all 3083 * issues like callee-saved registers, stack slot allocation time, etc. 3084 */ 3085 static int mark_reg_read(struct bpf_verifier_env *env, 3086 const struct bpf_reg_state *state, 3087 struct bpf_reg_state *parent, u8 flag) 3088 { 3089 bool writes = parent == state->parent; /* Observe write marks */ 3090 int cnt = 0; 3091 3092 while (parent) { 3093 /* if read wasn't screened by an earlier write ... */ 3094 if (writes && state->live & REG_LIVE_WRITTEN) 3095 break; 3096 if (parent->live & REG_LIVE_DONE) { 3097 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 3098 reg_type_str(env, parent->type), 3099 parent->var_off.value, parent->off); 3100 return -EFAULT; 3101 } 3102 /* The first condition is more likely to be true than the 3103 * second, checked it first. 3104 */ 3105 if ((parent->live & REG_LIVE_READ) == flag || 3106 parent->live & REG_LIVE_READ64) 3107 /* The parentage chain never changes and 3108 * this parent was already marked as LIVE_READ. 3109 * There is no need to keep walking the chain again and 3110 * keep re-marking all parents as LIVE_READ. 3111 * This case happens when the same register is read 3112 * multiple times without writes into it in-between. 3113 * Also, if parent has the stronger REG_LIVE_READ64 set, 3114 * then no need to set the weak REG_LIVE_READ32. 3115 */ 3116 break; 3117 /* ... then we depend on parent's value */ 3118 parent->live |= flag; 3119 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 3120 if (flag == REG_LIVE_READ64) 3121 parent->live &= ~REG_LIVE_READ32; 3122 state = parent; 3123 parent = state->parent; 3124 writes = true; 3125 cnt++; 3126 } 3127 3128 if (env->longest_mark_read_walk < cnt) 3129 env->longest_mark_read_walk = cnt; 3130 return 0; 3131 } 3132 3133 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3134 { 3135 struct bpf_func_state *state = func(env, reg); 3136 int spi, ret; 3137 3138 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 3139 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 3140 * check_kfunc_call. 3141 */ 3142 if (reg->type == CONST_PTR_TO_DYNPTR) 3143 return 0; 3144 spi = dynptr_get_spi(env, reg); 3145 if (spi < 0) 3146 return spi; 3147 /* Caller ensures dynptr is valid and initialized, which means spi is in 3148 * bounds and spi is the first dynptr slot. Simply mark stack slot as 3149 * read. 3150 */ 3151 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr, 3152 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64); 3153 if (ret) 3154 return ret; 3155 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr, 3156 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64); 3157 } 3158 3159 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3160 int spi, int nr_slots) 3161 { 3162 struct bpf_func_state *state = func(env, reg); 3163 int err, i; 3164 3165 for (i = 0; i < nr_slots; i++) { 3166 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr; 3167 3168 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64); 3169 if (err) 3170 return err; 3171 3172 mark_stack_slot_scratched(env, spi - i); 3173 } 3174 3175 return 0; 3176 } 3177 3178 /* This function is supposed to be used by the following 32-bit optimization 3179 * code only. It returns TRUE if the source or destination register operates 3180 * on 64-bit, otherwise return FALSE. 3181 */ 3182 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 3183 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 3184 { 3185 u8 code, class, op; 3186 3187 code = insn->code; 3188 class = BPF_CLASS(code); 3189 op = BPF_OP(code); 3190 if (class == BPF_JMP) { 3191 /* BPF_EXIT for "main" will reach here. Return TRUE 3192 * conservatively. 3193 */ 3194 if (op == BPF_EXIT) 3195 return true; 3196 if (op == BPF_CALL) { 3197 /* BPF to BPF call will reach here because of marking 3198 * caller saved clobber with DST_OP_NO_MARK for which we 3199 * don't care the register def because they are anyway 3200 * marked as NOT_INIT already. 3201 */ 3202 if (insn->src_reg == BPF_PSEUDO_CALL) 3203 return false; 3204 /* Helper call will reach here because of arg type 3205 * check, conservatively return TRUE. 3206 */ 3207 if (t == SRC_OP) 3208 return true; 3209 3210 return false; 3211 } 3212 } 3213 3214 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3215 return false; 3216 3217 if (class == BPF_ALU64 || class == BPF_JMP || 3218 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3219 return true; 3220 3221 if (class == BPF_ALU || class == BPF_JMP32) 3222 return false; 3223 3224 if (class == BPF_LDX) { 3225 if (t != SRC_OP) 3226 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX; 3227 /* LDX source must be ptr. */ 3228 return true; 3229 } 3230 3231 if (class == BPF_STX) { 3232 /* BPF_STX (including atomic variants) has multiple source 3233 * operands, one of which is a ptr. Check whether the caller is 3234 * asking about it. 3235 */ 3236 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3237 return true; 3238 return BPF_SIZE(code) == BPF_DW; 3239 } 3240 3241 if (class == BPF_LD) { 3242 u8 mode = BPF_MODE(code); 3243 3244 /* LD_IMM64 */ 3245 if (mode == BPF_IMM) 3246 return true; 3247 3248 /* Both LD_IND and LD_ABS return 32-bit data. */ 3249 if (t != SRC_OP) 3250 return false; 3251 3252 /* Implicit ctx ptr. */ 3253 if (regno == BPF_REG_6) 3254 return true; 3255 3256 /* Explicit source could be any width. */ 3257 return true; 3258 } 3259 3260 if (class == BPF_ST) 3261 /* The only source register for BPF_ST is a ptr. */ 3262 return true; 3263 3264 /* Conservatively return true at default. */ 3265 return true; 3266 } 3267 3268 /* Return the regno defined by the insn, or -1. */ 3269 static int insn_def_regno(const struct bpf_insn *insn) 3270 { 3271 switch (BPF_CLASS(insn->code)) { 3272 case BPF_JMP: 3273 case BPF_JMP32: 3274 case BPF_ST: 3275 return -1; 3276 case BPF_STX: 3277 if ((BPF_MODE(insn->code) == BPF_ATOMIC || 3278 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) && 3279 (insn->imm & BPF_FETCH)) { 3280 if (insn->imm == BPF_CMPXCHG) 3281 return BPF_REG_0; 3282 else 3283 return insn->src_reg; 3284 } else { 3285 return -1; 3286 } 3287 default: 3288 return insn->dst_reg; 3289 } 3290 } 3291 3292 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 3293 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 3294 { 3295 int dst_reg = insn_def_regno(insn); 3296 3297 if (dst_reg == -1) 3298 return false; 3299 3300 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 3301 } 3302 3303 static void mark_insn_zext(struct bpf_verifier_env *env, 3304 struct bpf_reg_state *reg) 3305 { 3306 s32 def_idx = reg->subreg_def; 3307 3308 if (def_idx == DEF_NOT_SUBREG) 3309 return; 3310 3311 env->insn_aux_data[def_idx - 1].zext_dst = true; 3312 /* The dst will be zero extended, so won't be sub-register anymore. */ 3313 reg->subreg_def = DEF_NOT_SUBREG; 3314 } 3315 3316 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno, 3317 enum reg_arg_type t) 3318 { 3319 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3320 struct bpf_reg_state *reg; 3321 bool rw64; 3322 3323 if (regno >= MAX_BPF_REG) { 3324 verbose(env, "R%d is invalid\n", regno); 3325 return -EINVAL; 3326 } 3327 3328 mark_reg_scratched(env, regno); 3329 3330 reg = ®s[regno]; 3331 rw64 = is_reg64(env, insn, regno, reg, t); 3332 if (t == SRC_OP) { 3333 /* check whether register used as source operand can be read */ 3334 if (reg->type == NOT_INIT) { 3335 verbose(env, "R%d !read_ok\n", regno); 3336 return -EACCES; 3337 } 3338 /* We don't need to worry about FP liveness because it's read-only */ 3339 if (regno == BPF_REG_FP) 3340 return 0; 3341 3342 if (rw64) 3343 mark_insn_zext(env, reg); 3344 3345 return mark_reg_read(env, reg, reg->parent, 3346 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 3347 } else { 3348 /* check whether register used as dest operand can be written to */ 3349 if (regno == BPF_REG_FP) { 3350 verbose(env, "frame pointer is read only\n"); 3351 return -EACCES; 3352 } 3353 reg->live |= REG_LIVE_WRITTEN; 3354 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3355 if (t == DST_OP) 3356 mark_reg_unknown(env, regs, regno); 3357 } 3358 return 0; 3359 } 3360 3361 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3362 enum reg_arg_type t) 3363 { 3364 struct bpf_verifier_state *vstate = env->cur_state; 3365 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3366 3367 return __check_reg_arg(env, state->regs, regno, t); 3368 } 3369 3370 static int insn_stack_access_flags(int frameno, int spi) 3371 { 3372 return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno; 3373 } 3374 3375 static int insn_stack_access_spi(int insn_flags) 3376 { 3377 return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK; 3378 } 3379 3380 static int insn_stack_access_frameno(int insn_flags) 3381 { 3382 return insn_flags & INSN_F_FRAMENO_MASK; 3383 } 3384 3385 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 3386 { 3387 env->insn_aux_data[idx].jmp_point = true; 3388 } 3389 3390 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 3391 { 3392 return env->insn_aux_data[insn_idx].jmp_point; 3393 } 3394 3395 #define LR_FRAMENO_BITS 3 3396 #define LR_SPI_BITS 6 3397 #define LR_ENTRY_BITS (LR_SPI_BITS + LR_FRAMENO_BITS + 1) 3398 #define LR_SIZE_BITS 4 3399 #define LR_FRAMENO_MASK ((1ull << LR_FRAMENO_BITS) - 1) 3400 #define LR_SPI_MASK ((1ull << LR_SPI_BITS) - 1) 3401 #define LR_SIZE_MASK ((1ull << LR_SIZE_BITS) - 1) 3402 #define LR_SPI_OFF LR_FRAMENO_BITS 3403 #define LR_IS_REG_OFF (LR_SPI_BITS + LR_FRAMENO_BITS) 3404 #define LINKED_REGS_MAX 6 3405 3406 struct linked_reg { 3407 u8 frameno; 3408 union { 3409 u8 spi; 3410 u8 regno; 3411 }; 3412 bool is_reg; 3413 }; 3414 3415 struct linked_regs { 3416 int cnt; 3417 struct linked_reg entries[LINKED_REGS_MAX]; 3418 }; 3419 3420 static struct linked_reg *linked_regs_push(struct linked_regs *s) 3421 { 3422 if (s->cnt < LINKED_REGS_MAX) 3423 return &s->entries[s->cnt++]; 3424 3425 return NULL; 3426 } 3427 3428 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track 3429 * number of elements currently in stack. 3430 * Pack one history entry for linked registers as 10 bits in the following format: 3431 * - 3-bits frameno 3432 * - 6-bits spi_or_reg 3433 * - 1-bit is_reg 3434 */ 3435 static u64 linked_regs_pack(struct linked_regs *s) 3436 { 3437 u64 val = 0; 3438 int i; 3439 3440 for (i = 0; i < s->cnt; ++i) { 3441 struct linked_reg *e = &s->entries[i]; 3442 u64 tmp = 0; 3443 3444 tmp |= e->frameno; 3445 tmp |= e->spi << LR_SPI_OFF; 3446 tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF; 3447 3448 val <<= LR_ENTRY_BITS; 3449 val |= tmp; 3450 } 3451 val <<= LR_SIZE_BITS; 3452 val |= s->cnt; 3453 return val; 3454 } 3455 3456 static void linked_regs_unpack(u64 val, struct linked_regs *s) 3457 { 3458 int i; 3459 3460 s->cnt = val & LR_SIZE_MASK; 3461 val >>= LR_SIZE_BITS; 3462 3463 for (i = 0; i < s->cnt; ++i) { 3464 struct linked_reg *e = &s->entries[i]; 3465 3466 e->frameno = val & LR_FRAMENO_MASK; 3467 e->spi = (val >> LR_SPI_OFF) & LR_SPI_MASK; 3468 e->is_reg = (val >> LR_IS_REG_OFF) & 0x1; 3469 val >>= LR_ENTRY_BITS; 3470 } 3471 } 3472 3473 /* for any branch, call, exit record the history of jmps in the given state */ 3474 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur, 3475 int insn_flags, u64 linked_regs) 3476 { 3477 u32 cnt = cur->jmp_history_cnt; 3478 struct bpf_jmp_history_entry *p; 3479 size_t alloc_size; 3480 3481 /* combine instruction flags if we already recorded this instruction */ 3482 if (env->cur_hist_ent) { 3483 /* atomic instructions push insn_flags twice, for READ and 3484 * WRITE sides, but they should agree on stack slot 3485 */ 3486 WARN_ONCE((env->cur_hist_ent->flags & insn_flags) && 3487 (env->cur_hist_ent->flags & insn_flags) != insn_flags, 3488 "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n", 3489 env->insn_idx, env->cur_hist_ent->flags, insn_flags); 3490 env->cur_hist_ent->flags |= insn_flags; 3491 WARN_ONCE(env->cur_hist_ent->linked_regs != 0, 3492 "verifier insn history bug: insn_idx %d linked_regs != 0: %#llx\n", 3493 env->insn_idx, env->cur_hist_ent->linked_regs); 3494 env->cur_hist_ent->linked_regs = linked_regs; 3495 return 0; 3496 } 3497 3498 cnt++; 3499 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 3500 p = krealloc(cur->jmp_history, alloc_size, GFP_USER); 3501 if (!p) 3502 return -ENOMEM; 3503 cur->jmp_history = p; 3504 3505 p = &cur->jmp_history[cnt - 1]; 3506 p->idx = env->insn_idx; 3507 p->prev_idx = env->prev_insn_idx; 3508 p->flags = insn_flags; 3509 p->linked_regs = linked_regs; 3510 cur->jmp_history_cnt = cnt; 3511 env->cur_hist_ent = p; 3512 3513 return 0; 3514 } 3515 3516 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st, 3517 u32 hist_end, int insn_idx) 3518 { 3519 if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx) 3520 return &st->jmp_history[hist_end - 1]; 3521 return NULL; 3522 } 3523 3524 /* Backtrack one insn at a time. If idx is not at the top of recorded 3525 * history then previous instruction came from straight line execution. 3526 * Return -ENOENT if we exhausted all instructions within given state. 3527 * 3528 * It's legal to have a bit of a looping with the same starting and ending 3529 * insn index within the same state, e.g.: 3->4->5->3, so just because current 3530 * instruction index is the same as state's first_idx doesn't mean we are 3531 * done. If there is still some jump history left, we should keep going. We 3532 * need to take into account that we might have a jump history between given 3533 * state's parent and itself, due to checkpointing. In this case, we'll have 3534 * history entry recording a jump from last instruction of parent state and 3535 * first instruction of given state. 3536 */ 3537 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 3538 u32 *history) 3539 { 3540 u32 cnt = *history; 3541 3542 if (i == st->first_insn_idx) { 3543 if (cnt == 0) 3544 return -ENOENT; 3545 if (cnt == 1 && st->jmp_history[0].idx == i) 3546 return -ENOENT; 3547 } 3548 3549 if (cnt && st->jmp_history[cnt - 1].idx == i) { 3550 i = st->jmp_history[cnt - 1].prev_idx; 3551 (*history)--; 3552 } else { 3553 i--; 3554 } 3555 return i; 3556 } 3557 3558 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3559 { 3560 const struct btf_type *func; 3561 struct btf *desc_btf; 3562 3563 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3564 return NULL; 3565 3566 desc_btf = find_kfunc_desc_btf(data, insn->off); 3567 if (IS_ERR(desc_btf)) 3568 return "<error>"; 3569 3570 func = btf_type_by_id(desc_btf, insn->imm); 3571 return btf_name_by_offset(desc_btf, func->name_off); 3572 } 3573 3574 static inline void bt_init(struct backtrack_state *bt, u32 frame) 3575 { 3576 bt->frame = frame; 3577 } 3578 3579 static inline void bt_reset(struct backtrack_state *bt) 3580 { 3581 struct bpf_verifier_env *env = bt->env; 3582 3583 memset(bt, 0, sizeof(*bt)); 3584 bt->env = env; 3585 } 3586 3587 static inline u32 bt_empty(struct backtrack_state *bt) 3588 { 3589 u64 mask = 0; 3590 int i; 3591 3592 for (i = 0; i <= bt->frame; i++) 3593 mask |= bt->reg_masks[i] | bt->stack_masks[i]; 3594 3595 return mask == 0; 3596 } 3597 3598 static inline int bt_subprog_enter(struct backtrack_state *bt) 3599 { 3600 if (bt->frame == MAX_CALL_FRAMES - 1) { 3601 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame); 3602 WARN_ONCE(1, "verifier backtracking bug"); 3603 return -EFAULT; 3604 } 3605 bt->frame++; 3606 return 0; 3607 } 3608 3609 static inline int bt_subprog_exit(struct backtrack_state *bt) 3610 { 3611 if (bt->frame == 0) { 3612 verbose(bt->env, "BUG subprog exit from frame 0\n"); 3613 WARN_ONCE(1, "verifier backtracking bug"); 3614 return -EFAULT; 3615 } 3616 bt->frame--; 3617 return 0; 3618 } 3619 3620 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3621 { 3622 bt->reg_masks[frame] |= 1 << reg; 3623 } 3624 3625 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3626 { 3627 bt->reg_masks[frame] &= ~(1 << reg); 3628 } 3629 3630 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg) 3631 { 3632 bt_set_frame_reg(bt, bt->frame, reg); 3633 } 3634 3635 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg) 3636 { 3637 bt_clear_frame_reg(bt, bt->frame, reg); 3638 } 3639 3640 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3641 { 3642 bt->stack_masks[frame] |= 1ull << slot; 3643 } 3644 3645 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3646 { 3647 bt->stack_masks[frame] &= ~(1ull << slot); 3648 } 3649 3650 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame) 3651 { 3652 return bt->reg_masks[frame]; 3653 } 3654 3655 static inline u32 bt_reg_mask(struct backtrack_state *bt) 3656 { 3657 return bt->reg_masks[bt->frame]; 3658 } 3659 3660 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame) 3661 { 3662 return bt->stack_masks[frame]; 3663 } 3664 3665 static inline u64 bt_stack_mask(struct backtrack_state *bt) 3666 { 3667 return bt->stack_masks[bt->frame]; 3668 } 3669 3670 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg) 3671 { 3672 return bt->reg_masks[bt->frame] & (1 << reg); 3673 } 3674 3675 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg) 3676 { 3677 return bt->reg_masks[frame] & (1 << reg); 3678 } 3679 3680 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot) 3681 { 3682 return bt->stack_masks[frame] & (1ull << slot); 3683 } 3684 3685 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */ 3686 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask) 3687 { 3688 DECLARE_BITMAP(mask, 64); 3689 bool first = true; 3690 int i, n; 3691 3692 buf[0] = '\0'; 3693 3694 bitmap_from_u64(mask, reg_mask); 3695 for_each_set_bit(i, mask, 32) { 3696 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i); 3697 first = false; 3698 buf += n; 3699 buf_sz -= n; 3700 if (buf_sz < 0) 3701 break; 3702 } 3703 } 3704 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */ 3705 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask) 3706 { 3707 DECLARE_BITMAP(mask, 64); 3708 bool first = true; 3709 int i, n; 3710 3711 buf[0] = '\0'; 3712 3713 bitmap_from_u64(mask, stack_mask); 3714 for_each_set_bit(i, mask, 64) { 3715 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8); 3716 first = false; 3717 buf += n; 3718 buf_sz -= n; 3719 if (buf_sz < 0) 3720 break; 3721 } 3722 } 3723 3724 /* If any register R in hist->linked_regs is marked as precise in bt, 3725 * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs. 3726 */ 3727 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist) 3728 { 3729 struct linked_regs linked_regs; 3730 bool some_precise = false; 3731 int i; 3732 3733 if (!hist || hist->linked_regs == 0) 3734 return; 3735 3736 linked_regs_unpack(hist->linked_regs, &linked_regs); 3737 for (i = 0; i < linked_regs.cnt; ++i) { 3738 struct linked_reg *e = &linked_regs.entries[i]; 3739 3740 if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) || 3741 (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) { 3742 some_precise = true; 3743 break; 3744 } 3745 } 3746 3747 if (!some_precise) 3748 return; 3749 3750 for (i = 0; i < linked_regs.cnt; ++i) { 3751 struct linked_reg *e = &linked_regs.entries[i]; 3752 3753 if (e->is_reg) 3754 bt_set_frame_reg(bt, e->frameno, e->regno); 3755 else 3756 bt_set_frame_slot(bt, e->frameno, e->spi); 3757 } 3758 } 3759 3760 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx); 3761 3762 /* For given verifier state backtrack_insn() is called from the last insn to 3763 * the first insn. Its purpose is to compute a bitmask of registers and 3764 * stack slots that needs precision in the parent verifier state. 3765 * 3766 * @idx is an index of the instruction we are currently processing; 3767 * @subseq_idx is an index of the subsequent instruction that: 3768 * - *would be* executed next, if jump history is viewed in forward order; 3769 * - *was* processed previously during backtracking. 3770 */ 3771 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx, 3772 struct bpf_jmp_history_entry *hist, struct backtrack_state *bt) 3773 { 3774 const struct bpf_insn_cbs cbs = { 3775 .cb_call = disasm_kfunc_name, 3776 .cb_print = verbose, 3777 .private_data = env, 3778 }; 3779 struct bpf_insn *insn = env->prog->insnsi + idx; 3780 u8 class = BPF_CLASS(insn->code); 3781 u8 opcode = BPF_OP(insn->code); 3782 u8 mode = BPF_MODE(insn->code); 3783 u32 dreg = insn->dst_reg; 3784 u32 sreg = insn->src_reg; 3785 u32 spi, i, fr; 3786 3787 if (insn->code == 0) 3788 return 0; 3789 if (env->log.level & BPF_LOG_LEVEL2) { 3790 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt)); 3791 verbose(env, "mark_precise: frame%d: regs=%s ", 3792 bt->frame, env->tmp_str_buf); 3793 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt)); 3794 verbose(env, "stack=%s before ", env->tmp_str_buf); 3795 verbose(env, "%d: ", idx); 3796 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3797 } 3798 3799 /* If there is a history record that some registers gained range at this insn, 3800 * propagate precision marks to those registers, so that bt_is_reg_set() 3801 * accounts for these registers. 3802 */ 3803 bt_sync_linked_regs(bt, hist); 3804 3805 if (class == BPF_ALU || class == BPF_ALU64) { 3806 if (!bt_is_reg_set(bt, dreg)) 3807 return 0; 3808 if (opcode == BPF_END || opcode == BPF_NEG) { 3809 /* sreg is reserved and unused 3810 * dreg still need precision before this insn 3811 */ 3812 return 0; 3813 } else if (opcode == BPF_MOV) { 3814 if (BPF_SRC(insn->code) == BPF_X) { 3815 /* dreg = sreg or dreg = (s8, s16, s32)sreg 3816 * dreg needs precision after this insn 3817 * sreg needs precision before this insn 3818 */ 3819 bt_clear_reg(bt, dreg); 3820 if (sreg != BPF_REG_FP) 3821 bt_set_reg(bt, sreg); 3822 } else { 3823 /* dreg = K 3824 * dreg needs precision after this insn. 3825 * Corresponding register is already marked 3826 * as precise=true in this verifier state. 3827 * No further markings in parent are necessary 3828 */ 3829 bt_clear_reg(bt, dreg); 3830 } 3831 } else { 3832 if (BPF_SRC(insn->code) == BPF_X) { 3833 /* dreg += sreg 3834 * both dreg and sreg need precision 3835 * before this insn 3836 */ 3837 if (sreg != BPF_REG_FP) 3838 bt_set_reg(bt, sreg); 3839 } /* else dreg += K 3840 * dreg still needs precision before this insn 3841 */ 3842 } 3843 } else if (class == BPF_LDX) { 3844 if (!bt_is_reg_set(bt, dreg)) 3845 return 0; 3846 bt_clear_reg(bt, dreg); 3847 3848 /* scalars can only be spilled into stack w/o losing precision. 3849 * Load from any other memory can be zero extended. 3850 * The desire to keep that precision is already indicated 3851 * by 'precise' mark in corresponding register of this state. 3852 * No further tracking necessary. 3853 */ 3854 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 3855 return 0; 3856 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 3857 * that [fp - off] slot contains scalar that needs to be 3858 * tracked with precision 3859 */ 3860 spi = insn_stack_access_spi(hist->flags); 3861 fr = insn_stack_access_frameno(hist->flags); 3862 bt_set_frame_slot(bt, fr, spi); 3863 } else if (class == BPF_STX || class == BPF_ST) { 3864 if (bt_is_reg_set(bt, dreg)) 3865 /* stx & st shouldn't be using _scalar_ dst_reg 3866 * to access memory. It means backtracking 3867 * encountered a case of pointer subtraction. 3868 */ 3869 return -ENOTSUPP; 3870 /* scalars can only be spilled into stack */ 3871 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 3872 return 0; 3873 spi = insn_stack_access_spi(hist->flags); 3874 fr = insn_stack_access_frameno(hist->flags); 3875 if (!bt_is_frame_slot_set(bt, fr, spi)) 3876 return 0; 3877 bt_clear_frame_slot(bt, fr, spi); 3878 if (class == BPF_STX) 3879 bt_set_reg(bt, sreg); 3880 } else if (class == BPF_JMP || class == BPF_JMP32) { 3881 if (bpf_pseudo_call(insn)) { 3882 int subprog_insn_idx, subprog; 3883 3884 subprog_insn_idx = idx + insn->imm + 1; 3885 subprog = find_subprog(env, subprog_insn_idx); 3886 if (subprog < 0) 3887 return -EFAULT; 3888 3889 if (subprog_is_global(env, subprog)) { 3890 /* check that jump history doesn't have any 3891 * extra instructions from subprog; the next 3892 * instruction after call to global subprog 3893 * should be literally next instruction in 3894 * caller program 3895 */ 3896 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug"); 3897 /* r1-r5 are invalidated after subprog call, 3898 * so for global func call it shouldn't be set 3899 * anymore 3900 */ 3901 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3902 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3903 WARN_ONCE(1, "verifier backtracking bug"); 3904 return -EFAULT; 3905 } 3906 /* global subprog always sets R0 */ 3907 bt_clear_reg(bt, BPF_REG_0); 3908 return 0; 3909 } else { 3910 /* static subprog call instruction, which 3911 * means that we are exiting current subprog, 3912 * so only r1-r5 could be still requested as 3913 * precise, r0 and r6-r10 or any stack slot in 3914 * the current frame should be zero by now 3915 */ 3916 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3917 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3918 WARN_ONCE(1, "verifier backtracking bug"); 3919 return -EFAULT; 3920 } 3921 /* we are now tracking register spills correctly, 3922 * so any instance of leftover slots is a bug 3923 */ 3924 if (bt_stack_mask(bt) != 0) { 3925 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt)); 3926 WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)"); 3927 return -EFAULT; 3928 } 3929 /* propagate r1-r5 to the caller */ 3930 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 3931 if (bt_is_reg_set(bt, i)) { 3932 bt_clear_reg(bt, i); 3933 bt_set_frame_reg(bt, bt->frame - 1, i); 3934 } 3935 } 3936 if (bt_subprog_exit(bt)) 3937 return -EFAULT; 3938 return 0; 3939 } 3940 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) { 3941 /* exit from callback subprog to callback-calling helper or 3942 * kfunc call. Use idx/subseq_idx check to discern it from 3943 * straight line code backtracking. 3944 * Unlike the subprog call handling above, we shouldn't 3945 * propagate precision of r1-r5 (if any requested), as they are 3946 * not actually arguments passed directly to callback subprogs 3947 */ 3948 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3949 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3950 WARN_ONCE(1, "verifier backtracking bug"); 3951 return -EFAULT; 3952 } 3953 if (bt_stack_mask(bt) != 0) { 3954 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt)); 3955 WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)"); 3956 return -EFAULT; 3957 } 3958 /* clear r1-r5 in callback subprog's mask */ 3959 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3960 bt_clear_reg(bt, i); 3961 if (bt_subprog_exit(bt)) 3962 return -EFAULT; 3963 return 0; 3964 } else if (opcode == BPF_CALL) { 3965 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 3966 * catch this error later. Make backtracking conservative 3967 * with ENOTSUPP. 3968 */ 3969 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 3970 return -ENOTSUPP; 3971 /* regular helper call sets R0 */ 3972 bt_clear_reg(bt, BPF_REG_0); 3973 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3974 /* if backtracing was looking for registers R1-R5 3975 * they should have been found already. 3976 */ 3977 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3978 WARN_ONCE(1, "verifier backtracking bug"); 3979 return -EFAULT; 3980 } 3981 } else if (opcode == BPF_EXIT) { 3982 bool r0_precise; 3983 3984 /* Backtracking to a nested function call, 'idx' is a part of 3985 * the inner frame 'subseq_idx' is a part of the outer frame. 3986 * In case of a regular function call, instructions giving 3987 * precision to registers R1-R5 should have been found already. 3988 * In case of a callback, it is ok to have R1-R5 marked for 3989 * backtracking, as these registers are set by the function 3990 * invoking callback. 3991 */ 3992 if (subseq_idx >= 0 && calls_callback(env, subseq_idx)) 3993 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3994 bt_clear_reg(bt, i); 3995 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3996 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3997 WARN_ONCE(1, "verifier backtracking bug"); 3998 return -EFAULT; 3999 } 4000 4001 /* BPF_EXIT in subprog or callback always returns 4002 * right after the call instruction, so by checking 4003 * whether the instruction at subseq_idx-1 is subprog 4004 * call or not we can distinguish actual exit from 4005 * *subprog* from exit from *callback*. In the former 4006 * case, we need to propagate r0 precision, if 4007 * necessary. In the former we never do that. 4008 */ 4009 r0_precise = subseq_idx - 1 >= 0 && 4010 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) && 4011 bt_is_reg_set(bt, BPF_REG_0); 4012 4013 bt_clear_reg(bt, BPF_REG_0); 4014 if (bt_subprog_enter(bt)) 4015 return -EFAULT; 4016 4017 if (r0_precise) 4018 bt_set_reg(bt, BPF_REG_0); 4019 /* r6-r9 and stack slots will stay set in caller frame 4020 * bitmasks until we return back from callee(s) 4021 */ 4022 return 0; 4023 } else if (BPF_SRC(insn->code) == BPF_X) { 4024 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg)) 4025 return 0; 4026 /* dreg <cond> sreg 4027 * Both dreg and sreg need precision before 4028 * this insn. If only sreg was marked precise 4029 * before it would be equally necessary to 4030 * propagate it to dreg. 4031 */ 4032 bt_set_reg(bt, dreg); 4033 bt_set_reg(bt, sreg); 4034 } else if (BPF_SRC(insn->code) == BPF_K) { 4035 /* dreg <cond> K 4036 * Only dreg still needs precision before 4037 * this insn, so for the K-based conditional 4038 * there is nothing new to be marked. 4039 */ 4040 } 4041 } else if (class == BPF_LD) { 4042 if (!bt_is_reg_set(bt, dreg)) 4043 return 0; 4044 bt_clear_reg(bt, dreg); 4045 /* It's ld_imm64 or ld_abs or ld_ind. 4046 * For ld_imm64 no further tracking of precision 4047 * into parent is necessary 4048 */ 4049 if (mode == BPF_IND || mode == BPF_ABS) 4050 /* to be analyzed */ 4051 return -ENOTSUPP; 4052 } 4053 /* Propagate precision marks to linked registers, to account for 4054 * registers marked as precise in this function. 4055 */ 4056 bt_sync_linked_regs(bt, hist); 4057 return 0; 4058 } 4059 4060 /* the scalar precision tracking algorithm: 4061 * . at the start all registers have precise=false. 4062 * . scalar ranges are tracked as normal through alu and jmp insns. 4063 * . once precise value of the scalar register is used in: 4064 * . ptr + scalar alu 4065 * . if (scalar cond K|scalar) 4066 * . helper_call(.., scalar, ...) where ARG_CONST is expected 4067 * backtrack through the verifier states and mark all registers and 4068 * stack slots with spilled constants that these scalar regisers 4069 * should be precise. 4070 * . during state pruning two registers (or spilled stack slots) 4071 * are equivalent if both are not precise. 4072 * 4073 * Note the verifier cannot simply walk register parentage chain, 4074 * since many different registers and stack slots could have been 4075 * used to compute single precise scalar. 4076 * 4077 * The approach of starting with precise=true for all registers and then 4078 * backtrack to mark a register as not precise when the verifier detects 4079 * that program doesn't care about specific value (e.g., when helper 4080 * takes register as ARG_ANYTHING parameter) is not safe. 4081 * 4082 * It's ok to walk single parentage chain of the verifier states. 4083 * It's possible that this backtracking will go all the way till 1st insn. 4084 * All other branches will be explored for needing precision later. 4085 * 4086 * The backtracking needs to deal with cases like: 4087 * 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) 4088 * r9 -= r8 4089 * r5 = r9 4090 * if r5 > 0x79f goto pc+7 4091 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 4092 * r5 += 1 4093 * ... 4094 * call bpf_perf_event_output#25 4095 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 4096 * 4097 * and this case: 4098 * r6 = 1 4099 * call foo // uses callee's r6 inside to compute r0 4100 * r0 += r6 4101 * if r0 == 0 goto 4102 * 4103 * to track above reg_mask/stack_mask needs to be independent for each frame. 4104 * 4105 * Also if parent's curframe > frame where backtracking started, 4106 * the verifier need to mark registers in both frames, otherwise callees 4107 * may incorrectly prune callers. This is similar to 4108 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 4109 * 4110 * For now backtracking falls back into conservative marking. 4111 */ 4112 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 4113 struct bpf_verifier_state *st) 4114 { 4115 struct bpf_func_state *func; 4116 struct bpf_reg_state *reg; 4117 int i, j; 4118 4119 if (env->log.level & BPF_LOG_LEVEL2) { 4120 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n", 4121 st->curframe); 4122 } 4123 4124 /* big hammer: mark all scalars precise in this path. 4125 * pop_stack may still get !precise scalars. 4126 * We also skip current state and go straight to first parent state, 4127 * because precision markings in current non-checkpointed state are 4128 * not needed. See why in the comment in __mark_chain_precision below. 4129 */ 4130 for (st = st->parent; st; st = st->parent) { 4131 for (i = 0; i <= st->curframe; i++) { 4132 func = st->frame[i]; 4133 for (j = 0; j < BPF_REG_FP; j++) { 4134 reg = &func->regs[j]; 4135 if (reg->type != SCALAR_VALUE || reg->precise) 4136 continue; 4137 reg->precise = true; 4138 if (env->log.level & BPF_LOG_LEVEL2) { 4139 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n", 4140 i, j); 4141 } 4142 } 4143 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 4144 if (!is_spilled_reg(&func->stack[j])) 4145 continue; 4146 reg = &func->stack[j].spilled_ptr; 4147 if (reg->type != SCALAR_VALUE || reg->precise) 4148 continue; 4149 reg->precise = true; 4150 if (env->log.level & BPF_LOG_LEVEL2) { 4151 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n", 4152 i, -(j + 1) * 8); 4153 } 4154 } 4155 } 4156 } 4157 } 4158 4159 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 4160 { 4161 struct bpf_func_state *func; 4162 struct bpf_reg_state *reg; 4163 int i, j; 4164 4165 for (i = 0; i <= st->curframe; i++) { 4166 func = st->frame[i]; 4167 for (j = 0; j < BPF_REG_FP; j++) { 4168 reg = &func->regs[j]; 4169 if (reg->type != SCALAR_VALUE) 4170 continue; 4171 reg->precise = false; 4172 } 4173 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 4174 if (!is_spilled_reg(&func->stack[j])) 4175 continue; 4176 reg = &func->stack[j].spilled_ptr; 4177 if (reg->type != SCALAR_VALUE) 4178 continue; 4179 reg->precise = false; 4180 } 4181 } 4182 } 4183 4184 /* 4185 * __mark_chain_precision() backtracks BPF program instruction sequence and 4186 * chain of verifier states making sure that register *regno* (if regno >= 0) 4187 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 4188 * SCALARS, as well as any other registers and slots that contribute to 4189 * a tracked state of given registers/stack slots, depending on specific BPF 4190 * assembly instructions (see backtrack_insns() for exact instruction handling 4191 * logic). This backtracking relies on recorded jmp_history and is able to 4192 * traverse entire chain of parent states. This process ends only when all the 4193 * necessary registers/slots and their transitive dependencies are marked as 4194 * precise. 4195 * 4196 * One important and subtle aspect is that precise marks *do not matter* in 4197 * the currently verified state (current state). It is important to understand 4198 * why this is the case. 4199 * 4200 * First, note that current state is the state that is not yet "checkpointed", 4201 * i.e., it is not yet put into env->explored_states, and it has no children 4202 * states as well. It's ephemeral, and can end up either a) being discarded if 4203 * compatible explored state is found at some point or BPF_EXIT instruction is 4204 * reached or b) checkpointed and put into env->explored_states, branching out 4205 * into one or more children states. 4206 * 4207 * In the former case, precise markings in current state are completely 4208 * ignored by state comparison code (see regsafe() for details). Only 4209 * checkpointed ("old") state precise markings are important, and if old 4210 * state's register/slot is precise, regsafe() assumes current state's 4211 * register/slot as precise and checks value ranges exactly and precisely. If 4212 * states turn out to be compatible, current state's necessary precise 4213 * markings and any required parent states' precise markings are enforced 4214 * after the fact with propagate_precision() logic, after the fact. But it's 4215 * important to realize that in this case, even after marking current state 4216 * registers/slots as precise, we immediately discard current state. So what 4217 * actually matters is any of the precise markings propagated into current 4218 * state's parent states, which are always checkpointed (due to b) case above). 4219 * As such, for scenario a) it doesn't matter if current state has precise 4220 * markings set or not. 4221 * 4222 * Now, for the scenario b), checkpointing and forking into child(ren) 4223 * state(s). Note that before current state gets to checkpointing step, any 4224 * processed instruction always assumes precise SCALAR register/slot 4225 * knowledge: if precise value or range is useful to prune jump branch, BPF 4226 * verifier takes this opportunity enthusiastically. Similarly, when 4227 * register's value is used to calculate offset or memory address, exact 4228 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 4229 * what we mentioned above about state comparison ignoring precise markings 4230 * during state comparison, BPF verifier ignores and also assumes precise 4231 * markings *at will* during instruction verification process. But as verifier 4232 * assumes precision, it also propagates any precision dependencies across 4233 * parent states, which are not yet finalized, so can be further restricted 4234 * based on new knowledge gained from restrictions enforced by their children 4235 * states. This is so that once those parent states are finalized, i.e., when 4236 * they have no more active children state, state comparison logic in 4237 * is_state_visited() would enforce strict and precise SCALAR ranges, if 4238 * required for correctness. 4239 * 4240 * To build a bit more intuition, note also that once a state is checkpointed, 4241 * the path we took to get to that state is not important. This is crucial 4242 * property for state pruning. When state is checkpointed and finalized at 4243 * some instruction index, it can be correctly and safely used to "short 4244 * circuit" any *compatible* state that reaches exactly the same instruction 4245 * index. I.e., if we jumped to that instruction from a completely different 4246 * code path than original finalized state was derived from, it doesn't 4247 * matter, current state can be discarded because from that instruction 4248 * forward having a compatible state will ensure we will safely reach the 4249 * exit. States describe preconditions for further exploration, but completely 4250 * forget the history of how we got here. 4251 * 4252 * This also means that even if we needed precise SCALAR range to get to 4253 * finalized state, but from that point forward *that same* SCALAR register is 4254 * never used in a precise context (i.e., it's precise value is not needed for 4255 * correctness), it's correct and safe to mark such register as "imprecise" 4256 * (i.e., precise marking set to false). This is what we rely on when we do 4257 * not set precise marking in current state. If no child state requires 4258 * precision for any given SCALAR register, it's safe to dictate that it can 4259 * be imprecise. If any child state does require this register to be precise, 4260 * we'll mark it precise later retroactively during precise markings 4261 * propagation from child state to parent states. 4262 * 4263 * Skipping precise marking setting in current state is a mild version of 4264 * relying on the above observation. But we can utilize this property even 4265 * more aggressively by proactively forgetting any precise marking in the 4266 * current state (which we inherited from the parent state), right before we 4267 * checkpoint it and branch off into new child state. This is done by 4268 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 4269 * finalized states which help in short circuiting more future states. 4270 */ 4271 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno) 4272 { 4273 struct backtrack_state *bt = &env->bt; 4274 struct bpf_verifier_state *st = env->cur_state; 4275 int first_idx = st->first_insn_idx; 4276 int last_idx = env->insn_idx; 4277 int subseq_idx = -1; 4278 struct bpf_func_state *func; 4279 struct bpf_reg_state *reg; 4280 bool skip_first = true; 4281 int i, fr, err; 4282 4283 if (!env->bpf_capable) 4284 return 0; 4285 4286 /* set frame number from which we are starting to backtrack */ 4287 bt_init(bt, env->cur_state->curframe); 4288 4289 /* Do sanity checks against current state of register and/or stack 4290 * slot, but don't set precise flag in current state, as precision 4291 * tracking in the current state is unnecessary. 4292 */ 4293 func = st->frame[bt->frame]; 4294 if (regno >= 0) { 4295 reg = &func->regs[regno]; 4296 if (reg->type != SCALAR_VALUE) { 4297 WARN_ONCE(1, "backtracing misuse"); 4298 return -EFAULT; 4299 } 4300 bt_set_reg(bt, regno); 4301 } 4302 4303 if (bt_empty(bt)) 4304 return 0; 4305 4306 for (;;) { 4307 DECLARE_BITMAP(mask, 64); 4308 u32 history = st->jmp_history_cnt; 4309 struct bpf_jmp_history_entry *hist; 4310 4311 if (env->log.level & BPF_LOG_LEVEL2) { 4312 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n", 4313 bt->frame, last_idx, first_idx, subseq_idx); 4314 } 4315 4316 if (last_idx < 0) { 4317 /* we are at the entry into subprog, which 4318 * is expected for global funcs, but only if 4319 * requested precise registers are R1-R5 4320 * (which are global func's input arguments) 4321 */ 4322 if (st->curframe == 0 && 4323 st->frame[0]->subprogno > 0 && 4324 st->frame[0]->callsite == BPF_MAIN_FUNC && 4325 bt_stack_mask(bt) == 0 && 4326 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) { 4327 bitmap_from_u64(mask, bt_reg_mask(bt)); 4328 for_each_set_bit(i, mask, 32) { 4329 reg = &st->frame[0]->regs[i]; 4330 bt_clear_reg(bt, i); 4331 if (reg->type == SCALAR_VALUE) 4332 reg->precise = true; 4333 } 4334 return 0; 4335 } 4336 4337 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n", 4338 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt)); 4339 WARN_ONCE(1, "verifier backtracking bug"); 4340 return -EFAULT; 4341 } 4342 4343 for (i = last_idx;;) { 4344 if (skip_first) { 4345 err = 0; 4346 skip_first = false; 4347 } else { 4348 hist = get_jmp_hist_entry(st, history, i); 4349 err = backtrack_insn(env, i, subseq_idx, hist, bt); 4350 } 4351 if (err == -ENOTSUPP) { 4352 mark_all_scalars_precise(env, env->cur_state); 4353 bt_reset(bt); 4354 return 0; 4355 } else if (err) { 4356 return err; 4357 } 4358 if (bt_empty(bt)) 4359 /* Found assignment(s) into tracked register in this state. 4360 * Since this state is already marked, just return. 4361 * Nothing to be tracked further in the parent state. 4362 */ 4363 return 0; 4364 subseq_idx = i; 4365 i = get_prev_insn_idx(st, i, &history); 4366 if (i == -ENOENT) 4367 break; 4368 if (i >= env->prog->len) { 4369 /* This can happen if backtracking reached insn 0 4370 * and there are still reg_mask or stack_mask 4371 * to backtrack. 4372 * It means the backtracking missed the spot where 4373 * particular register was initialized with a constant. 4374 */ 4375 verbose(env, "BUG backtracking idx %d\n", i); 4376 WARN_ONCE(1, "verifier backtracking bug"); 4377 return -EFAULT; 4378 } 4379 } 4380 st = st->parent; 4381 if (!st) 4382 break; 4383 4384 for (fr = bt->frame; fr >= 0; fr--) { 4385 func = st->frame[fr]; 4386 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4387 for_each_set_bit(i, mask, 32) { 4388 reg = &func->regs[i]; 4389 if (reg->type != SCALAR_VALUE) { 4390 bt_clear_frame_reg(bt, fr, i); 4391 continue; 4392 } 4393 if (reg->precise) 4394 bt_clear_frame_reg(bt, fr, i); 4395 else 4396 reg->precise = true; 4397 } 4398 4399 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4400 for_each_set_bit(i, mask, 64) { 4401 if (i >= func->allocated_stack / BPF_REG_SIZE) { 4402 verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n", 4403 i, func->allocated_stack / BPF_REG_SIZE); 4404 WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)"); 4405 return -EFAULT; 4406 } 4407 4408 if (!is_spilled_scalar_reg(&func->stack[i])) { 4409 bt_clear_frame_slot(bt, fr, i); 4410 continue; 4411 } 4412 reg = &func->stack[i].spilled_ptr; 4413 if (reg->precise) 4414 bt_clear_frame_slot(bt, fr, i); 4415 else 4416 reg->precise = true; 4417 } 4418 if (env->log.level & BPF_LOG_LEVEL2) { 4419 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4420 bt_frame_reg_mask(bt, fr)); 4421 verbose(env, "mark_precise: frame%d: parent state regs=%s ", 4422 fr, env->tmp_str_buf); 4423 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4424 bt_frame_stack_mask(bt, fr)); 4425 verbose(env, "stack=%s: ", env->tmp_str_buf); 4426 print_verifier_state(env, func, true); 4427 } 4428 } 4429 4430 if (bt_empty(bt)) 4431 return 0; 4432 4433 subseq_idx = first_idx; 4434 last_idx = st->last_insn_idx; 4435 first_idx = st->first_insn_idx; 4436 } 4437 4438 /* if we still have requested precise regs or slots, we missed 4439 * something (e.g., stack access through non-r10 register), so 4440 * fallback to marking all precise 4441 */ 4442 if (!bt_empty(bt)) { 4443 mark_all_scalars_precise(env, env->cur_state); 4444 bt_reset(bt); 4445 } 4446 4447 return 0; 4448 } 4449 4450 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 4451 { 4452 return __mark_chain_precision(env, regno); 4453 } 4454 4455 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 4456 * desired reg and stack masks across all relevant frames 4457 */ 4458 static int mark_chain_precision_batch(struct bpf_verifier_env *env) 4459 { 4460 return __mark_chain_precision(env, -1); 4461 } 4462 4463 static bool is_spillable_regtype(enum bpf_reg_type type) 4464 { 4465 switch (base_type(type)) { 4466 case PTR_TO_MAP_VALUE: 4467 case PTR_TO_STACK: 4468 case PTR_TO_CTX: 4469 case PTR_TO_PACKET: 4470 case PTR_TO_PACKET_META: 4471 case PTR_TO_PACKET_END: 4472 case PTR_TO_FLOW_KEYS: 4473 case CONST_PTR_TO_MAP: 4474 case PTR_TO_SOCKET: 4475 case PTR_TO_SOCK_COMMON: 4476 case PTR_TO_TCP_SOCK: 4477 case PTR_TO_XDP_SOCK: 4478 case PTR_TO_BTF_ID: 4479 case PTR_TO_BUF: 4480 case PTR_TO_MEM: 4481 case PTR_TO_FUNC: 4482 case PTR_TO_MAP_KEY: 4483 case PTR_TO_ARENA: 4484 return true; 4485 default: 4486 return false; 4487 } 4488 } 4489 4490 /* Does this register contain a constant zero? */ 4491 static bool register_is_null(struct bpf_reg_state *reg) 4492 { 4493 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 4494 } 4495 4496 /* check if register is a constant scalar value */ 4497 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32) 4498 { 4499 return reg->type == SCALAR_VALUE && 4500 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off); 4501 } 4502 4503 /* assuming is_reg_const() is true, return constant value of a register */ 4504 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32) 4505 { 4506 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value; 4507 } 4508 4509 static bool __is_pointer_value(bool allow_ptr_leaks, 4510 const struct bpf_reg_state *reg) 4511 { 4512 if (allow_ptr_leaks) 4513 return false; 4514 4515 return reg->type != SCALAR_VALUE; 4516 } 4517 4518 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env, 4519 struct bpf_reg_state *src_reg) 4520 { 4521 if (src_reg->type != SCALAR_VALUE) 4522 return; 4523 4524 if (src_reg->id & BPF_ADD_CONST) { 4525 /* 4526 * The verifier is processing rX = rY insn and 4527 * rY->id has special linked register already. 4528 * Cleared it, since multiple rX += const are not supported. 4529 */ 4530 src_reg->id = 0; 4531 src_reg->off = 0; 4532 } 4533 4534 if (!src_reg->id && !tnum_is_const(src_reg->var_off)) 4535 /* Ensure that src_reg has a valid ID that will be copied to 4536 * dst_reg and then will be used by sync_linked_regs() to 4537 * propagate min/max range. 4538 */ 4539 src_reg->id = ++env->id_gen; 4540 } 4541 4542 /* Copy src state preserving dst->parent and dst->live fields */ 4543 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 4544 { 4545 struct bpf_reg_state *parent = dst->parent; 4546 enum bpf_reg_liveness live = dst->live; 4547 4548 *dst = *src; 4549 dst->parent = parent; 4550 dst->live = live; 4551 } 4552 4553 static void save_register_state(struct bpf_verifier_env *env, 4554 struct bpf_func_state *state, 4555 int spi, struct bpf_reg_state *reg, 4556 int size) 4557 { 4558 int i; 4559 4560 copy_register_state(&state->stack[spi].spilled_ptr, reg); 4561 if (size == BPF_REG_SIZE) 4562 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4563 4564 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 4565 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 4566 4567 /* size < 8 bytes spill */ 4568 for (; i; i--) 4569 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]); 4570 } 4571 4572 static bool is_bpf_st_mem(struct bpf_insn *insn) 4573 { 4574 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 4575 } 4576 4577 static int get_reg_width(struct bpf_reg_state *reg) 4578 { 4579 return fls64(reg->umax_value); 4580 } 4581 4582 /* See comment for mark_fastcall_pattern_for_call() */ 4583 static void check_fastcall_stack_contract(struct bpf_verifier_env *env, 4584 struct bpf_func_state *state, int insn_idx, int off) 4585 { 4586 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 4587 struct bpf_insn_aux_data *aux = env->insn_aux_data; 4588 int i; 4589 4590 if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern) 4591 return; 4592 /* access to the region [max_stack_depth .. fastcall_stack_off) 4593 * from something that is not a part of the fastcall pattern, 4594 * disable fastcall rewrites for current subprogram by setting 4595 * fastcall_stack_off to a value smaller than any possible offset. 4596 */ 4597 subprog->fastcall_stack_off = S16_MIN; 4598 /* reset fastcall aux flags within subprogram, 4599 * happens at most once per subprogram 4600 */ 4601 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 4602 aux[i].fastcall_spills_num = 0; 4603 aux[i].fastcall_pattern = 0; 4604 } 4605 } 4606 4607 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 4608 * stack boundary and alignment are checked in check_mem_access() 4609 */ 4610 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 4611 /* stack frame we're writing to */ 4612 struct bpf_func_state *state, 4613 int off, int size, int value_regno, 4614 int insn_idx) 4615 { 4616 struct bpf_func_state *cur; /* state of the current function */ 4617 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 4618 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4619 struct bpf_reg_state *reg = NULL; 4620 int insn_flags = insn_stack_access_flags(state->frameno, spi); 4621 4622 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 4623 * so it's aligned access and [off, off + size) are within stack limits 4624 */ 4625 if (!env->allow_ptr_leaks && 4626 is_spilled_reg(&state->stack[spi]) && 4627 size != BPF_REG_SIZE) { 4628 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 4629 return -EACCES; 4630 } 4631 4632 cur = env->cur_state->frame[env->cur_state->curframe]; 4633 if (value_regno >= 0) 4634 reg = &cur->regs[value_regno]; 4635 if (!env->bypass_spec_v4) { 4636 bool sanitize = reg && is_spillable_regtype(reg->type); 4637 4638 for (i = 0; i < size; i++) { 4639 u8 type = state->stack[spi].slot_type[i]; 4640 4641 if (type != STACK_MISC && type != STACK_ZERO) { 4642 sanitize = true; 4643 break; 4644 } 4645 } 4646 4647 if (sanitize) 4648 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 4649 } 4650 4651 err = destroy_if_dynptr_stack_slot(env, state, spi); 4652 if (err) 4653 return err; 4654 4655 check_fastcall_stack_contract(env, state, insn_idx, off); 4656 mark_stack_slot_scratched(env, spi); 4657 if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) { 4658 bool reg_value_fits; 4659 4660 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size; 4661 /* Make sure that reg had an ID to build a relation on spill. */ 4662 if (reg_value_fits) 4663 assign_scalar_id_before_mov(env, reg); 4664 save_register_state(env, state, spi, reg, size); 4665 /* Break the relation on a narrowing spill. */ 4666 if (!reg_value_fits) 4667 state->stack[spi].spilled_ptr.id = 0; 4668 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 4669 env->bpf_capable) { 4670 struct bpf_reg_state *tmp_reg = &env->fake_reg[0]; 4671 4672 memset(tmp_reg, 0, sizeof(*tmp_reg)); 4673 __mark_reg_known(tmp_reg, insn->imm); 4674 tmp_reg->type = SCALAR_VALUE; 4675 save_register_state(env, state, spi, tmp_reg, size); 4676 } else if (reg && is_spillable_regtype(reg->type)) { 4677 /* register containing pointer is being spilled into stack */ 4678 if (size != BPF_REG_SIZE) { 4679 verbose_linfo(env, insn_idx, "; "); 4680 verbose(env, "invalid size of register spill\n"); 4681 return -EACCES; 4682 } 4683 if (state != cur && reg->type == PTR_TO_STACK) { 4684 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4685 return -EINVAL; 4686 } 4687 save_register_state(env, state, spi, reg, size); 4688 } else { 4689 u8 type = STACK_MISC; 4690 4691 /* regular write of data into stack destroys any spilled ptr */ 4692 state->stack[spi].spilled_ptr.type = NOT_INIT; 4693 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 4694 if (is_stack_slot_special(&state->stack[spi])) 4695 for (i = 0; i < BPF_REG_SIZE; i++) 4696 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 4697 4698 /* only mark the slot as written if all 8 bytes were written 4699 * otherwise read propagation may incorrectly stop too soon 4700 * when stack slots are partially written. 4701 * This heuristic means that read propagation will be 4702 * conservative, since it will add reg_live_read marks 4703 * to stack slots all the way to first state when programs 4704 * writes+reads less than 8 bytes 4705 */ 4706 if (size == BPF_REG_SIZE) 4707 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4708 4709 /* when we zero initialize stack slots mark them as such */ 4710 if ((reg && register_is_null(reg)) || 4711 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4712 /* STACK_ZERO case happened because register spill 4713 * wasn't properly aligned at the stack slot boundary, 4714 * so it's not a register spill anymore; force 4715 * originating register to be precise to make 4716 * STACK_ZERO correct for subsequent states 4717 */ 4718 err = mark_chain_precision(env, value_regno); 4719 if (err) 4720 return err; 4721 type = STACK_ZERO; 4722 } 4723 4724 /* Mark slots affected by this stack write. */ 4725 for (i = 0; i < size; i++) 4726 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 4727 insn_flags = 0; /* not a register spill */ 4728 } 4729 4730 if (insn_flags) 4731 return push_jmp_history(env, env->cur_state, insn_flags, 0); 4732 return 0; 4733 } 4734 4735 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 4736 * known to contain a variable offset. 4737 * This function checks whether the write is permitted and conservatively 4738 * tracks the effects of the write, considering that each stack slot in the 4739 * dynamic range is potentially written to. 4740 * 4741 * 'off' includes 'regno->off'. 4742 * 'value_regno' can be -1, meaning that an unknown value is being written to 4743 * the stack. 4744 * 4745 * Spilled pointers in range are not marked as written because we don't know 4746 * what's going to be actually written. This means that read propagation for 4747 * future reads cannot be terminated by this write. 4748 * 4749 * For privileged programs, uninitialized stack slots are considered 4750 * initialized by this write (even though we don't know exactly what offsets 4751 * are going to be written to). The idea is that we don't want the verifier to 4752 * reject future reads that access slots written to through variable offsets. 4753 */ 4754 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4755 /* func where register points to */ 4756 struct bpf_func_state *state, 4757 int ptr_regno, int off, int size, 4758 int value_regno, int insn_idx) 4759 { 4760 struct bpf_func_state *cur; /* state of the current function */ 4761 int min_off, max_off; 4762 int i, err; 4763 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 4764 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4765 bool writing_zero = false; 4766 /* set if the fact that we're writing a zero is used to let any 4767 * stack slots remain STACK_ZERO 4768 */ 4769 bool zero_used = false; 4770 4771 cur = env->cur_state->frame[env->cur_state->curframe]; 4772 ptr_reg = &cur->regs[ptr_regno]; 4773 min_off = ptr_reg->smin_value + off; 4774 max_off = ptr_reg->smax_value + off + size; 4775 if (value_regno >= 0) 4776 value_reg = &cur->regs[value_regno]; 4777 if ((value_reg && register_is_null(value_reg)) || 4778 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4779 writing_zero = true; 4780 4781 for (i = min_off; i < max_off; i++) { 4782 int spi; 4783 4784 spi = __get_spi(i); 4785 err = destroy_if_dynptr_stack_slot(env, state, spi); 4786 if (err) 4787 return err; 4788 } 4789 4790 check_fastcall_stack_contract(env, state, insn_idx, min_off); 4791 /* Variable offset writes destroy any spilled pointers in range. */ 4792 for (i = min_off; i < max_off; i++) { 4793 u8 new_type, *stype; 4794 int slot, spi; 4795 4796 slot = -i - 1; 4797 spi = slot / BPF_REG_SIZE; 4798 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4799 mark_stack_slot_scratched(env, spi); 4800 4801 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4802 /* Reject the write if range we may write to has not 4803 * been initialized beforehand. If we didn't reject 4804 * here, the ptr status would be erased below (even 4805 * though not all slots are actually overwritten), 4806 * possibly opening the door to leaks. 4807 * 4808 * We do however catch STACK_INVALID case below, and 4809 * only allow reading possibly uninitialized memory 4810 * later for CAP_PERFMON, as the write may not happen to 4811 * that slot. 4812 */ 4813 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4814 insn_idx, i); 4815 return -EINVAL; 4816 } 4817 4818 /* If writing_zero and the spi slot contains a spill of value 0, 4819 * maintain the spill type. 4820 */ 4821 if (writing_zero && *stype == STACK_SPILL && 4822 is_spilled_scalar_reg(&state->stack[spi])) { 4823 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr; 4824 4825 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) { 4826 zero_used = true; 4827 continue; 4828 } 4829 } 4830 4831 /* Erase all other spilled pointers. */ 4832 state->stack[spi].spilled_ptr.type = NOT_INIT; 4833 4834 /* Update the slot type. */ 4835 new_type = STACK_MISC; 4836 if (writing_zero && *stype == STACK_ZERO) { 4837 new_type = STACK_ZERO; 4838 zero_used = true; 4839 } 4840 /* If the slot is STACK_INVALID, we check whether it's OK to 4841 * pretend that it will be initialized by this write. The slot 4842 * might not actually be written to, and so if we mark it as 4843 * initialized future reads might leak uninitialized memory. 4844 * For privileged programs, we will accept such reads to slots 4845 * that may or may not be written because, if we're reject 4846 * them, the error would be too confusing. 4847 */ 4848 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4849 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4850 insn_idx, i); 4851 return -EINVAL; 4852 } 4853 *stype = new_type; 4854 } 4855 if (zero_used) { 4856 /* backtracking doesn't work for STACK_ZERO yet. */ 4857 err = mark_chain_precision(env, value_regno); 4858 if (err) 4859 return err; 4860 } 4861 return 0; 4862 } 4863 4864 /* When register 'dst_regno' is assigned some values from stack[min_off, 4865 * max_off), we set the register's type according to the types of the 4866 * respective stack slots. If all the stack values are known to be zeros, then 4867 * so is the destination reg. Otherwise, the register is considered to be 4868 * SCALAR. This function does not deal with register filling; the caller must 4869 * ensure that all spilled registers in the stack range have been marked as 4870 * read. 4871 */ 4872 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4873 /* func where src register points to */ 4874 struct bpf_func_state *ptr_state, 4875 int min_off, int max_off, int dst_regno) 4876 { 4877 struct bpf_verifier_state *vstate = env->cur_state; 4878 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4879 int i, slot, spi; 4880 u8 *stype; 4881 int zeros = 0; 4882 4883 for (i = min_off; i < max_off; i++) { 4884 slot = -i - 1; 4885 spi = slot / BPF_REG_SIZE; 4886 mark_stack_slot_scratched(env, spi); 4887 stype = ptr_state->stack[spi].slot_type; 4888 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4889 break; 4890 zeros++; 4891 } 4892 if (zeros == max_off - min_off) { 4893 /* Any access_size read into register is zero extended, 4894 * so the whole register == const_zero. 4895 */ 4896 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4897 } else { 4898 /* have read misc data from the stack */ 4899 mark_reg_unknown(env, state->regs, dst_regno); 4900 } 4901 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4902 } 4903 4904 /* Read the stack at 'off' and put the results into the register indicated by 4905 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4906 * spilled reg. 4907 * 4908 * 'dst_regno' can be -1, meaning that the read value is not going to a 4909 * register. 4910 * 4911 * The access is assumed to be within the current stack bounds. 4912 */ 4913 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4914 /* func where src register points to */ 4915 struct bpf_func_state *reg_state, 4916 int off, int size, int dst_regno) 4917 { 4918 struct bpf_verifier_state *vstate = env->cur_state; 4919 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4920 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4921 struct bpf_reg_state *reg; 4922 u8 *stype, type; 4923 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi); 4924 4925 stype = reg_state->stack[spi].slot_type; 4926 reg = ®_state->stack[spi].spilled_ptr; 4927 4928 mark_stack_slot_scratched(env, spi); 4929 check_fastcall_stack_contract(env, state, env->insn_idx, off); 4930 4931 if (is_spilled_reg(®_state->stack[spi])) { 4932 u8 spill_size = 1; 4933 4934 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4935 spill_size++; 4936 4937 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4938 if (reg->type != SCALAR_VALUE) { 4939 verbose_linfo(env, env->insn_idx, "; "); 4940 verbose(env, "invalid size of register fill\n"); 4941 return -EACCES; 4942 } 4943 4944 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4945 if (dst_regno < 0) 4946 return 0; 4947 4948 if (size <= spill_size && 4949 bpf_stack_narrow_access_ok(off, size, spill_size)) { 4950 /* The earlier check_reg_arg() has decided the 4951 * subreg_def for this insn. Save it first. 4952 */ 4953 s32 subreg_def = state->regs[dst_regno].subreg_def; 4954 4955 copy_register_state(&state->regs[dst_regno], reg); 4956 state->regs[dst_regno].subreg_def = subreg_def; 4957 4958 /* Break the relation on a narrowing fill. 4959 * coerce_reg_to_size will adjust the boundaries. 4960 */ 4961 if (get_reg_width(reg) > size * BITS_PER_BYTE) 4962 state->regs[dst_regno].id = 0; 4963 } else { 4964 int spill_cnt = 0, zero_cnt = 0; 4965 4966 for (i = 0; i < size; i++) { 4967 type = stype[(slot - i) % BPF_REG_SIZE]; 4968 if (type == STACK_SPILL) { 4969 spill_cnt++; 4970 continue; 4971 } 4972 if (type == STACK_MISC) 4973 continue; 4974 if (type == STACK_ZERO) { 4975 zero_cnt++; 4976 continue; 4977 } 4978 if (type == STACK_INVALID && env->allow_uninit_stack) 4979 continue; 4980 verbose(env, "invalid read from stack off %d+%d size %d\n", 4981 off, i, size); 4982 return -EACCES; 4983 } 4984 4985 if (spill_cnt == size && 4986 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 4987 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4988 /* this IS register fill, so keep insn_flags */ 4989 } else if (zero_cnt == size) { 4990 /* similarly to mark_reg_stack_read(), preserve zeroes */ 4991 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4992 insn_flags = 0; /* not restoring original register state */ 4993 } else { 4994 mark_reg_unknown(env, state->regs, dst_regno); 4995 insn_flags = 0; /* not restoring original register state */ 4996 } 4997 } 4998 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4999 } else if (dst_regno >= 0) { 5000 /* restore register state from stack */ 5001 copy_register_state(&state->regs[dst_regno], reg); 5002 /* mark reg as written since spilled pointer state likely 5003 * has its liveness marks cleared by is_state_visited() 5004 * which resets stack/reg liveness for state transitions 5005 */ 5006 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 5007 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 5008 /* If dst_regno==-1, the caller is asking us whether 5009 * it is acceptable to use this value as a SCALAR_VALUE 5010 * (e.g. for XADD). 5011 * We must not allow unprivileged callers to do that 5012 * with spilled pointers. 5013 */ 5014 verbose(env, "leaking pointer from stack off %d\n", 5015 off); 5016 return -EACCES; 5017 } 5018 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 5019 } else { 5020 for (i = 0; i < size; i++) { 5021 type = stype[(slot - i) % BPF_REG_SIZE]; 5022 if (type == STACK_MISC) 5023 continue; 5024 if (type == STACK_ZERO) 5025 continue; 5026 if (type == STACK_INVALID && env->allow_uninit_stack) 5027 continue; 5028 verbose(env, "invalid read from stack off %d+%d size %d\n", 5029 off, i, size); 5030 return -EACCES; 5031 } 5032 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 5033 if (dst_regno >= 0) 5034 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 5035 insn_flags = 0; /* we are not restoring spilled register */ 5036 } 5037 if (insn_flags) 5038 return push_jmp_history(env, env->cur_state, insn_flags, 0); 5039 return 0; 5040 } 5041 5042 enum bpf_access_src { 5043 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 5044 ACCESS_HELPER = 2, /* the access is performed by a helper */ 5045 }; 5046 5047 static int check_stack_range_initialized(struct bpf_verifier_env *env, 5048 int regno, int off, int access_size, 5049 bool zero_size_allowed, 5050 enum bpf_access_src type, 5051 struct bpf_call_arg_meta *meta); 5052 5053 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 5054 { 5055 return cur_regs(env) + regno; 5056 } 5057 5058 /* Read the stack at 'ptr_regno + off' and put the result into the register 5059 * 'dst_regno'. 5060 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 5061 * but not its variable offset. 5062 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 5063 * 5064 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 5065 * filling registers (i.e. reads of spilled register cannot be detected when 5066 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 5067 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 5068 * offset; for a fixed offset check_stack_read_fixed_off should be used 5069 * instead. 5070 */ 5071 static int check_stack_read_var_off(struct bpf_verifier_env *env, 5072 int ptr_regno, int off, int size, int dst_regno) 5073 { 5074 /* The state of the source register. */ 5075 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5076 struct bpf_func_state *ptr_state = func(env, reg); 5077 int err; 5078 int min_off, max_off; 5079 5080 /* Note that we pass a NULL meta, so raw access will not be permitted. 5081 */ 5082 err = check_stack_range_initialized(env, ptr_regno, off, size, 5083 false, ACCESS_DIRECT, NULL); 5084 if (err) 5085 return err; 5086 5087 min_off = reg->smin_value + off; 5088 max_off = reg->smax_value + off; 5089 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 5090 check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off); 5091 return 0; 5092 } 5093 5094 /* check_stack_read dispatches to check_stack_read_fixed_off or 5095 * check_stack_read_var_off. 5096 * 5097 * The caller must ensure that the offset falls within the allocated stack 5098 * bounds. 5099 * 5100 * 'dst_regno' is a register which will receive the value from the stack. It 5101 * can be -1, meaning that the read value is not going to a register. 5102 */ 5103 static int check_stack_read(struct bpf_verifier_env *env, 5104 int ptr_regno, int off, int size, 5105 int dst_regno) 5106 { 5107 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5108 struct bpf_func_state *state = func(env, reg); 5109 int err; 5110 /* Some accesses are only permitted with a static offset. */ 5111 bool var_off = !tnum_is_const(reg->var_off); 5112 5113 /* The offset is required to be static when reads don't go to a 5114 * register, in order to not leak pointers (see 5115 * check_stack_read_fixed_off). 5116 */ 5117 if (dst_regno < 0 && var_off) { 5118 char tn_buf[48]; 5119 5120 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5121 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 5122 tn_buf, off, size); 5123 return -EACCES; 5124 } 5125 /* Variable offset is prohibited for unprivileged mode for simplicity 5126 * since it requires corresponding support in Spectre masking for stack 5127 * ALU. See also retrieve_ptr_limit(). The check in 5128 * check_stack_access_for_ptr_arithmetic() called by 5129 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 5130 * with variable offsets, therefore no check is required here. Further, 5131 * just checking it here would be insufficient as speculative stack 5132 * writes could still lead to unsafe speculative behaviour. 5133 */ 5134 if (!var_off) { 5135 off += reg->var_off.value; 5136 err = check_stack_read_fixed_off(env, state, off, size, 5137 dst_regno); 5138 } else { 5139 /* Variable offset stack reads need more conservative handling 5140 * than fixed offset ones. Note that dst_regno >= 0 on this 5141 * branch. 5142 */ 5143 err = check_stack_read_var_off(env, ptr_regno, off, size, 5144 dst_regno); 5145 } 5146 return err; 5147 } 5148 5149 5150 /* check_stack_write dispatches to check_stack_write_fixed_off or 5151 * check_stack_write_var_off. 5152 * 5153 * 'ptr_regno' is the register used as a pointer into the stack. 5154 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 5155 * 'value_regno' is the register whose value we're writing to the stack. It can 5156 * be -1, meaning that we're not writing from a register. 5157 * 5158 * The caller must ensure that the offset falls within the maximum stack size. 5159 */ 5160 static int check_stack_write(struct bpf_verifier_env *env, 5161 int ptr_regno, int off, int size, 5162 int value_regno, int insn_idx) 5163 { 5164 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5165 struct bpf_func_state *state = func(env, reg); 5166 int err; 5167 5168 if (tnum_is_const(reg->var_off)) { 5169 off += reg->var_off.value; 5170 err = check_stack_write_fixed_off(env, state, off, size, 5171 value_regno, insn_idx); 5172 } else { 5173 /* Variable offset stack reads need more conservative handling 5174 * than fixed offset ones. 5175 */ 5176 err = check_stack_write_var_off(env, state, 5177 ptr_regno, off, size, 5178 value_regno, insn_idx); 5179 } 5180 return err; 5181 } 5182 5183 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 5184 int off, int size, enum bpf_access_type type) 5185 { 5186 struct bpf_reg_state *regs = cur_regs(env); 5187 struct bpf_map *map = regs[regno].map_ptr; 5188 u32 cap = bpf_map_flags_to_cap(map); 5189 5190 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 5191 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 5192 map->value_size, off, size); 5193 return -EACCES; 5194 } 5195 5196 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 5197 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 5198 map->value_size, off, size); 5199 return -EACCES; 5200 } 5201 5202 return 0; 5203 } 5204 5205 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 5206 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 5207 int off, int size, u32 mem_size, 5208 bool zero_size_allowed) 5209 { 5210 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 5211 struct bpf_reg_state *reg; 5212 5213 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 5214 return 0; 5215 5216 reg = &cur_regs(env)[regno]; 5217 switch (reg->type) { 5218 case PTR_TO_MAP_KEY: 5219 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 5220 mem_size, off, size); 5221 break; 5222 case PTR_TO_MAP_VALUE: 5223 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 5224 mem_size, off, size); 5225 break; 5226 case PTR_TO_PACKET: 5227 case PTR_TO_PACKET_META: 5228 case PTR_TO_PACKET_END: 5229 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 5230 off, size, regno, reg->id, off, mem_size); 5231 break; 5232 case PTR_TO_MEM: 5233 default: 5234 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 5235 mem_size, off, size); 5236 } 5237 5238 return -EACCES; 5239 } 5240 5241 /* check read/write into a memory region with possible variable offset */ 5242 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 5243 int off, int size, u32 mem_size, 5244 bool zero_size_allowed) 5245 { 5246 struct bpf_verifier_state *vstate = env->cur_state; 5247 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5248 struct bpf_reg_state *reg = &state->regs[regno]; 5249 int err; 5250 5251 /* We may have adjusted the register pointing to memory region, so we 5252 * need to try adding each of min_value and max_value to off 5253 * to make sure our theoretical access will be safe. 5254 * 5255 * The minimum value is only important with signed 5256 * comparisons where we can't assume the floor of a 5257 * value is 0. If we are using signed variables for our 5258 * index'es we need to make sure that whatever we use 5259 * will have a set floor within our range. 5260 */ 5261 if (reg->smin_value < 0 && 5262 (reg->smin_value == S64_MIN || 5263 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5264 reg->smin_value + off < 0)) { 5265 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5266 regno); 5267 return -EACCES; 5268 } 5269 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5270 mem_size, zero_size_allowed); 5271 if (err) { 5272 verbose(env, "R%d min value is outside of the allowed memory range\n", 5273 regno); 5274 return err; 5275 } 5276 5277 /* If we haven't set a max value then we need to bail since we can't be 5278 * sure we won't do bad things. 5279 * If reg->umax_value + off could overflow, treat that as unbounded too. 5280 */ 5281 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5282 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5283 regno); 5284 return -EACCES; 5285 } 5286 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5287 mem_size, zero_size_allowed); 5288 if (err) { 5289 verbose(env, "R%d max value is outside of the allowed memory range\n", 5290 regno); 5291 return err; 5292 } 5293 5294 return 0; 5295 } 5296 5297 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5298 const struct bpf_reg_state *reg, int regno, 5299 bool fixed_off_ok) 5300 { 5301 /* Access to this pointer-typed register or passing it to a helper 5302 * is only allowed in its original, unmodified form. 5303 */ 5304 5305 if (reg->off < 0) { 5306 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5307 reg_type_str(env, reg->type), regno, reg->off); 5308 return -EACCES; 5309 } 5310 5311 if (!fixed_off_ok && reg->off) { 5312 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5313 reg_type_str(env, reg->type), regno, reg->off); 5314 return -EACCES; 5315 } 5316 5317 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5318 char tn_buf[48]; 5319 5320 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5321 verbose(env, "variable %s access var_off=%s disallowed\n", 5322 reg_type_str(env, reg->type), tn_buf); 5323 return -EACCES; 5324 } 5325 5326 return 0; 5327 } 5328 5329 static int check_ptr_off_reg(struct bpf_verifier_env *env, 5330 const struct bpf_reg_state *reg, int regno) 5331 { 5332 return __check_ptr_off_reg(env, reg, regno, false); 5333 } 5334 5335 static int map_kptr_match_type(struct bpf_verifier_env *env, 5336 struct btf_field *kptr_field, 5337 struct bpf_reg_state *reg, u32 regno) 5338 { 5339 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5340 int perm_flags; 5341 const char *reg_name = ""; 5342 5343 if (btf_is_kernel(reg->btf)) { 5344 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5345 5346 /* Only unreferenced case accepts untrusted pointers */ 5347 if (kptr_field->type == BPF_KPTR_UNREF) 5348 perm_flags |= PTR_UNTRUSTED; 5349 } else { 5350 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5351 if (kptr_field->type == BPF_KPTR_PERCPU) 5352 perm_flags |= MEM_PERCPU; 5353 } 5354 5355 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5356 goto bad_type; 5357 5358 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5359 reg_name = btf_type_name(reg->btf, reg->btf_id); 5360 5361 /* For ref_ptr case, release function check should ensure we get one 5362 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5363 * normal store of unreferenced kptr, we must ensure var_off is zero. 5364 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5365 * reg->off and reg->ref_obj_id are not needed here. 5366 */ 5367 if (__check_ptr_off_reg(env, reg, regno, true)) 5368 return -EACCES; 5369 5370 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5371 * we also need to take into account the reg->off. 5372 * 5373 * We want to support cases like: 5374 * 5375 * struct foo { 5376 * struct bar br; 5377 * struct baz bz; 5378 * }; 5379 * 5380 * struct foo *v; 5381 * v = func(); // PTR_TO_BTF_ID 5382 * val->foo = v; // reg->off is zero, btf and btf_id match type 5383 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5384 * // first member type of struct after comparison fails 5385 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5386 * // to match type 5387 * 5388 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5389 * is zero. We must also ensure that btf_struct_ids_match does not walk 5390 * the struct to match type against first member of struct, i.e. reject 5391 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5392 * strict mode to true for type match. 5393 */ 5394 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5395 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5396 kptr_field->type != BPF_KPTR_UNREF)) 5397 goto bad_type; 5398 return 0; 5399 bad_type: 5400 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5401 reg_type_str(env, reg->type), reg_name); 5402 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5403 if (kptr_field->type == BPF_KPTR_UNREF) 5404 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5405 targ_name); 5406 else 5407 verbose(env, "\n"); 5408 return -EINVAL; 5409 } 5410 5411 static bool in_sleepable(struct bpf_verifier_env *env) 5412 { 5413 return env->prog->sleepable || 5414 (env->cur_state && env->cur_state->in_sleepable); 5415 } 5416 5417 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5418 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5419 */ 5420 static bool in_rcu_cs(struct bpf_verifier_env *env) 5421 { 5422 return env->cur_state->active_rcu_lock || 5423 env->cur_state->active_lock.ptr || 5424 !in_sleepable(env); 5425 } 5426 5427 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5428 BTF_SET_START(rcu_protected_types) 5429 BTF_ID(struct, prog_test_ref_kfunc) 5430 #ifdef CONFIG_CGROUPS 5431 BTF_ID(struct, cgroup) 5432 #endif 5433 #ifdef CONFIG_BPF_JIT 5434 BTF_ID(struct, bpf_cpumask) 5435 #endif 5436 BTF_ID(struct, task_struct) 5437 BTF_ID(struct, bpf_crypto_ctx) 5438 BTF_SET_END(rcu_protected_types) 5439 5440 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5441 { 5442 if (!btf_is_kernel(btf)) 5443 return true; 5444 return btf_id_set_contains(&rcu_protected_types, btf_id); 5445 } 5446 5447 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 5448 { 5449 struct btf_struct_meta *meta; 5450 5451 if (btf_is_kernel(kptr_field->kptr.btf)) 5452 return NULL; 5453 5454 meta = btf_find_struct_meta(kptr_field->kptr.btf, 5455 kptr_field->kptr.btf_id); 5456 5457 return meta ? meta->record : NULL; 5458 } 5459 5460 static bool rcu_safe_kptr(const struct btf_field *field) 5461 { 5462 const struct btf_field_kptr *kptr = &field->kptr; 5463 5464 return field->type == BPF_KPTR_PERCPU || 5465 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 5466 } 5467 5468 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 5469 { 5470 struct btf_record *rec; 5471 u32 ret; 5472 5473 ret = PTR_MAYBE_NULL; 5474 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 5475 ret |= MEM_RCU; 5476 if (kptr_field->type == BPF_KPTR_PERCPU) 5477 ret |= MEM_PERCPU; 5478 else if (!btf_is_kernel(kptr_field->kptr.btf)) 5479 ret |= MEM_ALLOC; 5480 5481 rec = kptr_pointee_btf_record(kptr_field); 5482 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 5483 ret |= NON_OWN_REF; 5484 } else { 5485 ret |= PTR_UNTRUSTED; 5486 } 5487 5488 return ret; 5489 } 5490 5491 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5492 int value_regno, int insn_idx, 5493 struct btf_field *kptr_field) 5494 { 5495 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5496 int class = BPF_CLASS(insn->code); 5497 struct bpf_reg_state *val_reg; 5498 5499 /* Things we already checked for in check_map_access and caller: 5500 * - Reject cases where variable offset may touch kptr 5501 * - size of access (must be BPF_DW) 5502 * - tnum_is_const(reg->var_off) 5503 * - kptr_field->offset == off + reg->var_off.value 5504 */ 5505 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5506 if (BPF_MODE(insn->code) != BPF_MEM) { 5507 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5508 return -EACCES; 5509 } 5510 5511 /* We only allow loading referenced kptr, since it will be marked as 5512 * untrusted, similar to unreferenced kptr. 5513 */ 5514 if (class != BPF_LDX && 5515 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 5516 verbose(env, "store to referenced kptr disallowed\n"); 5517 return -EACCES; 5518 } 5519 5520 if (class == BPF_LDX) { 5521 val_reg = reg_state(env, value_regno); 5522 /* We can simply mark the value_regno receiving the pointer 5523 * value from map as PTR_TO_BTF_ID, with the correct type. 5524 */ 5525 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5526 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field)); 5527 } else if (class == BPF_STX) { 5528 val_reg = reg_state(env, value_regno); 5529 if (!register_is_null(val_reg) && 5530 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5531 return -EACCES; 5532 } else if (class == BPF_ST) { 5533 if (insn->imm) { 5534 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5535 kptr_field->offset); 5536 return -EACCES; 5537 } 5538 } else { 5539 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5540 return -EACCES; 5541 } 5542 return 0; 5543 } 5544 5545 /* check read/write into a map element with possible variable offset */ 5546 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5547 int off, int size, bool zero_size_allowed, 5548 enum bpf_access_src src) 5549 { 5550 struct bpf_verifier_state *vstate = env->cur_state; 5551 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5552 struct bpf_reg_state *reg = &state->regs[regno]; 5553 struct bpf_map *map = reg->map_ptr; 5554 struct btf_record *rec; 5555 int err, i; 5556 5557 err = check_mem_region_access(env, regno, off, size, map->value_size, 5558 zero_size_allowed); 5559 if (err) 5560 return err; 5561 5562 if (IS_ERR_OR_NULL(map->record)) 5563 return 0; 5564 rec = map->record; 5565 for (i = 0; i < rec->cnt; i++) { 5566 struct btf_field *field = &rec->fields[i]; 5567 u32 p = field->offset; 5568 5569 /* If any part of a field can be touched by load/store, reject 5570 * this program. To check that [x1, x2) overlaps with [y1, y2), 5571 * it is sufficient to check x1 < y2 && y1 < x2. 5572 */ 5573 if (reg->smin_value + off < p + field->size && 5574 p < reg->umax_value + off + size) { 5575 switch (field->type) { 5576 case BPF_KPTR_UNREF: 5577 case BPF_KPTR_REF: 5578 case BPF_KPTR_PERCPU: 5579 if (src != ACCESS_DIRECT) { 5580 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 5581 return -EACCES; 5582 } 5583 if (!tnum_is_const(reg->var_off)) { 5584 verbose(env, "kptr access cannot have variable offset\n"); 5585 return -EACCES; 5586 } 5587 if (p != off + reg->var_off.value) { 5588 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 5589 p, off + reg->var_off.value); 5590 return -EACCES; 5591 } 5592 if (size != bpf_size_to_bytes(BPF_DW)) { 5593 verbose(env, "kptr access size must be BPF_DW\n"); 5594 return -EACCES; 5595 } 5596 break; 5597 default: 5598 verbose(env, "%s cannot be accessed directly by load/store\n", 5599 btf_field_type_name(field->type)); 5600 return -EACCES; 5601 } 5602 } 5603 } 5604 return 0; 5605 } 5606 5607 #define MAX_PACKET_OFF 0xffff 5608 5609 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5610 const struct bpf_call_arg_meta *meta, 5611 enum bpf_access_type t) 5612 { 5613 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5614 5615 switch (prog_type) { 5616 /* Program types only with direct read access go here! */ 5617 case BPF_PROG_TYPE_LWT_IN: 5618 case BPF_PROG_TYPE_LWT_OUT: 5619 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5620 case BPF_PROG_TYPE_SK_REUSEPORT: 5621 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5622 case BPF_PROG_TYPE_CGROUP_SKB: 5623 if (t == BPF_WRITE) 5624 return false; 5625 fallthrough; 5626 5627 /* Program types with direct read + write access go here! */ 5628 case BPF_PROG_TYPE_SCHED_CLS: 5629 case BPF_PROG_TYPE_SCHED_ACT: 5630 case BPF_PROG_TYPE_XDP: 5631 case BPF_PROG_TYPE_LWT_XMIT: 5632 case BPF_PROG_TYPE_SK_SKB: 5633 case BPF_PROG_TYPE_SK_MSG: 5634 if (meta) 5635 return meta->pkt_access; 5636 5637 env->seen_direct_write = true; 5638 return true; 5639 5640 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5641 if (t == BPF_WRITE) 5642 env->seen_direct_write = true; 5643 5644 return true; 5645 5646 default: 5647 return false; 5648 } 5649 } 5650 5651 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5652 int size, bool zero_size_allowed) 5653 { 5654 struct bpf_reg_state *regs = cur_regs(env); 5655 struct bpf_reg_state *reg = ®s[regno]; 5656 int err; 5657 5658 /* We may have added a variable offset to the packet pointer; but any 5659 * reg->range we have comes after that. We are only checking the fixed 5660 * offset. 5661 */ 5662 5663 /* We don't allow negative numbers, because we aren't tracking enough 5664 * detail to prove they're safe. 5665 */ 5666 if (reg->smin_value < 0) { 5667 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5668 regno); 5669 return -EACCES; 5670 } 5671 5672 err = reg->range < 0 ? -EINVAL : 5673 __check_mem_access(env, regno, off, size, reg->range, 5674 zero_size_allowed); 5675 if (err) { 5676 verbose(env, "R%d offset is outside of the packet\n", regno); 5677 return err; 5678 } 5679 5680 /* __check_mem_access has made sure "off + size - 1" is within u16. 5681 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5682 * otherwise find_good_pkt_pointers would have refused to set range info 5683 * that __check_mem_access would have rejected this pkt access. 5684 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5685 */ 5686 env->prog->aux->max_pkt_offset = 5687 max_t(u32, env->prog->aux->max_pkt_offset, 5688 off + reg->umax_value + size - 1); 5689 5690 return err; 5691 } 5692 5693 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5694 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5695 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5696 struct btf **btf, u32 *btf_id, bool *is_retval, bool is_ldsx) 5697 { 5698 struct bpf_insn_access_aux info = { 5699 .reg_type = *reg_type, 5700 .log = &env->log, 5701 .is_retval = false, 5702 .is_ldsx = is_ldsx, 5703 }; 5704 5705 if (env->ops->is_valid_access && 5706 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5707 /* A non zero info.ctx_field_size indicates that this field is a 5708 * candidate for later verifier transformation to load the whole 5709 * field and then apply a mask when accessed with a narrower 5710 * access than actual ctx access size. A zero info.ctx_field_size 5711 * will only allow for whole field access and rejects any other 5712 * type of narrower access. 5713 */ 5714 *reg_type = info.reg_type; 5715 *is_retval = info.is_retval; 5716 5717 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5718 *btf = info.btf; 5719 *btf_id = info.btf_id; 5720 } else { 5721 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5722 } 5723 /* remember the offset of last byte accessed in ctx */ 5724 if (env->prog->aux->max_ctx_offset < off + size) 5725 env->prog->aux->max_ctx_offset = off + size; 5726 return 0; 5727 } 5728 5729 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5730 return -EACCES; 5731 } 5732 5733 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5734 int size) 5735 { 5736 if (size < 0 || off < 0 || 5737 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5738 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5739 off, size); 5740 return -EACCES; 5741 } 5742 return 0; 5743 } 5744 5745 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5746 u32 regno, int off, int size, 5747 enum bpf_access_type t) 5748 { 5749 struct bpf_reg_state *regs = cur_regs(env); 5750 struct bpf_reg_state *reg = ®s[regno]; 5751 struct bpf_insn_access_aux info = {}; 5752 bool valid; 5753 5754 if (reg->smin_value < 0) { 5755 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5756 regno); 5757 return -EACCES; 5758 } 5759 5760 switch (reg->type) { 5761 case PTR_TO_SOCK_COMMON: 5762 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5763 break; 5764 case PTR_TO_SOCKET: 5765 valid = bpf_sock_is_valid_access(off, size, t, &info); 5766 break; 5767 case PTR_TO_TCP_SOCK: 5768 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5769 break; 5770 case PTR_TO_XDP_SOCK: 5771 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5772 break; 5773 default: 5774 valid = false; 5775 } 5776 5777 5778 if (valid) { 5779 env->insn_aux_data[insn_idx].ctx_field_size = 5780 info.ctx_field_size; 5781 return 0; 5782 } 5783 5784 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5785 regno, reg_type_str(env, reg->type), off, size); 5786 5787 return -EACCES; 5788 } 5789 5790 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5791 { 5792 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5793 } 5794 5795 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5796 { 5797 const struct bpf_reg_state *reg = reg_state(env, regno); 5798 5799 return reg->type == PTR_TO_CTX; 5800 } 5801 5802 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5803 { 5804 const struct bpf_reg_state *reg = reg_state(env, regno); 5805 5806 return type_is_sk_pointer(reg->type); 5807 } 5808 5809 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5810 { 5811 const struct bpf_reg_state *reg = reg_state(env, regno); 5812 5813 return type_is_pkt_pointer(reg->type); 5814 } 5815 5816 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5817 { 5818 const struct bpf_reg_state *reg = reg_state(env, regno); 5819 5820 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5821 return reg->type == PTR_TO_FLOW_KEYS; 5822 } 5823 5824 static bool is_arena_reg(struct bpf_verifier_env *env, int regno) 5825 { 5826 const struct bpf_reg_state *reg = reg_state(env, regno); 5827 5828 return reg->type == PTR_TO_ARENA; 5829 } 5830 5831 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5832 #ifdef CONFIG_NET 5833 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5834 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5835 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5836 #endif 5837 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5838 }; 5839 5840 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5841 { 5842 /* A referenced register is always trusted. */ 5843 if (reg->ref_obj_id) 5844 return true; 5845 5846 /* Types listed in the reg2btf_ids are always trusted */ 5847 if (reg2btf_ids[base_type(reg->type)] && 5848 !bpf_type_has_unsafe_modifiers(reg->type)) 5849 return true; 5850 5851 /* If a register is not referenced, it is trusted if it has the 5852 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5853 * other type modifiers may be safe, but we elect to take an opt-in 5854 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5855 * not. 5856 * 5857 * Eventually, we should make PTR_TRUSTED the single source of truth 5858 * for whether a register is trusted. 5859 */ 5860 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5861 !bpf_type_has_unsafe_modifiers(reg->type); 5862 } 5863 5864 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5865 { 5866 return reg->type & MEM_RCU; 5867 } 5868 5869 static void clear_trusted_flags(enum bpf_type_flag *flag) 5870 { 5871 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5872 } 5873 5874 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5875 const struct bpf_reg_state *reg, 5876 int off, int size, bool strict) 5877 { 5878 struct tnum reg_off; 5879 int ip_align; 5880 5881 /* Byte size accesses are always allowed. */ 5882 if (!strict || size == 1) 5883 return 0; 5884 5885 /* For platforms that do not have a Kconfig enabling 5886 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5887 * NET_IP_ALIGN is universally set to '2'. And on platforms 5888 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5889 * to this code only in strict mode where we want to emulate 5890 * the NET_IP_ALIGN==2 checking. Therefore use an 5891 * unconditional IP align value of '2'. 5892 */ 5893 ip_align = 2; 5894 5895 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5896 if (!tnum_is_aligned(reg_off, size)) { 5897 char tn_buf[48]; 5898 5899 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5900 verbose(env, 5901 "misaligned packet access off %d+%s+%d+%d size %d\n", 5902 ip_align, tn_buf, reg->off, off, size); 5903 return -EACCES; 5904 } 5905 5906 return 0; 5907 } 5908 5909 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5910 const struct bpf_reg_state *reg, 5911 const char *pointer_desc, 5912 int off, int size, bool strict) 5913 { 5914 struct tnum reg_off; 5915 5916 /* Byte size accesses are always allowed. */ 5917 if (!strict || size == 1) 5918 return 0; 5919 5920 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5921 if (!tnum_is_aligned(reg_off, size)) { 5922 char tn_buf[48]; 5923 5924 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5925 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5926 pointer_desc, tn_buf, reg->off, off, size); 5927 return -EACCES; 5928 } 5929 5930 return 0; 5931 } 5932 5933 static int check_ptr_alignment(struct bpf_verifier_env *env, 5934 const struct bpf_reg_state *reg, int off, 5935 int size, bool strict_alignment_once) 5936 { 5937 bool strict = env->strict_alignment || strict_alignment_once; 5938 const char *pointer_desc = ""; 5939 5940 switch (reg->type) { 5941 case PTR_TO_PACKET: 5942 case PTR_TO_PACKET_META: 5943 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5944 * right in front, treat it the very same way. 5945 */ 5946 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5947 case PTR_TO_FLOW_KEYS: 5948 pointer_desc = "flow keys "; 5949 break; 5950 case PTR_TO_MAP_KEY: 5951 pointer_desc = "key "; 5952 break; 5953 case PTR_TO_MAP_VALUE: 5954 pointer_desc = "value "; 5955 break; 5956 case PTR_TO_CTX: 5957 pointer_desc = "context "; 5958 break; 5959 case PTR_TO_STACK: 5960 pointer_desc = "stack "; 5961 /* The stack spill tracking logic in check_stack_write_fixed_off() 5962 * and check_stack_read_fixed_off() relies on stack accesses being 5963 * aligned. 5964 */ 5965 strict = true; 5966 break; 5967 case PTR_TO_SOCKET: 5968 pointer_desc = "sock "; 5969 break; 5970 case PTR_TO_SOCK_COMMON: 5971 pointer_desc = "sock_common "; 5972 break; 5973 case PTR_TO_TCP_SOCK: 5974 pointer_desc = "tcp_sock "; 5975 break; 5976 case PTR_TO_XDP_SOCK: 5977 pointer_desc = "xdp_sock "; 5978 break; 5979 case PTR_TO_ARENA: 5980 return 0; 5981 default: 5982 break; 5983 } 5984 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5985 strict); 5986 } 5987 5988 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth) 5989 { 5990 if (env->prog->jit_requested) 5991 return round_up(stack_depth, 16); 5992 5993 /* round up to 32-bytes, since this is granularity 5994 * of interpreter stack size 5995 */ 5996 return round_up(max_t(u32, stack_depth, 1), 32); 5997 } 5998 5999 /* starting from main bpf function walk all instructions of the function 6000 * and recursively walk all callees that given function can call. 6001 * Ignore jump and exit insns. 6002 * Since recursion is prevented by check_cfg() this algorithm 6003 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 6004 */ 6005 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx) 6006 { 6007 struct bpf_subprog_info *subprog = env->subprog_info; 6008 struct bpf_insn *insn = env->prog->insnsi; 6009 int depth = 0, frame = 0, i, subprog_end; 6010 bool tail_call_reachable = false; 6011 int ret_insn[MAX_CALL_FRAMES]; 6012 int ret_prog[MAX_CALL_FRAMES]; 6013 int j; 6014 6015 i = subprog[idx].start; 6016 process_func: 6017 /* protect against potential stack overflow that might happen when 6018 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 6019 * depth for such case down to 256 so that the worst case scenario 6020 * would result in 8k stack size (32 which is tailcall limit * 256 = 6021 * 8k). 6022 * 6023 * To get the idea what might happen, see an example: 6024 * func1 -> sub rsp, 128 6025 * subfunc1 -> sub rsp, 256 6026 * tailcall1 -> add rsp, 256 6027 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 6028 * subfunc2 -> sub rsp, 64 6029 * subfunc22 -> sub rsp, 128 6030 * tailcall2 -> add rsp, 128 6031 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 6032 * 6033 * tailcall will unwind the current stack frame but it will not get rid 6034 * of caller's stack as shown on the example above. 6035 */ 6036 if (idx && subprog[idx].has_tail_call && depth >= 256) { 6037 verbose(env, 6038 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 6039 depth); 6040 return -EACCES; 6041 } 6042 depth += round_up_stack_depth(env, subprog[idx].stack_depth); 6043 if (depth > MAX_BPF_STACK) { 6044 verbose(env, "combined stack size of %d calls is %d. Too large\n", 6045 frame + 1, depth); 6046 return -EACCES; 6047 } 6048 continue_func: 6049 subprog_end = subprog[idx + 1].start; 6050 for (; i < subprog_end; i++) { 6051 int next_insn, sidx; 6052 6053 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 6054 bool err = false; 6055 6056 if (!is_bpf_throw_kfunc(insn + i)) 6057 continue; 6058 if (subprog[idx].is_cb) 6059 err = true; 6060 for (int c = 0; c < frame && !err; c++) { 6061 if (subprog[ret_prog[c]].is_cb) { 6062 err = true; 6063 break; 6064 } 6065 } 6066 if (!err) 6067 continue; 6068 verbose(env, 6069 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 6070 i, idx); 6071 return -EINVAL; 6072 } 6073 6074 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 6075 continue; 6076 /* remember insn and function to return to */ 6077 ret_insn[frame] = i + 1; 6078 ret_prog[frame] = idx; 6079 6080 /* find the callee */ 6081 next_insn = i + insn[i].imm + 1; 6082 sidx = find_subprog(env, next_insn); 6083 if (sidx < 0) { 6084 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 6085 next_insn); 6086 return -EFAULT; 6087 } 6088 if (subprog[sidx].is_async_cb) { 6089 if (subprog[sidx].has_tail_call) { 6090 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 6091 return -EFAULT; 6092 } 6093 /* async callbacks don't increase bpf prog stack size unless called directly */ 6094 if (!bpf_pseudo_call(insn + i)) 6095 continue; 6096 if (subprog[sidx].is_exception_cb) { 6097 verbose(env, "insn %d cannot call exception cb directly\n", i); 6098 return -EINVAL; 6099 } 6100 } 6101 i = next_insn; 6102 idx = sidx; 6103 6104 if (subprog[idx].has_tail_call) 6105 tail_call_reachable = true; 6106 6107 frame++; 6108 if (frame >= MAX_CALL_FRAMES) { 6109 verbose(env, "the call stack of %d frames is too deep !\n", 6110 frame); 6111 return -E2BIG; 6112 } 6113 goto process_func; 6114 } 6115 /* if tail call got detected across bpf2bpf calls then mark each of the 6116 * currently present subprog frames as tail call reachable subprogs; 6117 * this info will be utilized by JIT so that we will be preserving the 6118 * tail call counter throughout bpf2bpf calls combined with tailcalls 6119 */ 6120 if (tail_call_reachable) 6121 for (j = 0; j < frame; j++) { 6122 if (subprog[ret_prog[j]].is_exception_cb) { 6123 verbose(env, "cannot tail call within exception cb\n"); 6124 return -EINVAL; 6125 } 6126 subprog[ret_prog[j]].tail_call_reachable = true; 6127 } 6128 if (subprog[0].tail_call_reachable) 6129 env->prog->aux->tail_call_reachable = true; 6130 6131 /* end of for() loop means the last insn of the 'subprog' 6132 * was reached. Doesn't matter whether it was JA or EXIT 6133 */ 6134 if (frame == 0) 6135 return 0; 6136 depth -= round_up_stack_depth(env, subprog[idx].stack_depth); 6137 frame--; 6138 i = ret_insn[frame]; 6139 idx = ret_prog[frame]; 6140 goto continue_func; 6141 } 6142 6143 static int check_max_stack_depth(struct bpf_verifier_env *env) 6144 { 6145 struct bpf_subprog_info *si = env->subprog_info; 6146 int ret; 6147 6148 for (int i = 0; i < env->subprog_cnt; i++) { 6149 if (!i || si[i].is_async_cb) { 6150 ret = check_max_stack_depth_subprog(env, i); 6151 if (ret < 0) 6152 return ret; 6153 } 6154 continue; 6155 } 6156 return 0; 6157 } 6158 6159 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 6160 static int get_callee_stack_depth(struct bpf_verifier_env *env, 6161 const struct bpf_insn *insn, int idx) 6162 { 6163 int start = idx + insn->imm + 1, subprog; 6164 6165 subprog = find_subprog(env, start); 6166 if (subprog < 0) { 6167 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 6168 start); 6169 return -EFAULT; 6170 } 6171 return env->subprog_info[subprog].stack_depth; 6172 } 6173 #endif 6174 6175 static int __check_buffer_access(struct bpf_verifier_env *env, 6176 const char *buf_info, 6177 const struct bpf_reg_state *reg, 6178 int regno, int off, int size) 6179 { 6180 if (off < 0) { 6181 verbose(env, 6182 "R%d invalid %s buffer access: off=%d, size=%d\n", 6183 regno, buf_info, off, size); 6184 return -EACCES; 6185 } 6186 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6187 char tn_buf[48]; 6188 6189 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6190 verbose(env, 6191 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 6192 regno, off, tn_buf); 6193 return -EACCES; 6194 } 6195 6196 return 0; 6197 } 6198 6199 static int check_tp_buffer_access(struct bpf_verifier_env *env, 6200 const struct bpf_reg_state *reg, 6201 int regno, int off, int size) 6202 { 6203 int err; 6204 6205 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 6206 if (err) 6207 return err; 6208 6209 if (off + size > env->prog->aux->max_tp_access) 6210 env->prog->aux->max_tp_access = off + size; 6211 6212 return 0; 6213 } 6214 6215 static int check_buffer_access(struct bpf_verifier_env *env, 6216 const struct bpf_reg_state *reg, 6217 int regno, int off, int size, 6218 bool zero_size_allowed, 6219 u32 *max_access) 6220 { 6221 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 6222 int err; 6223 6224 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 6225 if (err) 6226 return err; 6227 6228 if (off + size > *max_access) 6229 *max_access = off + size; 6230 6231 return 0; 6232 } 6233 6234 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 6235 static void zext_32_to_64(struct bpf_reg_state *reg) 6236 { 6237 reg->var_off = tnum_subreg(reg->var_off); 6238 __reg_assign_32_into_64(reg); 6239 } 6240 6241 /* truncate register to smaller size (in bytes) 6242 * must be called with size < BPF_REG_SIZE 6243 */ 6244 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 6245 { 6246 u64 mask; 6247 6248 /* clear high bits in bit representation */ 6249 reg->var_off = tnum_cast(reg->var_off, size); 6250 6251 /* fix arithmetic bounds */ 6252 mask = ((u64)1 << (size * 8)) - 1; 6253 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 6254 reg->umin_value &= mask; 6255 reg->umax_value &= mask; 6256 } else { 6257 reg->umin_value = 0; 6258 reg->umax_value = mask; 6259 } 6260 reg->smin_value = reg->umin_value; 6261 reg->smax_value = reg->umax_value; 6262 6263 /* If size is smaller than 32bit register the 32bit register 6264 * values are also truncated so we push 64-bit bounds into 6265 * 32-bit bounds. Above were truncated < 32-bits already. 6266 */ 6267 if (size < 4) 6268 __mark_reg32_unbounded(reg); 6269 6270 reg_bounds_sync(reg); 6271 } 6272 6273 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 6274 { 6275 if (size == 1) { 6276 reg->smin_value = reg->s32_min_value = S8_MIN; 6277 reg->smax_value = reg->s32_max_value = S8_MAX; 6278 } else if (size == 2) { 6279 reg->smin_value = reg->s32_min_value = S16_MIN; 6280 reg->smax_value = reg->s32_max_value = S16_MAX; 6281 } else { 6282 /* size == 4 */ 6283 reg->smin_value = reg->s32_min_value = S32_MIN; 6284 reg->smax_value = reg->s32_max_value = S32_MAX; 6285 } 6286 reg->umin_value = reg->u32_min_value = 0; 6287 reg->umax_value = U64_MAX; 6288 reg->u32_max_value = U32_MAX; 6289 reg->var_off = tnum_unknown; 6290 } 6291 6292 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6293 { 6294 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6295 u64 top_smax_value, top_smin_value; 6296 u64 num_bits = size * 8; 6297 6298 if (tnum_is_const(reg->var_off)) { 6299 u64_cval = reg->var_off.value; 6300 if (size == 1) 6301 reg->var_off = tnum_const((s8)u64_cval); 6302 else if (size == 2) 6303 reg->var_off = tnum_const((s16)u64_cval); 6304 else 6305 /* size == 4 */ 6306 reg->var_off = tnum_const((s32)u64_cval); 6307 6308 u64_cval = reg->var_off.value; 6309 reg->smax_value = reg->smin_value = u64_cval; 6310 reg->umax_value = reg->umin_value = u64_cval; 6311 reg->s32_max_value = reg->s32_min_value = u64_cval; 6312 reg->u32_max_value = reg->u32_min_value = u64_cval; 6313 return; 6314 } 6315 6316 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6317 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6318 6319 if (top_smax_value != top_smin_value) 6320 goto out; 6321 6322 /* find the s64_min and s64_min after sign extension */ 6323 if (size == 1) { 6324 init_s64_max = (s8)reg->smax_value; 6325 init_s64_min = (s8)reg->smin_value; 6326 } else if (size == 2) { 6327 init_s64_max = (s16)reg->smax_value; 6328 init_s64_min = (s16)reg->smin_value; 6329 } else { 6330 init_s64_max = (s32)reg->smax_value; 6331 init_s64_min = (s32)reg->smin_value; 6332 } 6333 6334 s64_max = max(init_s64_max, init_s64_min); 6335 s64_min = min(init_s64_max, init_s64_min); 6336 6337 /* both of s64_max/s64_min positive or negative */ 6338 if ((s64_max >= 0) == (s64_min >= 0)) { 6339 reg->smin_value = reg->s32_min_value = s64_min; 6340 reg->smax_value = reg->s32_max_value = s64_max; 6341 reg->umin_value = reg->u32_min_value = s64_min; 6342 reg->umax_value = reg->u32_max_value = s64_max; 6343 reg->var_off = tnum_range(s64_min, s64_max); 6344 return; 6345 } 6346 6347 out: 6348 set_sext64_default_val(reg, size); 6349 } 6350 6351 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6352 { 6353 if (size == 1) { 6354 reg->s32_min_value = S8_MIN; 6355 reg->s32_max_value = S8_MAX; 6356 } else { 6357 /* size == 2 */ 6358 reg->s32_min_value = S16_MIN; 6359 reg->s32_max_value = S16_MAX; 6360 } 6361 reg->u32_min_value = 0; 6362 reg->u32_max_value = U32_MAX; 6363 reg->var_off = tnum_subreg(tnum_unknown); 6364 } 6365 6366 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6367 { 6368 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6369 u32 top_smax_value, top_smin_value; 6370 u32 num_bits = size * 8; 6371 6372 if (tnum_is_const(reg->var_off)) { 6373 u32_val = reg->var_off.value; 6374 if (size == 1) 6375 reg->var_off = tnum_const((s8)u32_val); 6376 else 6377 reg->var_off = tnum_const((s16)u32_val); 6378 6379 u32_val = reg->var_off.value; 6380 reg->s32_min_value = reg->s32_max_value = u32_val; 6381 reg->u32_min_value = reg->u32_max_value = u32_val; 6382 return; 6383 } 6384 6385 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 6386 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 6387 6388 if (top_smax_value != top_smin_value) 6389 goto out; 6390 6391 /* find the s32_min and s32_min after sign extension */ 6392 if (size == 1) { 6393 init_s32_max = (s8)reg->s32_max_value; 6394 init_s32_min = (s8)reg->s32_min_value; 6395 } else { 6396 /* size == 2 */ 6397 init_s32_max = (s16)reg->s32_max_value; 6398 init_s32_min = (s16)reg->s32_min_value; 6399 } 6400 s32_max = max(init_s32_max, init_s32_min); 6401 s32_min = min(init_s32_max, init_s32_min); 6402 6403 if ((s32_min >= 0) == (s32_max >= 0)) { 6404 reg->s32_min_value = s32_min; 6405 reg->s32_max_value = s32_max; 6406 reg->u32_min_value = (u32)s32_min; 6407 reg->u32_max_value = (u32)s32_max; 6408 reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max)); 6409 return; 6410 } 6411 6412 out: 6413 set_sext32_default_val(reg, size); 6414 } 6415 6416 static bool bpf_map_is_rdonly(const struct bpf_map *map) 6417 { 6418 /* A map is considered read-only if the following condition are true: 6419 * 6420 * 1) BPF program side cannot change any of the map content. The 6421 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6422 * and was set at map creation time. 6423 * 2) The map value(s) have been initialized from user space by a 6424 * loader and then "frozen", such that no new map update/delete 6425 * operations from syscall side are possible for the rest of 6426 * the map's lifetime from that point onwards. 6427 * 3) Any parallel/pending map update/delete operations from syscall 6428 * side have been completed. Only after that point, it's safe to 6429 * assume that map value(s) are immutable. 6430 */ 6431 return (map->map_flags & BPF_F_RDONLY_PROG) && 6432 READ_ONCE(map->frozen) && 6433 !bpf_map_write_active(map); 6434 } 6435 6436 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6437 bool is_ldsx) 6438 { 6439 void *ptr; 6440 u64 addr; 6441 int err; 6442 6443 err = map->ops->map_direct_value_addr(map, &addr, off); 6444 if (err) 6445 return err; 6446 ptr = (void *)(long)addr + off; 6447 6448 switch (size) { 6449 case sizeof(u8): 6450 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6451 break; 6452 case sizeof(u16): 6453 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6454 break; 6455 case sizeof(u32): 6456 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6457 break; 6458 case sizeof(u64): 6459 *val = *(u64 *)ptr; 6460 break; 6461 default: 6462 return -EINVAL; 6463 } 6464 return 0; 6465 } 6466 6467 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6468 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6469 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6470 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null) 6471 6472 /* 6473 * Allow list few fields as RCU trusted or full trusted. 6474 * This logic doesn't allow mix tagging and will be removed once GCC supports 6475 * btf_type_tag. 6476 */ 6477 6478 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6479 BTF_TYPE_SAFE_RCU(struct task_struct) { 6480 const cpumask_t *cpus_ptr; 6481 struct css_set __rcu *cgroups; 6482 struct task_struct __rcu *real_parent; 6483 struct task_struct *group_leader; 6484 }; 6485 6486 BTF_TYPE_SAFE_RCU(struct cgroup) { 6487 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6488 struct kernfs_node *kn; 6489 }; 6490 6491 BTF_TYPE_SAFE_RCU(struct css_set) { 6492 struct cgroup *dfl_cgrp; 6493 }; 6494 6495 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6496 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6497 struct file __rcu *exe_file; 6498 }; 6499 6500 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6501 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6502 */ 6503 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6504 struct sock *sk; 6505 }; 6506 6507 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6508 struct sock *sk; 6509 }; 6510 6511 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6512 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6513 struct seq_file *seq; 6514 }; 6515 6516 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6517 struct bpf_iter_meta *meta; 6518 struct task_struct *task; 6519 }; 6520 6521 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6522 struct file *file; 6523 }; 6524 6525 BTF_TYPE_SAFE_TRUSTED(struct file) { 6526 struct inode *f_inode; 6527 }; 6528 6529 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 6530 /* no negative dentry-s in places where bpf can see it */ 6531 struct inode *d_inode; 6532 }; 6533 6534 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) { 6535 struct sock *sk; 6536 }; 6537 6538 static bool type_is_rcu(struct bpf_verifier_env *env, 6539 struct bpf_reg_state *reg, 6540 const char *field_name, u32 btf_id) 6541 { 6542 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6543 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6544 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6545 6546 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6547 } 6548 6549 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6550 struct bpf_reg_state *reg, 6551 const char *field_name, u32 btf_id) 6552 { 6553 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6554 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6555 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6556 6557 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6558 } 6559 6560 static bool type_is_trusted(struct bpf_verifier_env *env, 6561 struct bpf_reg_state *reg, 6562 const char *field_name, u32 btf_id) 6563 { 6564 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 6565 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6566 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6567 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6568 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 6569 6570 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6571 } 6572 6573 static bool type_is_trusted_or_null(struct bpf_verifier_env *env, 6574 struct bpf_reg_state *reg, 6575 const char *field_name, u32 btf_id) 6576 { 6577 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)); 6578 6579 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, 6580 "__safe_trusted_or_null"); 6581 } 6582 6583 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6584 struct bpf_reg_state *regs, 6585 int regno, int off, int size, 6586 enum bpf_access_type atype, 6587 int value_regno) 6588 { 6589 struct bpf_reg_state *reg = regs + regno; 6590 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6591 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6592 const char *field_name = NULL; 6593 enum bpf_type_flag flag = 0; 6594 u32 btf_id = 0; 6595 int ret; 6596 6597 if (!env->allow_ptr_leaks) { 6598 verbose(env, 6599 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6600 tname); 6601 return -EPERM; 6602 } 6603 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6604 verbose(env, 6605 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6606 tname); 6607 return -EINVAL; 6608 } 6609 if (off < 0) { 6610 verbose(env, 6611 "R%d is ptr_%s invalid negative access: off=%d\n", 6612 regno, tname, off); 6613 return -EACCES; 6614 } 6615 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6616 char tn_buf[48]; 6617 6618 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6619 verbose(env, 6620 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6621 regno, tname, off, tn_buf); 6622 return -EACCES; 6623 } 6624 6625 if (reg->type & MEM_USER) { 6626 verbose(env, 6627 "R%d is ptr_%s access user memory: off=%d\n", 6628 regno, tname, off); 6629 return -EACCES; 6630 } 6631 6632 if (reg->type & MEM_PERCPU) { 6633 verbose(env, 6634 "R%d is ptr_%s access percpu memory: off=%d\n", 6635 regno, tname, off); 6636 return -EACCES; 6637 } 6638 6639 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6640 if (!btf_is_kernel(reg->btf)) { 6641 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 6642 return -EFAULT; 6643 } 6644 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6645 } else { 6646 /* Writes are permitted with default btf_struct_access for 6647 * program allocated objects (which always have ref_obj_id > 0), 6648 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6649 */ 6650 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6651 verbose(env, "only read is supported\n"); 6652 return -EACCES; 6653 } 6654 6655 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6656 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 6657 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 6658 return -EFAULT; 6659 } 6660 6661 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6662 } 6663 6664 if (ret < 0) 6665 return ret; 6666 6667 if (ret != PTR_TO_BTF_ID) { 6668 /* just mark; */ 6669 6670 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6671 /* If this is an untrusted pointer, all pointers formed by walking it 6672 * also inherit the untrusted flag. 6673 */ 6674 flag = PTR_UNTRUSTED; 6675 6676 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6677 /* By default any pointer obtained from walking a trusted pointer is no 6678 * longer trusted, unless the field being accessed has explicitly been 6679 * marked as inheriting its parent's state of trust (either full or RCU). 6680 * For example: 6681 * 'cgroups' pointer is untrusted if task->cgroups dereference 6682 * happened in a sleepable program outside of bpf_rcu_read_lock() 6683 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6684 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6685 * 6686 * A regular RCU-protected pointer with __rcu tag can also be deemed 6687 * trusted if we are in an RCU CS. Such pointer can be NULL. 6688 */ 6689 if (type_is_trusted(env, reg, field_name, btf_id)) { 6690 flag |= PTR_TRUSTED; 6691 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) { 6692 flag |= PTR_TRUSTED | PTR_MAYBE_NULL; 6693 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6694 if (type_is_rcu(env, reg, field_name, btf_id)) { 6695 /* ignore __rcu tag and mark it MEM_RCU */ 6696 flag |= MEM_RCU; 6697 } else if (flag & MEM_RCU || 6698 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6699 /* __rcu tagged pointers can be NULL */ 6700 flag |= MEM_RCU | PTR_MAYBE_NULL; 6701 6702 /* We always trust them */ 6703 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6704 flag & PTR_UNTRUSTED) 6705 flag &= ~PTR_UNTRUSTED; 6706 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6707 /* keep as-is */ 6708 } else { 6709 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6710 clear_trusted_flags(&flag); 6711 } 6712 } else { 6713 /* 6714 * If not in RCU CS or MEM_RCU pointer can be NULL then 6715 * aggressively mark as untrusted otherwise such 6716 * pointers will be plain PTR_TO_BTF_ID without flags 6717 * and will be allowed to be passed into helpers for 6718 * compat reasons. 6719 */ 6720 flag = PTR_UNTRUSTED; 6721 } 6722 } else { 6723 /* Old compat. Deprecated */ 6724 clear_trusted_flags(&flag); 6725 } 6726 6727 if (atype == BPF_READ && value_regno >= 0) 6728 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6729 6730 return 0; 6731 } 6732 6733 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6734 struct bpf_reg_state *regs, 6735 int regno, int off, int size, 6736 enum bpf_access_type atype, 6737 int value_regno) 6738 { 6739 struct bpf_reg_state *reg = regs + regno; 6740 struct bpf_map *map = reg->map_ptr; 6741 struct bpf_reg_state map_reg; 6742 enum bpf_type_flag flag = 0; 6743 const struct btf_type *t; 6744 const char *tname; 6745 u32 btf_id; 6746 int ret; 6747 6748 if (!btf_vmlinux) { 6749 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6750 return -ENOTSUPP; 6751 } 6752 6753 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6754 verbose(env, "map_ptr access not supported for map type %d\n", 6755 map->map_type); 6756 return -ENOTSUPP; 6757 } 6758 6759 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6760 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6761 6762 if (!env->allow_ptr_leaks) { 6763 verbose(env, 6764 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6765 tname); 6766 return -EPERM; 6767 } 6768 6769 if (off < 0) { 6770 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6771 regno, tname, off); 6772 return -EACCES; 6773 } 6774 6775 if (atype != BPF_READ) { 6776 verbose(env, "only read from %s is supported\n", tname); 6777 return -EACCES; 6778 } 6779 6780 /* Simulate access to a PTR_TO_BTF_ID */ 6781 memset(&map_reg, 0, sizeof(map_reg)); 6782 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6783 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6784 if (ret < 0) 6785 return ret; 6786 6787 if (value_regno >= 0) 6788 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6789 6790 return 0; 6791 } 6792 6793 /* Check that the stack access at the given offset is within bounds. The 6794 * maximum valid offset is -1. 6795 * 6796 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6797 * -state->allocated_stack for reads. 6798 */ 6799 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 6800 s64 off, 6801 struct bpf_func_state *state, 6802 enum bpf_access_type t) 6803 { 6804 struct bpf_insn_aux_data *aux = &env->insn_aux_data[env->insn_idx]; 6805 int min_valid_off, max_bpf_stack; 6806 6807 /* If accessing instruction is a spill/fill from bpf_fastcall pattern, 6808 * add room for all caller saved registers below MAX_BPF_STACK. 6809 * In case if bpf_fastcall rewrite won't happen maximal stack depth 6810 * would be checked by check_max_stack_depth_subprog(). 6811 */ 6812 max_bpf_stack = MAX_BPF_STACK; 6813 if (aux->fastcall_pattern) 6814 max_bpf_stack += CALLER_SAVED_REGS * BPF_REG_SIZE; 6815 6816 if (t == BPF_WRITE || env->allow_uninit_stack) 6817 min_valid_off = -max_bpf_stack; 6818 else 6819 min_valid_off = -state->allocated_stack; 6820 6821 if (off < min_valid_off || off > -1) 6822 return -EACCES; 6823 return 0; 6824 } 6825 6826 /* Check that the stack access at 'regno + off' falls within the maximum stack 6827 * bounds. 6828 * 6829 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6830 */ 6831 static int check_stack_access_within_bounds( 6832 struct bpf_verifier_env *env, 6833 int regno, int off, int access_size, 6834 enum bpf_access_src src, enum bpf_access_type type) 6835 { 6836 struct bpf_reg_state *regs = cur_regs(env); 6837 struct bpf_reg_state *reg = regs + regno; 6838 struct bpf_func_state *state = func(env, reg); 6839 s64 min_off, max_off; 6840 int err; 6841 char *err_extra; 6842 6843 if (src == ACCESS_HELPER) 6844 /* We don't know if helpers are reading or writing (or both). */ 6845 err_extra = " indirect access to"; 6846 else if (type == BPF_READ) 6847 err_extra = " read from"; 6848 else 6849 err_extra = " write to"; 6850 6851 if (tnum_is_const(reg->var_off)) { 6852 min_off = (s64)reg->var_off.value + off; 6853 max_off = min_off + access_size; 6854 } else { 6855 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6856 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6857 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6858 err_extra, regno); 6859 return -EACCES; 6860 } 6861 min_off = reg->smin_value + off; 6862 max_off = reg->smax_value + off + access_size; 6863 } 6864 6865 err = check_stack_slot_within_bounds(env, min_off, state, type); 6866 if (!err && max_off > 0) 6867 err = -EINVAL; /* out of stack access into non-negative offsets */ 6868 if (!err && access_size < 0) 6869 /* access_size should not be negative (or overflow an int); others checks 6870 * along the way should have prevented such an access. 6871 */ 6872 err = -EFAULT; /* invalid negative access size; integer overflow? */ 6873 6874 if (err) { 6875 if (tnum_is_const(reg->var_off)) { 6876 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 6877 err_extra, regno, off, access_size); 6878 } else { 6879 char tn_buf[48]; 6880 6881 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6882 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n", 6883 err_extra, regno, tn_buf, off, access_size); 6884 } 6885 return err; 6886 } 6887 6888 /* Note that there is no stack access with offset zero, so the needed stack 6889 * size is -min_off, not -min_off+1. 6890 */ 6891 return grow_stack_state(env, state, -min_off /* size */); 6892 } 6893 6894 static bool get_func_retval_range(struct bpf_prog *prog, 6895 struct bpf_retval_range *range) 6896 { 6897 if (prog->type == BPF_PROG_TYPE_LSM && 6898 prog->expected_attach_type == BPF_LSM_MAC && 6899 !bpf_lsm_get_retval_range(prog, range)) { 6900 return true; 6901 } 6902 return false; 6903 } 6904 6905 /* check whether memory at (regno + off) is accessible for t = (read | write) 6906 * if t==write, value_regno is a register which value is stored into memory 6907 * if t==read, value_regno is a register which will receive the value from memory 6908 * if t==write && value_regno==-1, some unknown value is stored into memory 6909 * if t==read && value_regno==-1, don't care what we read from memory 6910 */ 6911 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6912 int off, int bpf_size, enum bpf_access_type t, 6913 int value_regno, bool strict_alignment_once, bool is_ldsx) 6914 { 6915 struct bpf_reg_state *regs = cur_regs(env); 6916 struct bpf_reg_state *reg = regs + regno; 6917 int size, err = 0; 6918 6919 size = bpf_size_to_bytes(bpf_size); 6920 if (size < 0) 6921 return size; 6922 6923 /* alignment checks will add in reg->off themselves */ 6924 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6925 if (err) 6926 return err; 6927 6928 /* for access checks, reg->off is just part of off */ 6929 off += reg->off; 6930 6931 if (reg->type == PTR_TO_MAP_KEY) { 6932 if (t == BPF_WRITE) { 6933 verbose(env, "write to change key R%d not allowed\n", regno); 6934 return -EACCES; 6935 } 6936 6937 err = check_mem_region_access(env, regno, off, size, 6938 reg->map_ptr->key_size, false); 6939 if (err) 6940 return err; 6941 if (value_regno >= 0) 6942 mark_reg_unknown(env, regs, value_regno); 6943 } else if (reg->type == PTR_TO_MAP_VALUE) { 6944 struct btf_field *kptr_field = NULL; 6945 6946 if (t == BPF_WRITE && value_regno >= 0 && 6947 is_pointer_value(env, value_regno)) { 6948 verbose(env, "R%d leaks addr into map\n", value_regno); 6949 return -EACCES; 6950 } 6951 err = check_map_access_type(env, regno, off, size, t); 6952 if (err) 6953 return err; 6954 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6955 if (err) 6956 return err; 6957 if (tnum_is_const(reg->var_off)) 6958 kptr_field = btf_record_find(reg->map_ptr->record, 6959 off + reg->var_off.value, BPF_KPTR); 6960 if (kptr_field) { 6961 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6962 } else if (t == BPF_READ && value_regno >= 0) { 6963 struct bpf_map *map = reg->map_ptr; 6964 6965 /* if map is read-only, track its contents as scalars */ 6966 if (tnum_is_const(reg->var_off) && 6967 bpf_map_is_rdonly(map) && 6968 map->ops->map_direct_value_addr) { 6969 int map_off = off + reg->var_off.value; 6970 u64 val = 0; 6971 6972 err = bpf_map_direct_read(map, map_off, size, 6973 &val, is_ldsx); 6974 if (err) 6975 return err; 6976 6977 regs[value_regno].type = SCALAR_VALUE; 6978 __mark_reg_known(®s[value_regno], val); 6979 } else { 6980 mark_reg_unknown(env, regs, value_regno); 6981 } 6982 } 6983 } else if (base_type(reg->type) == PTR_TO_MEM) { 6984 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6985 6986 if (type_may_be_null(reg->type)) { 6987 verbose(env, "R%d invalid mem access '%s'\n", regno, 6988 reg_type_str(env, reg->type)); 6989 return -EACCES; 6990 } 6991 6992 if (t == BPF_WRITE && rdonly_mem) { 6993 verbose(env, "R%d cannot write into %s\n", 6994 regno, reg_type_str(env, reg->type)); 6995 return -EACCES; 6996 } 6997 6998 if (t == BPF_WRITE && value_regno >= 0 && 6999 is_pointer_value(env, value_regno)) { 7000 verbose(env, "R%d leaks addr into mem\n", value_regno); 7001 return -EACCES; 7002 } 7003 7004 err = check_mem_region_access(env, regno, off, size, 7005 reg->mem_size, false); 7006 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 7007 mark_reg_unknown(env, regs, value_regno); 7008 } else if (reg->type == PTR_TO_CTX) { 7009 bool is_retval = false; 7010 struct bpf_retval_range range; 7011 enum bpf_reg_type reg_type = SCALAR_VALUE; 7012 struct btf *btf = NULL; 7013 u32 btf_id = 0; 7014 7015 if (t == BPF_WRITE && value_regno >= 0 && 7016 is_pointer_value(env, value_regno)) { 7017 verbose(env, "R%d leaks addr into ctx\n", value_regno); 7018 return -EACCES; 7019 } 7020 7021 err = check_ptr_off_reg(env, reg, regno); 7022 if (err < 0) 7023 return err; 7024 7025 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 7026 &btf_id, &is_retval, is_ldsx); 7027 if (err) 7028 verbose_linfo(env, insn_idx, "; "); 7029 if (!err && t == BPF_READ && value_regno >= 0) { 7030 /* ctx access returns either a scalar, or a 7031 * PTR_TO_PACKET[_META,_END]. In the latter 7032 * case, we know the offset is zero. 7033 */ 7034 if (reg_type == SCALAR_VALUE) { 7035 if (is_retval && get_func_retval_range(env->prog, &range)) { 7036 err = __mark_reg_s32_range(env, regs, value_regno, 7037 range.minval, range.maxval); 7038 if (err) 7039 return err; 7040 } else { 7041 mark_reg_unknown(env, regs, value_regno); 7042 } 7043 } else { 7044 mark_reg_known_zero(env, regs, 7045 value_regno); 7046 if (type_may_be_null(reg_type)) 7047 regs[value_regno].id = ++env->id_gen; 7048 /* A load of ctx field could have different 7049 * actual load size with the one encoded in the 7050 * insn. When the dst is PTR, it is for sure not 7051 * a sub-register. 7052 */ 7053 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 7054 if (base_type(reg_type) == PTR_TO_BTF_ID) { 7055 regs[value_regno].btf = btf; 7056 regs[value_regno].btf_id = btf_id; 7057 } 7058 } 7059 regs[value_regno].type = reg_type; 7060 } 7061 7062 } else if (reg->type == PTR_TO_STACK) { 7063 /* Basic bounds checks. */ 7064 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 7065 if (err) 7066 return err; 7067 7068 if (t == BPF_READ) 7069 err = check_stack_read(env, regno, off, size, 7070 value_regno); 7071 else 7072 err = check_stack_write(env, regno, off, size, 7073 value_regno, insn_idx); 7074 } else if (reg_is_pkt_pointer(reg)) { 7075 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 7076 verbose(env, "cannot write into packet\n"); 7077 return -EACCES; 7078 } 7079 if (t == BPF_WRITE && value_regno >= 0 && 7080 is_pointer_value(env, value_regno)) { 7081 verbose(env, "R%d leaks addr into packet\n", 7082 value_regno); 7083 return -EACCES; 7084 } 7085 err = check_packet_access(env, regno, off, size, false); 7086 if (!err && t == BPF_READ && value_regno >= 0) 7087 mark_reg_unknown(env, regs, value_regno); 7088 } else if (reg->type == PTR_TO_FLOW_KEYS) { 7089 if (t == BPF_WRITE && value_regno >= 0 && 7090 is_pointer_value(env, value_regno)) { 7091 verbose(env, "R%d leaks addr into flow keys\n", 7092 value_regno); 7093 return -EACCES; 7094 } 7095 7096 err = check_flow_keys_access(env, off, size); 7097 if (!err && t == BPF_READ && value_regno >= 0) 7098 mark_reg_unknown(env, regs, value_regno); 7099 } else if (type_is_sk_pointer(reg->type)) { 7100 if (t == BPF_WRITE) { 7101 verbose(env, "R%d cannot write into %s\n", 7102 regno, reg_type_str(env, reg->type)); 7103 return -EACCES; 7104 } 7105 err = check_sock_access(env, insn_idx, regno, off, size, t); 7106 if (!err && value_regno >= 0) 7107 mark_reg_unknown(env, regs, value_regno); 7108 } else if (reg->type == PTR_TO_TP_BUFFER) { 7109 err = check_tp_buffer_access(env, reg, regno, off, size); 7110 if (!err && t == BPF_READ && value_regno >= 0) 7111 mark_reg_unknown(env, regs, value_regno); 7112 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 7113 !type_may_be_null(reg->type)) { 7114 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 7115 value_regno); 7116 } else if (reg->type == CONST_PTR_TO_MAP) { 7117 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 7118 value_regno); 7119 } else if (base_type(reg->type) == PTR_TO_BUF) { 7120 bool rdonly_mem = type_is_rdonly_mem(reg->type); 7121 u32 *max_access; 7122 7123 if (rdonly_mem) { 7124 if (t == BPF_WRITE) { 7125 verbose(env, "R%d cannot write into %s\n", 7126 regno, reg_type_str(env, reg->type)); 7127 return -EACCES; 7128 } 7129 max_access = &env->prog->aux->max_rdonly_access; 7130 } else { 7131 max_access = &env->prog->aux->max_rdwr_access; 7132 } 7133 7134 err = check_buffer_access(env, reg, regno, off, size, false, 7135 max_access); 7136 7137 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 7138 mark_reg_unknown(env, regs, value_regno); 7139 } else if (reg->type == PTR_TO_ARENA) { 7140 if (t == BPF_READ && value_regno >= 0) 7141 mark_reg_unknown(env, regs, value_regno); 7142 } else { 7143 verbose(env, "R%d invalid mem access '%s'\n", regno, 7144 reg_type_str(env, reg->type)); 7145 return -EACCES; 7146 } 7147 7148 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 7149 regs[value_regno].type == SCALAR_VALUE) { 7150 if (!is_ldsx) 7151 /* b/h/w load zero-extends, mark upper bits as known 0 */ 7152 coerce_reg_to_size(®s[value_regno], size); 7153 else 7154 coerce_reg_to_size_sx(®s[value_regno], size); 7155 } 7156 return err; 7157 } 7158 7159 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 7160 bool allow_trust_mismatch); 7161 7162 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 7163 { 7164 int load_reg; 7165 int err; 7166 7167 switch (insn->imm) { 7168 case BPF_ADD: 7169 case BPF_ADD | BPF_FETCH: 7170 case BPF_AND: 7171 case BPF_AND | BPF_FETCH: 7172 case BPF_OR: 7173 case BPF_OR | BPF_FETCH: 7174 case BPF_XOR: 7175 case BPF_XOR | BPF_FETCH: 7176 case BPF_XCHG: 7177 case BPF_CMPXCHG: 7178 break; 7179 default: 7180 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 7181 return -EINVAL; 7182 } 7183 7184 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 7185 verbose(env, "invalid atomic operand size\n"); 7186 return -EINVAL; 7187 } 7188 7189 /* check src1 operand */ 7190 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7191 if (err) 7192 return err; 7193 7194 /* check src2 operand */ 7195 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 7196 if (err) 7197 return err; 7198 7199 if (insn->imm == BPF_CMPXCHG) { 7200 /* Check comparison of R0 with memory location */ 7201 const u32 aux_reg = BPF_REG_0; 7202 7203 err = check_reg_arg(env, aux_reg, SRC_OP); 7204 if (err) 7205 return err; 7206 7207 if (is_pointer_value(env, aux_reg)) { 7208 verbose(env, "R%d leaks addr into mem\n", aux_reg); 7209 return -EACCES; 7210 } 7211 } 7212 7213 if (is_pointer_value(env, insn->src_reg)) { 7214 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 7215 return -EACCES; 7216 } 7217 7218 if (is_ctx_reg(env, insn->dst_reg) || 7219 is_pkt_reg(env, insn->dst_reg) || 7220 is_flow_key_reg(env, insn->dst_reg) || 7221 is_sk_reg(env, insn->dst_reg) || 7222 (is_arena_reg(env, insn->dst_reg) && !bpf_jit_supports_insn(insn, true))) { 7223 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 7224 insn->dst_reg, 7225 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 7226 return -EACCES; 7227 } 7228 7229 if (insn->imm & BPF_FETCH) { 7230 if (insn->imm == BPF_CMPXCHG) 7231 load_reg = BPF_REG_0; 7232 else 7233 load_reg = insn->src_reg; 7234 7235 /* check and record load of old value */ 7236 err = check_reg_arg(env, load_reg, DST_OP); 7237 if (err) 7238 return err; 7239 } else { 7240 /* This instruction accesses a memory location but doesn't 7241 * actually load it into a register. 7242 */ 7243 load_reg = -1; 7244 } 7245 7246 /* Check whether we can read the memory, with second call for fetch 7247 * case to simulate the register fill. 7248 */ 7249 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7250 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 7251 if (!err && load_reg >= 0) 7252 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7253 BPF_SIZE(insn->code), BPF_READ, load_reg, 7254 true, false); 7255 if (err) 7256 return err; 7257 7258 if (is_arena_reg(env, insn->dst_reg)) { 7259 err = save_aux_ptr_type(env, PTR_TO_ARENA, false); 7260 if (err) 7261 return err; 7262 } 7263 /* Check whether we can write into the same memory. */ 7264 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7265 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 7266 if (err) 7267 return err; 7268 return 0; 7269 } 7270 7271 /* When register 'regno' is used to read the stack (either directly or through 7272 * a helper function) make sure that it's within stack boundary and, depending 7273 * on the access type and privileges, that all elements of the stack are 7274 * initialized. 7275 * 7276 * 'off' includes 'regno->off', but not its dynamic part (if any). 7277 * 7278 * All registers that have been spilled on the stack in the slots within the 7279 * read offsets are marked as read. 7280 */ 7281 static int check_stack_range_initialized( 7282 struct bpf_verifier_env *env, int regno, int off, 7283 int access_size, bool zero_size_allowed, 7284 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 7285 { 7286 struct bpf_reg_state *reg = reg_state(env, regno); 7287 struct bpf_func_state *state = func(env, reg); 7288 int err, min_off, max_off, i, j, slot, spi; 7289 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 7290 enum bpf_access_type bounds_check_type; 7291 /* Some accesses can write anything into the stack, others are 7292 * read-only. 7293 */ 7294 bool clobber = false; 7295 7296 if (access_size == 0 && !zero_size_allowed) { 7297 verbose(env, "invalid zero-sized read\n"); 7298 return -EACCES; 7299 } 7300 7301 if (type == ACCESS_HELPER) { 7302 /* The bounds checks for writes are more permissive than for 7303 * reads. However, if raw_mode is not set, we'll do extra 7304 * checks below. 7305 */ 7306 bounds_check_type = BPF_WRITE; 7307 clobber = true; 7308 } else { 7309 bounds_check_type = BPF_READ; 7310 } 7311 err = check_stack_access_within_bounds(env, regno, off, access_size, 7312 type, bounds_check_type); 7313 if (err) 7314 return err; 7315 7316 7317 if (tnum_is_const(reg->var_off)) { 7318 min_off = max_off = reg->var_off.value + off; 7319 } else { 7320 /* Variable offset is prohibited for unprivileged mode for 7321 * simplicity since it requires corresponding support in 7322 * Spectre masking for stack ALU. 7323 * See also retrieve_ptr_limit(). 7324 */ 7325 if (!env->bypass_spec_v1) { 7326 char tn_buf[48]; 7327 7328 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7329 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 7330 regno, err_extra, tn_buf); 7331 return -EACCES; 7332 } 7333 /* Only initialized buffer on stack is allowed to be accessed 7334 * with variable offset. With uninitialized buffer it's hard to 7335 * guarantee that whole memory is marked as initialized on 7336 * helper return since specific bounds are unknown what may 7337 * cause uninitialized stack leaking. 7338 */ 7339 if (meta && meta->raw_mode) 7340 meta = NULL; 7341 7342 min_off = reg->smin_value + off; 7343 max_off = reg->smax_value + off; 7344 } 7345 7346 if (meta && meta->raw_mode) { 7347 /* Ensure we won't be overwriting dynptrs when simulating byte 7348 * by byte access in check_helper_call using meta.access_size. 7349 * This would be a problem if we have a helper in the future 7350 * which takes: 7351 * 7352 * helper(uninit_mem, len, dynptr) 7353 * 7354 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 7355 * may end up writing to dynptr itself when touching memory from 7356 * arg 1. This can be relaxed on a case by case basis for known 7357 * safe cases, but reject due to the possibilitiy of aliasing by 7358 * default. 7359 */ 7360 for (i = min_off; i < max_off + access_size; i++) { 7361 int stack_off = -i - 1; 7362 7363 spi = __get_spi(i); 7364 /* raw_mode may write past allocated_stack */ 7365 if (state->allocated_stack <= stack_off) 7366 continue; 7367 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 7368 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 7369 return -EACCES; 7370 } 7371 } 7372 meta->access_size = access_size; 7373 meta->regno = regno; 7374 return 0; 7375 } 7376 7377 for (i = min_off; i < max_off + access_size; i++) { 7378 u8 *stype; 7379 7380 slot = -i - 1; 7381 spi = slot / BPF_REG_SIZE; 7382 if (state->allocated_stack <= slot) { 7383 verbose(env, "verifier bug: allocated_stack too small"); 7384 return -EFAULT; 7385 } 7386 7387 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 7388 if (*stype == STACK_MISC) 7389 goto mark; 7390 if ((*stype == STACK_ZERO) || 7391 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 7392 if (clobber) { 7393 /* helper can write anything into the stack */ 7394 *stype = STACK_MISC; 7395 } 7396 goto mark; 7397 } 7398 7399 if (is_spilled_reg(&state->stack[spi]) && 7400 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 7401 env->allow_ptr_leaks)) { 7402 if (clobber) { 7403 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 7404 for (j = 0; j < BPF_REG_SIZE; j++) 7405 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 7406 } 7407 goto mark; 7408 } 7409 7410 if (tnum_is_const(reg->var_off)) { 7411 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 7412 err_extra, regno, min_off, i - min_off, access_size); 7413 } else { 7414 char tn_buf[48]; 7415 7416 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7417 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 7418 err_extra, regno, tn_buf, i - min_off, access_size); 7419 } 7420 return -EACCES; 7421 mark: 7422 /* reading any byte out of 8-byte 'spill_slot' will cause 7423 * the whole slot to be marked as 'read' 7424 */ 7425 mark_reg_read(env, &state->stack[spi].spilled_ptr, 7426 state->stack[spi].spilled_ptr.parent, 7427 REG_LIVE_READ64); 7428 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 7429 * be sure that whether stack slot is written to or not. Hence, 7430 * we must still conservatively propagate reads upwards even if 7431 * helper may write to the entire memory range. 7432 */ 7433 } 7434 return 0; 7435 } 7436 7437 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 7438 int access_size, bool zero_size_allowed, 7439 struct bpf_call_arg_meta *meta) 7440 { 7441 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7442 u32 *max_access; 7443 7444 switch (base_type(reg->type)) { 7445 case PTR_TO_PACKET: 7446 case PTR_TO_PACKET_META: 7447 return check_packet_access(env, regno, reg->off, access_size, 7448 zero_size_allowed); 7449 case PTR_TO_MAP_KEY: 7450 if (meta && meta->raw_mode) { 7451 verbose(env, "R%d cannot write into %s\n", regno, 7452 reg_type_str(env, reg->type)); 7453 return -EACCES; 7454 } 7455 return check_mem_region_access(env, regno, reg->off, access_size, 7456 reg->map_ptr->key_size, false); 7457 case PTR_TO_MAP_VALUE: 7458 if (check_map_access_type(env, regno, reg->off, access_size, 7459 meta && meta->raw_mode ? BPF_WRITE : 7460 BPF_READ)) 7461 return -EACCES; 7462 return check_map_access(env, regno, reg->off, access_size, 7463 zero_size_allowed, ACCESS_HELPER); 7464 case PTR_TO_MEM: 7465 if (type_is_rdonly_mem(reg->type)) { 7466 if (meta && meta->raw_mode) { 7467 verbose(env, "R%d cannot write into %s\n", regno, 7468 reg_type_str(env, reg->type)); 7469 return -EACCES; 7470 } 7471 } 7472 return check_mem_region_access(env, regno, reg->off, 7473 access_size, reg->mem_size, 7474 zero_size_allowed); 7475 case PTR_TO_BUF: 7476 if (type_is_rdonly_mem(reg->type)) { 7477 if (meta && meta->raw_mode) { 7478 verbose(env, "R%d cannot write into %s\n", regno, 7479 reg_type_str(env, reg->type)); 7480 return -EACCES; 7481 } 7482 7483 max_access = &env->prog->aux->max_rdonly_access; 7484 } else { 7485 max_access = &env->prog->aux->max_rdwr_access; 7486 } 7487 return check_buffer_access(env, reg, regno, reg->off, 7488 access_size, zero_size_allowed, 7489 max_access); 7490 case PTR_TO_STACK: 7491 return check_stack_range_initialized( 7492 env, 7493 regno, reg->off, access_size, 7494 zero_size_allowed, ACCESS_HELPER, meta); 7495 case PTR_TO_BTF_ID: 7496 return check_ptr_to_btf_access(env, regs, regno, reg->off, 7497 access_size, BPF_READ, -1); 7498 case PTR_TO_CTX: 7499 /* in case the function doesn't know how to access the context, 7500 * (because we are in a program of type SYSCALL for example), we 7501 * can not statically check its size. 7502 * Dynamically check it now. 7503 */ 7504 if (!env->ops->convert_ctx_access) { 7505 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 7506 int offset = access_size - 1; 7507 7508 /* Allow zero-byte read from PTR_TO_CTX */ 7509 if (access_size == 0) 7510 return zero_size_allowed ? 0 : -EACCES; 7511 7512 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 7513 atype, -1, false, false); 7514 } 7515 7516 fallthrough; 7517 default: /* scalar_value or invalid ptr */ 7518 /* Allow zero-byte read from NULL, regardless of pointer type */ 7519 if (zero_size_allowed && access_size == 0 && 7520 register_is_null(reg)) 7521 return 0; 7522 7523 verbose(env, "R%d type=%s ", regno, 7524 reg_type_str(env, reg->type)); 7525 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7526 return -EACCES; 7527 } 7528 } 7529 7530 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 7531 * size. 7532 * 7533 * @regno is the register containing the access size. regno-1 is the register 7534 * containing the pointer. 7535 */ 7536 static int check_mem_size_reg(struct bpf_verifier_env *env, 7537 struct bpf_reg_state *reg, u32 regno, 7538 bool zero_size_allowed, 7539 struct bpf_call_arg_meta *meta) 7540 { 7541 int err; 7542 7543 /* This is used to refine r0 return value bounds for helpers 7544 * that enforce this value as an upper bound on return values. 7545 * See do_refine_retval_range() for helpers that can refine 7546 * the return value. C type of helper is u32 so we pull register 7547 * bound from umax_value however, if negative verifier errors 7548 * out. Only upper bounds can be learned because retval is an 7549 * int type and negative retvals are allowed. 7550 */ 7551 meta->msize_max_value = reg->umax_value; 7552 7553 /* The register is SCALAR_VALUE; the access check 7554 * happens using its boundaries. 7555 */ 7556 if (!tnum_is_const(reg->var_off)) 7557 /* For unprivileged variable accesses, disable raw 7558 * mode so that the program is required to 7559 * initialize all the memory that the helper could 7560 * just partially fill up. 7561 */ 7562 meta = NULL; 7563 7564 if (reg->smin_value < 0) { 7565 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7566 regno); 7567 return -EACCES; 7568 } 7569 7570 if (reg->umin_value == 0 && !zero_size_allowed) { 7571 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n", 7572 regno, reg->umin_value, reg->umax_value); 7573 return -EACCES; 7574 } 7575 7576 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7577 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7578 regno); 7579 return -EACCES; 7580 } 7581 err = check_helper_mem_access(env, regno - 1, 7582 reg->umax_value, 7583 zero_size_allowed, meta); 7584 if (!err) 7585 err = mark_chain_precision(env, regno); 7586 return err; 7587 } 7588 7589 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7590 u32 regno, u32 mem_size) 7591 { 7592 bool may_be_null = type_may_be_null(reg->type); 7593 struct bpf_reg_state saved_reg; 7594 struct bpf_call_arg_meta meta; 7595 int err; 7596 7597 if (register_is_null(reg)) 7598 return 0; 7599 7600 memset(&meta, 0, sizeof(meta)); 7601 /* Assuming that the register contains a value check if the memory 7602 * access is safe. Temporarily save and restore the register's state as 7603 * the conversion shouldn't be visible to a caller. 7604 */ 7605 if (may_be_null) { 7606 saved_reg = *reg; 7607 mark_ptr_not_null_reg(reg); 7608 } 7609 7610 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 7611 /* Check access for BPF_WRITE */ 7612 meta.raw_mode = true; 7613 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 7614 7615 if (may_be_null) 7616 *reg = saved_reg; 7617 7618 return err; 7619 } 7620 7621 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7622 u32 regno) 7623 { 7624 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7625 bool may_be_null = type_may_be_null(mem_reg->type); 7626 struct bpf_reg_state saved_reg; 7627 struct bpf_call_arg_meta meta; 7628 int err; 7629 7630 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7631 7632 memset(&meta, 0, sizeof(meta)); 7633 7634 if (may_be_null) { 7635 saved_reg = *mem_reg; 7636 mark_ptr_not_null_reg(mem_reg); 7637 } 7638 7639 err = check_mem_size_reg(env, reg, regno, true, &meta); 7640 /* Check access for BPF_WRITE */ 7641 meta.raw_mode = true; 7642 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 7643 7644 if (may_be_null) 7645 *mem_reg = saved_reg; 7646 return err; 7647 } 7648 7649 /* Implementation details: 7650 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7651 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7652 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7653 * Two separate bpf_obj_new will also have different reg->id. 7654 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7655 * clears reg->id after value_or_null->value transition, since the verifier only 7656 * cares about the range of access to valid map value pointer and doesn't care 7657 * about actual address of the map element. 7658 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7659 * reg->id > 0 after value_or_null->value transition. By doing so 7660 * two bpf_map_lookups will be considered two different pointers that 7661 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7662 * returned from bpf_obj_new. 7663 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7664 * dead-locks. 7665 * Since only one bpf_spin_lock is allowed the checks are simpler than 7666 * reg_is_refcounted() logic. The verifier needs to remember only 7667 * one spin_lock instead of array of acquired_refs. 7668 * cur_state->active_lock remembers which map value element or allocated 7669 * object got locked and clears it after bpf_spin_unlock. 7670 */ 7671 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 7672 bool is_lock) 7673 { 7674 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7675 struct bpf_verifier_state *cur = env->cur_state; 7676 bool is_const = tnum_is_const(reg->var_off); 7677 u64 val = reg->var_off.value; 7678 struct bpf_map *map = NULL; 7679 struct btf *btf = NULL; 7680 struct btf_record *rec; 7681 7682 if (!is_const) { 7683 verbose(env, 7684 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 7685 regno); 7686 return -EINVAL; 7687 } 7688 if (reg->type == PTR_TO_MAP_VALUE) { 7689 map = reg->map_ptr; 7690 if (!map->btf) { 7691 verbose(env, 7692 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 7693 map->name); 7694 return -EINVAL; 7695 } 7696 } else { 7697 btf = reg->btf; 7698 } 7699 7700 rec = reg_btf_record(reg); 7701 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 7702 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 7703 map ? map->name : "kptr"); 7704 return -EINVAL; 7705 } 7706 if (rec->spin_lock_off != val + reg->off) { 7707 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 7708 val + reg->off, rec->spin_lock_off); 7709 return -EINVAL; 7710 } 7711 if (is_lock) { 7712 if (cur->active_lock.ptr) { 7713 verbose(env, 7714 "Locking two bpf_spin_locks are not allowed\n"); 7715 return -EINVAL; 7716 } 7717 if (map) 7718 cur->active_lock.ptr = map; 7719 else 7720 cur->active_lock.ptr = btf; 7721 cur->active_lock.id = reg->id; 7722 } else { 7723 void *ptr; 7724 7725 if (map) 7726 ptr = map; 7727 else 7728 ptr = btf; 7729 7730 if (!cur->active_lock.ptr) { 7731 verbose(env, "bpf_spin_unlock without taking a lock\n"); 7732 return -EINVAL; 7733 } 7734 if (cur->active_lock.ptr != ptr || 7735 cur->active_lock.id != reg->id) { 7736 verbose(env, "bpf_spin_unlock of different lock\n"); 7737 return -EINVAL; 7738 } 7739 7740 invalidate_non_owning_refs(env); 7741 7742 cur->active_lock.ptr = NULL; 7743 cur->active_lock.id = 0; 7744 } 7745 return 0; 7746 } 7747 7748 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7749 struct bpf_call_arg_meta *meta) 7750 { 7751 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7752 bool is_const = tnum_is_const(reg->var_off); 7753 struct bpf_map *map = reg->map_ptr; 7754 u64 val = reg->var_off.value; 7755 7756 if (!is_const) { 7757 verbose(env, 7758 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 7759 regno); 7760 return -EINVAL; 7761 } 7762 if (!map->btf) { 7763 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 7764 map->name); 7765 return -EINVAL; 7766 } 7767 if (!btf_record_has_field(map->record, BPF_TIMER)) { 7768 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 7769 return -EINVAL; 7770 } 7771 if (map->record->timer_off != val + reg->off) { 7772 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 7773 val + reg->off, map->record->timer_off); 7774 return -EINVAL; 7775 } 7776 if (meta->map_ptr) { 7777 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 7778 return -EFAULT; 7779 } 7780 meta->map_uid = reg->map_uid; 7781 meta->map_ptr = map; 7782 return 0; 7783 } 7784 7785 static int process_wq_func(struct bpf_verifier_env *env, int regno, 7786 struct bpf_kfunc_call_arg_meta *meta) 7787 { 7788 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7789 struct bpf_map *map = reg->map_ptr; 7790 u64 val = reg->var_off.value; 7791 7792 if (map->record->wq_off != val + reg->off) { 7793 verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n", 7794 val + reg->off, map->record->wq_off); 7795 return -EINVAL; 7796 } 7797 meta->map.uid = reg->map_uid; 7798 meta->map.ptr = map; 7799 return 0; 7800 } 7801 7802 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7803 struct bpf_call_arg_meta *meta) 7804 { 7805 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7806 struct btf_field *kptr_field; 7807 struct bpf_map *map_ptr; 7808 struct btf_record *rec; 7809 u32 kptr_off; 7810 7811 if (type_is_ptr_alloc_obj(reg->type)) { 7812 rec = reg_btf_record(reg); 7813 } else { /* PTR_TO_MAP_VALUE */ 7814 map_ptr = reg->map_ptr; 7815 if (!map_ptr->btf) { 7816 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7817 map_ptr->name); 7818 return -EINVAL; 7819 } 7820 rec = map_ptr->record; 7821 meta->map_ptr = map_ptr; 7822 } 7823 7824 if (!tnum_is_const(reg->var_off)) { 7825 verbose(env, 7826 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7827 regno); 7828 return -EINVAL; 7829 } 7830 7831 if (!btf_record_has_field(rec, BPF_KPTR)) { 7832 verbose(env, "R%d has no valid kptr\n", regno); 7833 return -EINVAL; 7834 } 7835 7836 kptr_off = reg->off + reg->var_off.value; 7837 kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR); 7838 if (!kptr_field) { 7839 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7840 return -EACCES; 7841 } 7842 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7843 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7844 return -EACCES; 7845 } 7846 meta->kptr_field = kptr_field; 7847 return 0; 7848 } 7849 7850 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7851 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7852 * 7853 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7854 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7855 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7856 * 7857 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7858 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7859 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7860 * mutate the view of the dynptr and also possibly destroy it. In the latter 7861 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7862 * memory that dynptr points to. 7863 * 7864 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7865 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7866 * readonly dynptr view yet, hence only the first case is tracked and checked. 7867 * 7868 * This is consistent with how C applies the const modifier to a struct object, 7869 * where the pointer itself inside bpf_dynptr becomes const but not what it 7870 * points to. 7871 * 7872 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7873 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7874 */ 7875 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7876 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7877 { 7878 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7879 int err; 7880 7881 if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) { 7882 verbose(env, 7883 "arg#%d expected pointer to stack or const struct bpf_dynptr\n", 7884 regno); 7885 return -EINVAL; 7886 } 7887 7888 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7889 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7890 */ 7891 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7892 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 7893 return -EFAULT; 7894 } 7895 7896 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7897 * constructing a mutable bpf_dynptr object. 7898 * 7899 * Currently, this is only possible with PTR_TO_STACK 7900 * pointing to a region of at least 16 bytes which doesn't 7901 * contain an existing bpf_dynptr. 7902 * 7903 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7904 * mutated or destroyed. However, the memory it points to 7905 * may be mutated. 7906 * 7907 * None - Points to a initialized dynptr that can be mutated and 7908 * destroyed, including mutation of the memory it points 7909 * to. 7910 */ 7911 if (arg_type & MEM_UNINIT) { 7912 int i; 7913 7914 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7915 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7916 return -EINVAL; 7917 } 7918 7919 /* we write BPF_DW bits (8 bytes) at a time */ 7920 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7921 err = check_mem_access(env, insn_idx, regno, 7922 i, BPF_DW, BPF_WRITE, -1, false, false); 7923 if (err) 7924 return err; 7925 } 7926 7927 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7928 } else /* MEM_RDONLY and None case from above */ { 7929 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7930 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7931 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7932 return -EINVAL; 7933 } 7934 7935 if (!is_dynptr_reg_valid_init(env, reg)) { 7936 verbose(env, 7937 "Expected an initialized dynptr as arg #%d\n", 7938 regno); 7939 return -EINVAL; 7940 } 7941 7942 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7943 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7944 verbose(env, 7945 "Expected a dynptr of type %s as arg #%d\n", 7946 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 7947 return -EINVAL; 7948 } 7949 7950 err = mark_dynptr_read(env, reg); 7951 } 7952 return err; 7953 } 7954 7955 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7956 { 7957 struct bpf_func_state *state = func(env, reg); 7958 7959 return state->stack[spi].spilled_ptr.ref_obj_id; 7960 } 7961 7962 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7963 { 7964 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7965 } 7966 7967 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7968 { 7969 return meta->kfunc_flags & KF_ITER_NEW; 7970 } 7971 7972 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7973 { 7974 return meta->kfunc_flags & KF_ITER_NEXT; 7975 } 7976 7977 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7978 { 7979 return meta->kfunc_flags & KF_ITER_DESTROY; 7980 } 7981 7982 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx, 7983 const struct btf_param *arg) 7984 { 7985 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7986 * kfunc is iter state pointer 7987 */ 7988 if (is_iter_kfunc(meta)) 7989 return arg_idx == 0; 7990 7991 /* iter passed as an argument to a generic kfunc */ 7992 return btf_param_match_suffix(meta->btf, arg, "__iter"); 7993 } 7994 7995 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7996 struct bpf_kfunc_call_arg_meta *meta) 7997 { 7998 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7999 const struct btf_type *t; 8000 int spi, err, i, nr_slots, btf_id; 8001 8002 /* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs() 8003 * ensures struct convention, so we wouldn't need to do any BTF 8004 * validation here. But given iter state can be passed as a parameter 8005 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more 8006 * conservative here. 8007 */ 8008 btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1); 8009 if (btf_id < 0) { 8010 verbose(env, "expected valid iter pointer as arg #%d\n", regno); 8011 return -EINVAL; 8012 } 8013 t = btf_type_by_id(meta->btf, btf_id); 8014 nr_slots = t->size / BPF_REG_SIZE; 8015 8016 if (is_iter_new_kfunc(meta)) { 8017 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 8018 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 8019 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 8020 iter_type_str(meta->btf, btf_id), regno); 8021 return -EINVAL; 8022 } 8023 8024 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 8025 err = check_mem_access(env, insn_idx, regno, 8026 i, BPF_DW, BPF_WRITE, -1, false, false); 8027 if (err) 8028 return err; 8029 } 8030 8031 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 8032 if (err) 8033 return err; 8034 } else { 8035 /* iter_next() or iter_destroy(), as well as any kfunc 8036 * accepting iter argument, expect initialized iter state 8037 */ 8038 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 8039 switch (err) { 8040 case 0: 8041 break; 8042 case -EINVAL: 8043 verbose(env, "expected an initialized iter_%s as arg #%d\n", 8044 iter_type_str(meta->btf, btf_id), regno); 8045 return err; 8046 case -EPROTO: 8047 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 8048 return err; 8049 default: 8050 return err; 8051 } 8052 8053 spi = iter_get_spi(env, reg, nr_slots); 8054 if (spi < 0) 8055 return spi; 8056 8057 err = mark_iter_read(env, reg, spi, nr_slots); 8058 if (err) 8059 return err; 8060 8061 /* remember meta->iter info for process_iter_next_call() */ 8062 meta->iter.spi = spi; 8063 meta->iter.frameno = reg->frameno; 8064 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 8065 8066 if (is_iter_destroy_kfunc(meta)) { 8067 err = unmark_stack_slots_iter(env, reg, nr_slots); 8068 if (err) 8069 return err; 8070 } 8071 } 8072 8073 return 0; 8074 } 8075 8076 /* Look for a previous loop entry at insn_idx: nearest parent state 8077 * stopped at insn_idx with callsites matching those in cur->frame. 8078 */ 8079 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 8080 struct bpf_verifier_state *cur, 8081 int insn_idx) 8082 { 8083 struct bpf_verifier_state_list *sl; 8084 struct bpf_verifier_state *st; 8085 8086 /* Explored states are pushed in stack order, most recent states come first */ 8087 sl = *explored_state(env, insn_idx); 8088 for (; sl; sl = sl->next) { 8089 /* If st->branches != 0 state is a part of current DFS verification path, 8090 * hence cur & st for a loop. 8091 */ 8092 st = &sl->state; 8093 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 8094 st->dfs_depth < cur->dfs_depth) 8095 return st; 8096 } 8097 8098 return NULL; 8099 } 8100 8101 static void reset_idmap_scratch(struct bpf_verifier_env *env); 8102 static bool regs_exact(const struct bpf_reg_state *rold, 8103 const struct bpf_reg_state *rcur, 8104 struct bpf_idmap *idmap); 8105 8106 static void maybe_widen_reg(struct bpf_verifier_env *env, 8107 struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 8108 struct bpf_idmap *idmap) 8109 { 8110 if (rold->type != SCALAR_VALUE) 8111 return; 8112 if (rold->type != rcur->type) 8113 return; 8114 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap)) 8115 return; 8116 __mark_reg_unknown(env, rcur); 8117 } 8118 8119 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 8120 struct bpf_verifier_state *old, 8121 struct bpf_verifier_state *cur) 8122 { 8123 struct bpf_func_state *fold, *fcur; 8124 int i, fr; 8125 8126 reset_idmap_scratch(env); 8127 for (fr = old->curframe; fr >= 0; fr--) { 8128 fold = old->frame[fr]; 8129 fcur = cur->frame[fr]; 8130 8131 for (i = 0; i < MAX_BPF_REG; i++) 8132 maybe_widen_reg(env, 8133 &fold->regs[i], 8134 &fcur->regs[i], 8135 &env->idmap_scratch); 8136 8137 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) { 8138 if (!is_spilled_reg(&fold->stack[i]) || 8139 !is_spilled_reg(&fcur->stack[i])) 8140 continue; 8141 8142 maybe_widen_reg(env, 8143 &fold->stack[i].spilled_ptr, 8144 &fcur->stack[i].spilled_ptr, 8145 &env->idmap_scratch); 8146 } 8147 } 8148 return 0; 8149 } 8150 8151 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st, 8152 struct bpf_kfunc_call_arg_meta *meta) 8153 { 8154 int iter_frameno = meta->iter.frameno; 8155 int iter_spi = meta->iter.spi; 8156 8157 return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 8158 } 8159 8160 /* process_iter_next_call() is called when verifier gets to iterator's next 8161 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 8162 * to it as just "iter_next()" in comments below. 8163 * 8164 * BPF verifier relies on a crucial contract for any iter_next() 8165 * implementation: it should *eventually* return NULL, and once that happens 8166 * it should keep returning NULL. That is, once iterator exhausts elements to 8167 * iterate, it should never reset or spuriously return new elements. 8168 * 8169 * With the assumption of such contract, process_iter_next_call() simulates 8170 * a fork in the verifier state to validate loop logic correctness and safety 8171 * without having to simulate infinite amount of iterations. 8172 * 8173 * In current state, we first assume that iter_next() returned NULL and 8174 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 8175 * conditions we should not form an infinite loop and should eventually reach 8176 * exit. 8177 * 8178 * Besides that, we also fork current state and enqueue it for later 8179 * verification. In a forked state we keep iterator state as ACTIVE 8180 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 8181 * also bump iteration depth to prevent erroneous infinite loop detection 8182 * later on (see iter_active_depths_differ() comment for details). In this 8183 * state we assume that we'll eventually loop back to another iter_next() 8184 * calls (it could be in exactly same location or in some other instruction, 8185 * it doesn't matter, we don't make any unnecessary assumptions about this, 8186 * everything revolves around iterator state in a stack slot, not which 8187 * instruction is calling iter_next()). When that happens, we either will come 8188 * to iter_next() with equivalent state and can conclude that next iteration 8189 * will proceed in exactly the same way as we just verified, so it's safe to 8190 * assume that loop converges. If not, we'll go on another iteration 8191 * simulation with a different input state, until all possible starting states 8192 * are validated or we reach maximum number of instructions limit. 8193 * 8194 * This way, we will either exhaustively discover all possible input states 8195 * that iterator loop can start with and eventually will converge, or we'll 8196 * effectively regress into bounded loop simulation logic and either reach 8197 * maximum number of instructions if loop is not provably convergent, or there 8198 * is some statically known limit on number of iterations (e.g., if there is 8199 * an explicit `if n > 100 then break;` statement somewhere in the loop). 8200 * 8201 * Iteration convergence logic in is_state_visited() relies on exact 8202 * states comparison, which ignores read and precision marks. 8203 * This is necessary because read and precision marks are not finalized 8204 * while in the loop. Exact comparison might preclude convergence for 8205 * simple programs like below: 8206 * 8207 * i = 0; 8208 * while(iter_next(&it)) 8209 * i++; 8210 * 8211 * At each iteration step i++ would produce a new distinct state and 8212 * eventually instruction processing limit would be reached. 8213 * 8214 * To avoid such behavior speculatively forget (widen) range for 8215 * imprecise scalar registers, if those registers were not precise at the 8216 * end of the previous iteration and do not match exactly. 8217 * 8218 * This is a conservative heuristic that allows to verify wide range of programs, 8219 * however it precludes verification of programs that conjure an 8220 * imprecise value on the first loop iteration and use it as precise on a second. 8221 * For example, the following safe program would fail to verify: 8222 * 8223 * struct bpf_num_iter it; 8224 * int arr[10]; 8225 * int i = 0, a = 0; 8226 * bpf_iter_num_new(&it, 0, 10); 8227 * while (bpf_iter_num_next(&it)) { 8228 * if (a == 0) { 8229 * a = 1; 8230 * i = 7; // Because i changed verifier would forget 8231 * // it's range on second loop entry. 8232 * } else { 8233 * arr[i] = 42; // This would fail to verify. 8234 * } 8235 * } 8236 * bpf_iter_num_destroy(&it); 8237 */ 8238 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 8239 struct bpf_kfunc_call_arg_meta *meta) 8240 { 8241 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 8242 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 8243 struct bpf_reg_state *cur_iter, *queued_iter; 8244 8245 BTF_TYPE_EMIT(struct bpf_iter); 8246 8247 cur_iter = get_iter_from_state(cur_st, meta); 8248 8249 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 8250 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 8251 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 8252 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 8253 return -EFAULT; 8254 } 8255 8256 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 8257 /* Because iter_next() call is a checkpoint is_state_visitied() 8258 * should guarantee parent state with same call sites and insn_idx. 8259 */ 8260 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 8261 !same_callsites(cur_st->parent, cur_st)) { 8262 verbose(env, "bug: bad parent state for iter next call"); 8263 return -EFAULT; 8264 } 8265 /* Note cur_st->parent in the call below, it is necessary to skip 8266 * checkpoint created for cur_st by is_state_visited() 8267 * right at this instruction. 8268 */ 8269 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 8270 /* branch out active iter state */ 8271 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 8272 if (!queued_st) 8273 return -ENOMEM; 8274 8275 queued_iter = get_iter_from_state(queued_st, meta); 8276 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 8277 queued_iter->iter.depth++; 8278 if (prev_st) 8279 widen_imprecise_scalars(env, prev_st, queued_st); 8280 8281 queued_fr = queued_st->frame[queued_st->curframe]; 8282 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 8283 } 8284 8285 /* switch to DRAINED state, but keep the depth unchanged */ 8286 /* mark current iter state as drained and assume returned NULL */ 8287 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 8288 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 8289 8290 return 0; 8291 } 8292 8293 static bool arg_type_is_mem_size(enum bpf_arg_type type) 8294 { 8295 return type == ARG_CONST_SIZE || 8296 type == ARG_CONST_SIZE_OR_ZERO; 8297 } 8298 8299 static bool arg_type_is_release(enum bpf_arg_type type) 8300 { 8301 return type & OBJ_RELEASE; 8302 } 8303 8304 static bool arg_type_is_dynptr(enum bpf_arg_type type) 8305 { 8306 return base_type(type) == ARG_PTR_TO_DYNPTR; 8307 } 8308 8309 static int int_ptr_type_to_size(enum bpf_arg_type type) 8310 { 8311 if (type == ARG_PTR_TO_INT) 8312 return sizeof(u32); 8313 else if (type == ARG_PTR_TO_LONG) 8314 return sizeof(u64); 8315 8316 return -EINVAL; 8317 } 8318 8319 static int resolve_map_arg_type(struct bpf_verifier_env *env, 8320 const struct bpf_call_arg_meta *meta, 8321 enum bpf_arg_type *arg_type) 8322 { 8323 if (!meta->map_ptr) { 8324 /* kernel subsystem misconfigured verifier */ 8325 verbose(env, "invalid map_ptr to access map->type\n"); 8326 return -EACCES; 8327 } 8328 8329 switch (meta->map_ptr->map_type) { 8330 case BPF_MAP_TYPE_SOCKMAP: 8331 case BPF_MAP_TYPE_SOCKHASH: 8332 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 8333 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 8334 } else { 8335 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 8336 return -EINVAL; 8337 } 8338 break; 8339 case BPF_MAP_TYPE_BLOOM_FILTER: 8340 if (meta->func_id == BPF_FUNC_map_peek_elem) 8341 *arg_type = ARG_PTR_TO_MAP_VALUE; 8342 break; 8343 default: 8344 break; 8345 } 8346 return 0; 8347 } 8348 8349 struct bpf_reg_types { 8350 const enum bpf_reg_type types[10]; 8351 u32 *btf_id; 8352 }; 8353 8354 static const struct bpf_reg_types sock_types = { 8355 .types = { 8356 PTR_TO_SOCK_COMMON, 8357 PTR_TO_SOCKET, 8358 PTR_TO_TCP_SOCK, 8359 PTR_TO_XDP_SOCK, 8360 }, 8361 }; 8362 8363 #ifdef CONFIG_NET 8364 static const struct bpf_reg_types btf_id_sock_common_types = { 8365 .types = { 8366 PTR_TO_SOCK_COMMON, 8367 PTR_TO_SOCKET, 8368 PTR_TO_TCP_SOCK, 8369 PTR_TO_XDP_SOCK, 8370 PTR_TO_BTF_ID, 8371 PTR_TO_BTF_ID | PTR_TRUSTED, 8372 }, 8373 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 8374 }; 8375 #endif 8376 8377 static const struct bpf_reg_types mem_types = { 8378 .types = { 8379 PTR_TO_STACK, 8380 PTR_TO_PACKET, 8381 PTR_TO_PACKET_META, 8382 PTR_TO_MAP_KEY, 8383 PTR_TO_MAP_VALUE, 8384 PTR_TO_MEM, 8385 PTR_TO_MEM | MEM_RINGBUF, 8386 PTR_TO_BUF, 8387 PTR_TO_BTF_ID | PTR_TRUSTED, 8388 }, 8389 }; 8390 8391 static const struct bpf_reg_types int_ptr_types = { 8392 .types = { 8393 PTR_TO_STACK, 8394 PTR_TO_PACKET, 8395 PTR_TO_PACKET_META, 8396 PTR_TO_MAP_KEY, 8397 PTR_TO_MAP_VALUE, 8398 }, 8399 }; 8400 8401 static const struct bpf_reg_types spin_lock_types = { 8402 .types = { 8403 PTR_TO_MAP_VALUE, 8404 PTR_TO_BTF_ID | MEM_ALLOC, 8405 } 8406 }; 8407 8408 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 8409 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 8410 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 8411 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 8412 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 8413 static const struct bpf_reg_types btf_ptr_types = { 8414 .types = { 8415 PTR_TO_BTF_ID, 8416 PTR_TO_BTF_ID | PTR_TRUSTED, 8417 PTR_TO_BTF_ID | MEM_RCU, 8418 }, 8419 }; 8420 static const struct bpf_reg_types percpu_btf_ptr_types = { 8421 .types = { 8422 PTR_TO_BTF_ID | MEM_PERCPU, 8423 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 8424 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 8425 } 8426 }; 8427 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 8428 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 8429 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8430 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 8431 static const struct bpf_reg_types kptr_xchg_dest_types = { 8432 .types = { 8433 PTR_TO_MAP_VALUE, 8434 PTR_TO_BTF_ID | MEM_ALLOC 8435 } 8436 }; 8437 static const struct bpf_reg_types dynptr_types = { 8438 .types = { 8439 PTR_TO_STACK, 8440 CONST_PTR_TO_DYNPTR, 8441 } 8442 }; 8443 8444 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 8445 [ARG_PTR_TO_MAP_KEY] = &mem_types, 8446 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 8447 [ARG_CONST_SIZE] = &scalar_types, 8448 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 8449 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 8450 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 8451 [ARG_PTR_TO_CTX] = &context_types, 8452 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 8453 #ifdef CONFIG_NET 8454 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 8455 #endif 8456 [ARG_PTR_TO_SOCKET] = &fullsock_types, 8457 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 8458 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 8459 [ARG_PTR_TO_MEM] = &mem_types, 8460 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 8461 [ARG_PTR_TO_INT] = &int_ptr_types, 8462 [ARG_PTR_TO_LONG] = &int_ptr_types, 8463 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 8464 [ARG_PTR_TO_FUNC] = &func_ptr_types, 8465 [ARG_PTR_TO_STACK] = &stack_ptr_types, 8466 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 8467 [ARG_PTR_TO_TIMER] = &timer_types, 8468 [ARG_KPTR_XCHG_DEST] = &kptr_xchg_dest_types, 8469 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 8470 }; 8471 8472 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 8473 enum bpf_arg_type arg_type, 8474 const u32 *arg_btf_id, 8475 struct bpf_call_arg_meta *meta) 8476 { 8477 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8478 enum bpf_reg_type expected, type = reg->type; 8479 const struct bpf_reg_types *compatible; 8480 int i, j; 8481 8482 compatible = compatible_reg_types[base_type(arg_type)]; 8483 if (!compatible) { 8484 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 8485 return -EFAULT; 8486 } 8487 8488 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 8489 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 8490 * 8491 * Same for MAYBE_NULL: 8492 * 8493 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 8494 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 8495 * 8496 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 8497 * 8498 * Therefore we fold these flags depending on the arg_type before comparison. 8499 */ 8500 if (arg_type & MEM_RDONLY) 8501 type &= ~MEM_RDONLY; 8502 if (arg_type & PTR_MAYBE_NULL) 8503 type &= ~PTR_MAYBE_NULL; 8504 if (base_type(arg_type) == ARG_PTR_TO_MEM) 8505 type &= ~DYNPTR_TYPE_FLAG_MASK; 8506 8507 /* Local kptr types are allowed as the source argument of bpf_kptr_xchg */ 8508 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) { 8509 type &= ~MEM_ALLOC; 8510 type &= ~MEM_PERCPU; 8511 } 8512 8513 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 8514 expected = compatible->types[i]; 8515 if (expected == NOT_INIT) 8516 break; 8517 8518 if (type == expected) 8519 goto found; 8520 } 8521 8522 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 8523 for (j = 0; j + 1 < i; j++) 8524 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 8525 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 8526 return -EACCES; 8527 8528 found: 8529 if (base_type(reg->type) != PTR_TO_BTF_ID) 8530 return 0; 8531 8532 if (compatible == &mem_types) { 8533 if (!(arg_type & MEM_RDONLY)) { 8534 verbose(env, 8535 "%s() may write into memory pointed by R%d type=%s\n", 8536 func_id_name(meta->func_id), 8537 regno, reg_type_str(env, reg->type)); 8538 return -EACCES; 8539 } 8540 return 0; 8541 } 8542 8543 switch ((int)reg->type) { 8544 case PTR_TO_BTF_ID: 8545 case PTR_TO_BTF_ID | PTR_TRUSTED: 8546 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL: 8547 case PTR_TO_BTF_ID | MEM_RCU: 8548 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 8549 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 8550 { 8551 /* For bpf_sk_release, it needs to match against first member 8552 * 'struct sock_common', hence make an exception for it. This 8553 * allows bpf_sk_release to work for multiple socket types. 8554 */ 8555 bool strict_type_match = arg_type_is_release(arg_type) && 8556 meta->func_id != BPF_FUNC_sk_release; 8557 8558 if (type_may_be_null(reg->type) && 8559 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 8560 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 8561 return -EACCES; 8562 } 8563 8564 if (!arg_btf_id) { 8565 if (!compatible->btf_id) { 8566 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 8567 return -EFAULT; 8568 } 8569 arg_btf_id = compatible->btf_id; 8570 } 8571 8572 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8573 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8574 return -EACCES; 8575 } else { 8576 if (arg_btf_id == BPF_PTR_POISON) { 8577 verbose(env, "verifier internal error:"); 8578 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 8579 regno); 8580 return -EACCES; 8581 } 8582 8583 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 8584 btf_vmlinux, *arg_btf_id, 8585 strict_type_match)) { 8586 verbose(env, "R%d is of type %s but %s is expected\n", 8587 regno, btf_type_name(reg->btf, reg->btf_id), 8588 btf_type_name(btf_vmlinux, *arg_btf_id)); 8589 return -EACCES; 8590 } 8591 } 8592 break; 8593 } 8594 case PTR_TO_BTF_ID | MEM_ALLOC: 8595 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 8596 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8597 meta->func_id != BPF_FUNC_kptr_xchg) { 8598 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 8599 return -EFAULT; 8600 } 8601 /* Check if local kptr in src arg matches kptr in dst arg */ 8602 if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) { 8603 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8604 return -EACCES; 8605 } 8606 break; 8607 case PTR_TO_BTF_ID | MEM_PERCPU: 8608 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 8609 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8610 /* Handled by helper specific checks */ 8611 break; 8612 default: 8613 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 8614 return -EFAULT; 8615 } 8616 return 0; 8617 } 8618 8619 static struct btf_field * 8620 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8621 { 8622 struct btf_field *field; 8623 struct btf_record *rec; 8624 8625 rec = reg_btf_record(reg); 8626 if (!rec) 8627 return NULL; 8628 8629 field = btf_record_find(rec, off, fields); 8630 if (!field) 8631 return NULL; 8632 8633 return field; 8634 } 8635 8636 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 8637 const struct bpf_reg_state *reg, int regno, 8638 enum bpf_arg_type arg_type) 8639 { 8640 u32 type = reg->type; 8641 8642 /* When referenced register is passed to release function, its fixed 8643 * offset must be 0. 8644 * 8645 * We will check arg_type_is_release reg has ref_obj_id when storing 8646 * meta->release_regno. 8647 */ 8648 if (arg_type_is_release(arg_type)) { 8649 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8650 * may not directly point to the object being released, but to 8651 * dynptr pointing to such object, which might be at some offset 8652 * on the stack. In that case, we simply to fallback to the 8653 * default handling. 8654 */ 8655 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8656 return 0; 8657 8658 /* Doing check_ptr_off_reg check for the offset will catch this 8659 * because fixed_off_ok is false, but checking here allows us 8660 * to give the user a better error message. 8661 */ 8662 if (reg->off) { 8663 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 8664 regno); 8665 return -EINVAL; 8666 } 8667 return __check_ptr_off_reg(env, reg, regno, false); 8668 } 8669 8670 switch (type) { 8671 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8672 case PTR_TO_STACK: 8673 case PTR_TO_PACKET: 8674 case PTR_TO_PACKET_META: 8675 case PTR_TO_MAP_KEY: 8676 case PTR_TO_MAP_VALUE: 8677 case PTR_TO_MEM: 8678 case PTR_TO_MEM | MEM_RDONLY: 8679 case PTR_TO_MEM | MEM_RINGBUF: 8680 case PTR_TO_BUF: 8681 case PTR_TO_BUF | MEM_RDONLY: 8682 case PTR_TO_ARENA: 8683 case SCALAR_VALUE: 8684 return 0; 8685 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8686 * fixed offset. 8687 */ 8688 case PTR_TO_BTF_ID: 8689 case PTR_TO_BTF_ID | MEM_ALLOC: 8690 case PTR_TO_BTF_ID | PTR_TRUSTED: 8691 case PTR_TO_BTF_ID | MEM_RCU: 8692 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8693 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8694 /* When referenced PTR_TO_BTF_ID is passed to release function, 8695 * its fixed offset must be 0. In the other cases, fixed offset 8696 * can be non-zero. This was already checked above. So pass 8697 * fixed_off_ok as true to allow fixed offset for all other 8698 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8699 * still need to do checks instead of returning. 8700 */ 8701 return __check_ptr_off_reg(env, reg, regno, true); 8702 default: 8703 return __check_ptr_off_reg(env, reg, regno, false); 8704 } 8705 } 8706 8707 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8708 const struct bpf_func_proto *fn, 8709 struct bpf_reg_state *regs) 8710 { 8711 struct bpf_reg_state *state = NULL; 8712 int i; 8713 8714 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8715 if (arg_type_is_dynptr(fn->arg_type[i])) { 8716 if (state) { 8717 verbose(env, "verifier internal error: multiple dynptr args\n"); 8718 return NULL; 8719 } 8720 state = ®s[BPF_REG_1 + i]; 8721 } 8722 8723 if (!state) 8724 verbose(env, "verifier internal error: no dynptr arg found\n"); 8725 8726 return state; 8727 } 8728 8729 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8730 { 8731 struct bpf_func_state *state = func(env, reg); 8732 int spi; 8733 8734 if (reg->type == CONST_PTR_TO_DYNPTR) 8735 return reg->id; 8736 spi = dynptr_get_spi(env, reg); 8737 if (spi < 0) 8738 return spi; 8739 return state->stack[spi].spilled_ptr.id; 8740 } 8741 8742 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8743 { 8744 struct bpf_func_state *state = func(env, reg); 8745 int spi; 8746 8747 if (reg->type == CONST_PTR_TO_DYNPTR) 8748 return reg->ref_obj_id; 8749 spi = dynptr_get_spi(env, reg); 8750 if (spi < 0) 8751 return spi; 8752 return state->stack[spi].spilled_ptr.ref_obj_id; 8753 } 8754 8755 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8756 struct bpf_reg_state *reg) 8757 { 8758 struct bpf_func_state *state = func(env, reg); 8759 int spi; 8760 8761 if (reg->type == CONST_PTR_TO_DYNPTR) 8762 return reg->dynptr.type; 8763 8764 spi = __get_spi(reg->off); 8765 if (spi < 0) { 8766 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8767 return BPF_DYNPTR_TYPE_INVALID; 8768 } 8769 8770 return state->stack[spi].spilled_ptr.dynptr.type; 8771 } 8772 8773 static int check_reg_const_str(struct bpf_verifier_env *env, 8774 struct bpf_reg_state *reg, u32 regno) 8775 { 8776 struct bpf_map *map = reg->map_ptr; 8777 int err; 8778 int map_off; 8779 u64 map_addr; 8780 char *str_ptr; 8781 8782 if (reg->type != PTR_TO_MAP_VALUE) 8783 return -EINVAL; 8784 8785 if (!bpf_map_is_rdonly(map)) { 8786 verbose(env, "R%d does not point to a readonly map'\n", regno); 8787 return -EACCES; 8788 } 8789 8790 if (!tnum_is_const(reg->var_off)) { 8791 verbose(env, "R%d is not a constant address'\n", regno); 8792 return -EACCES; 8793 } 8794 8795 if (!map->ops->map_direct_value_addr) { 8796 verbose(env, "no direct value access support for this map type\n"); 8797 return -EACCES; 8798 } 8799 8800 err = check_map_access(env, regno, reg->off, 8801 map->value_size - reg->off, false, 8802 ACCESS_HELPER); 8803 if (err) 8804 return err; 8805 8806 map_off = reg->off + reg->var_off.value; 8807 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8808 if (err) { 8809 verbose(env, "direct value access on string failed\n"); 8810 return err; 8811 } 8812 8813 str_ptr = (char *)(long)(map_addr); 8814 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8815 verbose(env, "string is not zero-terminated\n"); 8816 return -EINVAL; 8817 } 8818 return 0; 8819 } 8820 8821 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8822 struct bpf_call_arg_meta *meta, 8823 const struct bpf_func_proto *fn, 8824 int insn_idx) 8825 { 8826 u32 regno = BPF_REG_1 + arg; 8827 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8828 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8829 enum bpf_reg_type type = reg->type; 8830 u32 *arg_btf_id = NULL; 8831 int err = 0; 8832 8833 if (arg_type == ARG_DONTCARE) 8834 return 0; 8835 8836 err = check_reg_arg(env, regno, SRC_OP); 8837 if (err) 8838 return err; 8839 8840 if (arg_type == ARG_ANYTHING) { 8841 if (is_pointer_value(env, regno)) { 8842 verbose(env, "R%d leaks addr into helper function\n", 8843 regno); 8844 return -EACCES; 8845 } 8846 return 0; 8847 } 8848 8849 if (type_is_pkt_pointer(type) && 8850 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8851 verbose(env, "helper access to the packet is not allowed\n"); 8852 return -EACCES; 8853 } 8854 8855 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8856 err = resolve_map_arg_type(env, meta, &arg_type); 8857 if (err) 8858 return err; 8859 } 8860 8861 if (register_is_null(reg) && type_may_be_null(arg_type)) 8862 /* A NULL register has a SCALAR_VALUE type, so skip 8863 * type checking. 8864 */ 8865 goto skip_type_check; 8866 8867 /* arg_btf_id and arg_size are in a union. */ 8868 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8869 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8870 arg_btf_id = fn->arg_btf_id[arg]; 8871 8872 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 8873 if (err) 8874 return err; 8875 8876 err = check_func_arg_reg_off(env, reg, regno, arg_type); 8877 if (err) 8878 return err; 8879 8880 skip_type_check: 8881 if (arg_type_is_release(arg_type)) { 8882 if (arg_type_is_dynptr(arg_type)) { 8883 struct bpf_func_state *state = func(env, reg); 8884 int spi; 8885 8886 /* Only dynptr created on stack can be released, thus 8887 * the get_spi and stack state checks for spilled_ptr 8888 * should only be done before process_dynptr_func for 8889 * PTR_TO_STACK. 8890 */ 8891 if (reg->type == PTR_TO_STACK) { 8892 spi = dynptr_get_spi(env, reg); 8893 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8894 verbose(env, "arg %d is an unacquired reference\n", regno); 8895 return -EINVAL; 8896 } 8897 } else { 8898 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8899 return -EINVAL; 8900 } 8901 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 8902 verbose(env, "R%d must be referenced when passed to release function\n", 8903 regno); 8904 return -EINVAL; 8905 } 8906 if (meta->release_regno) { 8907 verbose(env, "verifier internal error: more than one release argument\n"); 8908 return -EFAULT; 8909 } 8910 meta->release_regno = regno; 8911 } 8912 8913 if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) { 8914 if (meta->ref_obj_id) { 8915 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 8916 regno, reg->ref_obj_id, 8917 meta->ref_obj_id); 8918 return -EFAULT; 8919 } 8920 meta->ref_obj_id = reg->ref_obj_id; 8921 } 8922 8923 switch (base_type(arg_type)) { 8924 case ARG_CONST_MAP_PTR: 8925 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8926 if (meta->map_ptr) { 8927 /* Use map_uid (which is unique id of inner map) to reject: 8928 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8929 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8930 * if (inner_map1 && inner_map2) { 8931 * timer = bpf_map_lookup_elem(inner_map1); 8932 * if (timer) 8933 * // mismatch would have been allowed 8934 * bpf_timer_init(timer, inner_map2); 8935 * } 8936 * 8937 * Comparing map_ptr is enough to distinguish normal and outer maps. 8938 */ 8939 if (meta->map_ptr != reg->map_ptr || 8940 meta->map_uid != reg->map_uid) { 8941 verbose(env, 8942 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8943 meta->map_uid, reg->map_uid); 8944 return -EINVAL; 8945 } 8946 } 8947 meta->map_ptr = reg->map_ptr; 8948 meta->map_uid = reg->map_uid; 8949 break; 8950 case ARG_PTR_TO_MAP_KEY: 8951 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8952 * check that [key, key + map->key_size) are within 8953 * stack limits and initialized 8954 */ 8955 if (!meta->map_ptr) { 8956 /* in function declaration map_ptr must come before 8957 * map_key, so that it's verified and known before 8958 * we have to check map_key here. Otherwise it means 8959 * that kernel subsystem misconfigured verifier 8960 */ 8961 verbose(env, "invalid map_ptr to access map->key\n"); 8962 return -EACCES; 8963 } 8964 err = check_helper_mem_access(env, regno, 8965 meta->map_ptr->key_size, false, 8966 NULL); 8967 break; 8968 case ARG_PTR_TO_MAP_VALUE: 8969 if (type_may_be_null(arg_type) && register_is_null(reg)) 8970 return 0; 8971 8972 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8973 * check [value, value + map->value_size) validity 8974 */ 8975 if (!meta->map_ptr) { 8976 /* kernel subsystem misconfigured verifier */ 8977 verbose(env, "invalid map_ptr to access map->value\n"); 8978 return -EACCES; 8979 } 8980 meta->raw_mode = arg_type & MEM_UNINIT; 8981 err = check_helper_mem_access(env, regno, 8982 meta->map_ptr->value_size, false, 8983 meta); 8984 break; 8985 case ARG_PTR_TO_PERCPU_BTF_ID: 8986 if (!reg->btf_id) { 8987 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8988 return -EACCES; 8989 } 8990 meta->ret_btf = reg->btf; 8991 meta->ret_btf_id = reg->btf_id; 8992 break; 8993 case ARG_PTR_TO_SPIN_LOCK: 8994 if (in_rbtree_lock_required_cb(env)) { 8995 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8996 return -EACCES; 8997 } 8998 if (meta->func_id == BPF_FUNC_spin_lock) { 8999 err = process_spin_lock(env, regno, true); 9000 if (err) 9001 return err; 9002 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 9003 err = process_spin_lock(env, regno, false); 9004 if (err) 9005 return err; 9006 } else { 9007 verbose(env, "verifier internal error\n"); 9008 return -EFAULT; 9009 } 9010 break; 9011 case ARG_PTR_TO_TIMER: 9012 err = process_timer_func(env, regno, meta); 9013 if (err) 9014 return err; 9015 break; 9016 case ARG_PTR_TO_FUNC: 9017 meta->subprogno = reg->subprogno; 9018 break; 9019 case ARG_PTR_TO_MEM: 9020 /* The access to this pointer is only checked when we hit the 9021 * next is_mem_size argument below. 9022 */ 9023 meta->raw_mode = arg_type & MEM_UNINIT; 9024 if (arg_type & MEM_FIXED_SIZE) { 9025 err = check_helper_mem_access(env, regno, 9026 fn->arg_size[arg], false, 9027 meta); 9028 } 9029 break; 9030 case ARG_CONST_SIZE: 9031 err = check_mem_size_reg(env, reg, regno, false, meta); 9032 break; 9033 case ARG_CONST_SIZE_OR_ZERO: 9034 err = check_mem_size_reg(env, reg, regno, true, meta); 9035 break; 9036 case ARG_PTR_TO_DYNPTR: 9037 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 9038 if (err) 9039 return err; 9040 break; 9041 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 9042 if (!tnum_is_const(reg->var_off)) { 9043 verbose(env, "R%d is not a known constant'\n", 9044 regno); 9045 return -EACCES; 9046 } 9047 meta->mem_size = reg->var_off.value; 9048 err = mark_chain_precision(env, regno); 9049 if (err) 9050 return err; 9051 break; 9052 case ARG_PTR_TO_INT: 9053 case ARG_PTR_TO_LONG: 9054 { 9055 int size = int_ptr_type_to_size(arg_type); 9056 9057 err = check_helper_mem_access(env, regno, size, false, meta); 9058 if (err) 9059 return err; 9060 err = check_ptr_alignment(env, reg, 0, size, true); 9061 break; 9062 } 9063 case ARG_PTR_TO_CONST_STR: 9064 { 9065 err = check_reg_const_str(env, reg, regno); 9066 if (err) 9067 return err; 9068 break; 9069 } 9070 case ARG_KPTR_XCHG_DEST: 9071 err = process_kptr_func(env, regno, meta); 9072 if (err) 9073 return err; 9074 break; 9075 } 9076 9077 return err; 9078 } 9079 9080 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 9081 { 9082 enum bpf_attach_type eatype = env->prog->expected_attach_type; 9083 enum bpf_prog_type type = resolve_prog_type(env->prog); 9084 9085 if (func_id != BPF_FUNC_map_update_elem && 9086 func_id != BPF_FUNC_map_delete_elem) 9087 return false; 9088 9089 /* It's not possible to get access to a locked struct sock in these 9090 * contexts, so updating is safe. 9091 */ 9092 switch (type) { 9093 case BPF_PROG_TYPE_TRACING: 9094 if (eatype == BPF_TRACE_ITER) 9095 return true; 9096 break; 9097 case BPF_PROG_TYPE_SOCK_OPS: 9098 /* map_update allowed only via dedicated helpers with event type checks */ 9099 if (func_id == BPF_FUNC_map_delete_elem) 9100 return true; 9101 break; 9102 case BPF_PROG_TYPE_SOCKET_FILTER: 9103 case BPF_PROG_TYPE_SCHED_CLS: 9104 case BPF_PROG_TYPE_SCHED_ACT: 9105 case BPF_PROG_TYPE_XDP: 9106 case BPF_PROG_TYPE_SK_REUSEPORT: 9107 case BPF_PROG_TYPE_FLOW_DISSECTOR: 9108 case BPF_PROG_TYPE_SK_LOOKUP: 9109 return true; 9110 default: 9111 break; 9112 } 9113 9114 verbose(env, "cannot update sockmap in this context\n"); 9115 return false; 9116 } 9117 9118 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 9119 { 9120 return env->prog->jit_requested && 9121 bpf_jit_supports_subprog_tailcalls(); 9122 } 9123 9124 static int check_map_func_compatibility(struct bpf_verifier_env *env, 9125 struct bpf_map *map, int func_id) 9126 { 9127 if (!map) 9128 return 0; 9129 9130 /* We need a two way check, first is from map perspective ... */ 9131 switch (map->map_type) { 9132 case BPF_MAP_TYPE_PROG_ARRAY: 9133 if (func_id != BPF_FUNC_tail_call) 9134 goto error; 9135 break; 9136 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 9137 if (func_id != BPF_FUNC_perf_event_read && 9138 func_id != BPF_FUNC_perf_event_output && 9139 func_id != BPF_FUNC_skb_output && 9140 func_id != BPF_FUNC_perf_event_read_value && 9141 func_id != BPF_FUNC_xdp_output) 9142 goto error; 9143 break; 9144 case BPF_MAP_TYPE_RINGBUF: 9145 if (func_id != BPF_FUNC_ringbuf_output && 9146 func_id != BPF_FUNC_ringbuf_reserve && 9147 func_id != BPF_FUNC_ringbuf_query && 9148 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 9149 func_id != BPF_FUNC_ringbuf_submit_dynptr && 9150 func_id != BPF_FUNC_ringbuf_discard_dynptr) 9151 goto error; 9152 break; 9153 case BPF_MAP_TYPE_USER_RINGBUF: 9154 if (func_id != BPF_FUNC_user_ringbuf_drain) 9155 goto error; 9156 break; 9157 case BPF_MAP_TYPE_STACK_TRACE: 9158 if (func_id != BPF_FUNC_get_stackid) 9159 goto error; 9160 break; 9161 case BPF_MAP_TYPE_CGROUP_ARRAY: 9162 if (func_id != BPF_FUNC_skb_under_cgroup && 9163 func_id != BPF_FUNC_current_task_under_cgroup) 9164 goto error; 9165 break; 9166 case BPF_MAP_TYPE_CGROUP_STORAGE: 9167 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 9168 if (func_id != BPF_FUNC_get_local_storage) 9169 goto error; 9170 break; 9171 case BPF_MAP_TYPE_DEVMAP: 9172 case BPF_MAP_TYPE_DEVMAP_HASH: 9173 if (func_id != BPF_FUNC_redirect_map && 9174 func_id != BPF_FUNC_map_lookup_elem) 9175 goto error; 9176 break; 9177 /* Restrict bpf side of cpumap and xskmap, open when use-cases 9178 * appear. 9179 */ 9180 case BPF_MAP_TYPE_CPUMAP: 9181 if (func_id != BPF_FUNC_redirect_map) 9182 goto error; 9183 break; 9184 case BPF_MAP_TYPE_XSKMAP: 9185 if (func_id != BPF_FUNC_redirect_map && 9186 func_id != BPF_FUNC_map_lookup_elem) 9187 goto error; 9188 break; 9189 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 9190 case BPF_MAP_TYPE_HASH_OF_MAPS: 9191 if (func_id != BPF_FUNC_map_lookup_elem) 9192 goto error; 9193 break; 9194 case BPF_MAP_TYPE_SOCKMAP: 9195 if (func_id != BPF_FUNC_sk_redirect_map && 9196 func_id != BPF_FUNC_sock_map_update && 9197 func_id != BPF_FUNC_msg_redirect_map && 9198 func_id != BPF_FUNC_sk_select_reuseport && 9199 func_id != BPF_FUNC_map_lookup_elem && 9200 !may_update_sockmap(env, func_id)) 9201 goto error; 9202 break; 9203 case BPF_MAP_TYPE_SOCKHASH: 9204 if (func_id != BPF_FUNC_sk_redirect_hash && 9205 func_id != BPF_FUNC_sock_hash_update && 9206 func_id != BPF_FUNC_msg_redirect_hash && 9207 func_id != BPF_FUNC_sk_select_reuseport && 9208 func_id != BPF_FUNC_map_lookup_elem && 9209 !may_update_sockmap(env, func_id)) 9210 goto error; 9211 break; 9212 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 9213 if (func_id != BPF_FUNC_sk_select_reuseport) 9214 goto error; 9215 break; 9216 case BPF_MAP_TYPE_QUEUE: 9217 case BPF_MAP_TYPE_STACK: 9218 if (func_id != BPF_FUNC_map_peek_elem && 9219 func_id != BPF_FUNC_map_pop_elem && 9220 func_id != BPF_FUNC_map_push_elem) 9221 goto error; 9222 break; 9223 case BPF_MAP_TYPE_SK_STORAGE: 9224 if (func_id != BPF_FUNC_sk_storage_get && 9225 func_id != BPF_FUNC_sk_storage_delete && 9226 func_id != BPF_FUNC_kptr_xchg) 9227 goto error; 9228 break; 9229 case BPF_MAP_TYPE_INODE_STORAGE: 9230 if (func_id != BPF_FUNC_inode_storage_get && 9231 func_id != BPF_FUNC_inode_storage_delete && 9232 func_id != BPF_FUNC_kptr_xchg) 9233 goto error; 9234 break; 9235 case BPF_MAP_TYPE_TASK_STORAGE: 9236 if (func_id != BPF_FUNC_task_storage_get && 9237 func_id != BPF_FUNC_task_storage_delete && 9238 func_id != BPF_FUNC_kptr_xchg) 9239 goto error; 9240 break; 9241 case BPF_MAP_TYPE_CGRP_STORAGE: 9242 if (func_id != BPF_FUNC_cgrp_storage_get && 9243 func_id != BPF_FUNC_cgrp_storage_delete && 9244 func_id != BPF_FUNC_kptr_xchg) 9245 goto error; 9246 break; 9247 case BPF_MAP_TYPE_BLOOM_FILTER: 9248 if (func_id != BPF_FUNC_map_peek_elem && 9249 func_id != BPF_FUNC_map_push_elem) 9250 goto error; 9251 break; 9252 default: 9253 break; 9254 } 9255 9256 /* ... and second from the function itself. */ 9257 switch (func_id) { 9258 case BPF_FUNC_tail_call: 9259 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 9260 goto error; 9261 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 9262 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 9263 return -EINVAL; 9264 } 9265 break; 9266 case BPF_FUNC_perf_event_read: 9267 case BPF_FUNC_perf_event_output: 9268 case BPF_FUNC_perf_event_read_value: 9269 case BPF_FUNC_skb_output: 9270 case BPF_FUNC_xdp_output: 9271 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 9272 goto error; 9273 break; 9274 case BPF_FUNC_ringbuf_output: 9275 case BPF_FUNC_ringbuf_reserve: 9276 case BPF_FUNC_ringbuf_query: 9277 case BPF_FUNC_ringbuf_reserve_dynptr: 9278 case BPF_FUNC_ringbuf_submit_dynptr: 9279 case BPF_FUNC_ringbuf_discard_dynptr: 9280 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 9281 goto error; 9282 break; 9283 case BPF_FUNC_user_ringbuf_drain: 9284 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 9285 goto error; 9286 break; 9287 case BPF_FUNC_get_stackid: 9288 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 9289 goto error; 9290 break; 9291 case BPF_FUNC_current_task_under_cgroup: 9292 case BPF_FUNC_skb_under_cgroup: 9293 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 9294 goto error; 9295 break; 9296 case BPF_FUNC_redirect_map: 9297 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 9298 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 9299 map->map_type != BPF_MAP_TYPE_CPUMAP && 9300 map->map_type != BPF_MAP_TYPE_XSKMAP) 9301 goto error; 9302 break; 9303 case BPF_FUNC_sk_redirect_map: 9304 case BPF_FUNC_msg_redirect_map: 9305 case BPF_FUNC_sock_map_update: 9306 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 9307 goto error; 9308 break; 9309 case BPF_FUNC_sk_redirect_hash: 9310 case BPF_FUNC_msg_redirect_hash: 9311 case BPF_FUNC_sock_hash_update: 9312 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 9313 goto error; 9314 break; 9315 case BPF_FUNC_get_local_storage: 9316 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 9317 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 9318 goto error; 9319 break; 9320 case BPF_FUNC_sk_select_reuseport: 9321 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 9322 map->map_type != BPF_MAP_TYPE_SOCKMAP && 9323 map->map_type != BPF_MAP_TYPE_SOCKHASH) 9324 goto error; 9325 break; 9326 case BPF_FUNC_map_pop_elem: 9327 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9328 map->map_type != BPF_MAP_TYPE_STACK) 9329 goto error; 9330 break; 9331 case BPF_FUNC_map_peek_elem: 9332 case BPF_FUNC_map_push_elem: 9333 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9334 map->map_type != BPF_MAP_TYPE_STACK && 9335 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 9336 goto error; 9337 break; 9338 case BPF_FUNC_map_lookup_percpu_elem: 9339 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 9340 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 9341 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 9342 goto error; 9343 break; 9344 case BPF_FUNC_sk_storage_get: 9345 case BPF_FUNC_sk_storage_delete: 9346 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 9347 goto error; 9348 break; 9349 case BPF_FUNC_inode_storage_get: 9350 case BPF_FUNC_inode_storage_delete: 9351 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 9352 goto error; 9353 break; 9354 case BPF_FUNC_task_storage_get: 9355 case BPF_FUNC_task_storage_delete: 9356 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 9357 goto error; 9358 break; 9359 case BPF_FUNC_cgrp_storage_get: 9360 case BPF_FUNC_cgrp_storage_delete: 9361 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 9362 goto error; 9363 break; 9364 default: 9365 break; 9366 } 9367 9368 return 0; 9369 error: 9370 verbose(env, "cannot pass map_type %d into func %s#%d\n", 9371 map->map_type, func_id_name(func_id), func_id); 9372 return -EINVAL; 9373 } 9374 9375 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 9376 { 9377 int count = 0; 9378 9379 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 9380 count++; 9381 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 9382 count++; 9383 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 9384 count++; 9385 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 9386 count++; 9387 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 9388 count++; 9389 9390 /* We only support one arg being in raw mode at the moment, 9391 * which is sufficient for the helper functions we have 9392 * right now. 9393 */ 9394 return count <= 1; 9395 } 9396 9397 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 9398 { 9399 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 9400 bool has_size = fn->arg_size[arg] != 0; 9401 bool is_next_size = false; 9402 9403 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 9404 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 9405 9406 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 9407 return is_next_size; 9408 9409 return has_size == is_next_size || is_next_size == is_fixed; 9410 } 9411 9412 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 9413 { 9414 /* bpf_xxx(..., buf, len) call will access 'len' 9415 * bytes from memory 'buf'. Both arg types need 9416 * to be paired, so make sure there's no buggy 9417 * helper function specification. 9418 */ 9419 if (arg_type_is_mem_size(fn->arg1_type) || 9420 check_args_pair_invalid(fn, 0) || 9421 check_args_pair_invalid(fn, 1) || 9422 check_args_pair_invalid(fn, 2) || 9423 check_args_pair_invalid(fn, 3) || 9424 check_args_pair_invalid(fn, 4)) 9425 return false; 9426 9427 return true; 9428 } 9429 9430 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 9431 { 9432 int i; 9433 9434 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 9435 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 9436 return !!fn->arg_btf_id[i]; 9437 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 9438 return fn->arg_btf_id[i] == BPF_PTR_POISON; 9439 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 9440 /* arg_btf_id and arg_size are in a union. */ 9441 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 9442 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 9443 return false; 9444 } 9445 9446 return true; 9447 } 9448 9449 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 9450 { 9451 return check_raw_mode_ok(fn) && 9452 check_arg_pair_ok(fn) && 9453 check_btf_id_ok(fn) ? 0 : -EINVAL; 9454 } 9455 9456 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 9457 * are now invalid, so turn them into unknown SCALAR_VALUE. 9458 * 9459 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 9460 * since these slices point to packet data. 9461 */ 9462 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 9463 { 9464 struct bpf_func_state *state; 9465 struct bpf_reg_state *reg; 9466 9467 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9468 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 9469 mark_reg_invalid(env, reg); 9470 })); 9471 } 9472 9473 enum { 9474 AT_PKT_END = -1, 9475 BEYOND_PKT_END = -2, 9476 }; 9477 9478 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 9479 { 9480 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9481 struct bpf_reg_state *reg = &state->regs[regn]; 9482 9483 if (reg->type != PTR_TO_PACKET) 9484 /* PTR_TO_PACKET_META is not supported yet */ 9485 return; 9486 9487 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 9488 * How far beyond pkt_end it goes is unknown. 9489 * if (!range_open) it's the case of pkt >= pkt_end 9490 * if (range_open) it's the case of pkt > pkt_end 9491 * hence this pointer is at least 1 byte bigger than pkt_end 9492 */ 9493 if (range_open) 9494 reg->range = BEYOND_PKT_END; 9495 else 9496 reg->range = AT_PKT_END; 9497 } 9498 9499 /* The pointer with the specified id has released its reference to kernel 9500 * resources. Identify all copies of the same pointer and clear the reference. 9501 */ 9502 static int release_reference(struct bpf_verifier_env *env, 9503 int ref_obj_id) 9504 { 9505 struct bpf_func_state *state; 9506 struct bpf_reg_state *reg; 9507 int err; 9508 9509 err = release_reference_state(cur_func(env), ref_obj_id); 9510 if (err) 9511 return err; 9512 9513 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9514 if (reg->ref_obj_id == ref_obj_id) 9515 mark_reg_invalid(env, reg); 9516 })); 9517 9518 return 0; 9519 } 9520 9521 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9522 { 9523 struct bpf_func_state *unused; 9524 struct bpf_reg_state *reg; 9525 9526 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9527 if (type_is_non_owning_ref(reg->type)) 9528 mark_reg_invalid(env, reg); 9529 })); 9530 } 9531 9532 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9533 struct bpf_reg_state *regs) 9534 { 9535 int i; 9536 9537 /* after the call registers r0 - r5 were scratched */ 9538 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9539 mark_reg_not_init(env, regs, caller_saved[i]); 9540 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9541 } 9542 } 9543 9544 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9545 struct bpf_func_state *caller, 9546 struct bpf_func_state *callee, 9547 int insn_idx); 9548 9549 static int set_callee_state(struct bpf_verifier_env *env, 9550 struct bpf_func_state *caller, 9551 struct bpf_func_state *callee, int insn_idx); 9552 9553 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9554 set_callee_state_fn set_callee_state_cb, 9555 struct bpf_verifier_state *state) 9556 { 9557 struct bpf_func_state *caller, *callee; 9558 int err; 9559 9560 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9561 verbose(env, "the call stack of %d frames is too deep\n", 9562 state->curframe + 2); 9563 return -E2BIG; 9564 } 9565 9566 if (state->frame[state->curframe + 1]) { 9567 verbose(env, "verifier bug. Frame %d already allocated\n", 9568 state->curframe + 1); 9569 return -EFAULT; 9570 } 9571 9572 caller = state->frame[state->curframe]; 9573 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 9574 if (!callee) 9575 return -ENOMEM; 9576 state->frame[state->curframe + 1] = callee; 9577 9578 /* callee cannot access r0, r6 - r9 for reading and has to write 9579 * into its own stack before reading from it. 9580 * callee can read/write into caller's stack 9581 */ 9582 init_func_state(env, callee, 9583 /* remember the callsite, it will be used by bpf_exit */ 9584 callsite, 9585 state->curframe + 1 /* frameno within this callchain */, 9586 subprog /* subprog number within this prog */); 9587 /* Transfer references to the callee */ 9588 err = copy_reference_state(callee, caller); 9589 err = err ?: set_callee_state_cb(env, caller, callee, callsite); 9590 if (err) 9591 goto err_out; 9592 9593 /* only increment it after check_reg_arg() finished */ 9594 state->curframe++; 9595 9596 return 0; 9597 9598 err_out: 9599 free_func_state(callee); 9600 state->frame[state->curframe + 1] = NULL; 9601 return err; 9602 } 9603 9604 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, 9605 const struct btf *btf, 9606 struct bpf_reg_state *regs) 9607 { 9608 struct bpf_subprog_info *sub = subprog_info(env, subprog); 9609 struct bpf_verifier_log *log = &env->log; 9610 u32 i; 9611 int ret; 9612 9613 ret = btf_prepare_func_args(env, subprog); 9614 if (ret) 9615 return ret; 9616 9617 /* check that BTF function arguments match actual types that the 9618 * verifier sees. 9619 */ 9620 for (i = 0; i < sub->arg_cnt; i++) { 9621 u32 regno = i + 1; 9622 struct bpf_reg_state *reg = ®s[regno]; 9623 struct bpf_subprog_arg_info *arg = &sub->args[i]; 9624 9625 if (arg->arg_type == ARG_ANYTHING) { 9626 if (reg->type != SCALAR_VALUE) { 9627 bpf_log(log, "R%d is not a scalar\n", regno); 9628 return -EINVAL; 9629 } 9630 } else if (arg->arg_type == ARG_PTR_TO_CTX) { 9631 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9632 if (ret < 0) 9633 return ret; 9634 /* If function expects ctx type in BTF check that caller 9635 * is passing PTR_TO_CTX. 9636 */ 9637 if (reg->type != PTR_TO_CTX) { 9638 bpf_log(log, "arg#%d expects pointer to ctx\n", i); 9639 return -EINVAL; 9640 } 9641 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 9642 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9643 if (ret < 0) 9644 return ret; 9645 if (check_mem_reg(env, reg, regno, arg->mem_size)) 9646 return -EINVAL; 9647 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) { 9648 bpf_log(log, "arg#%d is expected to be non-NULL\n", i); 9649 return -EINVAL; 9650 } 9651 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 9652 /* 9653 * Can pass any value and the kernel won't crash, but 9654 * only PTR_TO_ARENA or SCALAR make sense. Everything 9655 * else is a bug in the bpf program. Point it out to 9656 * the user at the verification time instead of 9657 * run-time debug nightmare. 9658 */ 9659 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) { 9660 bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno); 9661 return -EINVAL; 9662 } 9663 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 9664 ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR); 9665 if (ret) 9666 return ret; 9667 9668 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0); 9669 if (ret) 9670 return ret; 9671 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 9672 struct bpf_call_arg_meta meta; 9673 int err; 9674 9675 if (register_is_null(reg) && type_may_be_null(arg->arg_type)) 9676 continue; 9677 9678 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */ 9679 err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta); 9680 err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type); 9681 if (err) 9682 return err; 9683 } else { 9684 bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n", 9685 i, arg->arg_type); 9686 return -EFAULT; 9687 } 9688 } 9689 9690 return 0; 9691 } 9692 9693 /* Compare BTF of a function call with given bpf_reg_state. 9694 * Returns: 9695 * EFAULT - there is a verifier bug. Abort verification. 9696 * EINVAL - there is a type mismatch or BTF is not available. 9697 * 0 - BTF matches with what bpf_reg_state expects. 9698 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized. 9699 */ 9700 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog, 9701 struct bpf_reg_state *regs) 9702 { 9703 struct bpf_prog *prog = env->prog; 9704 struct btf *btf = prog->aux->btf; 9705 u32 btf_id; 9706 int err; 9707 9708 if (!prog->aux->func_info) 9709 return -EINVAL; 9710 9711 btf_id = prog->aux->func_info[subprog].type_id; 9712 if (!btf_id) 9713 return -EFAULT; 9714 9715 if (prog->aux->func_info_aux[subprog].unreliable) 9716 return -EINVAL; 9717 9718 err = btf_check_func_arg_match(env, subprog, btf, regs); 9719 /* Compiler optimizations can remove arguments from static functions 9720 * or mismatched type can be passed into a global function. 9721 * In such cases mark the function as unreliable from BTF point of view. 9722 */ 9723 if (err) 9724 prog->aux->func_info_aux[subprog].unreliable = true; 9725 return err; 9726 } 9727 9728 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9729 int insn_idx, int subprog, 9730 set_callee_state_fn set_callee_state_cb) 9731 { 9732 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9733 struct bpf_func_state *caller, *callee; 9734 int err; 9735 9736 caller = state->frame[state->curframe]; 9737 err = btf_check_subprog_call(env, subprog, caller->regs); 9738 if (err == -EFAULT) 9739 return err; 9740 9741 /* set_callee_state is used for direct subprog calls, but we are 9742 * interested in validating only BPF helpers that can call subprogs as 9743 * callbacks 9744 */ 9745 env->subprog_info[subprog].is_cb = true; 9746 if (bpf_pseudo_kfunc_call(insn) && 9747 !is_callback_calling_kfunc(insn->imm)) { 9748 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 9749 func_id_name(insn->imm), insn->imm); 9750 return -EFAULT; 9751 } else if (!bpf_pseudo_kfunc_call(insn) && 9752 !is_callback_calling_function(insn->imm)) { /* helper */ 9753 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 9754 func_id_name(insn->imm), insn->imm); 9755 return -EFAULT; 9756 } 9757 9758 if (is_async_callback_calling_insn(insn)) { 9759 struct bpf_verifier_state *async_cb; 9760 9761 /* there is no real recursion here. timer and workqueue callbacks are async */ 9762 env->subprog_info[subprog].is_async_cb = true; 9763 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9764 insn_idx, subprog, 9765 is_bpf_wq_set_callback_impl_kfunc(insn->imm)); 9766 if (!async_cb) 9767 return -EFAULT; 9768 callee = async_cb->frame[0]; 9769 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9770 9771 /* Convert bpf_timer_set_callback() args into timer callback args */ 9772 err = set_callee_state_cb(env, caller, callee, insn_idx); 9773 if (err) 9774 return err; 9775 9776 return 0; 9777 } 9778 9779 /* for callback functions enqueue entry to callback and 9780 * proceed with next instruction within current frame. 9781 */ 9782 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9783 if (!callback_state) 9784 return -ENOMEM; 9785 9786 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9787 callback_state); 9788 if (err) 9789 return err; 9790 9791 callback_state->callback_unroll_depth++; 9792 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9793 caller->callback_depth = 0; 9794 return 0; 9795 } 9796 9797 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9798 int *insn_idx) 9799 { 9800 struct bpf_verifier_state *state = env->cur_state; 9801 struct bpf_func_state *caller; 9802 int err, subprog, target_insn; 9803 9804 target_insn = *insn_idx + insn->imm + 1; 9805 subprog = find_subprog(env, target_insn); 9806 if (subprog < 0) { 9807 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn); 9808 return -EFAULT; 9809 } 9810 9811 caller = state->frame[state->curframe]; 9812 err = btf_check_subprog_call(env, subprog, caller->regs); 9813 if (err == -EFAULT) 9814 return err; 9815 if (subprog_is_global(env, subprog)) { 9816 const char *sub_name = subprog_name(env, subprog); 9817 9818 /* Only global subprogs cannot be called with a lock held. */ 9819 if (env->cur_state->active_lock.ptr) { 9820 verbose(env, "global function calls are not allowed while holding a lock,\n" 9821 "use static function instead\n"); 9822 return -EINVAL; 9823 } 9824 9825 /* Only global subprogs cannot be called with preemption disabled. */ 9826 if (env->cur_state->active_preempt_lock) { 9827 verbose(env, "global function calls are not allowed with preemption disabled,\n" 9828 "use static function instead\n"); 9829 return -EINVAL; 9830 } 9831 9832 if (err) { 9833 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 9834 subprog, sub_name); 9835 return err; 9836 } 9837 9838 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 9839 subprog, sub_name); 9840 /* mark global subprog for verifying after main prog */ 9841 subprog_aux(env, subprog)->called = true; 9842 clear_caller_saved_regs(env, caller->regs); 9843 9844 /* All global functions return a 64-bit SCALAR_VALUE */ 9845 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9846 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9847 9848 /* continue with next insn after call */ 9849 return 0; 9850 } 9851 9852 /* for regular function entry setup new frame and continue 9853 * from that frame. 9854 */ 9855 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9856 if (err) 9857 return err; 9858 9859 clear_caller_saved_regs(env, caller->regs); 9860 9861 /* and go analyze first insn of the callee */ 9862 *insn_idx = env->subprog_info[subprog].start - 1; 9863 9864 if (env->log.level & BPF_LOG_LEVEL) { 9865 verbose(env, "caller:\n"); 9866 print_verifier_state(env, caller, true); 9867 verbose(env, "callee:\n"); 9868 print_verifier_state(env, state->frame[state->curframe], true); 9869 } 9870 9871 return 0; 9872 } 9873 9874 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9875 struct bpf_func_state *caller, 9876 struct bpf_func_state *callee) 9877 { 9878 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9879 * void *callback_ctx, u64 flags); 9880 * callback_fn(struct bpf_map *map, void *key, void *value, 9881 * void *callback_ctx); 9882 */ 9883 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9884 9885 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9886 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9887 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9888 9889 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9890 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9891 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9892 9893 /* pointer to stack or null */ 9894 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9895 9896 /* unused */ 9897 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9898 return 0; 9899 } 9900 9901 static int set_callee_state(struct bpf_verifier_env *env, 9902 struct bpf_func_state *caller, 9903 struct bpf_func_state *callee, int insn_idx) 9904 { 9905 int i; 9906 9907 /* copy r1 - r5 args that callee can access. The copy includes parent 9908 * pointers, which connects us up to the liveness chain 9909 */ 9910 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9911 callee->regs[i] = caller->regs[i]; 9912 return 0; 9913 } 9914 9915 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9916 struct bpf_func_state *caller, 9917 struct bpf_func_state *callee, 9918 int insn_idx) 9919 { 9920 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9921 struct bpf_map *map; 9922 int err; 9923 9924 /* valid map_ptr and poison value does not matter */ 9925 map = insn_aux->map_ptr_state.map_ptr; 9926 if (!map->ops->map_set_for_each_callback_args || 9927 !map->ops->map_for_each_callback) { 9928 verbose(env, "callback function not allowed for map\n"); 9929 return -ENOTSUPP; 9930 } 9931 9932 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9933 if (err) 9934 return err; 9935 9936 callee->in_callback_fn = true; 9937 callee->callback_ret_range = retval_range(0, 1); 9938 return 0; 9939 } 9940 9941 static int set_loop_callback_state(struct bpf_verifier_env *env, 9942 struct bpf_func_state *caller, 9943 struct bpf_func_state *callee, 9944 int insn_idx) 9945 { 9946 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9947 * u64 flags); 9948 * callback_fn(u32 index, void *callback_ctx); 9949 */ 9950 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9951 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9952 9953 /* unused */ 9954 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9955 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9956 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9957 9958 callee->in_callback_fn = true; 9959 callee->callback_ret_range = retval_range(0, 1); 9960 return 0; 9961 } 9962 9963 static int set_timer_callback_state(struct bpf_verifier_env *env, 9964 struct bpf_func_state *caller, 9965 struct bpf_func_state *callee, 9966 int insn_idx) 9967 { 9968 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9969 9970 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9971 * callback_fn(struct bpf_map *map, void *key, void *value); 9972 */ 9973 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9974 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9975 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9976 9977 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9978 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9979 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9980 9981 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9982 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9983 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9984 9985 /* unused */ 9986 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9987 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9988 callee->in_async_callback_fn = true; 9989 callee->callback_ret_range = retval_range(0, 1); 9990 return 0; 9991 } 9992 9993 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9994 struct bpf_func_state *caller, 9995 struct bpf_func_state *callee, 9996 int insn_idx) 9997 { 9998 /* bpf_find_vma(struct task_struct *task, u64 addr, 9999 * void *callback_fn, void *callback_ctx, u64 flags) 10000 * (callback_fn)(struct task_struct *task, 10001 * struct vm_area_struct *vma, void *callback_ctx); 10002 */ 10003 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 10004 10005 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 10006 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 10007 callee->regs[BPF_REG_2].btf = btf_vmlinux; 10008 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 10009 10010 /* pointer to stack or null */ 10011 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 10012 10013 /* unused */ 10014 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10015 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10016 callee->in_callback_fn = true; 10017 callee->callback_ret_range = retval_range(0, 1); 10018 return 0; 10019 } 10020 10021 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 10022 struct bpf_func_state *caller, 10023 struct bpf_func_state *callee, 10024 int insn_idx) 10025 { 10026 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 10027 * callback_ctx, u64 flags); 10028 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 10029 */ 10030 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 10031 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 10032 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 10033 10034 /* unused */ 10035 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 10036 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10037 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10038 10039 callee->in_callback_fn = true; 10040 callee->callback_ret_range = retval_range(0, 1); 10041 return 0; 10042 } 10043 10044 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 10045 struct bpf_func_state *caller, 10046 struct bpf_func_state *callee, 10047 int insn_idx) 10048 { 10049 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 10050 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 10051 * 10052 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 10053 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 10054 * by this point, so look at 'root' 10055 */ 10056 struct btf_field *field; 10057 10058 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 10059 BPF_RB_ROOT); 10060 if (!field || !field->graph_root.value_btf_id) 10061 return -EFAULT; 10062 10063 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 10064 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 10065 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 10066 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 10067 10068 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 10069 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10070 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10071 callee->in_callback_fn = true; 10072 callee->callback_ret_range = retval_range(0, 1); 10073 return 0; 10074 } 10075 10076 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 10077 10078 /* Are we currently verifying the callback for a rbtree helper that must 10079 * be called with lock held? If so, no need to complain about unreleased 10080 * lock 10081 */ 10082 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 10083 { 10084 struct bpf_verifier_state *state = env->cur_state; 10085 struct bpf_insn *insn = env->prog->insnsi; 10086 struct bpf_func_state *callee; 10087 int kfunc_btf_id; 10088 10089 if (!state->curframe) 10090 return false; 10091 10092 callee = state->frame[state->curframe]; 10093 10094 if (!callee->in_callback_fn) 10095 return false; 10096 10097 kfunc_btf_id = insn[callee->callsite].imm; 10098 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 10099 } 10100 10101 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg, 10102 bool return_32bit) 10103 { 10104 if (return_32bit) 10105 return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval; 10106 else 10107 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval; 10108 } 10109 10110 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 10111 { 10112 struct bpf_verifier_state *state = env->cur_state, *prev_st; 10113 struct bpf_func_state *caller, *callee; 10114 struct bpf_reg_state *r0; 10115 bool in_callback_fn; 10116 int err; 10117 10118 callee = state->frame[state->curframe]; 10119 r0 = &callee->regs[BPF_REG_0]; 10120 if (r0->type == PTR_TO_STACK) { 10121 /* technically it's ok to return caller's stack pointer 10122 * (or caller's caller's pointer) back to the caller, 10123 * since these pointers are valid. Only current stack 10124 * pointer will be invalid as soon as function exits, 10125 * but let's be conservative 10126 */ 10127 verbose(env, "cannot return stack pointer to the caller\n"); 10128 return -EINVAL; 10129 } 10130 10131 caller = state->frame[state->curframe - 1]; 10132 if (callee->in_callback_fn) { 10133 if (r0->type != SCALAR_VALUE) { 10134 verbose(env, "R0 not a scalar value\n"); 10135 return -EACCES; 10136 } 10137 10138 /* we are going to rely on register's precise value */ 10139 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64); 10140 err = err ?: mark_chain_precision(env, BPF_REG_0); 10141 if (err) 10142 return err; 10143 10144 /* enforce R0 return value range, and bpf_callback_t returns 64bit */ 10145 if (!retval_range_within(callee->callback_ret_range, r0, false)) { 10146 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 10147 "At callback return", "R0"); 10148 return -EINVAL; 10149 } 10150 if (!calls_callback(env, callee->callsite)) { 10151 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n", 10152 *insn_idx, callee->callsite); 10153 return -EFAULT; 10154 } 10155 } else { 10156 /* return to the caller whatever r0 had in the callee */ 10157 caller->regs[BPF_REG_0] = *r0; 10158 } 10159 10160 /* callback_fn frame should have released its own additions to parent's 10161 * reference state at this point, or check_reference_leak would 10162 * complain, hence it must be the same as the caller. There is no need 10163 * to copy it back. 10164 */ 10165 if (!callee->in_callback_fn) { 10166 /* Transfer references to the caller */ 10167 err = copy_reference_state(caller, callee); 10168 if (err) 10169 return err; 10170 } 10171 10172 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 10173 * there function call logic would reschedule callback visit. If iteration 10174 * converges is_state_visited() would prune that visit eventually. 10175 */ 10176 in_callback_fn = callee->in_callback_fn; 10177 if (in_callback_fn) 10178 *insn_idx = callee->callsite; 10179 else 10180 *insn_idx = callee->callsite + 1; 10181 10182 if (env->log.level & BPF_LOG_LEVEL) { 10183 verbose(env, "returning from callee:\n"); 10184 print_verifier_state(env, callee, true); 10185 verbose(env, "to caller at %d:\n", *insn_idx); 10186 print_verifier_state(env, caller, true); 10187 } 10188 /* clear everything in the callee. In case of exceptional exits using 10189 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 10190 free_func_state(callee); 10191 state->frame[state->curframe--] = NULL; 10192 10193 /* for callbacks widen imprecise scalars to make programs like below verify: 10194 * 10195 * struct ctx { int i; } 10196 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 10197 * ... 10198 * struct ctx = { .i = 0; } 10199 * bpf_loop(100, cb, &ctx, 0); 10200 * 10201 * This is similar to what is done in process_iter_next_call() for open 10202 * coded iterators. 10203 */ 10204 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 10205 if (prev_st) { 10206 err = widen_imprecise_scalars(env, prev_st, state); 10207 if (err) 10208 return err; 10209 } 10210 return 0; 10211 } 10212 10213 static int do_refine_retval_range(struct bpf_verifier_env *env, 10214 struct bpf_reg_state *regs, int ret_type, 10215 int func_id, 10216 struct bpf_call_arg_meta *meta) 10217 { 10218 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 10219 10220 if (ret_type != RET_INTEGER) 10221 return 0; 10222 10223 switch (func_id) { 10224 case BPF_FUNC_get_stack: 10225 case BPF_FUNC_get_task_stack: 10226 case BPF_FUNC_probe_read_str: 10227 case BPF_FUNC_probe_read_kernel_str: 10228 case BPF_FUNC_probe_read_user_str: 10229 ret_reg->smax_value = meta->msize_max_value; 10230 ret_reg->s32_max_value = meta->msize_max_value; 10231 ret_reg->smin_value = -MAX_ERRNO; 10232 ret_reg->s32_min_value = -MAX_ERRNO; 10233 reg_bounds_sync(ret_reg); 10234 break; 10235 case BPF_FUNC_get_smp_processor_id: 10236 ret_reg->umax_value = nr_cpu_ids - 1; 10237 ret_reg->u32_max_value = nr_cpu_ids - 1; 10238 ret_reg->smax_value = nr_cpu_ids - 1; 10239 ret_reg->s32_max_value = nr_cpu_ids - 1; 10240 ret_reg->umin_value = 0; 10241 ret_reg->u32_min_value = 0; 10242 ret_reg->smin_value = 0; 10243 ret_reg->s32_min_value = 0; 10244 reg_bounds_sync(ret_reg); 10245 break; 10246 } 10247 10248 return reg_bounds_sanity_check(env, ret_reg, "retval"); 10249 } 10250 10251 static int 10252 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 10253 int func_id, int insn_idx) 10254 { 10255 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 10256 struct bpf_map *map = meta->map_ptr; 10257 10258 if (func_id != BPF_FUNC_tail_call && 10259 func_id != BPF_FUNC_map_lookup_elem && 10260 func_id != BPF_FUNC_map_update_elem && 10261 func_id != BPF_FUNC_map_delete_elem && 10262 func_id != BPF_FUNC_map_push_elem && 10263 func_id != BPF_FUNC_map_pop_elem && 10264 func_id != BPF_FUNC_map_peek_elem && 10265 func_id != BPF_FUNC_for_each_map_elem && 10266 func_id != BPF_FUNC_redirect_map && 10267 func_id != BPF_FUNC_map_lookup_percpu_elem) 10268 return 0; 10269 10270 if (map == NULL) { 10271 verbose(env, "kernel subsystem misconfigured verifier\n"); 10272 return -EINVAL; 10273 } 10274 10275 /* In case of read-only, some additional restrictions 10276 * need to be applied in order to prevent altering the 10277 * state of the map from program side. 10278 */ 10279 if ((map->map_flags & BPF_F_RDONLY_PROG) && 10280 (func_id == BPF_FUNC_map_delete_elem || 10281 func_id == BPF_FUNC_map_update_elem || 10282 func_id == BPF_FUNC_map_push_elem || 10283 func_id == BPF_FUNC_map_pop_elem)) { 10284 verbose(env, "write into map forbidden\n"); 10285 return -EACCES; 10286 } 10287 10288 if (!aux->map_ptr_state.map_ptr) 10289 bpf_map_ptr_store(aux, meta->map_ptr, 10290 !meta->map_ptr->bypass_spec_v1, false); 10291 else if (aux->map_ptr_state.map_ptr != meta->map_ptr) 10292 bpf_map_ptr_store(aux, meta->map_ptr, 10293 !meta->map_ptr->bypass_spec_v1, true); 10294 return 0; 10295 } 10296 10297 static int 10298 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 10299 int func_id, int insn_idx) 10300 { 10301 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 10302 struct bpf_reg_state *regs = cur_regs(env), *reg; 10303 struct bpf_map *map = meta->map_ptr; 10304 u64 val, max; 10305 int err; 10306 10307 if (func_id != BPF_FUNC_tail_call) 10308 return 0; 10309 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 10310 verbose(env, "kernel subsystem misconfigured verifier\n"); 10311 return -EINVAL; 10312 } 10313 10314 reg = ®s[BPF_REG_3]; 10315 val = reg->var_off.value; 10316 max = map->max_entries; 10317 10318 if (!(is_reg_const(reg, false) && val < max)) { 10319 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 10320 return 0; 10321 } 10322 10323 err = mark_chain_precision(env, BPF_REG_3); 10324 if (err) 10325 return err; 10326 if (bpf_map_key_unseen(aux)) 10327 bpf_map_key_store(aux, val); 10328 else if (!bpf_map_key_poisoned(aux) && 10329 bpf_map_key_immediate(aux) != val) 10330 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 10331 return 0; 10332 } 10333 10334 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 10335 { 10336 struct bpf_func_state *state = cur_func(env); 10337 bool refs_lingering = false; 10338 int i; 10339 10340 if (!exception_exit && state->frameno && !state->in_callback_fn) 10341 return 0; 10342 10343 for (i = 0; i < state->acquired_refs; i++) { 10344 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 10345 continue; 10346 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 10347 state->refs[i].id, state->refs[i].insn_idx); 10348 refs_lingering = true; 10349 } 10350 return refs_lingering ? -EINVAL : 0; 10351 } 10352 10353 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 10354 struct bpf_reg_state *regs) 10355 { 10356 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 10357 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 10358 struct bpf_map *fmt_map = fmt_reg->map_ptr; 10359 struct bpf_bprintf_data data = {}; 10360 int err, fmt_map_off, num_args; 10361 u64 fmt_addr; 10362 char *fmt; 10363 10364 /* data must be an array of u64 */ 10365 if (data_len_reg->var_off.value % 8) 10366 return -EINVAL; 10367 num_args = data_len_reg->var_off.value / 8; 10368 10369 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 10370 * and map_direct_value_addr is set. 10371 */ 10372 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 10373 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 10374 fmt_map_off); 10375 if (err) { 10376 verbose(env, "verifier bug\n"); 10377 return -EFAULT; 10378 } 10379 fmt = (char *)(long)fmt_addr + fmt_map_off; 10380 10381 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 10382 * can focus on validating the format specifiers. 10383 */ 10384 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 10385 if (err < 0) 10386 verbose(env, "Invalid format string\n"); 10387 10388 return err; 10389 } 10390 10391 static int check_get_func_ip(struct bpf_verifier_env *env) 10392 { 10393 enum bpf_prog_type type = resolve_prog_type(env->prog); 10394 int func_id = BPF_FUNC_get_func_ip; 10395 10396 if (type == BPF_PROG_TYPE_TRACING) { 10397 if (!bpf_prog_has_trampoline(env->prog)) { 10398 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 10399 func_id_name(func_id), func_id); 10400 return -ENOTSUPP; 10401 } 10402 return 0; 10403 } else if (type == BPF_PROG_TYPE_KPROBE) { 10404 return 0; 10405 } 10406 10407 verbose(env, "func %s#%d not supported for program type %d\n", 10408 func_id_name(func_id), func_id, type); 10409 return -ENOTSUPP; 10410 } 10411 10412 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 10413 { 10414 return &env->insn_aux_data[env->insn_idx]; 10415 } 10416 10417 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 10418 { 10419 struct bpf_reg_state *regs = cur_regs(env); 10420 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 10421 bool reg_is_null = register_is_null(reg); 10422 10423 if (reg_is_null) 10424 mark_chain_precision(env, BPF_REG_4); 10425 10426 return reg_is_null; 10427 } 10428 10429 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 10430 { 10431 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 10432 10433 if (!state->initialized) { 10434 state->initialized = 1; 10435 state->fit_for_inline = loop_flag_is_zero(env); 10436 state->callback_subprogno = subprogno; 10437 return; 10438 } 10439 10440 if (!state->fit_for_inline) 10441 return; 10442 10443 state->fit_for_inline = (loop_flag_is_zero(env) && 10444 state->callback_subprogno == subprogno); 10445 } 10446 10447 static int get_helper_proto(struct bpf_verifier_env *env, int func_id, 10448 const struct bpf_func_proto **ptr) 10449 { 10450 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) 10451 return -ERANGE; 10452 10453 if (!env->ops->get_func_proto) 10454 return -EINVAL; 10455 10456 *ptr = env->ops->get_func_proto(func_id, env->prog); 10457 return *ptr ? 0 : -EINVAL; 10458 } 10459 10460 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10461 int *insn_idx_p) 10462 { 10463 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 10464 bool returns_cpu_specific_alloc_ptr = false; 10465 const struct bpf_func_proto *fn = NULL; 10466 enum bpf_return_type ret_type; 10467 enum bpf_type_flag ret_flag; 10468 struct bpf_reg_state *regs; 10469 struct bpf_call_arg_meta meta; 10470 int insn_idx = *insn_idx_p; 10471 bool changes_data; 10472 int i, err, func_id; 10473 10474 /* find function prototype */ 10475 func_id = insn->imm; 10476 err = get_helper_proto(env, insn->imm, &fn); 10477 if (err == -ERANGE) { 10478 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id); 10479 return -EINVAL; 10480 } 10481 10482 if (err) { 10483 verbose(env, "program of this type cannot use helper %s#%d\n", 10484 func_id_name(func_id), func_id); 10485 return err; 10486 } 10487 10488 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 10489 if (!env->prog->gpl_compatible && fn->gpl_only) { 10490 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10491 return -EINVAL; 10492 } 10493 10494 if (fn->allowed && !fn->allowed(env->prog)) { 10495 verbose(env, "helper call is not allowed in probe\n"); 10496 return -EINVAL; 10497 } 10498 10499 if (!in_sleepable(env) && fn->might_sleep) { 10500 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 10501 return -EINVAL; 10502 } 10503 10504 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10505 changes_data = bpf_helper_changes_pkt_data(fn->func); 10506 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10507 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 10508 func_id_name(func_id), func_id); 10509 return -EINVAL; 10510 } 10511 10512 memset(&meta, 0, sizeof(meta)); 10513 meta.pkt_access = fn->pkt_access; 10514 10515 err = check_func_proto(fn, func_id); 10516 if (err) { 10517 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 10518 func_id_name(func_id), func_id); 10519 return err; 10520 } 10521 10522 if (env->cur_state->active_rcu_lock) { 10523 if (fn->might_sleep) { 10524 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 10525 func_id_name(func_id), func_id); 10526 return -EINVAL; 10527 } 10528 10529 if (in_sleepable(env) && is_storage_get_function(func_id)) 10530 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10531 } 10532 10533 if (env->cur_state->active_preempt_lock) { 10534 if (fn->might_sleep) { 10535 verbose(env, "sleepable helper %s#%d in non-preemptible region\n", 10536 func_id_name(func_id), func_id); 10537 return -EINVAL; 10538 } 10539 10540 if (in_sleepable(env) && is_storage_get_function(func_id)) 10541 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10542 } 10543 10544 meta.func_id = func_id; 10545 /* check args */ 10546 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10547 err = check_func_arg(env, i, &meta, fn, insn_idx); 10548 if (err) 10549 return err; 10550 } 10551 10552 err = record_func_map(env, &meta, func_id, insn_idx); 10553 if (err) 10554 return err; 10555 10556 err = record_func_key(env, &meta, func_id, insn_idx); 10557 if (err) 10558 return err; 10559 10560 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10561 * is inferred from register state. 10562 */ 10563 for (i = 0; i < meta.access_size; i++) { 10564 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 10565 BPF_WRITE, -1, false, false); 10566 if (err) 10567 return err; 10568 } 10569 10570 regs = cur_regs(env); 10571 10572 if (meta.release_regno) { 10573 err = -EINVAL; 10574 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 10575 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 10576 * is safe to do directly. 10577 */ 10578 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 10579 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 10580 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 10581 return -EFAULT; 10582 } 10583 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 10584 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 10585 u32 ref_obj_id = meta.ref_obj_id; 10586 bool in_rcu = in_rcu_cs(env); 10587 struct bpf_func_state *state; 10588 struct bpf_reg_state *reg; 10589 10590 err = release_reference_state(cur_func(env), ref_obj_id); 10591 if (!err) { 10592 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10593 if (reg->ref_obj_id == ref_obj_id) { 10594 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 10595 reg->ref_obj_id = 0; 10596 reg->type &= ~MEM_ALLOC; 10597 reg->type |= MEM_RCU; 10598 } else { 10599 mark_reg_invalid(env, reg); 10600 } 10601 } 10602 })); 10603 } 10604 } else if (meta.ref_obj_id) { 10605 err = release_reference(env, meta.ref_obj_id); 10606 } else if (register_is_null(®s[meta.release_regno])) { 10607 /* meta.ref_obj_id can only be 0 if register that is meant to be 10608 * released is NULL, which must be > R0. 10609 */ 10610 err = 0; 10611 } 10612 if (err) { 10613 verbose(env, "func %s#%d reference has not been acquired before\n", 10614 func_id_name(func_id), func_id); 10615 return err; 10616 } 10617 } 10618 10619 switch (func_id) { 10620 case BPF_FUNC_tail_call: 10621 err = check_reference_leak(env, false); 10622 if (err) { 10623 verbose(env, "tail_call would lead to reference leak\n"); 10624 return err; 10625 } 10626 break; 10627 case BPF_FUNC_get_local_storage: 10628 /* check that flags argument in get_local_storage(map, flags) is 0, 10629 * this is required because get_local_storage() can't return an error. 10630 */ 10631 if (!register_is_null(®s[BPF_REG_2])) { 10632 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10633 return -EINVAL; 10634 } 10635 break; 10636 case BPF_FUNC_for_each_map_elem: 10637 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10638 set_map_elem_callback_state); 10639 break; 10640 case BPF_FUNC_timer_set_callback: 10641 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10642 set_timer_callback_state); 10643 break; 10644 case BPF_FUNC_find_vma: 10645 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10646 set_find_vma_callback_state); 10647 break; 10648 case BPF_FUNC_snprintf: 10649 err = check_bpf_snprintf_call(env, regs); 10650 break; 10651 case BPF_FUNC_loop: 10652 update_loop_inline_state(env, meta.subprogno); 10653 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10654 * is finished, thus mark it precise. 10655 */ 10656 err = mark_chain_precision(env, BPF_REG_1); 10657 if (err) 10658 return err; 10659 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) { 10660 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10661 set_loop_callback_state); 10662 } else { 10663 cur_func(env)->callback_depth = 0; 10664 if (env->log.level & BPF_LOG_LEVEL2) 10665 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10666 env->cur_state->curframe); 10667 } 10668 break; 10669 case BPF_FUNC_dynptr_from_mem: 10670 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10671 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10672 reg_type_str(env, regs[BPF_REG_1].type)); 10673 return -EACCES; 10674 } 10675 break; 10676 case BPF_FUNC_set_retval: 10677 if (prog_type == BPF_PROG_TYPE_LSM && 10678 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10679 if (!env->prog->aux->attach_func_proto->type) { 10680 /* Make sure programs that attach to void 10681 * hooks don't try to modify return value. 10682 */ 10683 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10684 return -EINVAL; 10685 } 10686 } 10687 break; 10688 case BPF_FUNC_dynptr_data: 10689 { 10690 struct bpf_reg_state *reg; 10691 int id, ref_obj_id; 10692 10693 reg = get_dynptr_arg_reg(env, fn, regs); 10694 if (!reg) 10695 return -EFAULT; 10696 10697 10698 if (meta.dynptr_id) { 10699 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 10700 return -EFAULT; 10701 } 10702 if (meta.ref_obj_id) { 10703 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 10704 return -EFAULT; 10705 } 10706 10707 id = dynptr_id(env, reg); 10708 if (id < 0) { 10709 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 10710 return id; 10711 } 10712 10713 ref_obj_id = dynptr_ref_obj_id(env, reg); 10714 if (ref_obj_id < 0) { 10715 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 10716 return ref_obj_id; 10717 } 10718 10719 meta.dynptr_id = id; 10720 meta.ref_obj_id = ref_obj_id; 10721 10722 break; 10723 } 10724 case BPF_FUNC_dynptr_write: 10725 { 10726 enum bpf_dynptr_type dynptr_type; 10727 struct bpf_reg_state *reg; 10728 10729 reg = get_dynptr_arg_reg(env, fn, regs); 10730 if (!reg) 10731 return -EFAULT; 10732 10733 dynptr_type = dynptr_get_type(env, reg); 10734 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10735 return -EFAULT; 10736 10737 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 10738 /* this will trigger clear_all_pkt_pointers(), which will 10739 * invalidate all dynptr slices associated with the skb 10740 */ 10741 changes_data = true; 10742 10743 break; 10744 } 10745 case BPF_FUNC_per_cpu_ptr: 10746 case BPF_FUNC_this_cpu_ptr: 10747 { 10748 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 10749 const struct btf_type *type; 10750 10751 if (reg->type & MEM_RCU) { 10752 type = btf_type_by_id(reg->btf, reg->btf_id); 10753 if (!type || !btf_type_is_struct(type)) { 10754 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 10755 return -EFAULT; 10756 } 10757 returns_cpu_specific_alloc_ptr = true; 10758 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 10759 } 10760 break; 10761 } 10762 case BPF_FUNC_user_ringbuf_drain: 10763 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10764 set_user_ringbuf_callback_state); 10765 break; 10766 } 10767 10768 if (err) 10769 return err; 10770 10771 /* reset caller saved regs */ 10772 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10773 mark_reg_not_init(env, regs, caller_saved[i]); 10774 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10775 } 10776 10777 /* helper call returns 64-bit value. */ 10778 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10779 10780 /* update return register (already marked as written above) */ 10781 ret_type = fn->ret_type; 10782 ret_flag = type_flag(ret_type); 10783 10784 switch (base_type(ret_type)) { 10785 case RET_INTEGER: 10786 /* sets type to SCALAR_VALUE */ 10787 mark_reg_unknown(env, regs, BPF_REG_0); 10788 break; 10789 case RET_VOID: 10790 regs[BPF_REG_0].type = NOT_INIT; 10791 break; 10792 case RET_PTR_TO_MAP_VALUE: 10793 /* There is no offset yet applied, variable or fixed */ 10794 mark_reg_known_zero(env, regs, BPF_REG_0); 10795 /* remember map_ptr, so that check_map_access() 10796 * can check 'value_size' boundary of memory access 10797 * to map element returned from bpf_map_lookup_elem() 10798 */ 10799 if (meta.map_ptr == NULL) { 10800 verbose(env, 10801 "kernel subsystem misconfigured verifier\n"); 10802 return -EINVAL; 10803 } 10804 regs[BPF_REG_0].map_ptr = meta.map_ptr; 10805 regs[BPF_REG_0].map_uid = meta.map_uid; 10806 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10807 if (!type_may_be_null(ret_type) && 10808 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 10809 regs[BPF_REG_0].id = ++env->id_gen; 10810 } 10811 break; 10812 case RET_PTR_TO_SOCKET: 10813 mark_reg_known_zero(env, regs, BPF_REG_0); 10814 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10815 break; 10816 case RET_PTR_TO_SOCK_COMMON: 10817 mark_reg_known_zero(env, regs, BPF_REG_0); 10818 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10819 break; 10820 case RET_PTR_TO_TCP_SOCK: 10821 mark_reg_known_zero(env, regs, BPF_REG_0); 10822 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10823 break; 10824 case RET_PTR_TO_MEM: 10825 mark_reg_known_zero(env, regs, BPF_REG_0); 10826 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10827 regs[BPF_REG_0].mem_size = meta.mem_size; 10828 break; 10829 case RET_PTR_TO_MEM_OR_BTF_ID: 10830 { 10831 const struct btf_type *t; 10832 10833 mark_reg_known_zero(env, regs, BPF_REG_0); 10834 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10835 if (!btf_type_is_struct(t)) { 10836 u32 tsize; 10837 const struct btf_type *ret; 10838 const char *tname; 10839 10840 /* resolve the type size of ksym. */ 10841 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10842 if (IS_ERR(ret)) { 10843 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10844 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10845 tname, PTR_ERR(ret)); 10846 return -EINVAL; 10847 } 10848 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10849 regs[BPF_REG_0].mem_size = tsize; 10850 } else { 10851 if (returns_cpu_specific_alloc_ptr) { 10852 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10853 } else { 10854 /* MEM_RDONLY may be carried from ret_flag, but it 10855 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10856 * it will confuse the check of PTR_TO_BTF_ID in 10857 * check_mem_access(). 10858 */ 10859 ret_flag &= ~MEM_RDONLY; 10860 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10861 } 10862 10863 regs[BPF_REG_0].btf = meta.ret_btf; 10864 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10865 } 10866 break; 10867 } 10868 case RET_PTR_TO_BTF_ID: 10869 { 10870 struct btf *ret_btf; 10871 int ret_btf_id; 10872 10873 mark_reg_known_zero(env, regs, BPF_REG_0); 10874 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10875 if (func_id == BPF_FUNC_kptr_xchg) { 10876 ret_btf = meta.kptr_field->kptr.btf; 10877 ret_btf_id = meta.kptr_field->kptr.btf_id; 10878 if (!btf_is_kernel(ret_btf)) { 10879 regs[BPF_REG_0].type |= MEM_ALLOC; 10880 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10881 regs[BPF_REG_0].type |= MEM_PERCPU; 10882 } 10883 } else { 10884 if (fn->ret_btf_id == BPF_PTR_POISON) { 10885 verbose(env, "verifier internal error:"); 10886 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 10887 func_id_name(func_id)); 10888 return -EINVAL; 10889 } 10890 ret_btf = btf_vmlinux; 10891 ret_btf_id = *fn->ret_btf_id; 10892 } 10893 if (ret_btf_id == 0) { 10894 verbose(env, "invalid return type %u of func %s#%d\n", 10895 base_type(ret_type), func_id_name(func_id), 10896 func_id); 10897 return -EINVAL; 10898 } 10899 regs[BPF_REG_0].btf = ret_btf; 10900 regs[BPF_REG_0].btf_id = ret_btf_id; 10901 break; 10902 } 10903 default: 10904 verbose(env, "unknown return type %u of func %s#%d\n", 10905 base_type(ret_type), func_id_name(func_id), func_id); 10906 return -EINVAL; 10907 } 10908 10909 if (type_may_be_null(regs[BPF_REG_0].type)) 10910 regs[BPF_REG_0].id = ++env->id_gen; 10911 10912 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 10913 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 10914 func_id_name(func_id), func_id); 10915 return -EFAULT; 10916 } 10917 10918 if (is_dynptr_ref_function(func_id)) 10919 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 10920 10921 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 10922 /* For release_reference() */ 10923 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10924 } else if (is_acquire_function(func_id, meta.map_ptr)) { 10925 int id = acquire_reference_state(env, insn_idx); 10926 10927 if (id < 0) 10928 return id; 10929 /* For mark_ptr_or_null_reg() */ 10930 regs[BPF_REG_0].id = id; 10931 /* For release_reference() */ 10932 regs[BPF_REG_0].ref_obj_id = id; 10933 } 10934 10935 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 10936 if (err) 10937 return err; 10938 10939 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 10940 if (err) 10941 return err; 10942 10943 if ((func_id == BPF_FUNC_get_stack || 10944 func_id == BPF_FUNC_get_task_stack) && 10945 !env->prog->has_callchain_buf) { 10946 const char *err_str; 10947 10948 #ifdef CONFIG_PERF_EVENTS 10949 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10950 err_str = "cannot get callchain buffer for func %s#%d\n"; 10951 #else 10952 err = -ENOTSUPP; 10953 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10954 #endif 10955 if (err) { 10956 verbose(env, err_str, func_id_name(func_id), func_id); 10957 return err; 10958 } 10959 10960 env->prog->has_callchain_buf = true; 10961 } 10962 10963 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10964 env->prog->call_get_stack = true; 10965 10966 if (func_id == BPF_FUNC_get_func_ip) { 10967 if (check_get_func_ip(env)) 10968 return -ENOTSUPP; 10969 env->prog->call_get_func_ip = true; 10970 } 10971 10972 if (changes_data) 10973 clear_all_pkt_pointers(env); 10974 return 0; 10975 } 10976 10977 /* mark_btf_func_reg_size() is used when the reg size is determined by 10978 * the BTF func_proto's return value size and argument. 10979 */ 10980 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10981 size_t reg_size) 10982 { 10983 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 10984 10985 if (regno == BPF_REG_0) { 10986 /* Function return value */ 10987 reg->live |= REG_LIVE_WRITTEN; 10988 reg->subreg_def = reg_size == sizeof(u64) ? 10989 DEF_NOT_SUBREG : env->insn_idx + 1; 10990 } else { 10991 /* Function argument */ 10992 if (reg_size == sizeof(u64)) { 10993 mark_insn_zext(env, reg); 10994 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 10995 } else { 10996 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 10997 } 10998 } 10999 } 11000 11001 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 11002 { 11003 return meta->kfunc_flags & KF_ACQUIRE; 11004 } 11005 11006 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 11007 { 11008 return meta->kfunc_flags & KF_RELEASE; 11009 } 11010 11011 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 11012 { 11013 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 11014 } 11015 11016 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 11017 { 11018 return meta->kfunc_flags & KF_SLEEPABLE; 11019 } 11020 11021 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 11022 { 11023 return meta->kfunc_flags & KF_DESTRUCTIVE; 11024 } 11025 11026 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 11027 { 11028 return meta->kfunc_flags & KF_RCU; 11029 } 11030 11031 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 11032 { 11033 return meta->kfunc_flags & KF_RCU_PROTECTED; 11034 } 11035 11036 static bool is_kfunc_arg_mem_size(const struct btf *btf, 11037 const struct btf_param *arg, 11038 const struct bpf_reg_state *reg) 11039 { 11040 const struct btf_type *t; 11041 11042 t = btf_type_skip_modifiers(btf, arg->type, NULL); 11043 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 11044 return false; 11045 11046 return btf_param_match_suffix(btf, arg, "__sz"); 11047 } 11048 11049 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 11050 const struct btf_param *arg, 11051 const struct bpf_reg_state *reg) 11052 { 11053 const struct btf_type *t; 11054 11055 t = btf_type_skip_modifiers(btf, arg->type, NULL); 11056 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 11057 return false; 11058 11059 return btf_param_match_suffix(btf, arg, "__szk"); 11060 } 11061 11062 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 11063 { 11064 return btf_param_match_suffix(btf, arg, "__opt"); 11065 } 11066 11067 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 11068 { 11069 return btf_param_match_suffix(btf, arg, "__k"); 11070 } 11071 11072 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 11073 { 11074 return btf_param_match_suffix(btf, arg, "__ign"); 11075 } 11076 11077 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg) 11078 { 11079 return btf_param_match_suffix(btf, arg, "__map"); 11080 } 11081 11082 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 11083 { 11084 return btf_param_match_suffix(btf, arg, "__alloc"); 11085 } 11086 11087 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 11088 { 11089 return btf_param_match_suffix(btf, arg, "__uninit"); 11090 } 11091 11092 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 11093 { 11094 return btf_param_match_suffix(btf, arg, "__refcounted_kptr"); 11095 } 11096 11097 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 11098 { 11099 return btf_param_match_suffix(btf, arg, "__nullable"); 11100 } 11101 11102 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 11103 { 11104 return btf_param_match_suffix(btf, arg, "__str"); 11105 } 11106 11107 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 11108 const struct btf_param *arg, 11109 const char *name) 11110 { 11111 int len, target_len = strlen(name); 11112 const char *param_name; 11113 11114 param_name = btf_name_by_offset(btf, arg->name_off); 11115 if (str_is_empty(param_name)) 11116 return false; 11117 len = strlen(param_name); 11118 if (len != target_len) 11119 return false; 11120 if (strcmp(param_name, name)) 11121 return false; 11122 11123 return true; 11124 } 11125 11126 enum { 11127 KF_ARG_DYNPTR_ID, 11128 KF_ARG_LIST_HEAD_ID, 11129 KF_ARG_LIST_NODE_ID, 11130 KF_ARG_RB_ROOT_ID, 11131 KF_ARG_RB_NODE_ID, 11132 KF_ARG_WORKQUEUE_ID, 11133 }; 11134 11135 BTF_ID_LIST(kf_arg_btf_ids) 11136 BTF_ID(struct, bpf_dynptr) 11137 BTF_ID(struct, bpf_list_head) 11138 BTF_ID(struct, bpf_list_node) 11139 BTF_ID(struct, bpf_rb_root) 11140 BTF_ID(struct, bpf_rb_node) 11141 BTF_ID(struct, bpf_wq) 11142 11143 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 11144 const struct btf_param *arg, int type) 11145 { 11146 const struct btf_type *t; 11147 u32 res_id; 11148 11149 t = btf_type_skip_modifiers(btf, arg->type, NULL); 11150 if (!t) 11151 return false; 11152 if (!btf_type_is_ptr(t)) 11153 return false; 11154 t = btf_type_skip_modifiers(btf, t->type, &res_id); 11155 if (!t) 11156 return false; 11157 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 11158 } 11159 11160 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 11161 { 11162 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 11163 } 11164 11165 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 11166 { 11167 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 11168 } 11169 11170 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 11171 { 11172 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 11173 } 11174 11175 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 11176 { 11177 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 11178 } 11179 11180 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 11181 { 11182 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 11183 } 11184 11185 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg) 11186 { 11187 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID); 11188 } 11189 11190 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 11191 const struct btf_param *arg) 11192 { 11193 const struct btf_type *t; 11194 11195 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 11196 if (!t) 11197 return false; 11198 11199 return true; 11200 } 11201 11202 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 11203 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 11204 const struct btf *btf, 11205 const struct btf_type *t, int rec) 11206 { 11207 const struct btf_type *member_type; 11208 const struct btf_member *member; 11209 u32 i; 11210 11211 if (!btf_type_is_struct(t)) 11212 return false; 11213 11214 for_each_member(i, t, member) { 11215 const struct btf_array *array; 11216 11217 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 11218 if (btf_type_is_struct(member_type)) { 11219 if (rec >= 3) { 11220 verbose(env, "max struct nesting depth exceeded\n"); 11221 return false; 11222 } 11223 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 11224 return false; 11225 continue; 11226 } 11227 if (btf_type_is_array(member_type)) { 11228 array = btf_array(member_type); 11229 if (!array->nelems) 11230 return false; 11231 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 11232 if (!btf_type_is_scalar(member_type)) 11233 return false; 11234 continue; 11235 } 11236 if (!btf_type_is_scalar(member_type)) 11237 return false; 11238 } 11239 return true; 11240 } 11241 11242 enum kfunc_ptr_arg_type { 11243 KF_ARG_PTR_TO_CTX, 11244 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 11245 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 11246 KF_ARG_PTR_TO_DYNPTR, 11247 KF_ARG_PTR_TO_ITER, 11248 KF_ARG_PTR_TO_LIST_HEAD, 11249 KF_ARG_PTR_TO_LIST_NODE, 11250 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 11251 KF_ARG_PTR_TO_MEM, 11252 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 11253 KF_ARG_PTR_TO_CALLBACK, 11254 KF_ARG_PTR_TO_RB_ROOT, 11255 KF_ARG_PTR_TO_RB_NODE, 11256 KF_ARG_PTR_TO_NULL, 11257 KF_ARG_PTR_TO_CONST_STR, 11258 KF_ARG_PTR_TO_MAP, 11259 KF_ARG_PTR_TO_WORKQUEUE, 11260 }; 11261 11262 enum special_kfunc_type { 11263 KF_bpf_obj_new_impl, 11264 KF_bpf_obj_drop_impl, 11265 KF_bpf_refcount_acquire_impl, 11266 KF_bpf_list_push_front_impl, 11267 KF_bpf_list_push_back_impl, 11268 KF_bpf_list_pop_front, 11269 KF_bpf_list_pop_back, 11270 KF_bpf_cast_to_kern_ctx, 11271 KF_bpf_rdonly_cast, 11272 KF_bpf_rcu_read_lock, 11273 KF_bpf_rcu_read_unlock, 11274 KF_bpf_rbtree_remove, 11275 KF_bpf_rbtree_add_impl, 11276 KF_bpf_rbtree_first, 11277 KF_bpf_dynptr_from_skb, 11278 KF_bpf_dynptr_from_xdp, 11279 KF_bpf_dynptr_slice, 11280 KF_bpf_dynptr_slice_rdwr, 11281 KF_bpf_dynptr_clone, 11282 KF_bpf_percpu_obj_new_impl, 11283 KF_bpf_percpu_obj_drop_impl, 11284 KF_bpf_throw, 11285 KF_bpf_wq_set_callback_impl, 11286 KF_bpf_preempt_disable, 11287 KF_bpf_preempt_enable, 11288 KF_bpf_iter_css_task_new, 11289 KF_bpf_session_cookie, 11290 }; 11291 11292 BTF_SET_START(special_kfunc_set) 11293 BTF_ID(func, bpf_obj_new_impl) 11294 BTF_ID(func, bpf_obj_drop_impl) 11295 BTF_ID(func, bpf_refcount_acquire_impl) 11296 BTF_ID(func, bpf_list_push_front_impl) 11297 BTF_ID(func, bpf_list_push_back_impl) 11298 BTF_ID(func, bpf_list_pop_front) 11299 BTF_ID(func, bpf_list_pop_back) 11300 BTF_ID(func, bpf_cast_to_kern_ctx) 11301 BTF_ID(func, bpf_rdonly_cast) 11302 BTF_ID(func, bpf_rbtree_remove) 11303 BTF_ID(func, bpf_rbtree_add_impl) 11304 BTF_ID(func, bpf_rbtree_first) 11305 BTF_ID(func, bpf_dynptr_from_skb) 11306 BTF_ID(func, bpf_dynptr_from_xdp) 11307 BTF_ID(func, bpf_dynptr_slice) 11308 BTF_ID(func, bpf_dynptr_slice_rdwr) 11309 BTF_ID(func, bpf_dynptr_clone) 11310 BTF_ID(func, bpf_percpu_obj_new_impl) 11311 BTF_ID(func, bpf_percpu_obj_drop_impl) 11312 BTF_ID(func, bpf_throw) 11313 BTF_ID(func, bpf_wq_set_callback_impl) 11314 #ifdef CONFIG_CGROUPS 11315 BTF_ID(func, bpf_iter_css_task_new) 11316 #endif 11317 BTF_SET_END(special_kfunc_set) 11318 11319 BTF_ID_LIST(special_kfunc_list) 11320 BTF_ID(func, bpf_obj_new_impl) 11321 BTF_ID(func, bpf_obj_drop_impl) 11322 BTF_ID(func, bpf_refcount_acquire_impl) 11323 BTF_ID(func, bpf_list_push_front_impl) 11324 BTF_ID(func, bpf_list_push_back_impl) 11325 BTF_ID(func, bpf_list_pop_front) 11326 BTF_ID(func, bpf_list_pop_back) 11327 BTF_ID(func, bpf_cast_to_kern_ctx) 11328 BTF_ID(func, bpf_rdonly_cast) 11329 BTF_ID(func, bpf_rcu_read_lock) 11330 BTF_ID(func, bpf_rcu_read_unlock) 11331 BTF_ID(func, bpf_rbtree_remove) 11332 BTF_ID(func, bpf_rbtree_add_impl) 11333 BTF_ID(func, bpf_rbtree_first) 11334 BTF_ID(func, bpf_dynptr_from_skb) 11335 BTF_ID(func, bpf_dynptr_from_xdp) 11336 BTF_ID(func, bpf_dynptr_slice) 11337 BTF_ID(func, bpf_dynptr_slice_rdwr) 11338 BTF_ID(func, bpf_dynptr_clone) 11339 BTF_ID(func, bpf_percpu_obj_new_impl) 11340 BTF_ID(func, bpf_percpu_obj_drop_impl) 11341 BTF_ID(func, bpf_throw) 11342 BTF_ID(func, bpf_wq_set_callback_impl) 11343 BTF_ID(func, bpf_preempt_disable) 11344 BTF_ID(func, bpf_preempt_enable) 11345 #ifdef CONFIG_CGROUPS 11346 BTF_ID(func, bpf_iter_css_task_new) 11347 #else 11348 BTF_ID_UNUSED 11349 #endif 11350 #ifdef CONFIG_BPF_EVENTS 11351 BTF_ID(func, bpf_session_cookie) 11352 #else 11353 BTF_ID_UNUSED 11354 #endif 11355 11356 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 11357 { 11358 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 11359 meta->arg_owning_ref) { 11360 return false; 11361 } 11362 11363 return meta->kfunc_flags & KF_RET_NULL; 11364 } 11365 11366 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 11367 { 11368 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 11369 } 11370 11371 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 11372 { 11373 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 11374 } 11375 11376 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta) 11377 { 11378 return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable]; 11379 } 11380 11381 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta) 11382 { 11383 return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable]; 11384 } 11385 11386 static enum kfunc_ptr_arg_type 11387 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 11388 struct bpf_kfunc_call_arg_meta *meta, 11389 const struct btf_type *t, const struct btf_type *ref_t, 11390 const char *ref_tname, const struct btf_param *args, 11391 int argno, int nargs) 11392 { 11393 u32 regno = argno + 1; 11394 struct bpf_reg_state *regs = cur_regs(env); 11395 struct bpf_reg_state *reg = ®s[regno]; 11396 bool arg_mem_size = false; 11397 11398 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 11399 return KF_ARG_PTR_TO_CTX; 11400 11401 /* In this function, we verify the kfunc's BTF as per the argument type, 11402 * leaving the rest of the verification with respect to the register 11403 * type to our caller. When a set of conditions hold in the BTF type of 11404 * arguments, we resolve it to a known kfunc_ptr_arg_type. 11405 */ 11406 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 11407 return KF_ARG_PTR_TO_CTX; 11408 11409 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg)) 11410 return KF_ARG_PTR_TO_NULL; 11411 11412 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 11413 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 11414 11415 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 11416 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 11417 11418 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 11419 return KF_ARG_PTR_TO_DYNPTR; 11420 11421 if (is_kfunc_arg_iter(meta, argno, &args[argno])) 11422 return KF_ARG_PTR_TO_ITER; 11423 11424 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 11425 return KF_ARG_PTR_TO_LIST_HEAD; 11426 11427 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 11428 return KF_ARG_PTR_TO_LIST_NODE; 11429 11430 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 11431 return KF_ARG_PTR_TO_RB_ROOT; 11432 11433 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 11434 return KF_ARG_PTR_TO_RB_NODE; 11435 11436 if (is_kfunc_arg_const_str(meta->btf, &args[argno])) 11437 return KF_ARG_PTR_TO_CONST_STR; 11438 11439 if (is_kfunc_arg_map(meta->btf, &args[argno])) 11440 return KF_ARG_PTR_TO_MAP; 11441 11442 if (is_kfunc_arg_wq(meta->btf, &args[argno])) 11443 return KF_ARG_PTR_TO_WORKQUEUE; 11444 11445 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 11446 if (!btf_type_is_struct(ref_t)) { 11447 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 11448 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 11449 return -EINVAL; 11450 } 11451 return KF_ARG_PTR_TO_BTF_ID; 11452 } 11453 11454 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 11455 return KF_ARG_PTR_TO_CALLBACK; 11456 11457 if (argno + 1 < nargs && 11458 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 11459 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 11460 arg_mem_size = true; 11461 11462 /* This is the catch all argument type of register types supported by 11463 * check_helper_mem_access. However, we only allow when argument type is 11464 * pointer to scalar, or struct composed (recursively) of scalars. When 11465 * arg_mem_size is true, the pointer can be void *. 11466 */ 11467 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 11468 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 11469 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 11470 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 11471 return -EINVAL; 11472 } 11473 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 11474 } 11475 11476 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 11477 struct bpf_reg_state *reg, 11478 const struct btf_type *ref_t, 11479 const char *ref_tname, u32 ref_id, 11480 struct bpf_kfunc_call_arg_meta *meta, 11481 int argno) 11482 { 11483 const struct btf_type *reg_ref_t; 11484 bool strict_type_match = false; 11485 const struct btf *reg_btf; 11486 const char *reg_ref_tname; 11487 bool taking_projection; 11488 bool struct_same; 11489 u32 reg_ref_id; 11490 11491 if (base_type(reg->type) == PTR_TO_BTF_ID) { 11492 reg_btf = reg->btf; 11493 reg_ref_id = reg->btf_id; 11494 } else { 11495 reg_btf = btf_vmlinux; 11496 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 11497 } 11498 11499 /* Enforce strict type matching for calls to kfuncs that are acquiring 11500 * or releasing a reference, or are no-cast aliases. We do _not_ 11501 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 11502 * as we want to enable BPF programs to pass types that are bitwise 11503 * equivalent without forcing them to explicitly cast with something 11504 * like bpf_cast_to_kern_ctx(). 11505 * 11506 * For example, say we had a type like the following: 11507 * 11508 * struct bpf_cpumask { 11509 * cpumask_t cpumask; 11510 * refcount_t usage; 11511 * }; 11512 * 11513 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 11514 * to a struct cpumask, so it would be safe to pass a struct 11515 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 11516 * 11517 * The philosophy here is similar to how we allow scalars of different 11518 * types to be passed to kfuncs as long as the size is the same. The 11519 * only difference here is that we're simply allowing 11520 * btf_struct_ids_match() to walk the struct at the 0th offset, and 11521 * resolve types. 11522 */ 11523 if ((is_kfunc_release(meta) && reg->ref_obj_id) || 11524 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 11525 strict_type_match = true; 11526 11527 WARN_ON_ONCE(is_kfunc_release(meta) && 11528 (reg->off || !tnum_is_const(reg->var_off) || 11529 reg->var_off.value)); 11530 11531 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 11532 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 11533 struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match); 11534 /* If kfunc is accepting a projection type (ie. __sk_buff), it cannot 11535 * actually use it -- it must cast to the underlying type. So we allow 11536 * caller to pass in the underlying type. 11537 */ 11538 taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname); 11539 if (!taking_projection && !struct_same) { 11540 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 11541 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 11542 btf_type_str(reg_ref_t), reg_ref_tname); 11543 return -EINVAL; 11544 } 11545 return 0; 11546 } 11547 11548 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11549 { 11550 struct bpf_verifier_state *state = env->cur_state; 11551 struct btf_record *rec = reg_btf_record(reg); 11552 11553 if (!state->active_lock.ptr) { 11554 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 11555 return -EFAULT; 11556 } 11557 11558 if (type_flag(reg->type) & NON_OWN_REF) { 11559 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 11560 return -EFAULT; 11561 } 11562 11563 reg->type |= NON_OWN_REF; 11564 if (rec->refcount_off >= 0) 11565 reg->type |= MEM_RCU; 11566 11567 return 0; 11568 } 11569 11570 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 11571 { 11572 struct bpf_func_state *state, *unused; 11573 struct bpf_reg_state *reg; 11574 int i; 11575 11576 state = cur_func(env); 11577 11578 if (!ref_obj_id) { 11579 verbose(env, "verifier internal error: ref_obj_id is zero for " 11580 "owning -> non-owning conversion\n"); 11581 return -EFAULT; 11582 } 11583 11584 for (i = 0; i < state->acquired_refs; i++) { 11585 if (state->refs[i].id != ref_obj_id) 11586 continue; 11587 11588 /* Clear ref_obj_id here so release_reference doesn't clobber 11589 * the whole reg 11590 */ 11591 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11592 if (reg->ref_obj_id == ref_obj_id) { 11593 reg->ref_obj_id = 0; 11594 ref_set_non_owning(env, reg); 11595 } 11596 })); 11597 return 0; 11598 } 11599 11600 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 11601 return -EFAULT; 11602 } 11603 11604 /* Implementation details: 11605 * 11606 * Each register points to some region of memory, which we define as an 11607 * allocation. Each allocation may embed a bpf_spin_lock which protects any 11608 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 11609 * allocation. The lock and the data it protects are colocated in the same 11610 * memory region. 11611 * 11612 * Hence, everytime a register holds a pointer value pointing to such 11613 * allocation, the verifier preserves a unique reg->id for it. 11614 * 11615 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 11616 * bpf_spin_lock is called. 11617 * 11618 * To enable this, lock state in the verifier captures two values: 11619 * active_lock.ptr = Register's type specific pointer 11620 * active_lock.id = A unique ID for each register pointer value 11621 * 11622 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11623 * supported register types. 11624 * 11625 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11626 * allocated objects is the reg->btf pointer. 11627 * 11628 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11629 * can establish the provenance of the map value statically for each distinct 11630 * lookup into such maps. They always contain a single map value hence unique 11631 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11632 * 11633 * So, in case of global variables, they use array maps with max_entries = 1, 11634 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11635 * into the same map value as max_entries is 1, as described above). 11636 * 11637 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11638 * outer map pointer (in verifier context), but each lookup into an inner map 11639 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11640 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11641 * will get different reg->id assigned to each lookup, hence different 11642 * active_lock.id. 11643 * 11644 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11645 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11646 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11647 */ 11648 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11649 { 11650 void *ptr; 11651 u32 id; 11652 11653 switch ((int)reg->type) { 11654 case PTR_TO_MAP_VALUE: 11655 ptr = reg->map_ptr; 11656 break; 11657 case PTR_TO_BTF_ID | MEM_ALLOC: 11658 ptr = reg->btf; 11659 break; 11660 default: 11661 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 11662 return -EFAULT; 11663 } 11664 id = reg->id; 11665 11666 if (!env->cur_state->active_lock.ptr) 11667 return -EINVAL; 11668 if (env->cur_state->active_lock.ptr != ptr || 11669 env->cur_state->active_lock.id != id) { 11670 verbose(env, "held lock and object are not in the same allocation\n"); 11671 return -EINVAL; 11672 } 11673 return 0; 11674 } 11675 11676 static bool is_bpf_list_api_kfunc(u32 btf_id) 11677 { 11678 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11679 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11680 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11681 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 11682 } 11683 11684 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11685 { 11686 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 11687 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11688 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 11689 } 11690 11691 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11692 { 11693 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 11694 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11695 } 11696 11697 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11698 { 11699 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11700 } 11701 11702 static bool is_async_callback_calling_kfunc(u32 btf_id) 11703 { 11704 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl]; 11705 } 11706 11707 static bool is_bpf_throw_kfunc(struct bpf_insn *insn) 11708 { 11709 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 11710 insn->imm == special_kfunc_list[KF_bpf_throw]; 11711 } 11712 11713 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id) 11714 { 11715 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl]; 11716 } 11717 11718 static bool is_callback_calling_kfunc(u32 btf_id) 11719 { 11720 return is_sync_callback_calling_kfunc(btf_id) || 11721 is_async_callback_calling_kfunc(btf_id); 11722 } 11723 11724 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11725 { 11726 return is_bpf_rbtree_api_kfunc(btf_id); 11727 } 11728 11729 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11730 enum btf_field_type head_field_type, 11731 u32 kfunc_btf_id) 11732 { 11733 bool ret; 11734 11735 switch (head_field_type) { 11736 case BPF_LIST_HEAD: 11737 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11738 break; 11739 case BPF_RB_ROOT: 11740 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11741 break; 11742 default: 11743 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11744 btf_field_type_name(head_field_type)); 11745 return false; 11746 } 11747 11748 if (!ret) 11749 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11750 btf_field_type_name(head_field_type)); 11751 return ret; 11752 } 11753 11754 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11755 enum btf_field_type node_field_type, 11756 u32 kfunc_btf_id) 11757 { 11758 bool ret; 11759 11760 switch (node_field_type) { 11761 case BPF_LIST_NODE: 11762 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11763 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 11764 break; 11765 case BPF_RB_NODE: 11766 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11767 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 11768 break; 11769 default: 11770 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11771 btf_field_type_name(node_field_type)); 11772 return false; 11773 } 11774 11775 if (!ret) 11776 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11777 btf_field_type_name(node_field_type)); 11778 return ret; 11779 } 11780 11781 static int 11782 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11783 struct bpf_reg_state *reg, u32 regno, 11784 struct bpf_kfunc_call_arg_meta *meta, 11785 enum btf_field_type head_field_type, 11786 struct btf_field **head_field) 11787 { 11788 const char *head_type_name; 11789 struct btf_field *field; 11790 struct btf_record *rec; 11791 u32 head_off; 11792 11793 if (meta->btf != btf_vmlinux) { 11794 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11795 return -EFAULT; 11796 } 11797 11798 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11799 return -EFAULT; 11800 11801 head_type_name = btf_field_type_name(head_field_type); 11802 if (!tnum_is_const(reg->var_off)) { 11803 verbose(env, 11804 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11805 regno, head_type_name); 11806 return -EINVAL; 11807 } 11808 11809 rec = reg_btf_record(reg); 11810 head_off = reg->off + reg->var_off.value; 11811 field = btf_record_find(rec, head_off, head_field_type); 11812 if (!field) { 11813 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11814 return -EINVAL; 11815 } 11816 11817 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11818 if (check_reg_allocation_locked(env, reg)) { 11819 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11820 rec->spin_lock_off, head_type_name); 11821 return -EINVAL; 11822 } 11823 11824 if (*head_field) { 11825 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 11826 return -EFAULT; 11827 } 11828 *head_field = field; 11829 return 0; 11830 } 11831 11832 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11833 struct bpf_reg_state *reg, u32 regno, 11834 struct bpf_kfunc_call_arg_meta *meta) 11835 { 11836 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 11837 &meta->arg_list_head.field); 11838 } 11839 11840 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11841 struct bpf_reg_state *reg, u32 regno, 11842 struct bpf_kfunc_call_arg_meta *meta) 11843 { 11844 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 11845 &meta->arg_rbtree_root.field); 11846 } 11847 11848 static int 11849 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11850 struct bpf_reg_state *reg, u32 regno, 11851 struct bpf_kfunc_call_arg_meta *meta, 11852 enum btf_field_type head_field_type, 11853 enum btf_field_type node_field_type, 11854 struct btf_field **node_field) 11855 { 11856 const char *node_type_name; 11857 const struct btf_type *et, *t; 11858 struct btf_field *field; 11859 u32 node_off; 11860 11861 if (meta->btf != btf_vmlinux) { 11862 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11863 return -EFAULT; 11864 } 11865 11866 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11867 return -EFAULT; 11868 11869 node_type_name = btf_field_type_name(node_field_type); 11870 if (!tnum_is_const(reg->var_off)) { 11871 verbose(env, 11872 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11873 regno, node_type_name); 11874 return -EINVAL; 11875 } 11876 11877 node_off = reg->off + reg->var_off.value; 11878 field = reg_find_field_offset(reg, node_off, node_field_type); 11879 if (!field) { 11880 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11881 return -EINVAL; 11882 } 11883 11884 field = *node_field; 11885 11886 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11887 t = btf_type_by_id(reg->btf, reg->btf_id); 11888 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11889 field->graph_root.value_btf_id, true)) { 11890 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11891 "in struct %s, but arg is at offset=%d in struct %s\n", 11892 btf_field_type_name(head_field_type), 11893 btf_field_type_name(node_field_type), 11894 field->graph_root.node_offset, 11895 btf_name_by_offset(field->graph_root.btf, et->name_off), 11896 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11897 return -EINVAL; 11898 } 11899 meta->arg_btf = reg->btf; 11900 meta->arg_btf_id = reg->btf_id; 11901 11902 if (node_off != field->graph_root.node_offset) { 11903 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11904 node_off, btf_field_type_name(node_field_type), 11905 field->graph_root.node_offset, 11906 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11907 return -EINVAL; 11908 } 11909 11910 return 0; 11911 } 11912 11913 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11914 struct bpf_reg_state *reg, u32 regno, 11915 struct bpf_kfunc_call_arg_meta *meta) 11916 { 11917 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11918 BPF_LIST_HEAD, BPF_LIST_NODE, 11919 &meta->arg_list_head.field); 11920 } 11921 11922 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11923 struct bpf_reg_state *reg, u32 regno, 11924 struct bpf_kfunc_call_arg_meta *meta) 11925 { 11926 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11927 BPF_RB_ROOT, BPF_RB_NODE, 11928 &meta->arg_rbtree_root.field); 11929 } 11930 11931 /* 11932 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 11933 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 11934 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 11935 * them can only be attached to some specific hook points. 11936 */ 11937 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 11938 { 11939 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11940 11941 switch (prog_type) { 11942 case BPF_PROG_TYPE_LSM: 11943 return true; 11944 case BPF_PROG_TYPE_TRACING: 11945 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 11946 return true; 11947 fallthrough; 11948 default: 11949 return in_sleepable(env); 11950 } 11951 } 11952 11953 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11954 int insn_idx) 11955 { 11956 const char *func_name = meta->func_name, *ref_tname; 11957 const struct btf *btf = meta->btf; 11958 const struct btf_param *args; 11959 struct btf_record *rec; 11960 u32 i, nargs; 11961 int ret; 11962 11963 args = (const struct btf_param *)(meta->func_proto + 1); 11964 nargs = btf_type_vlen(meta->func_proto); 11965 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 11966 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11967 MAX_BPF_FUNC_REG_ARGS); 11968 return -EINVAL; 11969 } 11970 11971 /* Check that BTF function arguments match actual types that the 11972 * verifier sees. 11973 */ 11974 for (i = 0; i < nargs; i++) { 11975 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 11976 const struct btf_type *t, *ref_t, *resolve_ret; 11977 enum bpf_arg_type arg_type = ARG_DONTCARE; 11978 u32 regno = i + 1, ref_id, type_size; 11979 bool is_ret_buf_sz = false; 11980 int kf_arg_type; 11981 11982 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11983 11984 if (is_kfunc_arg_ignore(btf, &args[i])) 11985 continue; 11986 11987 if (btf_type_is_scalar(t)) { 11988 if (reg->type != SCALAR_VALUE) { 11989 verbose(env, "R%d is not a scalar\n", regno); 11990 return -EINVAL; 11991 } 11992 11993 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11994 if (meta->arg_constant.found) { 11995 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11996 return -EFAULT; 11997 } 11998 if (!tnum_is_const(reg->var_off)) { 11999 verbose(env, "R%d must be a known constant\n", regno); 12000 return -EINVAL; 12001 } 12002 ret = mark_chain_precision(env, regno); 12003 if (ret < 0) 12004 return ret; 12005 meta->arg_constant.found = true; 12006 meta->arg_constant.value = reg->var_off.value; 12007 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 12008 meta->r0_rdonly = true; 12009 is_ret_buf_sz = true; 12010 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 12011 is_ret_buf_sz = true; 12012 } 12013 12014 if (is_ret_buf_sz) { 12015 if (meta->r0_size) { 12016 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 12017 return -EINVAL; 12018 } 12019 12020 if (!tnum_is_const(reg->var_off)) { 12021 verbose(env, "R%d is not a const\n", regno); 12022 return -EINVAL; 12023 } 12024 12025 meta->r0_size = reg->var_off.value; 12026 ret = mark_chain_precision(env, regno); 12027 if (ret) 12028 return ret; 12029 } 12030 continue; 12031 } 12032 12033 if (!btf_type_is_ptr(t)) { 12034 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 12035 return -EINVAL; 12036 } 12037 12038 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 12039 (register_is_null(reg) || type_may_be_null(reg->type)) && 12040 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 12041 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 12042 return -EACCES; 12043 } 12044 12045 if (reg->ref_obj_id) { 12046 if (is_kfunc_release(meta) && meta->ref_obj_id) { 12047 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 12048 regno, reg->ref_obj_id, 12049 meta->ref_obj_id); 12050 return -EFAULT; 12051 } 12052 meta->ref_obj_id = reg->ref_obj_id; 12053 if (is_kfunc_release(meta)) 12054 meta->release_regno = regno; 12055 } 12056 12057 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 12058 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12059 12060 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 12061 if (kf_arg_type < 0) 12062 return kf_arg_type; 12063 12064 switch (kf_arg_type) { 12065 case KF_ARG_PTR_TO_NULL: 12066 continue; 12067 case KF_ARG_PTR_TO_MAP: 12068 if (!reg->map_ptr) { 12069 verbose(env, "pointer in R%d isn't map pointer\n", regno); 12070 return -EINVAL; 12071 } 12072 if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) { 12073 /* Use map_uid (which is unique id of inner map) to reject: 12074 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 12075 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 12076 * if (inner_map1 && inner_map2) { 12077 * wq = bpf_map_lookup_elem(inner_map1); 12078 * if (wq) 12079 * // mismatch would have been allowed 12080 * bpf_wq_init(wq, inner_map2); 12081 * } 12082 * 12083 * Comparing map_ptr is enough to distinguish normal and outer maps. 12084 */ 12085 if (meta->map.ptr != reg->map_ptr || 12086 meta->map.uid != reg->map_uid) { 12087 verbose(env, 12088 "workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 12089 meta->map.uid, reg->map_uid); 12090 return -EINVAL; 12091 } 12092 } 12093 meta->map.ptr = reg->map_ptr; 12094 meta->map.uid = reg->map_uid; 12095 fallthrough; 12096 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 12097 case KF_ARG_PTR_TO_BTF_ID: 12098 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 12099 break; 12100 12101 if (!is_trusted_reg(reg)) { 12102 if (!is_kfunc_rcu(meta)) { 12103 verbose(env, "R%d must be referenced or trusted\n", regno); 12104 return -EINVAL; 12105 } 12106 if (!is_rcu_reg(reg)) { 12107 verbose(env, "R%d must be a rcu pointer\n", regno); 12108 return -EINVAL; 12109 } 12110 } 12111 fallthrough; 12112 case KF_ARG_PTR_TO_CTX: 12113 case KF_ARG_PTR_TO_DYNPTR: 12114 case KF_ARG_PTR_TO_ITER: 12115 case KF_ARG_PTR_TO_LIST_HEAD: 12116 case KF_ARG_PTR_TO_LIST_NODE: 12117 case KF_ARG_PTR_TO_RB_ROOT: 12118 case KF_ARG_PTR_TO_RB_NODE: 12119 case KF_ARG_PTR_TO_MEM: 12120 case KF_ARG_PTR_TO_MEM_SIZE: 12121 case KF_ARG_PTR_TO_CALLBACK: 12122 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12123 case KF_ARG_PTR_TO_CONST_STR: 12124 case KF_ARG_PTR_TO_WORKQUEUE: 12125 break; 12126 default: 12127 WARN_ON_ONCE(1); 12128 return -EFAULT; 12129 } 12130 12131 if (is_kfunc_release(meta) && reg->ref_obj_id) 12132 arg_type |= OBJ_RELEASE; 12133 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 12134 if (ret < 0) 12135 return ret; 12136 12137 switch (kf_arg_type) { 12138 case KF_ARG_PTR_TO_CTX: 12139 if (reg->type != PTR_TO_CTX) { 12140 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 12141 return -EINVAL; 12142 } 12143 12144 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12145 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 12146 if (ret < 0) 12147 return -EINVAL; 12148 meta->ret_btf_id = ret; 12149 } 12150 break; 12151 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 12152 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 12153 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) { 12154 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i); 12155 return -EINVAL; 12156 } 12157 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 12158 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 12159 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i); 12160 return -EINVAL; 12161 } 12162 } else { 12163 verbose(env, "arg#%d expected pointer to allocated object\n", i); 12164 return -EINVAL; 12165 } 12166 if (!reg->ref_obj_id) { 12167 verbose(env, "allocated object must be referenced\n"); 12168 return -EINVAL; 12169 } 12170 if (meta->btf == btf_vmlinux) { 12171 meta->arg_btf = reg->btf; 12172 meta->arg_btf_id = reg->btf_id; 12173 } 12174 break; 12175 case KF_ARG_PTR_TO_DYNPTR: 12176 { 12177 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 12178 int clone_ref_obj_id = 0; 12179 12180 if (reg->type == CONST_PTR_TO_DYNPTR) 12181 dynptr_arg_type |= MEM_RDONLY; 12182 12183 if (is_kfunc_arg_uninit(btf, &args[i])) 12184 dynptr_arg_type |= MEM_UNINIT; 12185 12186 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 12187 dynptr_arg_type |= DYNPTR_TYPE_SKB; 12188 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 12189 dynptr_arg_type |= DYNPTR_TYPE_XDP; 12190 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 12191 (dynptr_arg_type & MEM_UNINIT)) { 12192 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 12193 12194 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 12195 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 12196 return -EFAULT; 12197 } 12198 12199 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 12200 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 12201 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 12202 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 12203 return -EFAULT; 12204 } 12205 } 12206 12207 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 12208 if (ret < 0) 12209 return ret; 12210 12211 if (!(dynptr_arg_type & MEM_UNINIT)) { 12212 int id = dynptr_id(env, reg); 12213 12214 if (id < 0) { 12215 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 12216 return id; 12217 } 12218 meta->initialized_dynptr.id = id; 12219 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 12220 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 12221 } 12222 12223 break; 12224 } 12225 case KF_ARG_PTR_TO_ITER: 12226 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 12227 if (!check_css_task_iter_allowlist(env)) { 12228 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 12229 return -EINVAL; 12230 } 12231 } 12232 ret = process_iter_arg(env, regno, insn_idx, meta); 12233 if (ret < 0) 12234 return ret; 12235 break; 12236 case KF_ARG_PTR_TO_LIST_HEAD: 12237 if (reg->type != PTR_TO_MAP_VALUE && 12238 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12239 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 12240 return -EINVAL; 12241 } 12242 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 12243 verbose(env, "allocated object must be referenced\n"); 12244 return -EINVAL; 12245 } 12246 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 12247 if (ret < 0) 12248 return ret; 12249 break; 12250 case KF_ARG_PTR_TO_RB_ROOT: 12251 if (reg->type != PTR_TO_MAP_VALUE && 12252 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12253 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 12254 return -EINVAL; 12255 } 12256 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 12257 verbose(env, "allocated object must be referenced\n"); 12258 return -EINVAL; 12259 } 12260 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 12261 if (ret < 0) 12262 return ret; 12263 break; 12264 case KF_ARG_PTR_TO_LIST_NODE: 12265 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12266 verbose(env, "arg#%d expected pointer to allocated object\n", i); 12267 return -EINVAL; 12268 } 12269 if (!reg->ref_obj_id) { 12270 verbose(env, "allocated object must be referenced\n"); 12271 return -EINVAL; 12272 } 12273 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 12274 if (ret < 0) 12275 return ret; 12276 break; 12277 case KF_ARG_PTR_TO_RB_NODE: 12278 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 12279 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 12280 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 12281 return -EINVAL; 12282 } 12283 if (in_rbtree_lock_required_cb(env)) { 12284 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 12285 return -EINVAL; 12286 } 12287 } else { 12288 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12289 verbose(env, "arg#%d expected pointer to allocated object\n", i); 12290 return -EINVAL; 12291 } 12292 if (!reg->ref_obj_id) { 12293 verbose(env, "allocated object must be referenced\n"); 12294 return -EINVAL; 12295 } 12296 } 12297 12298 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 12299 if (ret < 0) 12300 return ret; 12301 break; 12302 case KF_ARG_PTR_TO_MAP: 12303 /* If argument has '__map' suffix expect 'struct bpf_map *' */ 12304 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP]; 12305 ref_t = btf_type_by_id(btf_vmlinux, ref_id); 12306 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12307 fallthrough; 12308 case KF_ARG_PTR_TO_BTF_ID: 12309 /* Only base_type is checked, further checks are done here */ 12310 if ((base_type(reg->type) != PTR_TO_BTF_ID || 12311 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 12312 !reg2btf_ids[base_type(reg->type)]) { 12313 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 12314 verbose(env, "expected %s or socket\n", 12315 reg_type_str(env, base_type(reg->type) | 12316 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 12317 return -EINVAL; 12318 } 12319 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 12320 if (ret < 0) 12321 return ret; 12322 break; 12323 case KF_ARG_PTR_TO_MEM: 12324 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 12325 if (IS_ERR(resolve_ret)) { 12326 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 12327 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 12328 return -EINVAL; 12329 } 12330 ret = check_mem_reg(env, reg, regno, type_size); 12331 if (ret < 0) 12332 return ret; 12333 break; 12334 case KF_ARG_PTR_TO_MEM_SIZE: 12335 { 12336 struct bpf_reg_state *buff_reg = ®s[regno]; 12337 const struct btf_param *buff_arg = &args[i]; 12338 struct bpf_reg_state *size_reg = ®s[regno + 1]; 12339 const struct btf_param *size_arg = &args[i + 1]; 12340 12341 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 12342 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 12343 if (ret < 0) { 12344 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 12345 return ret; 12346 } 12347 } 12348 12349 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 12350 if (meta->arg_constant.found) { 12351 verbose(env, "verifier internal error: only one constant argument permitted\n"); 12352 return -EFAULT; 12353 } 12354 if (!tnum_is_const(size_reg->var_off)) { 12355 verbose(env, "R%d must be a known constant\n", regno + 1); 12356 return -EINVAL; 12357 } 12358 meta->arg_constant.found = true; 12359 meta->arg_constant.value = size_reg->var_off.value; 12360 } 12361 12362 /* Skip next '__sz' or '__szk' argument */ 12363 i++; 12364 break; 12365 } 12366 case KF_ARG_PTR_TO_CALLBACK: 12367 if (reg->type != PTR_TO_FUNC) { 12368 verbose(env, "arg%d expected pointer to func\n", i); 12369 return -EINVAL; 12370 } 12371 meta->subprogno = reg->subprogno; 12372 break; 12373 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12374 if (!type_is_ptr_alloc_obj(reg->type)) { 12375 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 12376 return -EINVAL; 12377 } 12378 if (!type_is_non_owning_ref(reg->type)) 12379 meta->arg_owning_ref = true; 12380 12381 rec = reg_btf_record(reg); 12382 if (!rec) { 12383 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 12384 return -EFAULT; 12385 } 12386 12387 if (rec->refcount_off < 0) { 12388 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 12389 return -EINVAL; 12390 } 12391 12392 meta->arg_btf = reg->btf; 12393 meta->arg_btf_id = reg->btf_id; 12394 break; 12395 case KF_ARG_PTR_TO_CONST_STR: 12396 if (reg->type != PTR_TO_MAP_VALUE) { 12397 verbose(env, "arg#%d doesn't point to a const string\n", i); 12398 return -EINVAL; 12399 } 12400 ret = check_reg_const_str(env, reg, regno); 12401 if (ret) 12402 return ret; 12403 break; 12404 case KF_ARG_PTR_TO_WORKQUEUE: 12405 if (reg->type != PTR_TO_MAP_VALUE) { 12406 verbose(env, "arg#%d doesn't point to a map value\n", i); 12407 return -EINVAL; 12408 } 12409 ret = process_wq_func(env, regno, meta); 12410 if (ret < 0) 12411 return ret; 12412 break; 12413 } 12414 } 12415 12416 if (is_kfunc_release(meta) && !meta->release_regno) { 12417 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 12418 func_name); 12419 return -EINVAL; 12420 } 12421 12422 return 0; 12423 } 12424 12425 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 12426 struct bpf_insn *insn, 12427 struct bpf_kfunc_call_arg_meta *meta, 12428 const char **kfunc_name) 12429 { 12430 const struct btf_type *func, *func_proto; 12431 u32 func_id, *kfunc_flags; 12432 const char *func_name; 12433 struct btf *desc_btf; 12434 12435 if (kfunc_name) 12436 *kfunc_name = NULL; 12437 12438 if (!insn->imm) 12439 return -EINVAL; 12440 12441 desc_btf = find_kfunc_desc_btf(env, insn->off); 12442 if (IS_ERR(desc_btf)) 12443 return PTR_ERR(desc_btf); 12444 12445 func_id = insn->imm; 12446 func = btf_type_by_id(desc_btf, func_id); 12447 func_name = btf_name_by_offset(desc_btf, func->name_off); 12448 if (kfunc_name) 12449 *kfunc_name = func_name; 12450 func_proto = btf_type_by_id(desc_btf, func->type); 12451 12452 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 12453 if (!kfunc_flags) { 12454 return -EACCES; 12455 } 12456 12457 memset(meta, 0, sizeof(*meta)); 12458 meta->btf = desc_btf; 12459 meta->func_id = func_id; 12460 meta->kfunc_flags = *kfunc_flags; 12461 meta->func_proto = func_proto; 12462 meta->func_name = func_name; 12463 12464 return 0; 12465 } 12466 12467 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 12468 12469 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 12470 int *insn_idx_p) 12471 { 12472 bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable; 12473 u32 i, nargs, ptr_type_id, release_ref_obj_id; 12474 struct bpf_reg_state *regs = cur_regs(env); 12475 const char *func_name, *ptr_type_name; 12476 const struct btf_type *t, *ptr_type; 12477 struct bpf_kfunc_call_arg_meta meta; 12478 struct bpf_insn_aux_data *insn_aux; 12479 int err, insn_idx = *insn_idx_p; 12480 const struct btf_param *args; 12481 const struct btf_type *ret_t; 12482 struct btf *desc_btf; 12483 12484 /* skip for now, but return error when we find this in fixup_kfunc_call */ 12485 if (!insn->imm) 12486 return 0; 12487 12488 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 12489 if (err == -EACCES && func_name) 12490 verbose(env, "calling kernel function %s is not allowed\n", func_name); 12491 if (err) 12492 return err; 12493 desc_btf = meta.btf; 12494 insn_aux = &env->insn_aux_data[insn_idx]; 12495 12496 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 12497 12498 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 12499 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 12500 return -EACCES; 12501 } 12502 12503 sleepable = is_kfunc_sleepable(&meta); 12504 if (sleepable && !in_sleepable(env)) { 12505 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 12506 return -EACCES; 12507 } 12508 12509 /* Check the arguments */ 12510 err = check_kfunc_args(env, &meta, insn_idx); 12511 if (err < 0) 12512 return err; 12513 12514 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12515 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12516 set_rbtree_add_callback_state); 12517 if (err) { 12518 verbose(env, "kfunc %s#%d failed callback verification\n", 12519 func_name, meta.func_id); 12520 return err; 12521 } 12522 } 12523 12524 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) { 12525 meta.r0_size = sizeof(u64); 12526 meta.r0_rdonly = false; 12527 } 12528 12529 if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) { 12530 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12531 set_timer_callback_state); 12532 if (err) { 12533 verbose(env, "kfunc %s#%d failed callback verification\n", 12534 func_name, meta.func_id); 12535 return err; 12536 } 12537 } 12538 12539 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 12540 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 12541 12542 preempt_disable = is_kfunc_bpf_preempt_disable(&meta); 12543 preempt_enable = is_kfunc_bpf_preempt_enable(&meta); 12544 12545 if (env->cur_state->active_rcu_lock) { 12546 struct bpf_func_state *state; 12547 struct bpf_reg_state *reg; 12548 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 12549 12550 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 12551 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 12552 return -EACCES; 12553 } 12554 12555 if (rcu_lock) { 12556 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 12557 return -EINVAL; 12558 } else if (rcu_unlock) { 12559 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({ 12560 if (reg->type & MEM_RCU) { 12561 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 12562 reg->type |= PTR_UNTRUSTED; 12563 } 12564 })); 12565 env->cur_state->active_rcu_lock = false; 12566 } else if (sleepable) { 12567 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 12568 return -EACCES; 12569 } 12570 } else if (rcu_lock) { 12571 env->cur_state->active_rcu_lock = true; 12572 } else if (rcu_unlock) { 12573 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 12574 return -EINVAL; 12575 } 12576 12577 if (env->cur_state->active_preempt_lock) { 12578 if (preempt_disable) { 12579 env->cur_state->active_preempt_lock++; 12580 } else if (preempt_enable) { 12581 env->cur_state->active_preempt_lock--; 12582 } else if (sleepable) { 12583 verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name); 12584 return -EACCES; 12585 } 12586 } else if (preempt_disable) { 12587 env->cur_state->active_preempt_lock++; 12588 } else if (preempt_enable) { 12589 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name); 12590 return -EINVAL; 12591 } 12592 12593 /* In case of release function, we get register number of refcounted 12594 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 12595 */ 12596 if (meta.release_regno) { 12597 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 12598 if (err) { 12599 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12600 func_name, meta.func_id); 12601 return err; 12602 } 12603 } 12604 12605 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 12606 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 12607 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12608 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 12609 insn_aux->insert_off = regs[BPF_REG_2].off; 12610 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 12611 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 12612 if (err) { 12613 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 12614 func_name, meta.func_id); 12615 return err; 12616 } 12617 12618 err = release_reference(env, release_ref_obj_id); 12619 if (err) { 12620 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12621 func_name, meta.func_id); 12622 return err; 12623 } 12624 } 12625 12626 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 12627 if (!bpf_jit_supports_exceptions()) { 12628 verbose(env, "JIT does not support calling kfunc %s#%d\n", 12629 func_name, meta.func_id); 12630 return -ENOTSUPP; 12631 } 12632 env->seen_exception = true; 12633 12634 /* In the case of the default callback, the cookie value passed 12635 * to bpf_throw becomes the return value of the program. 12636 */ 12637 if (!env->exception_callback_subprog) { 12638 err = check_return_code(env, BPF_REG_1, "R1"); 12639 if (err < 0) 12640 return err; 12641 } 12642 } 12643 12644 for (i = 0; i < CALLER_SAVED_REGS; i++) 12645 mark_reg_not_init(env, regs, caller_saved[i]); 12646 12647 /* Check return type */ 12648 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 12649 12650 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 12651 /* Only exception is bpf_obj_new_impl */ 12652 if (meta.btf != btf_vmlinux || 12653 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 12654 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] && 12655 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 12656 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 12657 return -EINVAL; 12658 } 12659 } 12660 12661 if (btf_type_is_scalar(t)) { 12662 mark_reg_unknown(env, regs, BPF_REG_0); 12663 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 12664 } else if (btf_type_is_ptr(t)) { 12665 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 12666 12667 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12668 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 12669 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12670 struct btf_struct_meta *struct_meta; 12671 struct btf *ret_btf; 12672 u32 ret_btf_id; 12673 12674 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set) 12675 return -ENOMEM; 12676 12677 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 12678 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 12679 return -EINVAL; 12680 } 12681 12682 ret_btf = env->prog->aux->btf; 12683 ret_btf_id = meta.arg_constant.value; 12684 12685 /* This may be NULL due to user not supplying a BTF */ 12686 if (!ret_btf) { 12687 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 12688 return -EINVAL; 12689 } 12690 12691 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 12692 if (!ret_t || !__btf_type_is_struct(ret_t)) { 12693 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 12694 return -EINVAL; 12695 } 12696 12697 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12698 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 12699 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 12700 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 12701 return -EINVAL; 12702 } 12703 12704 if (!bpf_global_percpu_ma_set) { 12705 mutex_lock(&bpf_percpu_ma_lock); 12706 if (!bpf_global_percpu_ma_set) { 12707 /* Charge memory allocated with bpf_global_percpu_ma to 12708 * root memcg. The obj_cgroup for root memcg is NULL. 12709 */ 12710 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 12711 if (!err) 12712 bpf_global_percpu_ma_set = true; 12713 } 12714 mutex_unlock(&bpf_percpu_ma_lock); 12715 if (err) 12716 return err; 12717 } 12718 12719 mutex_lock(&bpf_percpu_ma_lock); 12720 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 12721 mutex_unlock(&bpf_percpu_ma_lock); 12722 if (err) 12723 return err; 12724 } 12725 12726 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 12727 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12728 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 12729 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 12730 return -EINVAL; 12731 } 12732 12733 if (struct_meta) { 12734 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 12735 return -EINVAL; 12736 } 12737 } 12738 12739 mark_reg_known_zero(env, regs, BPF_REG_0); 12740 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12741 regs[BPF_REG_0].btf = ret_btf; 12742 regs[BPF_REG_0].btf_id = ret_btf_id; 12743 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) 12744 regs[BPF_REG_0].type |= MEM_PERCPU; 12745 12746 insn_aux->obj_new_size = ret_t->size; 12747 insn_aux->kptr_struct_meta = struct_meta; 12748 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 12749 mark_reg_known_zero(env, regs, BPF_REG_0); 12750 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12751 regs[BPF_REG_0].btf = meta.arg_btf; 12752 regs[BPF_REG_0].btf_id = meta.arg_btf_id; 12753 12754 insn_aux->kptr_struct_meta = 12755 btf_find_struct_meta(meta.arg_btf, 12756 meta.arg_btf_id); 12757 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 12758 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 12759 struct btf_field *field = meta.arg_list_head.field; 12760 12761 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12762 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12763 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12764 struct btf_field *field = meta.arg_rbtree_root.field; 12765 12766 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12767 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12768 mark_reg_known_zero(env, regs, BPF_REG_0); 12769 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 12770 regs[BPF_REG_0].btf = desc_btf; 12771 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 12772 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 12773 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 12774 if (!ret_t || !btf_type_is_struct(ret_t)) { 12775 verbose(env, 12776 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 12777 return -EINVAL; 12778 } 12779 12780 mark_reg_known_zero(env, regs, BPF_REG_0); 12781 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 12782 regs[BPF_REG_0].btf = desc_btf; 12783 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 12784 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 12785 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 12786 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 12787 12788 mark_reg_known_zero(env, regs, BPF_REG_0); 12789 12790 if (!meta.arg_constant.found) { 12791 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 12792 return -EFAULT; 12793 } 12794 12795 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 12796 12797 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 12798 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 12799 12800 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 12801 regs[BPF_REG_0].type |= MEM_RDONLY; 12802 } else { 12803 /* this will set env->seen_direct_write to true */ 12804 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 12805 verbose(env, "the prog does not allow writes to packet data\n"); 12806 return -EINVAL; 12807 } 12808 } 12809 12810 if (!meta.initialized_dynptr.id) { 12811 verbose(env, "verifier internal error: no dynptr id\n"); 12812 return -EFAULT; 12813 } 12814 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 12815 12816 /* we don't need to set BPF_REG_0's ref obj id 12817 * because packet slices are not refcounted (see 12818 * dynptr_type_refcounted) 12819 */ 12820 } else { 12821 verbose(env, "kernel function %s unhandled dynamic return type\n", 12822 meta.func_name); 12823 return -EFAULT; 12824 } 12825 } else if (btf_type_is_void(ptr_type)) { 12826 /* kfunc returning 'void *' is equivalent to returning scalar */ 12827 mark_reg_unknown(env, regs, BPF_REG_0); 12828 } else if (!__btf_type_is_struct(ptr_type)) { 12829 if (!meta.r0_size) { 12830 __u32 sz; 12831 12832 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 12833 meta.r0_size = sz; 12834 meta.r0_rdonly = true; 12835 } 12836 } 12837 if (!meta.r0_size) { 12838 ptr_type_name = btf_name_by_offset(desc_btf, 12839 ptr_type->name_off); 12840 verbose(env, 12841 "kernel function %s returns pointer type %s %s is not supported\n", 12842 func_name, 12843 btf_type_str(ptr_type), 12844 ptr_type_name); 12845 return -EINVAL; 12846 } 12847 12848 mark_reg_known_zero(env, regs, BPF_REG_0); 12849 regs[BPF_REG_0].type = PTR_TO_MEM; 12850 regs[BPF_REG_0].mem_size = meta.r0_size; 12851 12852 if (meta.r0_rdonly) 12853 regs[BPF_REG_0].type |= MEM_RDONLY; 12854 12855 /* Ensures we don't access the memory after a release_reference() */ 12856 if (meta.ref_obj_id) 12857 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 12858 } else { 12859 mark_reg_known_zero(env, regs, BPF_REG_0); 12860 regs[BPF_REG_0].btf = desc_btf; 12861 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 12862 regs[BPF_REG_0].btf_id = ptr_type_id; 12863 12864 if (is_iter_next_kfunc(&meta)) { 12865 struct bpf_reg_state *cur_iter; 12866 12867 cur_iter = get_iter_from_state(env->cur_state, &meta); 12868 12869 if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */ 12870 regs[BPF_REG_0].type |= MEM_RCU; 12871 else 12872 regs[BPF_REG_0].type |= PTR_TRUSTED; 12873 } 12874 } 12875 12876 if (is_kfunc_ret_null(&meta)) { 12877 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 12878 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 12879 regs[BPF_REG_0].id = ++env->id_gen; 12880 } 12881 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 12882 if (is_kfunc_acquire(&meta)) { 12883 int id = acquire_reference_state(env, insn_idx); 12884 12885 if (id < 0) 12886 return id; 12887 if (is_kfunc_ret_null(&meta)) 12888 regs[BPF_REG_0].id = id; 12889 regs[BPF_REG_0].ref_obj_id = id; 12890 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12891 ref_set_non_owning(env, ®s[BPF_REG_0]); 12892 } 12893 12894 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 12895 regs[BPF_REG_0].id = ++env->id_gen; 12896 } else if (btf_type_is_void(t)) { 12897 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12898 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 12899 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 12900 insn_aux->kptr_struct_meta = 12901 btf_find_struct_meta(meta.arg_btf, 12902 meta.arg_btf_id); 12903 } 12904 } 12905 } 12906 12907 nargs = btf_type_vlen(meta.func_proto); 12908 args = (const struct btf_param *)(meta.func_proto + 1); 12909 for (i = 0; i < nargs; i++) { 12910 u32 regno = i + 1; 12911 12912 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 12913 if (btf_type_is_ptr(t)) 12914 mark_btf_func_reg_size(env, regno, sizeof(void *)); 12915 else 12916 /* scalar. ensured by btf_check_kfunc_arg_match() */ 12917 mark_btf_func_reg_size(env, regno, t->size); 12918 } 12919 12920 if (is_iter_next_kfunc(&meta)) { 12921 err = process_iter_next_call(env, insn_idx, &meta); 12922 if (err) 12923 return err; 12924 } 12925 12926 return 0; 12927 } 12928 12929 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 12930 const struct bpf_reg_state *reg, 12931 enum bpf_reg_type type) 12932 { 12933 bool known = tnum_is_const(reg->var_off); 12934 s64 val = reg->var_off.value; 12935 s64 smin = reg->smin_value; 12936 12937 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 12938 verbose(env, "math between %s pointer and %lld is not allowed\n", 12939 reg_type_str(env, type), val); 12940 return false; 12941 } 12942 12943 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 12944 verbose(env, "%s pointer offset %d is not allowed\n", 12945 reg_type_str(env, type), reg->off); 12946 return false; 12947 } 12948 12949 if (smin == S64_MIN) { 12950 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 12951 reg_type_str(env, type)); 12952 return false; 12953 } 12954 12955 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 12956 verbose(env, "value %lld makes %s pointer be out of bounds\n", 12957 smin, reg_type_str(env, type)); 12958 return false; 12959 } 12960 12961 return true; 12962 } 12963 12964 enum { 12965 REASON_BOUNDS = -1, 12966 REASON_TYPE = -2, 12967 REASON_PATHS = -3, 12968 REASON_LIMIT = -4, 12969 REASON_STACK = -5, 12970 }; 12971 12972 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 12973 u32 *alu_limit, bool mask_to_left) 12974 { 12975 u32 max = 0, ptr_limit = 0; 12976 12977 switch (ptr_reg->type) { 12978 case PTR_TO_STACK: 12979 /* Offset 0 is out-of-bounds, but acceptable start for the 12980 * left direction, see BPF_REG_FP. Also, unknown scalar 12981 * offset where we would need to deal with min/max bounds is 12982 * currently prohibited for unprivileged. 12983 */ 12984 max = MAX_BPF_STACK + mask_to_left; 12985 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 12986 break; 12987 case PTR_TO_MAP_VALUE: 12988 max = ptr_reg->map_ptr->value_size; 12989 ptr_limit = (mask_to_left ? 12990 ptr_reg->smin_value : 12991 ptr_reg->umax_value) + ptr_reg->off; 12992 break; 12993 default: 12994 return REASON_TYPE; 12995 } 12996 12997 if (ptr_limit >= max) 12998 return REASON_LIMIT; 12999 *alu_limit = ptr_limit; 13000 return 0; 13001 } 13002 13003 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 13004 const struct bpf_insn *insn) 13005 { 13006 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 13007 } 13008 13009 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 13010 u32 alu_state, u32 alu_limit) 13011 { 13012 /* If we arrived here from different branches with different 13013 * state or limits to sanitize, then this won't work. 13014 */ 13015 if (aux->alu_state && 13016 (aux->alu_state != alu_state || 13017 aux->alu_limit != alu_limit)) 13018 return REASON_PATHS; 13019 13020 /* Corresponding fixup done in do_misc_fixups(). */ 13021 aux->alu_state = alu_state; 13022 aux->alu_limit = alu_limit; 13023 return 0; 13024 } 13025 13026 static int sanitize_val_alu(struct bpf_verifier_env *env, 13027 struct bpf_insn *insn) 13028 { 13029 struct bpf_insn_aux_data *aux = cur_aux(env); 13030 13031 if (can_skip_alu_sanitation(env, insn)) 13032 return 0; 13033 13034 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 13035 } 13036 13037 static bool sanitize_needed(u8 opcode) 13038 { 13039 return opcode == BPF_ADD || opcode == BPF_SUB; 13040 } 13041 13042 struct bpf_sanitize_info { 13043 struct bpf_insn_aux_data aux; 13044 bool mask_to_left; 13045 }; 13046 13047 static struct bpf_verifier_state * 13048 sanitize_speculative_path(struct bpf_verifier_env *env, 13049 const struct bpf_insn *insn, 13050 u32 next_idx, u32 curr_idx) 13051 { 13052 struct bpf_verifier_state *branch; 13053 struct bpf_reg_state *regs; 13054 13055 branch = push_stack(env, next_idx, curr_idx, true); 13056 if (branch && insn) { 13057 regs = branch->frame[branch->curframe]->regs; 13058 if (BPF_SRC(insn->code) == BPF_K) { 13059 mark_reg_unknown(env, regs, insn->dst_reg); 13060 } else if (BPF_SRC(insn->code) == BPF_X) { 13061 mark_reg_unknown(env, regs, insn->dst_reg); 13062 mark_reg_unknown(env, regs, insn->src_reg); 13063 } 13064 } 13065 return branch; 13066 } 13067 13068 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 13069 struct bpf_insn *insn, 13070 const struct bpf_reg_state *ptr_reg, 13071 const struct bpf_reg_state *off_reg, 13072 struct bpf_reg_state *dst_reg, 13073 struct bpf_sanitize_info *info, 13074 const bool commit_window) 13075 { 13076 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 13077 struct bpf_verifier_state *vstate = env->cur_state; 13078 bool off_is_imm = tnum_is_const(off_reg->var_off); 13079 bool off_is_neg = off_reg->smin_value < 0; 13080 bool ptr_is_dst_reg = ptr_reg == dst_reg; 13081 u8 opcode = BPF_OP(insn->code); 13082 u32 alu_state, alu_limit; 13083 struct bpf_reg_state tmp; 13084 bool ret; 13085 int err; 13086 13087 if (can_skip_alu_sanitation(env, insn)) 13088 return 0; 13089 13090 /* We already marked aux for masking from non-speculative 13091 * paths, thus we got here in the first place. We only care 13092 * to explore bad access from here. 13093 */ 13094 if (vstate->speculative) 13095 goto do_sim; 13096 13097 if (!commit_window) { 13098 if (!tnum_is_const(off_reg->var_off) && 13099 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 13100 return REASON_BOUNDS; 13101 13102 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 13103 (opcode == BPF_SUB && !off_is_neg); 13104 } 13105 13106 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 13107 if (err < 0) 13108 return err; 13109 13110 if (commit_window) { 13111 /* In commit phase we narrow the masking window based on 13112 * the observed pointer move after the simulated operation. 13113 */ 13114 alu_state = info->aux.alu_state; 13115 alu_limit = abs(info->aux.alu_limit - alu_limit); 13116 } else { 13117 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 13118 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 13119 alu_state |= ptr_is_dst_reg ? 13120 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 13121 13122 /* Limit pruning on unknown scalars to enable deep search for 13123 * potential masking differences from other program paths. 13124 */ 13125 if (!off_is_imm) 13126 env->explore_alu_limits = true; 13127 } 13128 13129 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 13130 if (err < 0) 13131 return err; 13132 do_sim: 13133 /* If we're in commit phase, we're done here given we already 13134 * pushed the truncated dst_reg into the speculative verification 13135 * stack. 13136 * 13137 * Also, when register is a known constant, we rewrite register-based 13138 * operation to immediate-based, and thus do not need masking (and as 13139 * a consequence, do not need to simulate the zero-truncation either). 13140 */ 13141 if (commit_window || off_is_imm) 13142 return 0; 13143 13144 /* Simulate and find potential out-of-bounds access under 13145 * speculative execution from truncation as a result of 13146 * masking when off was not within expected range. If off 13147 * sits in dst, then we temporarily need to move ptr there 13148 * to simulate dst (== 0) +/-= ptr. Needed, for example, 13149 * for cases where we use K-based arithmetic in one direction 13150 * and truncated reg-based in the other in order to explore 13151 * bad access. 13152 */ 13153 if (!ptr_is_dst_reg) { 13154 tmp = *dst_reg; 13155 copy_register_state(dst_reg, ptr_reg); 13156 } 13157 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 13158 env->insn_idx); 13159 if (!ptr_is_dst_reg && ret) 13160 *dst_reg = tmp; 13161 return !ret ? REASON_STACK : 0; 13162 } 13163 13164 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 13165 { 13166 struct bpf_verifier_state *vstate = env->cur_state; 13167 13168 /* If we simulate paths under speculation, we don't update the 13169 * insn as 'seen' such that when we verify unreachable paths in 13170 * the non-speculative domain, sanitize_dead_code() can still 13171 * rewrite/sanitize them. 13172 */ 13173 if (!vstate->speculative) 13174 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 13175 } 13176 13177 static int sanitize_err(struct bpf_verifier_env *env, 13178 const struct bpf_insn *insn, int reason, 13179 const struct bpf_reg_state *off_reg, 13180 const struct bpf_reg_state *dst_reg) 13181 { 13182 static const char *err = "pointer arithmetic with it prohibited for !root"; 13183 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 13184 u32 dst = insn->dst_reg, src = insn->src_reg; 13185 13186 switch (reason) { 13187 case REASON_BOUNDS: 13188 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 13189 off_reg == dst_reg ? dst : src, err); 13190 break; 13191 case REASON_TYPE: 13192 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 13193 off_reg == dst_reg ? src : dst, err); 13194 break; 13195 case REASON_PATHS: 13196 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 13197 dst, op, err); 13198 break; 13199 case REASON_LIMIT: 13200 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 13201 dst, op, err); 13202 break; 13203 case REASON_STACK: 13204 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 13205 dst, err); 13206 break; 13207 default: 13208 verbose(env, "verifier internal error: unknown reason (%d)\n", 13209 reason); 13210 break; 13211 } 13212 13213 return -EACCES; 13214 } 13215 13216 /* check that stack access falls within stack limits and that 'reg' doesn't 13217 * have a variable offset. 13218 * 13219 * Variable offset is prohibited for unprivileged mode for simplicity since it 13220 * requires corresponding support in Spectre masking for stack ALU. See also 13221 * retrieve_ptr_limit(). 13222 * 13223 * 13224 * 'off' includes 'reg->off'. 13225 */ 13226 static int check_stack_access_for_ptr_arithmetic( 13227 struct bpf_verifier_env *env, 13228 int regno, 13229 const struct bpf_reg_state *reg, 13230 int off) 13231 { 13232 if (!tnum_is_const(reg->var_off)) { 13233 char tn_buf[48]; 13234 13235 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 13236 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 13237 regno, tn_buf, off); 13238 return -EACCES; 13239 } 13240 13241 if (off >= 0 || off < -MAX_BPF_STACK) { 13242 verbose(env, "R%d stack pointer arithmetic goes out of range, " 13243 "prohibited for !root; off=%d\n", regno, off); 13244 return -EACCES; 13245 } 13246 13247 return 0; 13248 } 13249 13250 static int sanitize_check_bounds(struct bpf_verifier_env *env, 13251 const struct bpf_insn *insn, 13252 const struct bpf_reg_state *dst_reg) 13253 { 13254 u32 dst = insn->dst_reg; 13255 13256 /* For unprivileged we require that resulting offset must be in bounds 13257 * in order to be able to sanitize access later on. 13258 */ 13259 if (env->bypass_spec_v1) 13260 return 0; 13261 13262 switch (dst_reg->type) { 13263 case PTR_TO_STACK: 13264 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 13265 dst_reg->off + dst_reg->var_off.value)) 13266 return -EACCES; 13267 break; 13268 case PTR_TO_MAP_VALUE: 13269 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 13270 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 13271 "prohibited for !root\n", dst); 13272 return -EACCES; 13273 } 13274 break; 13275 default: 13276 break; 13277 } 13278 13279 return 0; 13280 } 13281 13282 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 13283 * Caller should also handle BPF_MOV case separately. 13284 * If we return -EACCES, caller may want to try again treating pointer as a 13285 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 13286 */ 13287 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 13288 struct bpf_insn *insn, 13289 const struct bpf_reg_state *ptr_reg, 13290 const struct bpf_reg_state *off_reg) 13291 { 13292 struct bpf_verifier_state *vstate = env->cur_state; 13293 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13294 struct bpf_reg_state *regs = state->regs, *dst_reg; 13295 bool known = tnum_is_const(off_reg->var_off); 13296 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 13297 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 13298 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 13299 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 13300 struct bpf_sanitize_info info = {}; 13301 u8 opcode = BPF_OP(insn->code); 13302 u32 dst = insn->dst_reg; 13303 int ret; 13304 13305 dst_reg = ®s[dst]; 13306 13307 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 13308 smin_val > smax_val || umin_val > umax_val) { 13309 /* Taint dst register if offset had invalid bounds derived from 13310 * e.g. dead branches. 13311 */ 13312 __mark_reg_unknown(env, dst_reg); 13313 return 0; 13314 } 13315 13316 if (BPF_CLASS(insn->code) != BPF_ALU64) { 13317 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 13318 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13319 __mark_reg_unknown(env, dst_reg); 13320 return 0; 13321 } 13322 13323 verbose(env, 13324 "R%d 32-bit pointer arithmetic prohibited\n", 13325 dst); 13326 return -EACCES; 13327 } 13328 13329 if (ptr_reg->type & PTR_MAYBE_NULL) { 13330 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 13331 dst, reg_type_str(env, ptr_reg->type)); 13332 return -EACCES; 13333 } 13334 13335 switch (base_type(ptr_reg->type)) { 13336 case PTR_TO_CTX: 13337 case PTR_TO_MAP_VALUE: 13338 case PTR_TO_MAP_KEY: 13339 case PTR_TO_STACK: 13340 case PTR_TO_PACKET_META: 13341 case PTR_TO_PACKET: 13342 case PTR_TO_TP_BUFFER: 13343 case PTR_TO_BTF_ID: 13344 case PTR_TO_MEM: 13345 case PTR_TO_BUF: 13346 case PTR_TO_FUNC: 13347 case CONST_PTR_TO_DYNPTR: 13348 break; 13349 case PTR_TO_FLOW_KEYS: 13350 if (known) 13351 break; 13352 fallthrough; 13353 case CONST_PTR_TO_MAP: 13354 /* smin_val represents the known value */ 13355 if (known && smin_val == 0 && opcode == BPF_ADD) 13356 break; 13357 fallthrough; 13358 default: 13359 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 13360 dst, reg_type_str(env, ptr_reg->type)); 13361 return -EACCES; 13362 } 13363 13364 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 13365 * The id may be overwritten later if we create a new variable offset. 13366 */ 13367 dst_reg->type = ptr_reg->type; 13368 dst_reg->id = ptr_reg->id; 13369 13370 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 13371 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 13372 return -EINVAL; 13373 13374 /* pointer types do not carry 32-bit bounds at the moment. */ 13375 __mark_reg32_unbounded(dst_reg); 13376 13377 if (sanitize_needed(opcode)) { 13378 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 13379 &info, false); 13380 if (ret < 0) 13381 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13382 } 13383 13384 switch (opcode) { 13385 case BPF_ADD: 13386 /* We can take a fixed offset as long as it doesn't overflow 13387 * the s32 'off' field 13388 */ 13389 if (known && (ptr_reg->off + smin_val == 13390 (s64)(s32)(ptr_reg->off + smin_val))) { 13391 /* pointer += K. Accumulate it into fixed offset */ 13392 dst_reg->smin_value = smin_ptr; 13393 dst_reg->smax_value = smax_ptr; 13394 dst_reg->umin_value = umin_ptr; 13395 dst_reg->umax_value = umax_ptr; 13396 dst_reg->var_off = ptr_reg->var_off; 13397 dst_reg->off = ptr_reg->off + smin_val; 13398 dst_reg->raw = ptr_reg->raw; 13399 break; 13400 } 13401 /* A new variable offset is created. Note that off_reg->off 13402 * == 0, since it's a scalar. 13403 * dst_reg gets the pointer type and since some positive 13404 * integer value was added to the pointer, give it a new 'id' 13405 * if it's a PTR_TO_PACKET. 13406 * this creates a new 'base' pointer, off_reg (variable) gets 13407 * added into the variable offset, and we copy the fixed offset 13408 * from ptr_reg. 13409 */ 13410 if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) || 13411 check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) { 13412 dst_reg->smin_value = S64_MIN; 13413 dst_reg->smax_value = S64_MAX; 13414 } 13415 if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) || 13416 check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) { 13417 dst_reg->umin_value = 0; 13418 dst_reg->umax_value = U64_MAX; 13419 } 13420 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 13421 dst_reg->off = ptr_reg->off; 13422 dst_reg->raw = ptr_reg->raw; 13423 if (reg_is_pkt_pointer(ptr_reg)) { 13424 dst_reg->id = ++env->id_gen; 13425 /* something was added to pkt_ptr, set range to zero */ 13426 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13427 } 13428 break; 13429 case BPF_SUB: 13430 if (dst_reg == off_reg) { 13431 /* scalar -= pointer. Creates an unknown scalar */ 13432 verbose(env, "R%d tried to subtract pointer from scalar\n", 13433 dst); 13434 return -EACCES; 13435 } 13436 /* We don't allow subtraction from FP, because (according to 13437 * test_verifier.c test "invalid fp arithmetic", JITs might not 13438 * be able to deal with it. 13439 */ 13440 if (ptr_reg->type == PTR_TO_STACK) { 13441 verbose(env, "R%d subtraction from stack pointer prohibited\n", 13442 dst); 13443 return -EACCES; 13444 } 13445 if (known && (ptr_reg->off - smin_val == 13446 (s64)(s32)(ptr_reg->off - smin_val))) { 13447 /* pointer -= K. Subtract it from fixed offset */ 13448 dst_reg->smin_value = smin_ptr; 13449 dst_reg->smax_value = smax_ptr; 13450 dst_reg->umin_value = umin_ptr; 13451 dst_reg->umax_value = umax_ptr; 13452 dst_reg->var_off = ptr_reg->var_off; 13453 dst_reg->id = ptr_reg->id; 13454 dst_reg->off = ptr_reg->off - smin_val; 13455 dst_reg->raw = ptr_reg->raw; 13456 break; 13457 } 13458 /* A new variable offset is created. If the subtrahend is known 13459 * nonnegative, then any reg->range we had before is still good. 13460 */ 13461 if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) || 13462 check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) { 13463 /* Overflow possible, we know nothing */ 13464 dst_reg->smin_value = S64_MIN; 13465 dst_reg->smax_value = S64_MAX; 13466 } 13467 if (umin_ptr < umax_val) { 13468 /* Overflow possible, we know nothing */ 13469 dst_reg->umin_value = 0; 13470 dst_reg->umax_value = U64_MAX; 13471 } else { 13472 /* Cannot overflow (as long as bounds are consistent) */ 13473 dst_reg->umin_value = umin_ptr - umax_val; 13474 dst_reg->umax_value = umax_ptr - umin_val; 13475 } 13476 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 13477 dst_reg->off = ptr_reg->off; 13478 dst_reg->raw = ptr_reg->raw; 13479 if (reg_is_pkt_pointer(ptr_reg)) { 13480 dst_reg->id = ++env->id_gen; 13481 /* something was added to pkt_ptr, set range to zero */ 13482 if (smin_val < 0) 13483 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13484 } 13485 break; 13486 case BPF_AND: 13487 case BPF_OR: 13488 case BPF_XOR: 13489 /* bitwise ops on pointers are troublesome, prohibit. */ 13490 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 13491 dst, bpf_alu_string[opcode >> 4]); 13492 return -EACCES; 13493 default: 13494 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 13495 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 13496 dst, bpf_alu_string[opcode >> 4]); 13497 return -EACCES; 13498 } 13499 13500 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 13501 return -EINVAL; 13502 reg_bounds_sync(dst_reg); 13503 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 13504 return -EACCES; 13505 if (sanitize_needed(opcode)) { 13506 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 13507 &info, true); 13508 if (ret < 0) 13509 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13510 } 13511 13512 return 0; 13513 } 13514 13515 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 13516 struct bpf_reg_state *src_reg) 13517 { 13518 s32 *dst_smin = &dst_reg->s32_min_value; 13519 s32 *dst_smax = &dst_reg->s32_max_value; 13520 u32 *dst_umin = &dst_reg->u32_min_value; 13521 u32 *dst_umax = &dst_reg->u32_max_value; 13522 13523 if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) || 13524 check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) { 13525 *dst_smin = S32_MIN; 13526 *dst_smax = S32_MAX; 13527 } 13528 if (check_add_overflow(*dst_umin, src_reg->u32_min_value, dst_umin) || 13529 check_add_overflow(*dst_umax, src_reg->u32_max_value, dst_umax)) { 13530 *dst_umin = 0; 13531 *dst_umax = U32_MAX; 13532 } 13533 } 13534 13535 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 13536 struct bpf_reg_state *src_reg) 13537 { 13538 s64 *dst_smin = &dst_reg->smin_value; 13539 s64 *dst_smax = &dst_reg->smax_value; 13540 u64 *dst_umin = &dst_reg->umin_value; 13541 u64 *dst_umax = &dst_reg->umax_value; 13542 13543 if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) || 13544 check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) { 13545 *dst_smin = S64_MIN; 13546 *dst_smax = S64_MAX; 13547 } 13548 if (check_add_overflow(*dst_umin, src_reg->umin_value, dst_umin) || 13549 check_add_overflow(*dst_umax, src_reg->umax_value, dst_umax)) { 13550 *dst_umin = 0; 13551 *dst_umax = U64_MAX; 13552 } 13553 } 13554 13555 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 13556 struct bpf_reg_state *src_reg) 13557 { 13558 s32 *dst_smin = &dst_reg->s32_min_value; 13559 s32 *dst_smax = &dst_reg->s32_max_value; 13560 u32 umin_val = src_reg->u32_min_value; 13561 u32 umax_val = src_reg->u32_max_value; 13562 13563 if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) || 13564 check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) { 13565 /* Overflow possible, we know nothing */ 13566 *dst_smin = S32_MIN; 13567 *dst_smax = S32_MAX; 13568 } 13569 if (dst_reg->u32_min_value < umax_val) { 13570 /* Overflow possible, we know nothing */ 13571 dst_reg->u32_min_value = 0; 13572 dst_reg->u32_max_value = U32_MAX; 13573 } else { 13574 /* Cannot overflow (as long as bounds are consistent) */ 13575 dst_reg->u32_min_value -= umax_val; 13576 dst_reg->u32_max_value -= umin_val; 13577 } 13578 } 13579 13580 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 13581 struct bpf_reg_state *src_reg) 13582 { 13583 s64 *dst_smin = &dst_reg->smin_value; 13584 s64 *dst_smax = &dst_reg->smax_value; 13585 u64 umin_val = src_reg->umin_value; 13586 u64 umax_val = src_reg->umax_value; 13587 13588 if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) || 13589 check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) { 13590 /* Overflow possible, we know nothing */ 13591 *dst_smin = S64_MIN; 13592 *dst_smax = S64_MAX; 13593 } 13594 if (dst_reg->umin_value < umax_val) { 13595 /* Overflow possible, we know nothing */ 13596 dst_reg->umin_value = 0; 13597 dst_reg->umax_value = U64_MAX; 13598 } else { 13599 /* Cannot overflow (as long as bounds are consistent) */ 13600 dst_reg->umin_value -= umax_val; 13601 dst_reg->umax_value -= umin_val; 13602 } 13603 } 13604 13605 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 13606 struct bpf_reg_state *src_reg) 13607 { 13608 s32 smin_val = src_reg->s32_min_value; 13609 u32 umin_val = src_reg->u32_min_value; 13610 u32 umax_val = src_reg->u32_max_value; 13611 13612 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 13613 /* Ain't nobody got time to multiply that sign */ 13614 __mark_reg32_unbounded(dst_reg); 13615 return; 13616 } 13617 /* Both values are positive, so we can work with unsigned and 13618 * copy the result to signed (unless it exceeds S32_MAX). 13619 */ 13620 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 13621 /* Potential overflow, we know nothing */ 13622 __mark_reg32_unbounded(dst_reg); 13623 return; 13624 } 13625 dst_reg->u32_min_value *= umin_val; 13626 dst_reg->u32_max_value *= umax_val; 13627 if (dst_reg->u32_max_value > S32_MAX) { 13628 /* Overflow possible, we know nothing */ 13629 dst_reg->s32_min_value = S32_MIN; 13630 dst_reg->s32_max_value = S32_MAX; 13631 } else { 13632 dst_reg->s32_min_value = dst_reg->u32_min_value; 13633 dst_reg->s32_max_value = dst_reg->u32_max_value; 13634 } 13635 } 13636 13637 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 13638 struct bpf_reg_state *src_reg) 13639 { 13640 s64 smin_val = src_reg->smin_value; 13641 u64 umin_val = src_reg->umin_value; 13642 u64 umax_val = src_reg->umax_value; 13643 13644 if (smin_val < 0 || dst_reg->smin_value < 0) { 13645 /* Ain't nobody got time to multiply that sign */ 13646 __mark_reg64_unbounded(dst_reg); 13647 return; 13648 } 13649 /* Both values are positive, so we can work with unsigned and 13650 * copy the result to signed (unless it exceeds S64_MAX). 13651 */ 13652 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 13653 /* Potential overflow, we know nothing */ 13654 __mark_reg64_unbounded(dst_reg); 13655 return; 13656 } 13657 dst_reg->umin_value *= umin_val; 13658 dst_reg->umax_value *= umax_val; 13659 if (dst_reg->umax_value > S64_MAX) { 13660 /* Overflow possible, we know nothing */ 13661 dst_reg->smin_value = S64_MIN; 13662 dst_reg->smax_value = S64_MAX; 13663 } else { 13664 dst_reg->smin_value = dst_reg->umin_value; 13665 dst_reg->smax_value = dst_reg->umax_value; 13666 } 13667 } 13668 13669 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 13670 struct bpf_reg_state *src_reg) 13671 { 13672 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13673 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13674 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13675 u32 umax_val = src_reg->u32_max_value; 13676 13677 if (src_known && dst_known) { 13678 __mark_reg32_known(dst_reg, var32_off.value); 13679 return; 13680 } 13681 13682 /* We get our minimum from the var_off, since that's inherently 13683 * bitwise. Our maximum is the minimum of the operands' maxima. 13684 */ 13685 dst_reg->u32_min_value = var32_off.value; 13686 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 13687 13688 /* Safe to set s32 bounds by casting u32 result into s32 when u32 13689 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 13690 */ 13691 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 13692 dst_reg->s32_min_value = dst_reg->u32_min_value; 13693 dst_reg->s32_max_value = dst_reg->u32_max_value; 13694 } else { 13695 dst_reg->s32_min_value = S32_MIN; 13696 dst_reg->s32_max_value = S32_MAX; 13697 } 13698 } 13699 13700 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 13701 struct bpf_reg_state *src_reg) 13702 { 13703 bool src_known = tnum_is_const(src_reg->var_off); 13704 bool dst_known = tnum_is_const(dst_reg->var_off); 13705 u64 umax_val = src_reg->umax_value; 13706 13707 if (src_known && dst_known) { 13708 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13709 return; 13710 } 13711 13712 /* We get our minimum from the var_off, since that's inherently 13713 * bitwise. Our maximum is the minimum of the operands' maxima. 13714 */ 13715 dst_reg->umin_value = dst_reg->var_off.value; 13716 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 13717 13718 /* Safe to set s64 bounds by casting u64 result into s64 when u64 13719 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 13720 */ 13721 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 13722 dst_reg->smin_value = dst_reg->umin_value; 13723 dst_reg->smax_value = dst_reg->umax_value; 13724 } else { 13725 dst_reg->smin_value = S64_MIN; 13726 dst_reg->smax_value = S64_MAX; 13727 } 13728 /* We may learn something more from the var_off */ 13729 __update_reg_bounds(dst_reg); 13730 } 13731 13732 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 13733 struct bpf_reg_state *src_reg) 13734 { 13735 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13736 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13737 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13738 u32 umin_val = src_reg->u32_min_value; 13739 13740 if (src_known && dst_known) { 13741 __mark_reg32_known(dst_reg, var32_off.value); 13742 return; 13743 } 13744 13745 /* We get our maximum from the var_off, and our minimum is the 13746 * maximum of the operands' minima 13747 */ 13748 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 13749 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13750 13751 /* Safe to set s32 bounds by casting u32 result into s32 when u32 13752 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 13753 */ 13754 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 13755 dst_reg->s32_min_value = dst_reg->u32_min_value; 13756 dst_reg->s32_max_value = dst_reg->u32_max_value; 13757 } else { 13758 dst_reg->s32_min_value = S32_MIN; 13759 dst_reg->s32_max_value = S32_MAX; 13760 } 13761 } 13762 13763 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 13764 struct bpf_reg_state *src_reg) 13765 { 13766 bool src_known = tnum_is_const(src_reg->var_off); 13767 bool dst_known = tnum_is_const(dst_reg->var_off); 13768 u64 umin_val = src_reg->umin_value; 13769 13770 if (src_known && dst_known) { 13771 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13772 return; 13773 } 13774 13775 /* We get our maximum from the var_off, and our minimum is the 13776 * maximum of the operands' minima 13777 */ 13778 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 13779 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13780 13781 /* Safe to set s64 bounds by casting u64 result into s64 when u64 13782 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 13783 */ 13784 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 13785 dst_reg->smin_value = dst_reg->umin_value; 13786 dst_reg->smax_value = dst_reg->umax_value; 13787 } else { 13788 dst_reg->smin_value = S64_MIN; 13789 dst_reg->smax_value = S64_MAX; 13790 } 13791 /* We may learn something more from the var_off */ 13792 __update_reg_bounds(dst_reg); 13793 } 13794 13795 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 13796 struct bpf_reg_state *src_reg) 13797 { 13798 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13799 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13800 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13801 13802 if (src_known && dst_known) { 13803 __mark_reg32_known(dst_reg, var32_off.value); 13804 return; 13805 } 13806 13807 /* We get both minimum and maximum from the var32_off. */ 13808 dst_reg->u32_min_value = var32_off.value; 13809 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13810 13811 /* Safe to set s32 bounds by casting u32 result into s32 when u32 13812 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 13813 */ 13814 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 13815 dst_reg->s32_min_value = dst_reg->u32_min_value; 13816 dst_reg->s32_max_value = dst_reg->u32_max_value; 13817 } else { 13818 dst_reg->s32_min_value = S32_MIN; 13819 dst_reg->s32_max_value = S32_MAX; 13820 } 13821 } 13822 13823 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 13824 struct bpf_reg_state *src_reg) 13825 { 13826 bool src_known = tnum_is_const(src_reg->var_off); 13827 bool dst_known = tnum_is_const(dst_reg->var_off); 13828 13829 if (src_known && dst_known) { 13830 /* dst_reg->var_off.value has been updated earlier */ 13831 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13832 return; 13833 } 13834 13835 /* We get both minimum and maximum from the var_off. */ 13836 dst_reg->umin_value = dst_reg->var_off.value; 13837 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13838 13839 /* Safe to set s64 bounds by casting u64 result into s64 when u64 13840 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 13841 */ 13842 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 13843 dst_reg->smin_value = dst_reg->umin_value; 13844 dst_reg->smax_value = dst_reg->umax_value; 13845 } else { 13846 dst_reg->smin_value = S64_MIN; 13847 dst_reg->smax_value = S64_MAX; 13848 } 13849 13850 __update_reg_bounds(dst_reg); 13851 } 13852 13853 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13854 u64 umin_val, u64 umax_val) 13855 { 13856 /* We lose all sign bit information (except what we can pick 13857 * up from var_off) 13858 */ 13859 dst_reg->s32_min_value = S32_MIN; 13860 dst_reg->s32_max_value = S32_MAX; 13861 /* If we might shift our top bit out, then we know nothing */ 13862 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 13863 dst_reg->u32_min_value = 0; 13864 dst_reg->u32_max_value = U32_MAX; 13865 } else { 13866 dst_reg->u32_min_value <<= umin_val; 13867 dst_reg->u32_max_value <<= umax_val; 13868 } 13869 } 13870 13871 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13872 struct bpf_reg_state *src_reg) 13873 { 13874 u32 umax_val = src_reg->u32_max_value; 13875 u32 umin_val = src_reg->u32_min_value; 13876 /* u32 alu operation will zext upper bits */ 13877 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13878 13879 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13880 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 13881 /* Not required but being careful mark reg64 bounds as unknown so 13882 * that we are forced to pick them up from tnum and zext later and 13883 * if some path skips this step we are still safe. 13884 */ 13885 __mark_reg64_unbounded(dst_reg); 13886 __update_reg32_bounds(dst_reg); 13887 } 13888 13889 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 13890 u64 umin_val, u64 umax_val) 13891 { 13892 /* Special case <<32 because it is a common compiler pattern to sign 13893 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 13894 * positive we know this shift will also be positive so we can track 13895 * bounds correctly. Otherwise we lose all sign bit information except 13896 * what we can pick up from var_off. Perhaps we can generalize this 13897 * later to shifts of any length. 13898 */ 13899 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 13900 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 13901 else 13902 dst_reg->smax_value = S64_MAX; 13903 13904 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 13905 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 13906 else 13907 dst_reg->smin_value = S64_MIN; 13908 13909 /* If we might shift our top bit out, then we know nothing */ 13910 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 13911 dst_reg->umin_value = 0; 13912 dst_reg->umax_value = U64_MAX; 13913 } else { 13914 dst_reg->umin_value <<= umin_val; 13915 dst_reg->umax_value <<= umax_val; 13916 } 13917 } 13918 13919 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 13920 struct bpf_reg_state *src_reg) 13921 { 13922 u64 umax_val = src_reg->umax_value; 13923 u64 umin_val = src_reg->umin_value; 13924 13925 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 13926 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 13927 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13928 13929 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 13930 /* We may learn something more from the var_off */ 13931 __update_reg_bounds(dst_reg); 13932 } 13933 13934 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 13935 struct bpf_reg_state *src_reg) 13936 { 13937 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13938 u32 umax_val = src_reg->u32_max_value; 13939 u32 umin_val = src_reg->u32_min_value; 13940 13941 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13942 * be negative, then either: 13943 * 1) src_reg might be zero, so the sign bit of the result is 13944 * unknown, so we lose our signed bounds 13945 * 2) it's known negative, thus the unsigned bounds capture the 13946 * signed bounds 13947 * 3) the signed bounds cross zero, so they tell us nothing 13948 * about the result 13949 * If the value in dst_reg is known nonnegative, then again the 13950 * unsigned bounds capture the signed bounds. 13951 * Thus, in all cases it suffices to blow away our signed bounds 13952 * and rely on inferring new ones from the unsigned bounds and 13953 * var_off of the result. 13954 */ 13955 dst_reg->s32_min_value = S32_MIN; 13956 dst_reg->s32_max_value = S32_MAX; 13957 13958 dst_reg->var_off = tnum_rshift(subreg, umin_val); 13959 dst_reg->u32_min_value >>= umax_val; 13960 dst_reg->u32_max_value >>= umin_val; 13961 13962 __mark_reg64_unbounded(dst_reg); 13963 __update_reg32_bounds(dst_reg); 13964 } 13965 13966 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 13967 struct bpf_reg_state *src_reg) 13968 { 13969 u64 umax_val = src_reg->umax_value; 13970 u64 umin_val = src_reg->umin_value; 13971 13972 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13973 * be negative, then either: 13974 * 1) src_reg might be zero, so the sign bit of the result is 13975 * unknown, so we lose our signed bounds 13976 * 2) it's known negative, thus the unsigned bounds capture the 13977 * signed bounds 13978 * 3) the signed bounds cross zero, so they tell us nothing 13979 * about the result 13980 * If the value in dst_reg is known nonnegative, then again the 13981 * unsigned bounds capture the signed bounds. 13982 * Thus, in all cases it suffices to blow away our signed bounds 13983 * and rely on inferring new ones from the unsigned bounds and 13984 * var_off of the result. 13985 */ 13986 dst_reg->smin_value = S64_MIN; 13987 dst_reg->smax_value = S64_MAX; 13988 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 13989 dst_reg->umin_value >>= umax_val; 13990 dst_reg->umax_value >>= umin_val; 13991 13992 /* Its not easy to operate on alu32 bounds here because it depends 13993 * on bits being shifted in. Take easy way out and mark unbounded 13994 * so we can recalculate later from tnum. 13995 */ 13996 __mark_reg32_unbounded(dst_reg); 13997 __update_reg_bounds(dst_reg); 13998 } 13999 14000 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 14001 struct bpf_reg_state *src_reg) 14002 { 14003 u64 umin_val = src_reg->u32_min_value; 14004 14005 /* Upon reaching here, src_known is true and 14006 * umax_val is equal to umin_val. 14007 */ 14008 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 14009 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 14010 14011 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 14012 14013 /* blow away the dst_reg umin_value/umax_value and rely on 14014 * dst_reg var_off to refine the result. 14015 */ 14016 dst_reg->u32_min_value = 0; 14017 dst_reg->u32_max_value = U32_MAX; 14018 14019 __mark_reg64_unbounded(dst_reg); 14020 __update_reg32_bounds(dst_reg); 14021 } 14022 14023 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 14024 struct bpf_reg_state *src_reg) 14025 { 14026 u64 umin_val = src_reg->umin_value; 14027 14028 /* Upon reaching here, src_known is true and umax_val is equal 14029 * to umin_val. 14030 */ 14031 dst_reg->smin_value >>= umin_val; 14032 dst_reg->smax_value >>= umin_val; 14033 14034 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 14035 14036 /* blow away the dst_reg umin_value/umax_value and rely on 14037 * dst_reg var_off to refine the result. 14038 */ 14039 dst_reg->umin_value = 0; 14040 dst_reg->umax_value = U64_MAX; 14041 14042 /* Its not easy to operate on alu32 bounds here because it depends 14043 * on bits being shifted in from upper 32-bits. Take easy way out 14044 * and mark unbounded so we can recalculate later from tnum. 14045 */ 14046 __mark_reg32_unbounded(dst_reg); 14047 __update_reg_bounds(dst_reg); 14048 } 14049 14050 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn, 14051 const struct bpf_reg_state *src_reg) 14052 { 14053 bool src_is_const = false; 14054 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 14055 14056 if (insn_bitness == 32) { 14057 if (tnum_subreg_is_const(src_reg->var_off) 14058 && src_reg->s32_min_value == src_reg->s32_max_value 14059 && src_reg->u32_min_value == src_reg->u32_max_value) 14060 src_is_const = true; 14061 } else { 14062 if (tnum_is_const(src_reg->var_off) 14063 && src_reg->smin_value == src_reg->smax_value 14064 && src_reg->umin_value == src_reg->umax_value) 14065 src_is_const = true; 14066 } 14067 14068 switch (BPF_OP(insn->code)) { 14069 case BPF_ADD: 14070 case BPF_SUB: 14071 case BPF_AND: 14072 case BPF_XOR: 14073 case BPF_OR: 14074 case BPF_MUL: 14075 return true; 14076 14077 /* Shift operators range is only computable if shift dimension operand 14078 * is a constant. Shifts greater than 31 or 63 are undefined. This 14079 * includes shifts by a negative number. 14080 */ 14081 case BPF_LSH: 14082 case BPF_RSH: 14083 case BPF_ARSH: 14084 return (src_is_const && src_reg->umax_value < insn_bitness); 14085 default: 14086 return false; 14087 } 14088 } 14089 14090 /* WARNING: This function does calculations on 64-bit values, but the actual 14091 * execution may occur on 32-bit values. Therefore, things like bitshifts 14092 * need extra checks in the 32-bit case. 14093 */ 14094 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 14095 struct bpf_insn *insn, 14096 struct bpf_reg_state *dst_reg, 14097 struct bpf_reg_state src_reg) 14098 { 14099 u8 opcode = BPF_OP(insn->code); 14100 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14101 int ret; 14102 14103 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) { 14104 __mark_reg_unknown(env, dst_reg); 14105 return 0; 14106 } 14107 14108 if (sanitize_needed(opcode)) { 14109 ret = sanitize_val_alu(env, insn); 14110 if (ret < 0) 14111 return sanitize_err(env, insn, ret, NULL, NULL); 14112 } 14113 14114 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 14115 * There are two classes of instructions: The first class we track both 14116 * alu32 and alu64 sign/unsigned bounds independently this provides the 14117 * greatest amount of precision when alu operations are mixed with jmp32 14118 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 14119 * and BPF_OR. This is possible because these ops have fairly easy to 14120 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 14121 * See alu32 verifier tests for examples. The second class of 14122 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 14123 * with regards to tracking sign/unsigned bounds because the bits may 14124 * cross subreg boundaries in the alu64 case. When this happens we mark 14125 * the reg unbounded in the subreg bound space and use the resulting 14126 * tnum to calculate an approximation of the sign/unsigned bounds. 14127 */ 14128 switch (opcode) { 14129 case BPF_ADD: 14130 scalar32_min_max_add(dst_reg, &src_reg); 14131 scalar_min_max_add(dst_reg, &src_reg); 14132 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 14133 break; 14134 case BPF_SUB: 14135 scalar32_min_max_sub(dst_reg, &src_reg); 14136 scalar_min_max_sub(dst_reg, &src_reg); 14137 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 14138 break; 14139 case BPF_MUL: 14140 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 14141 scalar32_min_max_mul(dst_reg, &src_reg); 14142 scalar_min_max_mul(dst_reg, &src_reg); 14143 break; 14144 case BPF_AND: 14145 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 14146 scalar32_min_max_and(dst_reg, &src_reg); 14147 scalar_min_max_and(dst_reg, &src_reg); 14148 break; 14149 case BPF_OR: 14150 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 14151 scalar32_min_max_or(dst_reg, &src_reg); 14152 scalar_min_max_or(dst_reg, &src_reg); 14153 break; 14154 case BPF_XOR: 14155 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 14156 scalar32_min_max_xor(dst_reg, &src_reg); 14157 scalar_min_max_xor(dst_reg, &src_reg); 14158 break; 14159 case BPF_LSH: 14160 if (alu32) 14161 scalar32_min_max_lsh(dst_reg, &src_reg); 14162 else 14163 scalar_min_max_lsh(dst_reg, &src_reg); 14164 break; 14165 case BPF_RSH: 14166 if (alu32) 14167 scalar32_min_max_rsh(dst_reg, &src_reg); 14168 else 14169 scalar_min_max_rsh(dst_reg, &src_reg); 14170 break; 14171 case BPF_ARSH: 14172 if (alu32) 14173 scalar32_min_max_arsh(dst_reg, &src_reg); 14174 else 14175 scalar_min_max_arsh(dst_reg, &src_reg); 14176 break; 14177 default: 14178 break; 14179 } 14180 14181 /* ALU32 ops are zero extended into 64bit register */ 14182 if (alu32) 14183 zext_32_to_64(dst_reg); 14184 reg_bounds_sync(dst_reg); 14185 return 0; 14186 } 14187 14188 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 14189 * and var_off. 14190 */ 14191 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 14192 struct bpf_insn *insn) 14193 { 14194 struct bpf_verifier_state *vstate = env->cur_state; 14195 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14196 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 14197 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 14198 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14199 u8 opcode = BPF_OP(insn->code); 14200 int err; 14201 14202 dst_reg = ®s[insn->dst_reg]; 14203 src_reg = NULL; 14204 14205 if (dst_reg->type == PTR_TO_ARENA) { 14206 struct bpf_insn_aux_data *aux = cur_aux(env); 14207 14208 if (BPF_CLASS(insn->code) == BPF_ALU64) 14209 /* 14210 * 32-bit operations zero upper bits automatically. 14211 * 64-bit operations need to be converted to 32. 14212 */ 14213 aux->needs_zext = true; 14214 14215 /* Any arithmetic operations are allowed on arena pointers */ 14216 return 0; 14217 } 14218 14219 if (dst_reg->type != SCALAR_VALUE) 14220 ptr_reg = dst_reg; 14221 14222 if (BPF_SRC(insn->code) == BPF_X) { 14223 src_reg = ®s[insn->src_reg]; 14224 if (src_reg->type != SCALAR_VALUE) { 14225 if (dst_reg->type != SCALAR_VALUE) { 14226 /* Combining two pointers by any ALU op yields 14227 * an arbitrary scalar. Disallow all math except 14228 * pointer subtraction 14229 */ 14230 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 14231 mark_reg_unknown(env, regs, insn->dst_reg); 14232 return 0; 14233 } 14234 verbose(env, "R%d pointer %s pointer prohibited\n", 14235 insn->dst_reg, 14236 bpf_alu_string[opcode >> 4]); 14237 return -EACCES; 14238 } else { 14239 /* scalar += pointer 14240 * This is legal, but we have to reverse our 14241 * src/dest handling in computing the range 14242 */ 14243 err = mark_chain_precision(env, insn->dst_reg); 14244 if (err) 14245 return err; 14246 return adjust_ptr_min_max_vals(env, insn, 14247 src_reg, dst_reg); 14248 } 14249 } else if (ptr_reg) { 14250 /* pointer += scalar */ 14251 err = mark_chain_precision(env, insn->src_reg); 14252 if (err) 14253 return err; 14254 return adjust_ptr_min_max_vals(env, insn, 14255 dst_reg, src_reg); 14256 } else if (dst_reg->precise) { 14257 /* if dst_reg is precise, src_reg should be precise as well */ 14258 err = mark_chain_precision(env, insn->src_reg); 14259 if (err) 14260 return err; 14261 } 14262 } else { 14263 /* Pretend the src is a reg with a known value, since we only 14264 * need to be able to read from this state. 14265 */ 14266 off_reg.type = SCALAR_VALUE; 14267 __mark_reg_known(&off_reg, insn->imm); 14268 src_reg = &off_reg; 14269 if (ptr_reg) /* pointer += K */ 14270 return adjust_ptr_min_max_vals(env, insn, 14271 ptr_reg, src_reg); 14272 } 14273 14274 /* Got here implies adding two SCALAR_VALUEs */ 14275 if (WARN_ON_ONCE(ptr_reg)) { 14276 print_verifier_state(env, state, true); 14277 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 14278 return -EINVAL; 14279 } 14280 if (WARN_ON(!src_reg)) { 14281 print_verifier_state(env, state, true); 14282 verbose(env, "verifier internal error: no src_reg\n"); 14283 return -EINVAL; 14284 } 14285 err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 14286 if (err) 14287 return err; 14288 /* 14289 * Compilers can generate the code 14290 * r1 = r2 14291 * r1 += 0x1 14292 * if r2 < 1000 goto ... 14293 * use r1 in memory access 14294 * So remember constant delta between r2 and r1 and update r1 after 14295 * 'if' condition. 14296 */ 14297 if (env->bpf_capable && BPF_OP(insn->code) == BPF_ADD && 14298 dst_reg->id && is_reg_const(src_reg, alu32)) { 14299 u64 val = reg_const_value(src_reg, alu32); 14300 14301 if ((dst_reg->id & BPF_ADD_CONST) || 14302 /* prevent overflow in sync_linked_regs() later */ 14303 val > (u32)S32_MAX) { 14304 /* 14305 * If the register already went through rX += val 14306 * we cannot accumulate another val into rx->off. 14307 */ 14308 dst_reg->off = 0; 14309 dst_reg->id = 0; 14310 } else { 14311 dst_reg->id |= BPF_ADD_CONST; 14312 dst_reg->off = val; 14313 } 14314 } else { 14315 /* 14316 * Make sure ID is cleared otherwise dst_reg min/max could be 14317 * incorrectly propagated into other registers by sync_linked_regs() 14318 */ 14319 dst_reg->id = 0; 14320 } 14321 return 0; 14322 } 14323 14324 /* check validity of 32-bit and 64-bit arithmetic operations */ 14325 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 14326 { 14327 struct bpf_reg_state *regs = cur_regs(env); 14328 u8 opcode = BPF_OP(insn->code); 14329 int err; 14330 14331 if (opcode == BPF_END || opcode == BPF_NEG) { 14332 if (opcode == BPF_NEG) { 14333 if (BPF_SRC(insn->code) != BPF_K || 14334 insn->src_reg != BPF_REG_0 || 14335 insn->off != 0 || insn->imm != 0) { 14336 verbose(env, "BPF_NEG uses reserved fields\n"); 14337 return -EINVAL; 14338 } 14339 } else { 14340 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 14341 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 14342 (BPF_CLASS(insn->code) == BPF_ALU64 && 14343 BPF_SRC(insn->code) != BPF_TO_LE)) { 14344 verbose(env, "BPF_END uses reserved fields\n"); 14345 return -EINVAL; 14346 } 14347 } 14348 14349 /* check src operand */ 14350 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14351 if (err) 14352 return err; 14353 14354 if (is_pointer_value(env, insn->dst_reg)) { 14355 verbose(env, "R%d pointer arithmetic prohibited\n", 14356 insn->dst_reg); 14357 return -EACCES; 14358 } 14359 14360 /* check dest operand */ 14361 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14362 if (err) 14363 return err; 14364 14365 } else if (opcode == BPF_MOV) { 14366 14367 if (BPF_SRC(insn->code) == BPF_X) { 14368 if (BPF_CLASS(insn->code) == BPF_ALU) { 14369 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) || 14370 insn->imm) { 14371 verbose(env, "BPF_MOV uses reserved fields\n"); 14372 return -EINVAL; 14373 } 14374 } else if (insn->off == BPF_ADDR_SPACE_CAST) { 14375 if (insn->imm != 1 && insn->imm != 1u << 16) { 14376 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n"); 14377 return -EINVAL; 14378 } 14379 if (!env->prog->aux->arena) { 14380 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n"); 14381 return -EINVAL; 14382 } 14383 } else { 14384 if ((insn->off != 0 && insn->off != 8 && insn->off != 16 && 14385 insn->off != 32) || insn->imm) { 14386 verbose(env, "BPF_MOV uses reserved fields\n"); 14387 return -EINVAL; 14388 } 14389 } 14390 14391 /* check src operand */ 14392 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14393 if (err) 14394 return err; 14395 } else { 14396 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 14397 verbose(env, "BPF_MOV uses reserved fields\n"); 14398 return -EINVAL; 14399 } 14400 } 14401 14402 /* check dest operand, mark as required later */ 14403 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14404 if (err) 14405 return err; 14406 14407 if (BPF_SRC(insn->code) == BPF_X) { 14408 struct bpf_reg_state *src_reg = regs + insn->src_reg; 14409 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 14410 14411 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14412 if (insn->imm) { 14413 /* off == BPF_ADDR_SPACE_CAST */ 14414 mark_reg_unknown(env, regs, insn->dst_reg); 14415 if (insn->imm == 1) { /* cast from as(1) to as(0) */ 14416 dst_reg->type = PTR_TO_ARENA; 14417 /* PTR_TO_ARENA is 32-bit */ 14418 dst_reg->subreg_def = env->insn_idx + 1; 14419 } 14420 } else if (insn->off == 0) { 14421 /* case: R1 = R2 14422 * copy register state to dest reg 14423 */ 14424 assign_scalar_id_before_mov(env, src_reg); 14425 copy_register_state(dst_reg, src_reg); 14426 dst_reg->live |= REG_LIVE_WRITTEN; 14427 dst_reg->subreg_def = DEF_NOT_SUBREG; 14428 } else { 14429 /* case: R1 = (s8, s16 s32)R2 */ 14430 if (is_pointer_value(env, insn->src_reg)) { 14431 verbose(env, 14432 "R%d sign-extension part of pointer\n", 14433 insn->src_reg); 14434 return -EACCES; 14435 } else if (src_reg->type == SCALAR_VALUE) { 14436 bool no_sext; 14437 14438 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 14439 if (no_sext) 14440 assign_scalar_id_before_mov(env, src_reg); 14441 copy_register_state(dst_reg, src_reg); 14442 if (!no_sext) 14443 dst_reg->id = 0; 14444 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 14445 dst_reg->live |= REG_LIVE_WRITTEN; 14446 dst_reg->subreg_def = DEF_NOT_SUBREG; 14447 } else { 14448 mark_reg_unknown(env, regs, insn->dst_reg); 14449 } 14450 } 14451 } else { 14452 /* R1 = (u32) R2 */ 14453 if (is_pointer_value(env, insn->src_reg)) { 14454 verbose(env, 14455 "R%d partial copy of pointer\n", 14456 insn->src_reg); 14457 return -EACCES; 14458 } else if (src_reg->type == SCALAR_VALUE) { 14459 if (insn->off == 0) { 14460 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 14461 14462 if (is_src_reg_u32) 14463 assign_scalar_id_before_mov(env, src_reg); 14464 copy_register_state(dst_reg, src_reg); 14465 /* Make sure ID is cleared if src_reg is not in u32 14466 * range otherwise dst_reg min/max could be incorrectly 14467 * propagated into src_reg by sync_linked_regs() 14468 */ 14469 if (!is_src_reg_u32) 14470 dst_reg->id = 0; 14471 dst_reg->live |= REG_LIVE_WRITTEN; 14472 dst_reg->subreg_def = env->insn_idx + 1; 14473 } else { 14474 /* case: W1 = (s8, s16)W2 */ 14475 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 14476 14477 if (no_sext) 14478 assign_scalar_id_before_mov(env, src_reg); 14479 copy_register_state(dst_reg, src_reg); 14480 if (!no_sext) 14481 dst_reg->id = 0; 14482 dst_reg->live |= REG_LIVE_WRITTEN; 14483 dst_reg->subreg_def = env->insn_idx + 1; 14484 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 14485 } 14486 } else { 14487 mark_reg_unknown(env, regs, 14488 insn->dst_reg); 14489 } 14490 zext_32_to_64(dst_reg); 14491 reg_bounds_sync(dst_reg); 14492 } 14493 } else { 14494 /* case: R = imm 14495 * remember the value we stored into this reg 14496 */ 14497 /* clear any state __mark_reg_known doesn't set */ 14498 mark_reg_unknown(env, regs, insn->dst_reg); 14499 regs[insn->dst_reg].type = SCALAR_VALUE; 14500 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14501 __mark_reg_known(regs + insn->dst_reg, 14502 insn->imm); 14503 } else { 14504 __mark_reg_known(regs + insn->dst_reg, 14505 (u32)insn->imm); 14506 } 14507 } 14508 14509 } else if (opcode > BPF_END) { 14510 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 14511 return -EINVAL; 14512 14513 } else { /* all other ALU ops: and, sub, xor, add, ... */ 14514 14515 if (BPF_SRC(insn->code) == BPF_X) { 14516 if (insn->imm != 0 || insn->off > 1 || 14517 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14518 verbose(env, "BPF_ALU uses reserved fields\n"); 14519 return -EINVAL; 14520 } 14521 /* check src1 operand */ 14522 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14523 if (err) 14524 return err; 14525 } else { 14526 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 14527 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14528 verbose(env, "BPF_ALU uses reserved fields\n"); 14529 return -EINVAL; 14530 } 14531 } 14532 14533 /* check src2 operand */ 14534 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14535 if (err) 14536 return err; 14537 14538 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 14539 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 14540 verbose(env, "div by zero\n"); 14541 return -EINVAL; 14542 } 14543 14544 if ((opcode == BPF_LSH || opcode == BPF_RSH || 14545 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 14546 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 14547 14548 if (insn->imm < 0 || insn->imm >= size) { 14549 verbose(env, "invalid shift %d\n", insn->imm); 14550 return -EINVAL; 14551 } 14552 } 14553 14554 /* check dest operand */ 14555 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14556 err = err ?: adjust_reg_min_max_vals(env, insn); 14557 if (err) 14558 return err; 14559 } 14560 14561 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 14562 } 14563 14564 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 14565 struct bpf_reg_state *dst_reg, 14566 enum bpf_reg_type type, 14567 bool range_right_open) 14568 { 14569 struct bpf_func_state *state; 14570 struct bpf_reg_state *reg; 14571 int new_range; 14572 14573 if (dst_reg->off < 0 || 14574 (dst_reg->off == 0 && range_right_open)) 14575 /* This doesn't give us any range */ 14576 return; 14577 14578 if (dst_reg->umax_value > MAX_PACKET_OFF || 14579 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 14580 /* Risk of overflow. For instance, ptr + (1<<63) may be less 14581 * than pkt_end, but that's because it's also less than pkt. 14582 */ 14583 return; 14584 14585 new_range = dst_reg->off; 14586 if (range_right_open) 14587 new_range++; 14588 14589 /* Examples for register markings: 14590 * 14591 * pkt_data in dst register: 14592 * 14593 * r2 = r3; 14594 * r2 += 8; 14595 * if (r2 > pkt_end) goto <handle exception> 14596 * <access okay> 14597 * 14598 * r2 = r3; 14599 * r2 += 8; 14600 * if (r2 < pkt_end) goto <access okay> 14601 * <handle exception> 14602 * 14603 * Where: 14604 * r2 == dst_reg, pkt_end == src_reg 14605 * r2=pkt(id=n,off=8,r=0) 14606 * r3=pkt(id=n,off=0,r=0) 14607 * 14608 * pkt_data in src register: 14609 * 14610 * r2 = r3; 14611 * r2 += 8; 14612 * if (pkt_end >= r2) goto <access okay> 14613 * <handle exception> 14614 * 14615 * r2 = r3; 14616 * r2 += 8; 14617 * if (pkt_end <= r2) goto <handle exception> 14618 * <access okay> 14619 * 14620 * Where: 14621 * pkt_end == dst_reg, r2 == src_reg 14622 * r2=pkt(id=n,off=8,r=0) 14623 * r3=pkt(id=n,off=0,r=0) 14624 * 14625 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 14626 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 14627 * and [r3, r3 + 8-1) respectively is safe to access depending on 14628 * the check. 14629 */ 14630 14631 /* If our ids match, then we must have the same max_value. And we 14632 * don't care about the other reg's fixed offset, since if it's too big 14633 * the range won't allow anything. 14634 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 14635 */ 14636 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14637 if (reg->type == type && reg->id == dst_reg->id) 14638 /* keep the maximum range already checked */ 14639 reg->range = max(reg->range, new_range); 14640 })); 14641 } 14642 14643 /* 14644 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 14645 */ 14646 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14647 u8 opcode, bool is_jmp32) 14648 { 14649 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 14650 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 14651 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value; 14652 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value; 14653 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value; 14654 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value; 14655 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value; 14656 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value; 14657 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value; 14658 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value; 14659 14660 switch (opcode) { 14661 case BPF_JEQ: 14662 /* constants, umin/umax and smin/smax checks would be 14663 * redundant in this case because they all should match 14664 */ 14665 if (tnum_is_const(t1) && tnum_is_const(t2)) 14666 return t1.value == t2.value; 14667 /* non-overlapping ranges */ 14668 if (umin1 > umax2 || umax1 < umin2) 14669 return 0; 14670 if (smin1 > smax2 || smax1 < smin2) 14671 return 0; 14672 if (!is_jmp32) { 14673 /* if 64-bit ranges are inconclusive, see if we can 14674 * utilize 32-bit subrange knowledge to eliminate 14675 * branches that can't be taken a priori 14676 */ 14677 if (reg1->u32_min_value > reg2->u32_max_value || 14678 reg1->u32_max_value < reg2->u32_min_value) 14679 return 0; 14680 if (reg1->s32_min_value > reg2->s32_max_value || 14681 reg1->s32_max_value < reg2->s32_min_value) 14682 return 0; 14683 } 14684 break; 14685 case BPF_JNE: 14686 /* constants, umin/umax and smin/smax checks would be 14687 * redundant in this case because they all should match 14688 */ 14689 if (tnum_is_const(t1) && tnum_is_const(t2)) 14690 return t1.value != t2.value; 14691 /* non-overlapping ranges */ 14692 if (umin1 > umax2 || umax1 < umin2) 14693 return 1; 14694 if (smin1 > smax2 || smax1 < smin2) 14695 return 1; 14696 if (!is_jmp32) { 14697 /* if 64-bit ranges are inconclusive, see if we can 14698 * utilize 32-bit subrange knowledge to eliminate 14699 * branches that can't be taken a priori 14700 */ 14701 if (reg1->u32_min_value > reg2->u32_max_value || 14702 reg1->u32_max_value < reg2->u32_min_value) 14703 return 1; 14704 if (reg1->s32_min_value > reg2->s32_max_value || 14705 reg1->s32_max_value < reg2->s32_min_value) 14706 return 1; 14707 } 14708 break; 14709 case BPF_JSET: 14710 if (!is_reg_const(reg2, is_jmp32)) { 14711 swap(reg1, reg2); 14712 swap(t1, t2); 14713 } 14714 if (!is_reg_const(reg2, is_jmp32)) 14715 return -1; 14716 if ((~t1.mask & t1.value) & t2.value) 14717 return 1; 14718 if (!((t1.mask | t1.value) & t2.value)) 14719 return 0; 14720 break; 14721 case BPF_JGT: 14722 if (umin1 > umax2) 14723 return 1; 14724 else if (umax1 <= umin2) 14725 return 0; 14726 break; 14727 case BPF_JSGT: 14728 if (smin1 > smax2) 14729 return 1; 14730 else if (smax1 <= smin2) 14731 return 0; 14732 break; 14733 case BPF_JLT: 14734 if (umax1 < umin2) 14735 return 1; 14736 else if (umin1 >= umax2) 14737 return 0; 14738 break; 14739 case BPF_JSLT: 14740 if (smax1 < smin2) 14741 return 1; 14742 else if (smin1 >= smax2) 14743 return 0; 14744 break; 14745 case BPF_JGE: 14746 if (umin1 >= umax2) 14747 return 1; 14748 else if (umax1 < umin2) 14749 return 0; 14750 break; 14751 case BPF_JSGE: 14752 if (smin1 >= smax2) 14753 return 1; 14754 else if (smax1 < smin2) 14755 return 0; 14756 break; 14757 case BPF_JLE: 14758 if (umax1 <= umin2) 14759 return 1; 14760 else if (umin1 > umax2) 14761 return 0; 14762 break; 14763 case BPF_JSLE: 14764 if (smax1 <= smin2) 14765 return 1; 14766 else if (smin1 > smax2) 14767 return 0; 14768 break; 14769 } 14770 14771 return -1; 14772 } 14773 14774 static int flip_opcode(u32 opcode) 14775 { 14776 /* How can we transform "a <op> b" into "b <op> a"? */ 14777 static const u8 opcode_flip[16] = { 14778 /* these stay the same */ 14779 [BPF_JEQ >> 4] = BPF_JEQ, 14780 [BPF_JNE >> 4] = BPF_JNE, 14781 [BPF_JSET >> 4] = BPF_JSET, 14782 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 14783 [BPF_JGE >> 4] = BPF_JLE, 14784 [BPF_JGT >> 4] = BPF_JLT, 14785 [BPF_JLE >> 4] = BPF_JGE, 14786 [BPF_JLT >> 4] = BPF_JGT, 14787 [BPF_JSGE >> 4] = BPF_JSLE, 14788 [BPF_JSGT >> 4] = BPF_JSLT, 14789 [BPF_JSLE >> 4] = BPF_JSGE, 14790 [BPF_JSLT >> 4] = BPF_JSGT 14791 }; 14792 return opcode_flip[opcode >> 4]; 14793 } 14794 14795 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 14796 struct bpf_reg_state *src_reg, 14797 u8 opcode) 14798 { 14799 struct bpf_reg_state *pkt; 14800 14801 if (src_reg->type == PTR_TO_PACKET_END) { 14802 pkt = dst_reg; 14803 } else if (dst_reg->type == PTR_TO_PACKET_END) { 14804 pkt = src_reg; 14805 opcode = flip_opcode(opcode); 14806 } else { 14807 return -1; 14808 } 14809 14810 if (pkt->range >= 0) 14811 return -1; 14812 14813 switch (opcode) { 14814 case BPF_JLE: 14815 /* pkt <= pkt_end */ 14816 fallthrough; 14817 case BPF_JGT: 14818 /* pkt > pkt_end */ 14819 if (pkt->range == BEYOND_PKT_END) 14820 /* pkt has at last one extra byte beyond pkt_end */ 14821 return opcode == BPF_JGT; 14822 break; 14823 case BPF_JLT: 14824 /* pkt < pkt_end */ 14825 fallthrough; 14826 case BPF_JGE: 14827 /* pkt >= pkt_end */ 14828 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 14829 return opcode == BPF_JGE; 14830 break; 14831 } 14832 return -1; 14833 } 14834 14835 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 14836 * and return: 14837 * 1 - branch will be taken and "goto target" will be executed 14838 * 0 - branch will not be taken and fall-through to next insn 14839 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 14840 * range [0,10] 14841 */ 14842 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14843 u8 opcode, bool is_jmp32) 14844 { 14845 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 14846 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 14847 14848 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 14849 u64 val; 14850 14851 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 14852 if (!is_reg_const(reg2, is_jmp32)) { 14853 opcode = flip_opcode(opcode); 14854 swap(reg1, reg2); 14855 } 14856 /* and ensure that reg2 is a constant */ 14857 if (!is_reg_const(reg2, is_jmp32)) 14858 return -1; 14859 14860 if (!reg_not_null(reg1)) 14861 return -1; 14862 14863 /* If pointer is valid tests against zero will fail so we can 14864 * use this to direct branch taken. 14865 */ 14866 val = reg_const_value(reg2, is_jmp32); 14867 if (val != 0) 14868 return -1; 14869 14870 switch (opcode) { 14871 case BPF_JEQ: 14872 return 0; 14873 case BPF_JNE: 14874 return 1; 14875 default: 14876 return -1; 14877 } 14878 } 14879 14880 /* now deal with two scalars, but not necessarily constants */ 14881 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32); 14882 } 14883 14884 /* Opcode that corresponds to a *false* branch condition. 14885 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 14886 */ 14887 static u8 rev_opcode(u8 opcode) 14888 { 14889 switch (opcode) { 14890 case BPF_JEQ: return BPF_JNE; 14891 case BPF_JNE: return BPF_JEQ; 14892 /* JSET doesn't have it's reverse opcode in BPF, so add 14893 * BPF_X flag to denote the reverse of that operation 14894 */ 14895 case BPF_JSET: return BPF_JSET | BPF_X; 14896 case BPF_JSET | BPF_X: return BPF_JSET; 14897 case BPF_JGE: return BPF_JLT; 14898 case BPF_JGT: return BPF_JLE; 14899 case BPF_JLE: return BPF_JGT; 14900 case BPF_JLT: return BPF_JGE; 14901 case BPF_JSGE: return BPF_JSLT; 14902 case BPF_JSGT: return BPF_JSLE; 14903 case BPF_JSLE: return BPF_JSGT; 14904 case BPF_JSLT: return BPF_JSGE; 14905 default: return 0; 14906 } 14907 } 14908 14909 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 14910 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14911 u8 opcode, bool is_jmp32) 14912 { 14913 struct tnum t; 14914 u64 val; 14915 14916 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */ 14917 switch (opcode) { 14918 case BPF_JGE: 14919 case BPF_JGT: 14920 case BPF_JSGE: 14921 case BPF_JSGT: 14922 opcode = flip_opcode(opcode); 14923 swap(reg1, reg2); 14924 break; 14925 default: 14926 break; 14927 } 14928 14929 switch (opcode) { 14930 case BPF_JEQ: 14931 if (is_jmp32) { 14932 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14933 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14934 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14935 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14936 reg2->u32_min_value = reg1->u32_min_value; 14937 reg2->u32_max_value = reg1->u32_max_value; 14938 reg2->s32_min_value = reg1->s32_min_value; 14939 reg2->s32_max_value = reg1->s32_max_value; 14940 14941 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 14942 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14943 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 14944 } else { 14945 reg1->umin_value = max(reg1->umin_value, reg2->umin_value); 14946 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14947 reg1->smin_value = max(reg1->smin_value, reg2->smin_value); 14948 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14949 reg2->umin_value = reg1->umin_value; 14950 reg2->umax_value = reg1->umax_value; 14951 reg2->smin_value = reg1->smin_value; 14952 reg2->smax_value = reg1->smax_value; 14953 14954 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 14955 reg2->var_off = reg1->var_off; 14956 } 14957 break; 14958 case BPF_JNE: 14959 if (!is_reg_const(reg2, is_jmp32)) 14960 swap(reg1, reg2); 14961 if (!is_reg_const(reg2, is_jmp32)) 14962 break; 14963 14964 /* try to recompute the bound of reg1 if reg2 is a const and 14965 * is exactly the edge of reg1. 14966 */ 14967 val = reg_const_value(reg2, is_jmp32); 14968 if (is_jmp32) { 14969 /* u32_min_value is not equal to 0xffffffff at this point, 14970 * because otherwise u32_max_value is 0xffffffff as well, 14971 * in such a case both reg1 and reg2 would be constants, 14972 * jump would be predicted and reg_set_min_max() won't 14973 * be called. 14974 * 14975 * Same reasoning works for all {u,s}{min,max}{32,64} cases 14976 * below. 14977 */ 14978 if (reg1->u32_min_value == (u32)val) 14979 reg1->u32_min_value++; 14980 if (reg1->u32_max_value == (u32)val) 14981 reg1->u32_max_value--; 14982 if (reg1->s32_min_value == (s32)val) 14983 reg1->s32_min_value++; 14984 if (reg1->s32_max_value == (s32)val) 14985 reg1->s32_max_value--; 14986 } else { 14987 if (reg1->umin_value == (u64)val) 14988 reg1->umin_value++; 14989 if (reg1->umax_value == (u64)val) 14990 reg1->umax_value--; 14991 if (reg1->smin_value == (s64)val) 14992 reg1->smin_value++; 14993 if (reg1->smax_value == (s64)val) 14994 reg1->smax_value--; 14995 } 14996 break; 14997 case BPF_JSET: 14998 if (!is_reg_const(reg2, is_jmp32)) 14999 swap(reg1, reg2); 15000 if (!is_reg_const(reg2, is_jmp32)) 15001 break; 15002 val = reg_const_value(reg2, is_jmp32); 15003 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 15004 * requires single bit to learn something useful. E.g., if we 15005 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 15006 * are actually set? We can learn something definite only if 15007 * it's a single-bit value to begin with. 15008 * 15009 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 15010 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 15011 * bit 1 is set, which we can readily use in adjustments. 15012 */ 15013 if (!is_power_of_2(val)) 15014 break; 15015 if (is_jmp32) { 15016 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 15017 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15018 } else { 15019 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 15020 } 15021 break; 15022 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 15023 if (!is_reg_const(reg2, is_jmp32)) 15024 swap(reg1, reg2); 15025 if (!is_reg_const(reg2, is_jmp32)) 15026 break; 15027 val = reg_const_value(reg2, is_jmp32); 15028 if (is_jmp32) { 15029 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 15030 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15031 } else { 15032 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 15033 } 15034 break; 15035 case BPF_JLE: 15036 if (is_jmp32) { 15037 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 15038 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 15039 } else { 15040 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 15041 reg2->umin_value = max(reg1->umin_value, reg2->umin_value); 15042 } 15043 break; 15044 case BPF_JLT: 15045 if (is_jmp32) { 15046 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1); 15047 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value); 15048 } else { 15049 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1); 15050 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value); 15051 } 15052 break; 15053 case BPF_JSLE: 15054 if (is_jmp32) { 15055 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 15056 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 15057 } else { 15058 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 15059 reg2->smin_value = max(reg1->smin_value, reg2->smin_value); 15060 } 15061 break; 15062 case BPF_JSLT: 15063 if (is_jmp32) { 15064 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1); 15065 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value); 15066 } else { 15067 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1); 15068 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value); 15069 } 15070 break; 15071 default: 15072 return; 15073 } 15074 } 15075 15076 /* Adjusts the register min/max values in the case that the dst_reg and 15077 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K 15078 * check, in which case we have a fake SCALAR_VALUE representing insn->imm). 15079 * Technically we can do similar adjustments for pointers to the same object, 15080 * but we don't support that right now. 15081 */ 15082 static int reg_set_min_max(struct bpf_verifier_env *env, 15083 struct bpf_reg_state *true_reg1, 15084 struct bpf_reg_state *true_reg2, 15085 struct bpf_reg_state *false_reg1, 15086 struct bpf_reg_state *false_reg2, 15087 u8 opcode, bool is_jmp32) 15088 { 15089 int err; 15090 15091 /* If either register is a pointer, we can't learn anything about its 15092 * variable offset from the compare (unless they were a pointer into 15093 * the same object, but we don't bother with that). 15094 */ 15095 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE) 15096 return 0; 15097 15098 /* fallthrough (FALSE) branch */ 15099 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32); 15100 reg_bounds_sync(false_reg1); 15101 reg_bounds_sync(false_reg2); 15102 15103 /* jump (TRUE) branch */ 15104 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32); 15105 reg_bounds_sync(true_reg1); 15106 reg_bounds_sync(true_reg2); 15107 15108 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1"); 15109 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2"); 15110 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1"); 15111 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2"); 15112 return err; 15113 } 15114 15115 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 15116 struct bpf_reg_state *reg, u32 id, 15117 bool is_null) 15118 { 15119 if (type_may_be_null(reg->type) && reg->id == id && 15120 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 15121 /* Old offset (both fixed and variable parts) should have been 15122 * known-zero, because we don't allow pointer arithmetic on 15123 * pointers that might be NULL. If we see this happening, don't 15124 * convert the register. 15125 * 15126 * But in some cases, some helpers that return local kptrs 15127 * advance offset for the returned pointer. In those cases, it 15128 * is fine to expect to see reg->off. 15129 */ 15130 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 15131 return; 15132 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 15133 WARN_ON_ONCE(reg->off)) 15134 return; 15135 15136 if (is_null) { 15137 reg->type = SCALAR_VALUE; 15138 /* We don't need id and ref_obj_id from this point 15139 * onwards anymore, thus we should better reset it, 15140 * so that state pruning has chances to take effect. 15141 */ 15142 reg->id = 0; 15143 reg->ref_obj_id = 0; 15144 15145 return; 15146 } 15147 15148 mark_ptr_not_null_reg(reg); 15149 15150 if (!reg_may_point_to_spin_lock(reg)) { 15151 /* For not-NULL ptr, reg->ref_obj_id will be reset 15152 * in release_reference(). 15153 * 15154 * reg->id is still used by spin_lock ptr. Other 15155 * than spin_lock ptr type, reg->id can be reset. 15156 */ 15157 reg->id = 0; 15158 } 15159 } 15160 } 15161 15162 /* The logic is similar to find_good_pkt_pointers(), both could eventually 15163 * be folded together at some point. 15164 */ 15165 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 15166 bool is_null) 15167 { 15168 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 15169 struct bpf_reg_state *regs = state->regs, *reg; 15170 u32 ref_obj_id = regs[regno].ref_obj_id; 15171 u32 id = regs[regno].id; 15172 15173 if (ref_obj_id && ref_obj_id == id && is_null) 15174 /* regs[regno] is in the " == NULL" branch. 15175 * No one could have freed the reference state before 15176 * doing the NULL check. 15177 */ 15178 WARN_ON_ONCE(release_reference_state(state, id)); 15179 15180 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15181 mark_ptr_or_null_reg(state, reg, id, is_null); 15182 })); 15183 } 15184 15185 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 15186 struct bpf_reg_state *dst_reg, 15187 struct bpf_reg_state *src_reg, 15188 struct bpf_verifier_state *this_branch, 15189 struct bpf_verifier_state *other_branch) 15190 { 15191 if (BPF_SRC(insn->code) != BPF_X) 15192 return false; 15193 15194 /* Pointers are always 64-bit. */ 15195 if (BPF_CLASS(insn->code) == BPF_JMP32) 15196 return false; 15197 15198 switch (BPF_OP(insn->code)) { 15199 case BPF_JGT: 15200 if ((dst_reg->type == PTR_TO_PACKET && 15201 src_reg->type == PTR_TO_PACKET_END) || 15202 (dst_reg->type == PTR_TO_PACKET_META && 15203 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15204 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 15205 find_good_pkt_pointers(this_branch, dst_reg, 15206 dst_reg->type, false); 15207 mark_pkt_end(other_branch, insn->dst_reg, true); 15208 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15209 src_reg->type == PTR_TO_PACKET) || 15210 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15211 src_reg->type == PTR_TO_PACKET_META)) { 15212 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 15213 find_good_pkt_pointers(other_branch, src_reg, 15214 src_reg->type, true); 15215 mark_pkt_end(this_branch, insn->src_reg, false); 15216 } else { 15217 return false; 15218 } 15219 break; 15220 case BPF_JLT: 15221 if ((dst_reg->type == PTR_TO_PACKET && 15222 src_reg->type == PTR_TO_PACKET_END) || 15223 (dst_reg->type == PTR_TO_PACKET_META && 15224 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15225 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 15226 find_good_pkt_pointers(other_branch, dst_reg, 15227 dst_reg->type, true); 15228 mark_pkt_end(this_branch, insn->dst_reg, false); 15229 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15230 src_reg->type == PTR_TO_PACKET) || 15231 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15232 src_reg->type == PTR_TO_PACKET_META)) { 15233 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 15234 find_good_pkt_pointers(this_branch, src_reg, 15235 src_reg->type, false); 15236 mark_pkt_end(other_branch, insn->src_reg, true); 15237 } else { 15238 return false; 15239 } 15240 break; 15241 case BPF_JGE: 15242 if ((dst_reg->type == PTR_TO_PACKET && 15243 src_reg->type == PTR_TO_PACKET_END) || 15244 (dst_reg->type == PTR_TO_PACKET_META && 15245 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15246 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 15247 find_good_pkt_pointers(this_branch, dst_reg, 15248 dst_reg->type, true); 15249 mark_pkt_end(other_branch, insn->dst_reg, false); 15250 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15251 src_reg->type == PTR_TO_PACKET) || 15252 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15253 src_reg->type == PTR_TO_PACKET_META)) { 15254 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 15255 find_good_pkt_pointers(other_branch, src_reg, 15256 src_reg->type, false); 15257 mark_pkt_end(this_branch, insn->src_reg, true); 15258 } else { 15259 return false; 15260 } 15261 break; 15262 case BPF_JLE: 15263 if ((dst_reg->type == PTR_TO_PACKET && 15264 src_reg->type == PTR_TO_PACKET_END) || 15265 (dst_reg->type == PTR_TO_PACKET_META && 15266 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15267 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 15268 find_good_pkt_pointers(other_branch, dst_reg, 15269 dst_reg->type, false); 15270 mark_pkt_end(this_branch, insn->dst_reg, true); 15271 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15272 src_reg->type == PTR_TO_PACKET) || 15273 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15274 src_reg->type == PTR_TO_PACKET_META)) { 15275 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 15276 find_good_pkt_pointers(this_branch, src_reg, 15277 src_reg->type, true); 15278 mark_pkt_end(other_branch, insn->src_reg, false); 15279 } else { 15280 return false; 15281 } 15282 break; 15283 default: 15284 return false; 15285 } 15286 15287 return true; 15288 } 15289 15290 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg, 15291 u32 id, u32 frameno, u32 spi_or_reg, bool is_reg) 15292 { 15293 struct linked_reg *e; 15294 15295 if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id) 15296 return; 15297 15298 e = linked_regs_push(reg_set); 15299 if (e) { 15300 e->frameno = frameno; 15301 e->is_reg = is_reg; 15302 e->regno = spi_or_reg; 15303 } else { 15304 reg->id = 0; 15305 } 15306 } 15307 15308 /* For all R being scalar registers or spilled scalar registers 15309 * in verifier state, save R in linked_regs if R->id == id. 15310 * If there are too many Rs sharing same id, reset id for leftover Rs. 15311 */ 15312 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id, 15313 struct linked_regs *linked_regs) 15314 { 15315 struct bpf_func_state *func; 15316 struct bpf_reg_state *reg; 15317 int i, j; 15318 15319 id = id & ~BPF_ADD_CONST; 15320 for (i = vstate->curframe; i >= 0; i--) { 15321 func = vstate->frame[i]; 15322 for (j = 0; j < BPF_REG_FP; j++) { 15323 reg = &func->regs[j]; 15324 __collect_linked_regs(linked_regs, reg, id, i, j, true); 15325 } 15326 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 15327 if (!is_spilled_reg(&func->stack[j])) 15328 continue; 15329 reg = &func->stack[j].spilled_ptr; 15330 __collect_linked_regs(linked_regs, reg, id, i, j, false); 15331 } 15332 } 15333 } 15334 15335 /* For all R in linked_regs, copy known_reg range into R 15336 * if R->id == known_reg->id. 15337 */ 15338 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg, 15339 struct linked_regs *linked_regs) 15340 { 15341 struct bpf_reg_state fake_reg; 15342 struct bpf_reg_state *reg; 15343 struct linked_reg *e; 15344 int i; 15345 15346 for (i = 0; i < linked_regs->cnt; ++i) { 15347 e = &linked_regs->entries[i]; 15348 reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno] 15349 : &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr; 15350 if (reg->type != SCALAR_VALUE || reg == known_reg) 15351 continue; 15352 if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST)) 15353 continue; 15354 if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) || 15355 reg->off == known_reg->off) { 15356 copy_register_state(reg, known_reg); 15357 } else { 15358 s32 saved_off = reg->off; 15359 15360 fake_reg.type = SCALAR_VALUE; 15361 __mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off); 15362 15363 /* reg = known_reg; reg += delta */ 15364 copy_register_state(reg, known_reg); 15365 /* 15366 * Must preserve off, id and add_const flag, 15367 * otherwise another sync_linked_regs() will be incorrect. 15368 */ 15369 reg->off = saved_off; 15370 15371 scalar32_min_max_add(reg, &fake_reg); 15372 scalar_min_max_add(reg, &fake_reg); 15373 reg->var_off = tnum_add(reg->var_off, fake_reg.var_off); 15374 } 15375 } 15376 } 15377 15378 static int check_cond_jmp_op(struct bpf_verifier_env *env, 15379 struct bpf_insn *insn, int *insn_idx) 15380 { 15381 struct bpf_verifier_state *this_branch = env->cur_state; 15382 struct bpf_verifier_state *other_branch; 15383 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 15384 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 15385 struct bpf_reg_state *eq_branch_regs; 15386 struct linked_regs linked_regs = {}; 15387 u8 opcode = BPF_OP(insn->code); 15388 bool is_jmp32; 15389 int pred = -1; 15390 int err; 15391 15392 /* Only conditional jumps are expected to reach here. */ 15393 if (opcode == BPF_JA || opcode > BPF_JCOND) { 15394 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 15395 return -EINVAL; 15396 } 15397 15398 if (opcode == BPF_JCOND) { 15399 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 15400 int idx = *insn_idx; 15401 15402 if (insn->code != (BPF_JMP | BPF_JCOND) || 15403 insn->src_reg != BPF_MAY_GOTO || 15404 insn->dst_reg || insn->imm || insn->off == 0) { 15405 verbose(env, "invalid may_goto off %d imm %d\n", 15406 insn->off, insn->imm); 15407 return -EINVAL; 15408 } 15409 prev_st = find_prev_entry(env, cur_st->parent, idx); 15410 15411 /* branch out 'fallthrough' insn as a new state to explore */ 15412 queued_st = push_stack(env, idx + 1, idx, false); 15413 if (!queued_st) 15414 return -ENOMEM; 15415 15416 queued_st->may_goto_depth++; 15417 if (prev_st) 15418 widen_imprecise_scalars(env, prev_st, queued_st); 15419 *insn_idx += insn->off; 15420 return 0; 15421 } 15422 15423 /* check src2 operand */ 15424 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15425 if (err) 15426 return err; 15427 15428 dst_reg = ®s[insn->dst_reg]; 15429 if (BPF_SRC(insn->code) == BPF_X) { 15430 if (insn->imm != 0) { 15431 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 15432 return -EINVAL; 15433 } 15434 15435 /* check src1 operand */ 15436 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15437 if (err) 15438 return err; 15439 15440 src_reg = ®s[insn->src_reg]; 15441 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 15442 is_pointer_value(env, insn->src_reg)) { 15443 verbose(env, "R%d pointer comparison prohibited\n", 15444 insn->src_reg); 15445 return -EACCES; 15446 } 15447 } else { 15448 if (insn->src_reg != BPF_REG_0) { 15449 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 15450 return -EINVAL; 15451 } 15452 src_reg = &env->fake_reg[0]; 15453 memset(src_reg, 0, sizeof(*src_reg)); 15454 src_reg->type = SCALAR_VALUE; 15455 __mark_reg_known(src_reg, insn->imm); 15456 } 15457 15458 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 15459 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32); 15460 if (pred >= 0) { 15461 /* If we get here with a dst_reg pointer type it is because 15462 * above is_branch_taken() special cased the 0 comparison. 15463 */ 15464 if (!__is_pointer_value(false, dst_reg)) 15465 err = mark_chain_precision(env, insn->dst_reg); 15466 if (BPF_SRC(insn->code) == BPF_X && !err && 15467 !__is_pointer_value(false, src_reg)) 15468 err = mark_chain_precision(env, insn->src_reg); 15469 if (err) 15470 return err; 15471 } 15472 15473 if (pred == 1) { 15474 /* Only follow the goto, ignore fall-through. If needed, push 15475 * the fall-through branch for simulation under speculative 15476 * execution. 15477 */ 15478 if (!env->bypass_spec_v1 && 15479 !sanitize_speculative_path(env, insn, *insn_idx + 1, 15480 *insn_idx)) 15481 return -EFAULT; 15482 if (env->log.level & BPF_LOG_LEVEL) 15483 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15484 *insn_idx += insn->off; 15485 return 0; 15486 } else if (pred == 0) { 15487 /* Only follow the fall-through branch, since that's where the 15488 * program will go. If needed, push the goto branch for 15489 * simulation under speculative execution. 15490 */ 15491 if (!env->bypass_spec_v1 && 15492 !sanitize_speculative_path(env, insn, 15493 *insn_idx + insn->off + 1, 15494 *insn_idx)) 15495 return -EFAULT; 15496 if (env->log.level & BPF_LOG_LEVEL) 15497 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15498 return 0; 15499 } 15500 15501 /* Push scalar registers sharing same ID to jump history, 15502 * do this before creating 'other_branch', so that both 15503 * 'this_branch' and 'other_branch' share this history 15504 * if parent state is created. 15505 */ 15506 if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id) 15507 collect_linked_regs(this_branch, src_reg->id, &linked_regs); 15508 if (dst_reg->type == SCALAR_VALUE && dst_reg->id) 15509 collect_linked_regs(this_branch, dst_reg->id, &linked_regs); 15510 if (linked_regs.cnt > 1) { 15511 err = push_jmp_history(env, this_branch, 0, linked_regs_pack(&linked_regs)); 15512 if (err) 15513 return err; 15514 } 15515 15516 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 15517 false); 15518 if (!other_branch) 15519 return -EFAULT; 15520 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 15521 15522 if (BPF_SRC(insn->code) == BPF_X) { 15523 err = reg_set_min_max(env, 15524 &other_branch_regs[insn->dst_reg], 15525 &other_branch_regs[insn->src_reg], 15526 dst_reg, src_reg, opcode, is_jmp32); 15527 } else /* BPF_SRC(insn->code) == BPF_K */ { 15528 /* reg_set_min_max() can mangle the fake_reg. Make a copy 15529 * so that these are two different memory locations. The 15530 * src_reg is not used beyond here in context of K. 15531 */ 15532 memcpy(&env->fake_reg[1], &env->fake_reg[0], 15533 sizeof(env->fake_reg[0])); 15534 err = reg_set_min_max(env, 15535 &other_branch_regs[insn->dst_reg], 15536 &env->fake_reg[0], 15537 dst_reg, &env->fake_reg[1], 15538 opcode, is_jmp32); 15539 } 15540 if (err) 15541 return err; 15542 15543 if (BPF_SRC(insn->code) == BPF_X && 15544 src_reg->type == SCALAR_VALUE && src_reg->id && 15545 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 15546 sync_linked_regs(this_branch, src_reg, &linked_regs); 15547 sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs); 15548 } 15549 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 15550 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 15551 sync_linked_regs(this_branch, dst_reg, &linked_regs); 15552 sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs); 15553 } 15554 15555 /* if one pointer register is compared to another pointer 15556 * register check if PTR_MAYBE_NULL could be lifted. 15557 * E.g. register A - maybe null 15558 * register B - not null 15559 * for JNE A, B, ... - A is not null in the false branch; 15560 * for JEQ A, B, ... - A is not null in the true branch. 15561 * 15562 * Since PTR_TO_BTF_ID points to a kernel struct that does 15563 * not need to be null checked by the BPF program, i.e., 15564 * could be null even without PTR_MAYBE_NULL marking, so 15565 * only propagate nullness when neither reg is that type. 15566 */ 15567 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 15568 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 15569 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 15570 base_type(src_reg->type) != PTR_TO_BTF_ID && 15571 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 15572 eq_branch_regs = NULL; 15573 switch (opcode) { 15574 case BPF_JEQ: 15575 eq_branch_regs = other_branch_regs; 15576 break; 15577 case BPF_JNE: 15578 eq_branch_regs = regs; 15579 break; 15580 default: 15581 /* do nothing */ 15582 break; 15583 } 15584 if (eq_branch_regs) { 15585 if (type_may_be_null(src_reg->type)) 15586 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 15587 else 15588 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 15589 } 15590 } 15591 15592 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 15593 * NOTE: these optimizations below are related with pointer comparison 15594 * which will never be JMP32. 15595 */ 15596 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 15597 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 15598 type_may_be_null(dst_reg->type)) { 15599 /* Mark all identical registers in each branch as either 15600 * safe or unknown depending R == 0 or R != 0 conditional. 15601 */ 15602 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 15603 opcode == BPF_JNE); 15604 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 15605 opcode == BPF_JEQ); 15606 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 15607 this_branch, other_branch) && 15608 is_pointer_value(env, insn->dst_reg)) { 15609 verbose(env, "R%d pointer comparison prohibited\n", 15610 insn->dst_reg); 15611 return -EACCES; 15612 } 15613 if (env->log.level & BPF_LOG_LEVEL) 15614 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15615 return 0; 15616 } 15617 15618 /* verify BPF_LD_IMM64 instruction */ 15619 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 15620 { 15621 struct bpf_insn_aux_data *aux = cur_aux(env); 15622 struct bpf_reg_state *regs = cur_regs(env); 15623 struct bpf_reg_state *dst_reg; 15624 struct bpf_map *map; 15625 int err; 15626 15627 if (BPF_SIZE(insn->code) != BPF_DW) { 15628 verbose(env, "invalid BPF_LD_IMM insn\n"); 15629 return -EINVAL; 15630 } 15631 if (insn->off != 0) { 15632 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 15633 return -EINVAL; 15634 } 15635 15636 err = check_reg_arg(env, insn->dst_reg, DST_OP); 15637 if (err) 15638 return err; 15639 15640 dst_reg = ®s[insn->dst_reg]; 15641 if (insn->src_reg == 0) { 15642 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 15643 15644 dst_reg->type = SCALAR_VALUE; 15645 __mark_reg_known(®s[insn->dst_reg], imm); 15646 return 0; 15647 } 15648 15649 /* All special src_reg cases are listed below. From this point onwards 15650 * we either succeed and assign a corresponding dst_reg->type after 15651 * zeroing the offset, or fail and reject the program. 15652 */ 15653 mark_reg_known_zero(env, regs, insn->dst_reg); 15654 15655 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 15656 dst_reg->type = aux->btf_var.reg_type; 15657 switch (base_type(dst_reg->type)) { 15658 case PTR_TO_MEM: 15659 dst_reg->mem_size = aux->btf_var.mem_size; 15660 break; 15661 case PTR_TO_BTF_ID: 15662 dst_reg->btf = aux->btf_var.btf; 15663 dst_reg->btf_id = aux->btf_var.btf_id; 15664 break; 15665 default: 15666 verbose(env, "bpf verifier is misconfigured\n"); 15667 return -EFAULT; 15668 } 15669 return 0; 15670 } 15671 15672 if (insn->src_reg == BPF_PSEUDO_FUNC) { 15673 struct bpf_prog_aux *aux = env->prog->aux; 15674 u32 subprogno = find_subprog(env, 15675 env->insn_idx + insn->imm + 1); 15676 15677 if (!aux->func_info) { 15678 verbose(env, "missing btf func_info\n"); 15679 return -EINVAL; 15680 } 15681 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 15682 verbose(env, "callback function not static\n"); 15683 return -EINVAL; 15684 } 15685 15686 dst_reg->type = PTR_TO_FUNC; 15687 dst_reg->subprogno = subprogno; 15688 return 0; 15689 } 15690 15691 map = env->used_maps[aux->map_index]; 15692 dst_reg->map_ptr = map; 15693 15694 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 15695 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 15696 if (map->map_type == BPF_MAP_TYPE_ARENA) { 15697 __mark_reg_unknown(env, dst_reg); 15698 return 0; 15699 } 15700 dst_reg->type = PTR_TO_MAP_VALUE; 15701 dst_reg->off = aux->map_off; 15702 WARN_ON_ONCE(map->max_entries != 1); 15703 /* We want reg->id to be same (0) as map_value is not distinct */ 15704 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 15705 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 15706 dst_reg->type = CONST_PTR_TO_MAP; 15707 } else { 15708 verbose(env, "bpf verifier is misconfigured\n"); 15709 return -EINVAL; 15710 } 15711 15712 return 0; 15713 } 15714 15715 static bool may_access_skb(enum bpf_prog_type type) 15716 { 15717 switch (type) { 15718 case BPF_PROG_TYPE_SOCKET_FILTER: 15719 case BPF_PROG_TYPE_SCHED_CLS: 15720 case BPF_PROG_TYPE_SCHED_ACT: 15721 return true; 15722 default: 15723 return false; 15724 } 15725 } 15726 15727 /* verify safety of LD_ABS|LD_IND instructions: 15728 * - they can only appear in the programs where ctx == skb 15729 * - since they are wrappers of function calls, they scratch R1-R5 registers, 15730 * preserve R6-R9, and store return value into R0 15731 * 15732 * Implicit input: 15733 * ctx == skb == R6 == CTX 15734 * 15735 * Explicit input: 15736 * SRC == any register 15737 * IMM == 32-bit immediate 15738 * 15739 * Output: 15740 * R0 - 8/16/32-bit skb data converted to cpu endianness 15741 */ 15742 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 15743 { 15744 struct bpf_reg_state *regs = cur_regs(env); 15745 static const int ctx_reg = BPF_REG_6; 15746 u8 mode = BPF_MODE(insn->code); 15747 int i, err; 15748 15749 if (!may_access_skb(resolve_prog_type(env->prog))) { 15750 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 15751 return -EINVAL; 15752 } 15753 15754 if (!env->ops->gen_ld_abs) { 15755 verbose(env, "bpf verifier is misconfigured\n"); 15756 return -EINVAL; 15757 } 15758 15759 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 15760 BPF_SIZE(insn->code) == BPF_DW || 15761 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 15762 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 15763 return -EINVAL; 15764 } 15765 15766 /* check whether implicit source operand (register R6) is readable */ 15767 err = check_reg_arg(env, ctx_reg, SRC_OP); 15768 if (err) 15769 return err; 15770 15771 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 15772 * gen_ld_abs() may terminate the program at runtime, leading to 15773 * reference leak. 15774 */ 15775 err = check_reference_leak(env, false); 15776 if (err) { 15777 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 15778 return err; 15779 } 15780 15781 if (env->cur_state->active_lock.ptr) { 15782 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 15783 return -EINVAL; 15784 } 15785 15786 if (env->cur_state->active_rcu_lock) { 15787 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 15788 return -EINVAL; 15789 } 15790 15791 if (env->cur_state->active_preempt_lock) { 15792 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_preempt_disable-ed region\n"); 15793 return -EINVAL; 15794 } 15795 15796 if (regs[ctx_reg].type != PTR_TO_CTX) { 15797 verbose(env, 15798 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 15799 return -EINVAL; 15800 } 15801 15802 if (mode == BPF_IND) { 15803 /* check explicit source operand */ 15804 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15805 if (err) 15806 return err; 15807 } 15808 15809 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 15810 if (err < 0) 15811 return err; 15812 15813 /* reset caller saved regs to unreadable */ 15814 for (i = 0; i < CALLER_SAVED_REGS; i++) { 15815 mark_reg_not_init(env, regs, caller_saved[i]); 15816 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 15817 } 15818 15819 /* mark destination R0 register as readable, since it contains 15820 * the value fetched from the packet. 15821 * Already marked as written above. 15822 */ 15823 mark_reg_unknown(env, regs, BPF_REG_0); 15824 /* ld_abs load up to 32-bit skb data. */ 15825 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 15826 return 0; 15827 } 15828 15829 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 15830 { 15831 const char *exit_ctx = "At program exit"; 15832 struct tnum enforce_attach_type_range = tnum_unknown; 15833 const struct bpf_prog *prog = env->prog; 15834 struct bpf_reg_state *reg; 15835 struct bpf_retval_range range = retval_range(0, 1); 15836 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 15837 int err; 15838 struct bpf_func_state *frame = env->cur_state->frame[0]; 15839 const bool is_subprog = frame->subprogno; 15840 bool return_32bit = false; 15841 15842 /* LSM and struct_ops func-ptr's return type could be "void" */ 15843 if (!is_subprog || frame->in_exception_callback_fn) { 15844 switch (prog_type) { 15845 case BPF_PROG_TYPE_LSM: 15846 if (prog->expected_attach_type == BPF_LSM_CGROUP) 15847 /* See below, can be 0 or 0-1 depending on hook. */ 15848 break; 15849 fallthrough; 15850 case BPF_PROG_TYPE_STRUCT_OPS: 15851 if (!prog->aux->attach_func_proto->type) 15852 return 0; 15853 break; 15854 default: 15855 break; 15856 } 15857 } 15858 15859 /* eBPF calling convention is such that R0 is used 15860 * to return the value from eBPF program. 15861 * Make sure that it's readable at this time 15862 * of bpf_exit, which means that program wrote 15863 * something into it earlier 15864 */ 15865 err = check_reg_arg(env, regno, SRC_OP); 15866 if (err) 15867 return err; 15868 15869 if (is_pointer_value(env, regno)) { 15870 verbose(env, "R%d leaks addr as return value\n", regno); 15871 return -EACCES; 15872 } 15873 15874 reg = cur_regs(env) + regno; 15875 15876 if (frame->in_async_callback_fn) { 15877 /* enforce return zero from async callbacks like timer */ 15878 exit_ctx = "At async callback return"; 15879 range = retval_range(0, 0); 15880 goto enforce_retval; 15881 } 15882 15883 if (is_subprog && !frame->in_exception_callback_fn) { 15884 if (reg->type != SCALAR_VALUE) { 15885 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 15886 regno, reg_type_str(env, reg->type)); 15887 return -EINVAL; 15888 } 15889 return 0; 15890 } 15891 15892 switch (prog_type) { 15893 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 15894 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 15895 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 15896 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG || 15897 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 15898 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 15899 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME || 15900 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 15901 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME || 15902 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME) 15903 range = retval_range(1, 1); 15904 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 15905 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 15906 range = retval_range(0, 3); 15907 break; 15908 case BPF_PROG_TYPE_CGROUP_SKB: 15909 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 15910 range = retval_range(0, 3); 15911 enforce_attach_type_range = tnum_range(2, 3); 15912 } 15913 break; 15914 case BPF_PROG_TYPE_CGROUP_SOCK: 15915 case BPF_PROG_TYPE_SOCK_OPS: 15916 case BPF_PROG_TYPE_CGROUP_DEVICE: 15917 case BPF_PROG_TYPE_CGROUP_SYSCTL: 15918 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 15919 break; 15920 case BPF_PROG_TYPE_RAW_TRACEPOINT: 15921 if (!env->prog->aux->attach_btf_id) 15922 return 0; 15923 range = retval_range(0, 0); 15924 break; 15925 case BPF_PROG_TYPE_TRACING: 15926 switch (env->prog->expected_attach_type) { 15927 case BPF_TRACE_FENTRY: 15928 case BPF_TRACE_FEXIT: 15929 range = retval_range(0, 0); 15930 break; 15931 case BPF_TRACE_RAW_TP: 15932 case BPF_MODIFY_RETURN: 15933 return 0; 15934 case BPF_TRACE_ITER: 15935 break; 15936 default: 15937 return -ENOTSUPP; 15938 } 15939 break; 15940 case BPF_PROG_TYPE_SK_LOOKUP: 15941 range = retval_range(SK_DROP, SK_PASS); 15942 break; 15943 15944 case BPF_PROG_TYPE_LSM: 15945 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 15946 /* no range found, any return value is allowed */ 15947 if (!get_func_retval_range(env->prog, &range)) 15948 return 0; 15949 /* no restricted range, any return value is allowed */ 15950 if (range.minval == S32_MIN && range.maxval == S32_MAX) 15951 return 0; 15952 return_32bit = true; 15953 } else if (!env->prog->aux->attach_func_proto->type) { 15954 /* Make sure programs that attach to void 15955 * hooks don't try to modify return value. 15956 */ 15957 range = retval_range(1, 1); 15958 } 15959 break; 15960 15961 case BPF_PROG_TYPE_NETFILTER: 15962 range = retval_range(NF_DROP, NF_ACCEPT); 15963 break; 15964 case BPF_PROG_TYPE_EXT: 15965 /* freplace program can return anything as its return value 15966 * depends on the to-be-replaced kernel func or bpf program. 15967 */ 15968 default: 15969 return 0; 15970 } 15971 15972 enforce_retval: 15973 if (reg->type != SCALAR_VALUE) { 15974 verbose(env, "%s the register R%d is not a known value (%s)\n", 15975 exit_ctx, regno, reg_type_str(env, reg->type)); 15976 return -EINVAL; 15977 } 15978 15979 err = mark_chain_precision(env, regno); 15980 if (err) 15981 return err; 15982 15983 if (!retval_range_within(range, reg, return_32bit)) { 15984 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 15985 if (!is_subprog && 15986 prog->expected_attach_type == BPF_LSM_CGROUP && 15987 prog_type == BPF_PROG_TYPE_LSM && 15988 !prog->aux->attach_func_proto->type) 15989 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 15990 return -EINVAL; 15991 } 15992 15993 if (!tnum_is_unknown(enforce_attach_type_range) && 15994 tnum_in(enforce_attach_type_range, reg->var_off)) 15995 env->prog->enforce_expected_attach_type = 1; 15996 return 0; 15997 } 15998 15999 /* non-recursive DFS pseudo code 16000 * 1 procedure DFS-iterative(G,v): 16001 * 2 label v as discovered 16002 * 3 let S be a stack 16003 * 4 S.push(v) 16004 * 5 while S is not empty 16005 * 6 t <- S.peek() 16006 * 7 if t is what we're looking for: 16007 * 8 return t 16008 * 9 for all edges e in G.adjacentEdges(t) do 16009 * 10 if edge e is already labelled 16010 * 11 continue with the next edge 16011 * 12 w <- G.adjacentVertex(t,e) 16012 * 13 if vertex w is not discovered and not explored 16013 * 14 label e as tree-edge 16014 * 15 label w as discovered 16015 * 16 S.push(w) 16016 * 17 continue at 5 16017 * 18 else if vertex w is discovered 16018 * 19 label e as back-edge 16019 * 20 else 16020 * 21 // vertex w is explored 16021 * 22 label e as forward- or cross-edge 16022 * 23 label t as explored 16023 * 24 S.pop() 16024 * 16025 * convention: 16026 * 0x10 - discovered 16027 * 0x11 - discovered and fall-through edge labelled 16028 * 0x12 - discovered and fall-through and branch edges labelled 16029 * 0x20 - explored 16030 */ 16031 16032 enum { 16033 DISCOVERED = 0x10, 16034 EXPLORED = 0x20, 16035 FALLTHROUGH = 1, 16036 BRANCH = 2, 16037 }; 16038 16039 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 16040 { 16041 env->insn_aux_data[idx].prune_point = true; 16042 } 16043 16044 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 16045 { 16046 return env->insn_aux_data[insn_idx].prune_point; 16047 } 16048 16049 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 16050 { 16051 env->insn_aux_data[idx].force_checkpoint = true; 16052 } 16053 16054 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 16055 { 16056 return env->insn_aux_data[insn_idx].force_checkpoint; 16057 } 16058 16059 static void mark_calls_callback(struct bpf_verifier_env *env, int idx) 16060 { 16061 env->insn_aux_data[idx].calls_callback = true; 16062 } 16063 16064 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx) 16065 { 16066 return env->insn_aux_data[insn_idx].calls_callback; 16067 } 16068 16069 enum { 16070 DONE_EXPLORING = 0, 16071 KEEP_EXPLORING = 1, 16072 }; 16073 16074 /* t, w, e - match pseudo-code above: 16075 * t - index of current instruction 16076 * w - next instruction 16077 * e - edge 16078 */ 16079 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 16080 { 16081 int *insn_stack = env->cfg.insn_stack; 16082 int *insn_state = env->cfg.insn_state; 16083 16084 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 16085 return DONE_EXPLORING; 16086 16087 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 16088 return DONE_EXPLORING; 16089 16090 if (w < 0 || w >= env->prog->len) { 16091 verbose_linfo(env, t, "%d: ", t); 16092 verbose(env, "jump out of range from insn %d to %d\n", t, w); 16093 return -EINVAL; 16094 } 16095 16096 if (e == BRANCH) { 16097 /* mark branch target for state pruning */ 16098 mark_prune_point(env, w); 16099 mark_jmp_point(env, w); 16100 } 16101 16102 if (insn_state[w] == 0) { 16103 /* tree-edge */ 16104 insn_state[t] = DISCOVERED | e; 16105 insn_state[w] = DISCOVERED; 16106 if (env->cfg.cur_stack >= env->prog->len) 16107 return -E2BIG; 16108 insn_stack[env->cfg.cur_stack++] = w; 16109 return KEEP_EXPLORING; 16110 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 16111 if (env->bpf_capable) 16112 return DONE_EXPLORING; 16113 verbose_linfo(env, t, "%d: ", t); 16114 verbose_linfo(env, w, "%d: ", w); 16115 verbose(env, "back-edge from insn %d to %d\n", t, w); 16116 return -EINVAL; 16117 } else if (insn_state[w] == EXPLORED) { 16118 /* forward- or cross-edge */ 16119 insn_state[t] = DISCOVERED | e; 16120 } else { 16121 verbose(env, "insn state internal bug\n"); 16122 return -EFAULT; 16123 } 16124 return DONE_EXPLORING; 16125 } 16126 16127 static int visit_func_call_insn(int t, struct bpf_insn *insns, 16128 struct bpf_verifier_env *env, 16129 bool visit_callee) 16130 { 16131 int ret, insn_sz; 16132 16133 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 16134 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 16135 if (ret) 16136 return ret; 16137 16138 mark_prune_point(env, t + insn_sz); 16139 /* when we exit from subprog, we need to record non-linear history */ 16140 mark_jmp_point(env, t + insn_sz); 16141 16142 if (visit_callee) { 16143 mark_prune_point(env, t); 16144 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env); 16145 } 16146 return ret; 16147 } 16148 16149 /* Bitmask with 1s for all caller saved registers */ 16150 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 16151 16152 /* Return a bitmask specifying which caller saved registers are 16153 * clobbered by a call to a helper *as if* this helper follows 16154 * bpf_fastcall contract: 16155 * - includes R0 if function is non-void; 16156 * - includes R1-R5 if corresponding parameter has is described 16157 * in the function prototype. 16158 */ 16159 static u32 helper_fastcall_clobber_mask(const struct bpf_func_proto *fn) 16160 { 16161 u32 mask; 16162 int i; 16163 16164 mask = 0; 16165 if (fn->ret_type != RET_VOID) 16166 mask |= BIT(BPF_REG_0); 16167 for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) 16168 if (fn->arg_type[i] != ARG_DONTCARE) 16169 mask |= BIT(BPF_REG_1 + i); 16170 return mask; 16171 } 16172 16173 /* True if do_misc_fixups() replaces calls to helper number 'imm', 16174 * replacement patch is presumed to follow bpf_fastcall contract 16175 * (see mark_fastcall_pattern_for_call() below). 16176 */ 16177 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm) 16178 { 16179 switch (imm) { 16180 #ifdef CONFIG_X86_64 16181 case BPF_FUNC_get_smp_processor_id: 16182 return env->prog->jit_requested && bpf_jit_supports_percpu_insn(); 16183 #endif 16184 default: 16185 return false; 16186 } 16187 } 16188 16189 /* Same as helper_fastcall_clobber_mask() but for kfuncs, see comment above */ 16190 static u32 kfunc_fastcall_clobber_mask(struct bpf_kfunc_call_arg_meta *meta) 16191 { 16192 u32 vlen, i, mask; 16193 16194 vlen = btf_type_vlen(meta->func_proto); 16195 mask = 0; 16196 if (!btf_type_is_void(btf_type_by_id(meta->btf, meta->func_proto->type))) 16197 mask |= BIT(BPF_REG_0); 16198 for (i = 0; i < vlen; ++i) 16199 mask |= BIT(BPF_REG_1 + i); 16200 return mask; 16201 } 16202 16203 /* Same as verifier_inlines_helper_call() but for kfuncs, see comment above */ 16204 static bool is_fastcall_kfunc_call(struct bpf_kfunc_call_arg_meta *meta) 16205 { 16206 if (meta->btf == btf_vmlinux) 16207 return meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 16208 meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]; 16209 return false; 16210 } 16211 16212 /* LLVM define a bpf_fastcall function attribute. 16213 * This attribute means that function scratches only some of 16214 * the caller saved registers defined by ABI. 16215 * For BPF the set of such registers could be defined as follows: 16216 * - R0 is scratched only if function is non-void; 16217 * - R1-R5 are scratched only if corresponding parameter type is defined 16218 * in the function prototype. 16219 * 16220 * The contract between kernel and clang allows to simultaneously use 16221 * such functions and maintain backwards compatibility with old 16222 * kernels that don't understand bpf_fastcall calls: 16223 * 16224 * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5 16225 * registers are not scratched by the call; 16226 * 16227 * - as a post-processing step, clang visits each bpf_fastcall call and adds 16228 * spill/fill for every live r0-r5; 16229 * 16230 * - stack offsets used for the spill/fill are allocated as lowest 16231 * stack offsets in whole function and are not used for any other 16232 * purposes; 16233 * 16234 * - when kernel loads a program, it looks for such patterns 16235 * (bpf_fastcall function surrounded by spills/fills) and checks if 16236 * spill/fill stack offsets are used exclusively in fastcall patterns; 16237 * 16238 * - if so, and if verifier or current JIT inlines the call to the 16239 * bpf_fastcall function (e.g. a helper call), kernel removes unnecessary 16240 * spill/fill pairs; 16241 * 16242 * - when old kernel loads a program, presence of spill/fill pairs 16243 * keeps BPF program valid, albeit slightly less efficient. 16244 * 16245 * For example: 16246 * 16247 * r1 = 1; 16248 * r2 = 2; 16249 * *(u64 *)(r10 - 8) = r1; r1 = 1; 16250 * *(u64 *)(r10 - 16) = r2; r2 = 2; 16251 * call %[to_be_inlined] --> call %[to_be_inlined] 16252 * r2 = *(u64 *)(r10 - 16); r0 = r1; 16253 * r1 = *(u64 *)(r10 - 8); r0 += r2; 16254 * r0 = r1; exit; 16255 * r0 += r2; 16256 * exit; 16257 * 16258 * The purpose of mark_fastcall_pattern_for_call is to: 16259 * - look for such patterns; 16260 * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern; 16261 * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction; 16262 * - update env->subprog_info[*]->fastcall_stack_off to find an offset 16263 * at which bpf_fastcall spill/fill stack slots start; 16264 * - update env->subprog_info[*]->keep_fastcall_stack. 16265 * 16266 * The .fastcall_pattern and .fastcall_stack_off are used by 16267 * check_fastcall_stack_contract() to check if every stack access to 16268 * fastcall spill/fill stack slot originates from spill/fill 16269 * instructions, members of fastcall patterns. 16270 * 16271 * If such condition holds true for a subprogram, fastcall patterns could 16272 * be rewritten by remove_fastcall_spills_fills(). 16273 * Otherwise bpf_fastcall patterns are not changed in the subprogram 16274 * (code, presumably, generated by an older clang version). 16275 * 16276 * For example, it is *not* safe to remove spill/fill below: 16277 * 16278 * r1 = 1; 16279 * *(u64 *)(r10 - 8) = r1; r1 = 1; 16280 * call %[to_be_inlined] --> call %[to_be_inlined] 16281 * r1 = *(u64 *)(r10 - 8); r0 = *(u64 *)(r10 - 8); <---- wrong !!! 16282 * r0 = *(u64 *)(r10 - 8); r0 += r1; 16283 * r0 += r1; exit; 16284 * exit; 16285 */ 16286 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env, 16287 struct bpf_subprog_info *subprog, 16288 int insn_idx, s16 lowest_off) 16289 { 16290 struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx; 16291 struct bpf_insn *call = &env->prog->insnsi[insn_idx]; 16292 const struct bpf_func_proto *fn; 16293 u32 clobbered_regs_mask = ALL_CALLER_SAVED_REGS; 16294 u32 expected_regs_mask; 16295 bool can_be_inlined = false; 16296 s16 off; 16297 int i; 16298 16299 if (bpf_helper_call(call)) { 16300 if (get_helper_proto(env, call->imm, &fn) < 0) 16301 /* error would be reported later */ 16302 return; 16303 clobbered_regs_mask = helper_fastcall_clobber_mask(fn); 16304 can_be_inlined = fn->allow_fastcall && 16305 (verifier_inlines_helper_call(env, call->imm) || 16306 bpf_jit_inlines_helper_call(call->imm)); 16307 } 16308 16309 if (bpf_pseudo_kfunc_call(call)) { 16310 struct bpf_kfunc_call_arg_meta meta; 16311 int err; 16312 16313 err = fetch_kfunc_meta(env, call, &meta, NULL); 16314 if (err < 0) 16315 /* error would be reported later */ 16316 return; 16317 16318 clobbered_regs_mask = kfunc_fastcall_clobber_mask(&meta); 16319 can_be_inlined = is_fastcall_kfunc_call(&meta); 16320 } 16321 16322 if (clobbered_regs_mask == ALL_CALLER_SAVED_REGS) 16323 return; 16324 16325 /* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */ 16326 expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS; 16327 16328 /* match pairs of form: 16329 * 16330 * *(u64 *)(r10 - Y) = rX (where Y % 8 == 0) 16331 * ... 16332 * call %[to_be_inlined] 16333 * ... 16334 * rX = *(u64 *)(r10 - Y) 16335 */ 16336 for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) { 16337 if (insn_idx - i < 0 || insn_idx + i >= env->prog->len) 16338 break; 16339 stx = &insns[insn_idx - i]; 16340 ldx = &insns[insn_idx + i]; 16341 /* must be a stack spill/fill pair */ 16342 if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) || 16343 ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) || 16344 stx->dst_reg != BPF_REG_10 || 16345 ldx->src_reg != BPF_REG_10) 16346 break; 16347 /* must be a spill/fill for the same reg */ 16348 if (stx->src_reg != ldx->dst_reg) 16349 break; 16350 /* must be one of the previously unseen registers */ 16351 if ((BIT(stx->src_reg) & expected_regs_mask) == 0) 16352 break; 16353 /* must be a spill/fill for the same expected offset, 16354 * no need to check offset alignment, BPF_DW stack access 16355 * is always 8-byte aligned. 16356 */ 16357 if (stx->off != off || ldx->off != off) 16358 break; 16359 expected_regs_mask &= ~BIT(stx->src_reg); 16360 env->insn_aux_data[insn_idx - i].fastcall_pattern = 1; 16361 env->insn_aux_data[insn_idx + i].fastcall_pattern = 1; 16362 } 16363 if (i == 1) 16364 return; 16365 16366 /* Conditionally set 'fastcall_spills_num' to allow forward 16367 * compatibility when more helper functions are marked as 16368 * bpf_fastcall at compile time than current kernel supports, e.g: 16369 * 16370 * 1: *(u64 *)(r10 - 8) = r1 16371 * 2: call A ;; assume A is bpf_fastcall for current kernel 16372 * 3: r1 = *(u64 *)(r10 - 8) 16373 * 4: *(u64 *)(r10 - 8) = r1 16374 * 5: call B ;; assume B is not bpf_fastcall for current kernel 16375 * 6: r1 = *(u64 *)(r10 - 8) 16376 * 16377 * There is no need to block bpf_fastcall rewrite for such program. 16378 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy, 16379 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills() 16380 * does not remove spill/fill pair {4,6}. 16381 */ 16382 if (can_be_inlined) 16383 env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1; 16384 else 16385 subprog->keep_fastcall_stack = 1; 16386 subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off); 16387 } 16388 16389 static int mark_fastcall_patterns(struct bpf_verifier_env *env) 16390 { 16391 struct bpf_subprog_info *subprog = env->subprog_info; 16392 struct bpf_insn *insn; 16393 s16 lowest_off; 16394 int s, i; 16395 16396 for (s = 0; s < env->subprog_cnt; ++s, ++subprog) { 16397 /* find lowest stack spill offset used in this subprog */ 16398 lowest_off = 0; 16399 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 16400 insn = env->prog->insnsi + i; 16401 if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) || 16402 insn->dst_reg != BPF_REG_10) 16403 continue; 16404 lowest_off = min(lowest_off, insn->off); 16405 } 16406 /* use this offset to find fastcall patterns */ 16407 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 16408 insn = env->prog->insnsi + i; 16409 if (insn->code != (BPF_JMP | BPF_CALL)) 16410 continue; 16411 mark_fastcall_pattern_for_call(env, subprog, i, lowest_off); 16412 } 16413 } 16414 return 0; 16415 } 16416 16417 /* Visits the instruction at index t and returns one of the following: 16418 * < 0 - an error occurred 16419 * DONE_EXPLORING - the instruction was fully explored 16420 * KEEP_EXPLORING - there is still work to be done before it is fully explored 16421 */ 16422 static int visit_insn(int t, struct bpf_verifier_env *env) 16423 { 16424 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 16425 int ret, off, insn_sz; 16426 16427 if (bpf_pseudo_func(insn)) 16428 return visit_func_call_insn(t, insns, env, true); 16429 16430 /* All non-branch instructions have a single fall-through edge. */ 16431 if (BPF_CLASS(insn->code) != BPF_JMP && 16432 BPF_CLASS(insn->code) != BPF_JMP32) { 16433 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 16434 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 16435 } 16436 16437 switch (BPF_OP(insn->code)) { 16438 case BPF_EXIT: 16439 return DONE_EXPLORING; 16440 16441 case BPF_CALL: 16442 if (is_async_callback_calling_insn(insn)) 16443 /* Mark this call insn as a prune point to trigger 16444 * is_state_visited() check before call itself is 16445 * processed by __check_func_call(). Otherwise new 16446 * async state will be pushed for further exploration. 16447 */ 16448 mark_prune_point(env, t); 16449 /* For functions that invoke callbacks it is not known how many times 16450 * callback would be called. Verifier models callback calling functions 16451 * by repeatedly visiting callback bodies and returning to origin call 16452 * instruction. 16453 * In order to stop such iteration verifier needs to identify when a 16454 * state identical some state from a previous iteration is reached. 16455 * Check below forces creation of checkpoint before callback calling 16456 * instruction to allow search for such identical states. 16457 */ 16458 if (is_sync_callback_calling_insn(insn)) { 16459 mark_calls_callback(env, t); 16460 mark_force_checkpoint(env, t); 16461 mark_prune_point(env, t); 16462 mark_jmp_point(env, t); 16463 } 16464 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 16465 struct bpf_kfunc_call_arg_meta meta; 16466 16467 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 16468 if (ret == 0 && is_iter_next_kfunc(&meta)) { 16469 mark_prune_point(env, t); 16470 /* Checking and saving state checkpoints at iter_next() call 16471 * is crucial for fast convergence of open-coded iterator loop 16472 * logic, so we need to force it. If we don't do that, 16473 * is_state_visited() might skip saving a checkpoint, causing 16474 * unnecessarily long sequence of not checkpointed 16475 * instructions and jumps, leading to exhaustion of jump 16476 * history buffer, and potentially other undesired outcomes. 16477 * It is expected that with correct open-coded iterators 16478 * convergence will happen quickly, so we don't run a risk of 16479 * exhausting memory. 16480 */ 16481 mark_force_checkpoint(env, t); 16482 } 16483 } 16484 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 16485 16486 case BPF_JA: 16487 if (BPF_SRC(insn->code) != BPF_K) 16488 return -EINVAL; 16489 16490 if (BPF_CLASS(insn->code) == BPF_JMP) 16491 off = insn->off; 16492 else 16493 off = insn->imm; 16494 16495 /* unconditional jump with single edge */ 16496 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 16497 if (ret) 16498 return ret; 16499 16500 mark_prune_point(env, t + off + 1); 16501 mark_jmp_point(env, t + off + 1); 16502 16503 return ret; 16504 16505 default: 16506 /* conditional jump with two edges */ 16507 mark_prune_point(env, t); 16508 if (is_may_goto_insn(insn)) 16509 mark_force_checkpoint(env, t); 16510 16511 ret = push_insn(t, t + 1, FALLTHROUGH, env); 16512 if (ret) 16513 return ret; 16514 16515 return push_insn(t, t + insn->off + 1, BRANCH, env); 16516 } 16517 } 16518 16519 /* non-recursive depth-first-search to detect loops in BPF program 16520 * loop == back-edge in directed graph 16521 */ 16522 static int check_cfg(struct bpf_verifier_env *env) 16523 { 16524 int insn_cnt = env->prog->len; 16525 int *insn_stack, *insn_state; 16526 int ex_insn_beg, i, ret = 0; 16527 bool ex_done = false; 16528 16529 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 16530 if (!insn_state) 16531 return -ENOMEM; 16532 16533 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 16534 if (!insn_stack) { 16535 kvfree(insn_state); 16536 return -ENOMEM; 16537 } 16538 16539 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 16540 insn_stack[0] = 0; /* 0 is the first instruction */ 16541 env->cfg.cur_stack = 1; 16542 16543 walk_cfg: 16544 while (env->cfg.cur_stack > 0) { 16545 int t = insn_stack[env->cfg.cur_stack - 1]; 16546 16547 ret = visit_insn(t, env); 16548 switch (ret) { 16549 case DONE_EXPLORING: 16550 insn_state[t] = EXPLORED; 16551 env->cfg.cur_stack--; 16552 break; 16553 case KEEP_EXPLORING: 16554 break; 16555 default: 16556 if (ret > 0) { 16557 verbose(env, "visit_insn internal bug\n"); 16558 ret = -EFAULT; 16559 } 16560 goto err_free; 16561 } 16562 } 16563 16564 if (env->cfg.cur_stack < 0) { 16565 verbose(env, "pop stack internal bug\n"); 16566 ret = -EFAULT; 16567 goto err_free; 16568 } 16569 16570 if (env->exception_callback_subprog && !ex_done) { 16571 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start; 16572 16573 insn_state[ex_insn_beg] = DISCOVERED; 16574 insn_stack[0] = ex_insn_beg; 16575 env->cfg.cur_stack = 1; 16576 ex_done = true; 16577 goto walk_cfg; 16578 } 16579 16580 for (i = 0; i < insn_cnt; i++) { 16581 struct bpf_insn *insn = &env->prog->insnsi[i]; 16582 16583 if (insn_state[i] != EXPLORED) { 16584 verbose(env, "unreachable insn %d\n", i); 16585 ret = -EINVAL; 16586 goto err_free; 16587 } 16588 if (bpf_is_ldimm64(insn)) { 16589 if (insn_state[i + 1] != 0) { 16590 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 16591 ret = -EINVAL; 16592 goto err_free; 16593 } 16594 i++; /* skip second half of ldimm64 */ 16595 } 16596 } 16597 ret = 0; /* cfg looks good */ 16598 16599 err_free: 16600 kvfree(insn_state); 16601 kvfree(insn_stack); 16602 env->cfg.insn_state = env->cfg.insn_stack = NULL; 16603 return ret; 16604 } 16605 16606 static int check_abnormal_return(struct bpf_verifier_env *env) 16607 { 16608 int i; 16609 16610 for (i = 1; i < env->subprog_cnt; i++) { 16611 if (env->subprog_info[i].has_ld_abs) { 16612 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 16613 return -EINVAL; 16614 } 16615 if (env->subprog_info[i].has_tail_call) { 16616 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 16617 return -EINVAL; 16618 } 16619 } 16620 return 0; 16621 } 16622 16623 /* The minimum supported BTF func info size */ 16624 #define MIN_BPF_FUNCINFO_SIZE 8 16625 #define MAX_FUNCINFO_REC_SIZE 252 16626 16627 static int check_btf_func_early(struct bpf_verifier_env *env, 16628 const union bpf_attr *attr, 16629 bpfptr_t uattr) 16630 { 16631 u32 krec_size = sizeof(struct bpf_func_info); 16632 const struct btf_type *type, *func_proto; 16633 u32 i, nfuncs, urec_size, min_size; 16634 struct bpf_func_info *krecord; 16635 struct bpf_prog *prog; 16636 const struct btf *btf; 16637 u32 prev_offset = 0; 16638 bpfptr_t urecord; 16639 int ret = -ENOMEM; 16640 16641 nfuncs = attr->func_info_cnt; 16642 if (!nfuncs) { 16643 if (check_abnormal_return(env)) 16644 return -EINVAL; 16645 return 0; 16646 } 16647 16648 urec_size = attr->func_info_rec_size; 16649 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 16650 urec_size > MAX_FUNCINFO_REC_SIZE || 16651 urec_size % sizeof(u32)) { 16652 verbose(env, "invalid func info rec size %u\n", urec_size); 16653 return -EINVAL; 16654 } 16655 16656 prog = env->prog; 16657 btf = prog->aux->btf; 16658 16659 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 16660 min_size = min_t(u32, krec_size, urec_size); 16661 16662 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 16663 if (!krecord) 16664 return -ENOMEM; 16665 16666 for (i = 0; i < nfuncs; i++) { 16667 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 16668 if (ret) { 16669 if (ret == -E2BIG) { 16670 verbose(env, "nonzero tailing record in func info"); 16671 /* set the size kernel expects so loader can zero 16672 * out the rest of the record. 16673 */ 16674 if (copy_to_bpfptr_offset(uattr, 16675 offsetof(union bpf_attr, func_info_rec_size), 16676 &min_size, sizeof(min_size))) 16677 ret = -EFAULT; 16678 } 16679 goto err_free; 16680 } 16681 16682 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 16683 ret = -EFAULT; 16684 goto err_free; 16685 } 16686 16687 /* check insn_off */ 16688 ret = -EINVAL; 16689 if (i == 0) { 16690 if (krecord[i].insn_off) { 16691 verbose(env, 16692 "nonzero insn_off %u for the first func info record", 16693 krecord[i].insn_off); 16694 goto err_free; 16695 } 16696 } else if (krecord[i].insn_off <= prev_offset) { 16697 verbose(env, 16698 "same or smaller insn offset (%u) than previous func info record (%u)", 16699 krecord[i].insn_off, prev_offset); 16700 goto err_free; 16701 } 16702 16703 /* check type_id */ 16704 type = btf_type_by_id(btf, krecord[i].type_id); 16705 if (!type || !btf_type_is_func(type)) { 16706 verbose(env, "invalid type id %d in func info", 16707 krecord[i].type_id); 16708 goto err_free; 16709 } 16710 16711 func_proto = btf_type_by_id(btf, type->type); 16712 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 16713 /* btf_func_check() already verified it during BTF load */ 16714 goto err_free; 16715 16716 prev_offset = krecord[i].insn_off; 16717 bpfptr_add(&urecord, urec_size); 16718 } 16719 16720 prog->aux->func_info = krecord; 16721 prog->aux->func_info_cnt = nfuncs; 16722 return 0; 16723 16724 err_free: 16725 kvfree(krecord); 16726 return ret; 16727 } 16728 16729 static int check_btf_func(struct bpf_verifier_env *env, 16730 const union bpf_attr *attr, 16731 bpfptr_t uattr) 16732 { 16733 const struct btf_type *type, *func_proto, *ret_type; 16734 u32 i, nfuncs, urec_size; 16735 struct bpf_func_info *krecord; 16736 struct bpf_func_info_aux *info_aux = NULL; 16737 struct bpf_prog *prog; 16738 const struct btf *btf; 16739 bpfptr_t urecord; 16740 bool scalar_return; 16741 int ret = -ENOMEM; 16742 16743 nfuncs = attr->func_info_cnt; 16744 if (!nfuncs) { 16745 if (check_abnormal_return(env)) 16746 return -EINVAL; 16747 return 0; 16748 } 16749 if (nfuncs != env->subprog_cnt) { 16750 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 16751 return -EINVAL; 16752 } 16753 16754 urec_size = attr->func_info_rec_size; 16755 16756 prog = env->prog; 16757 btf = prog->aux->btf; 16758 16759 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 16760 16761 krecord = prog->aux->func_info; 16762 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 16763 if (!info_aux) 16764 return -ENOMEM; 16765 16766 for (i = 0; i < nfuncs; i++) { 16767 /* check insn_off */ 16768 ret = -EINVAL; 16769 16770 if (env->subprog_info[i].start != krecord[i].insn_off) { 16771 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 16772 goto err_free; 16773 } 16774 16775 /* Already checked type_id */ 16776 type = btf_type_by_id(btf, krecord[i].type_id); 16777 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 16778 /* Already checked func_proto */ 16779 func_proto = btf_type_by_id(btf, type->type); 16780 16781 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 16782 scalar_return = 16783 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 16784 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 16785 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 16786 goto err_free; 16787 } 16788 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 16789 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 16790 goto err_free; 16791 } 16792 16793 bpfptr_add(&urecord, urec_size); 16794 } 16795 16796 prog->aux->func_info_aux = info_aux; 16797 return 0; 16798 16799 err_free: 16800 kfree(info_aux); 16801 return ret; 16802 } 16803 16804 static void adjust_btf_func(struct bpf_verifier_env *env) 16805 { 16806 struct bpf_prog_aux *aux = env->prog->aux; 16807 int i; 16808 16809 if (!aux->func_info) 16810 return; 16811 16812 /* func_info is not available for hidden subprogs */ 16813 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 16814 aux->func_info[i].insn_off = env->subprog_info[i].start; 16815 } 16816 16817 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 16818 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 16819 16820 static int check_btf_line(struct bpf_verifier_env *env, 16821 const union bpf_attr *attr, 16822 bpfptr_t uattr) 16823 { 16824 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 16825 struct bpf_subprog_info *sub; 16826 struct bpf_line_info *linfo; 16827 struct bpf_prog *prog; 16828 const struct btf *btf; 16829 bpfptr_t ulinfo; 16830 int err; 16831 16832 nr_linfo = attr->line_info_cnt; 16833 if (!nr_linfo) 16834 return 0; 16835 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 16836 return -EINVAL; 16837 16838 rec_size = attr->line_info_rec_size; 16839 if (rec_size < MIN_BPF_LINEINFO_SIZE || 16840 rec_size > MAX_LINEINFO_REC_SIZE || 16841 rec_size & (sizeof(u32) - 1)) 16842 return -EINVAL; 16843 16844 /* Need to zero it in case the userspace may 16845 * pass in a smaller bpf_line_info object. 16846 */ 16847 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 16848 GFP_KERNEL | __GFP_NOWARN); 16849 if (!linfo) 16850 return -ENOMEM; 16851 16852 prog = env->prog; 16853 btf = prog->aux->btf; 16854 16855 s = 0; 16856 sub = env->subprog_info; 16857 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 16858 expected_size = sizeof(struct bpf_line_info); 16859 ncopy = min_t(u32, expected_size, rec_size); 16860 for (i = 0; i < nr_linfo; i++) { 16861 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 16862 if (err) { 16863 if (err == -E2BIG) { 16864 verbose(env, "nonzero tailing record in line_info"); 16865 if (copy_to_bpfptr_offset(uattr, 16866 offsetof(union bpf_attr, line_info_rec_size), 16867 &expected_size, sizeof(expected_size))) 16868 err = -EFAULT; 16869 } 16870 goto err_free; 16871 } 16872 16873 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 16874 err = -EFAULT; 16875 goto err_free; 16876 } 16877 16878 /* 16879 * Check insn_off to ensure 16880 * 1) strictly increasing AND 16881 * 2) bounded by prog->len 16882 * 16883 * The linfo[0].insn_off == 0 check logically falls into 16884 * the later "missing bpf_line_info for func..." case 16885 * because the first linfo[0].insn_off must be the 16886 * first sub also and the first sub must have 16887 * subprog_info[0].start == 0. 16888 */ 16889 if ((i && linfo[i].insn_off <= prev_offset) || 16890 linfo[i].insn_off >= prog->len) { 16891 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 16892 i, linfo[i].insn_off, prev_offset, 16893 prog->len); 16894 err = -EINVAL; 16895 goto err_free; 16896 } 16897 16898 if (!prog->insnsi[linfo[i].insn_off].code) { 16899 verbose(env, 16900 "Invalid insn code at line_info[%u].insn_off\n", 16901 i); 16902 err = -EINVAL; 16903 goto err_free; 16904 } 16905 16906 if (!btf_name_by_offset(btf, linfo[i].line_off) || 16907 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 16908 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 16909 err = -EINVAL; 16910 goto err_free; 16911 } 16912 16913 if (s != env->subprog_cnt) { 16914 if (linfo[i].insn_off == sub[s].start) { 16915 sub[s].linfo_idx = i; 16916 s++; 16917 } else if (sub[s].start < linfo[i].insn_off) { 16918 verbose(env, "missing bpf_line_info for func#%u\n", s); 16919 err = -EINVAL; 16920 goto err_free; 16921 } 16922 } 16923 16924 prev_offset = linfo[i].insn_off; 16925 bpfptr_add(&ulinfo, rec_size); 16926 } 16927 16928 if (s != env->subprog_cnt) { 16929 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 16930 env->subprog_cnt - s, s); 16931 err = -EINVAL; 16932 goto err_free; 16933 } 16934 16935 prog->aux->linfo = linfo; 16936 prog->aux->nr_linfo = nr_linfo; 16937 16938 return 0; 16939 16940 err_free: 16941 kvfree(linfo); 16942 return err; 16943 } 16944 16945 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 16946 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 16947 16948 static int check_core_relo(struct bpf_verifier_env *env, 16949 const union bpf_attr *attr, 16950 bpfptr_t uattr) 16951 { 16952 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 16953 struct bpf_core_relo core_relo = {}; 16954 struct bpf_prog *prog = env->prog; 16955 const struct btf *btf = prog->aux->btf; 16956 struct bpf_core_ctx ctx = { 16957 .log = &env->log, 16958 .btf = btf, 16959 }; 16960 bpfptr_t u_core_relo; 16961 int err; 16962 16963 nr_core_relo = attr->core_relo_cnt; 16964 if (!nr_core_relo) 16965 return 0; 16966 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 16967 return -EINVAL; 16968 16969 rec_size = attr->core_relo_rec_size; 16970 if (rec_size < MIN_CORE_RELO_SIZE || 16971 rec_size > MAX_CORE_RELO_SIZE || 16972 rec_size % sizeof(u32)) 16973 return -EINVAL; 16974 16975 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 16976 expected_size = sizeof(struct bpf_core_relo); 16977 ncopy = min_t(u32, expected_size, rec_size); 16978 16979 /* Unlike func_info and line_info, copy and apply each CO-RE 16980 * relocation record one at a time. 16981 */ 16982 for (i = 0; i < nr_core_relo; i++) { 16983 /* future proofing when sizeof(bpf_core_relo) changes */ 16984 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 16985 if (err) { 16986 if (err == -E2BIG) { 16987 verbose(env, "nonzero tailing record in core_relo"); 16988 if (copy_to_bpfptr_offset(uattr, 16989 offsetof(union bpf_attr, core_relo_rec_size), 16990 &expected_size, sizeof(expected_size))) 16991 err = -EFAULT; 16992 } 16993 break; 16994 } 16995 16996 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 16997 err = -EFAULT; 16998 break; 16999 } 17000 17001 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 17002 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 17003 i, core_relo.insn_off, prog->len); 17004 err = -EINVAL; 17005 break; 17006 } 17007 17008 err = bpf_core_apply(&ctx, &core_relo, i, 17009 &prog->insnsi[core_relo.insn_off / 8]); 17010 if (err) 17011 break; 17012 bpfptr_add(&u_core_relo, rec_size); 17013 } 17014 return err; 17015 } 17016 17017 static int check_btf_info_early(struct bpf_verifier_env *env, 17018 const union bpf_attr *attr, 17019 bpfptr_t uattr) 17020 { 17021 struct btf *btf; 17022 int err; 17023 17024 if (!attr->func_info_cnt && !attr->line_info_cnt) { 17025 if (check_abnormal_return(env)) 17026 return -EINVAL; 17027 return 0; 17028 } 17029 17030 btf = btf_get_by_fd(attr->prog_btf_fd); 17031 if (IS_ERR(btf)) 17032 return PTR_ERR(btf); 17033 if (btf_is_kernel(btf)) { 17034 btf_put(btf); 17035 return -EACCES; 17036 } 17037 env->prog->aux->btf = btf; 17038 17039 err = check_btf_func_early(env, attr, uattr); 17040 if (err) 17041 return err; 17042 return 0; 17043 } 17044 17045 static int check_btf_info(struct bpf_verifier_env *env, 17046 const union bpf_attr *attr, 17047 bpfptr_t uattr) 17048 { 17049 int err; 17050 17051 if (!attr->func_info_cnt && !attr->line_info_cnt) { 17052 if (check_abnormal_return(env)) 17053 return -EINVAL; 17054 return 0; 17055 } 17056 17057 err = check_btf_func(env, attr, uattr); 17058 if (err) 17059 return err; 17060 17061 err = check_btf_line(env, attr, uattr); 17062 if (err) 17063 return err; 17064 17065 err = check_core_relo(env, attr, uattr); 17066 if (err) 17067 return err; 17068 17069 return 0; 17070 } 17071 17072 /* check %cur's range satisfies %old's */ 17073 static bool range_within(const struct bpf_reg_state *old, 17074 const struct bpf_reg_state *cur) 17075 { 17076 return old->umin_value <= cur->umin_value && 17077 old->umax_value >= cur->umax_value && 17078 old->smin_value <= cur->smin_value && 17079 old->smax_value >= cur->smax_value && 17080 old->u32_min_value <= cur->u32_min_value && 17081 old->u32_max_value >= cur->u32_max_value && 17082 old->s32_min_value <= cur->s32_min_value && 17083 old->s32_max_value >= cur->s32_max_value; 17084 } 17085 17086 /* If in the old state two registers had the same id, then they need to have 17087 * the same id in the new state as well. But that id could be different from 17088 * the old state, so we need to track the mapping from old to new ids. 17089 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 17090 * regs with old id 5 must also have new id 9 for the new state to be safe. But 17091 * regs with a different old id could still have new id 9, we don't care about 17092 * that. 17093 * So we look through our idmap to see if this old id has been seen before. If 17094 * so, we require the new id to match; otherwise, we add the id pair to the map. 17095 */ 17096 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 17097 { 17098 struct bpf_id_pair *map = idmap->map; 17099 unsigned int i; 17100 17101 /* either both IDs should be set or both should be zero */ 17102 if (!!old_id != !!cur_id) 17103 return false; 17104 17105 if (old_id == 0) /* cur_id == 0 as well */ 17106 return true; 17107 17108 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 17109 if (!map[i].old) { 17110 /* Reached an empty slot; haven't seen this id before */ 17111 map[i].old = old_id; 17112 map[i].cur = cur_id; 17113 return true; 17114 } 17115 if (map[i].old == old_id) 17116 return map[i].cur == cur_id; 17117 if (map[i].cur == cur_id) 17118 return false; 17119 } 17120 /* We ran out of idmap slots, which should be impossible */ 17121 WARN_ON_ONCE(1); 17122 return false; 17123 } 17124 17125 /* Similar to check_ids(), but allocate a unique temporary ID 17126 * for 'old_id' or 'cur_id' of zero. 17127 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 17128 */ 17129 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 17130 { 17131 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 17132 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 17133 17134 return check_ids(old_id, cur_id, idmap); 17135 } 17136 17137 static void clean_func_state(struct bpf_verifier_env *env, 17138 struct bpf_func_state *st) 17139 { 17140 enum bpf_reg_liveness live; 17141 int i, j; 17142 17143 for (i = 0; i < BPF_REG_FP; i++) { 17144 live = st->regs[i].live; 17145 /* liveness must not touch this register anymore */ 17146 st->regs[i].live |= REG_LIVE_DONE; 17147 if (!(live & REG_LIVE_READ)) 17148 /* since the register is unused, clear its state 17149 * to make further comparison simpler 17150 */ 17151 __mark_reg_not_init(env, &st->regs[i]); 17152 } 17153 17154 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 17155 live = st->stack[i].spilled_ptr.live; 17156 /* liveness must not touch this stack slot anymore */ 17157 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 17158 if (!(live & REG_LIVE_READ)) { 17159 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 17160 for (j = 0; j < BPF_REG_SIZE; j++) 17161 st->stack[i].slot_type[j] = STACK_INVALID; 17162 } 17163 } 17164 } 17165 17166 static void clean_verifier_state(struct bpf_verifier_env *env, 17167 struct bpf_verifier_state *st) 17168 { 17169 int i; 17170 17171 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 17172 /* all regs in this state in all frames were already marked */ 17173 return; 17174 17175 for (i = 0; i <= st->curframe; i++) 17176 clean_func_state(env, st->frame[i]); 17177 } 17178 17179 /* the parentage chains form a tree. 17180 * the verifier states are added to state lists at given insn and 17181 * pushed into state stack for future exploration. 17182 * when the verifier reaches bpf_exit insn some of the verifer states 17183 * stored in the state lists have their final liveness state already, 17184 * but a lot of states will get revised from liveness point of view when 17185 * the verifier explores other branches. 17186 * Example: 17187 * 1: r0 = 1 17188 * 2: if r1 == 100 goto pc+1 17189 * 3: r0 = 2 17190 * 4: exit 17191 * when the verifier reaches exit insn the register r0 in the state list of 17192 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 17193 * of insn 2 and goes exploring further. At the insn 4 it will walk the 17194 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 17195 * 17196 * Since the verifier pushes the branch states as it sees them while exploring 17197 * the program the condition of walking the branch instruction for the second 17198 * time means that all states below this branch were already explored and 17199 * their final liveness marks are already propagated. 17200 * Hence when the verifier completes the search of state list in is_state_visited() 17201 * we can call this clean_live_states() function to mark all liveness states 17202 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 17203 * will not be used. 17204 * This function also clears the registers and stack for states that !READ 17205 * to simplify state merging. 17206 * 17207 * Important note here that walking the same branch instruction in the callee 17208 * doesn't meant that the states are DONE. The verifier has to compare 17209 * the callsites 17210 */ 17211 static void clean_live_states(struct bpf_verifier_env *env, int insn, 17212 struct bpf_verifier_state *cur) 17213 { 17214 struct bpf_verifier_state_list *sl; 17215 17216 sl = *explored_state(env, insn); 17217 while (sl) { 17218 if (sl->state.branches) 17219 goto next; 17220 if (sl->state.insn_idx != insn || 17221 !same_callsites(&sl->state, cur)) 17222 goto next; 17223 clean_verifier_state(env, &sl->state); 17224 next: 17225 sl = sl->next; 17226 } 17227 } 17228 17229 static bool regs_exact(const struct bpf_reg_state *rold, 17230 const struct bpf_reg_state *rcur, 17231 struct bpf_idmap *idmap) 17232 { 17233 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 17234 check_ids(rold->id, rcur->id, idmap) && 17235 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 17236 } 17237 17238 enum exact_level { 17239 NOT_EXACT, 17240 EXACT, 17241 RANGE_WITHIN 17242 }; 17243 17244 /* Returns true if (rold safe implies rcur safe) */ 17245 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 17246 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, 17247 enum exact_level exact) 17248 { 17249 if (exact == EXACT) 17250 return regs_exact(rold, rcur, idmap); 17251 17252 if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT) 17253 /* explored state didn't use this */ 17254 return true; 17255 if (rold->type == NOT_INIT) { 17256 if (exact == NOT_EXACT || rcur->type == NOT_INIT) 17257 /* explored state can't have used this */ 17258 return true; 17259 } 17260 17261 /* Enforce that register types have to match exactly, including their 17262 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 17263 * rule. 17264 * 17265 * One can make a point that using a pointer register as unbounded 17266 * SCALAR would be technically acceptable, but this could lead to 17267 * pointer leaks because scalars are allowed to leak while pointers 17268 * are not. We could make this safe in special cases if root is 17269 * calling us, but it's probably not worth the hassle. 17270 * 17271 * Also, register types that are *not* MAYBE_NULL could technically be 17272 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 17273 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 17274 * to the same map). 17275 * However, if the old MAYBE_NULL register then got NULL checked, 17276 * doing so could have affected others with the same id, and we can't 17277 * check for that because we lost the id when we converted to 17278 * a non-MAYBE_NULL variant. 17279 * So, as a general rule we don't allow mixing MAYBE_NULL and 17280 * non-MAYBE_NULL registers as well. 17281 */ 17282 if (rold->type != rcur->type) 17283 return false; 17284 17285 switch (base_type(rold->type)) { 17286 case SCALAR_VALUE: 17287 if (env->explore_alu_limits) { 17288 /* explore_alu_limits disables tnum_in() and range_within() 17289 * logic and requires everything to be strict 17290 */ 17291 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 17292 check_scalar_ids(rold->id, rcur->id, idmap); 17293 } 17294 if (!rold->precise && exact == NOT_EXACT) 17295 return true; 17296 if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST)) 17297 return false; 17298 if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off)) 17299 return false; 17300 /* Why check_ids() for scalar registers? 17301 * 17302 * Consider the following BPF code: 17303 * 1: r6 = ... unbound scalar, ID=a ... 17304 * 2: r7 = ... unbound scalar, ID=b ... 17305 * 3: if (r6 > r7) goto +1 17306 * 4: r6 = r7 17307 * 5: if (r6 > X) goto ... 17308 * 6: ... memory operation using r7 ... 17309 * 17310 * First verification path is [1-6]: 17311 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 17312 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark 17313 * r7 <= X, because r6 and r7 share same id. 17314 * Next verification path is [1-4, 6]. 17315 * 17316 * Instruction (6) would be reached in two states: 17317 * I. r6{.id=b}, r7{.id=b} via path 1-6; 17318 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 17319 * 17320 * Use check_ids() to distinguish these states. 17321 * --- 17322 * Also verify that new value satisfies old value range knowledge. 17323 */ 17324 return range_within(rold, rcur) && 17325 tnum_in(rold->var_off, rcur->var_off) && 17326 check_scalar_ids(rold->id, rcur->id, idmap); 17327 case PTR_TO_MAP_KEY: 17328 case PTR_TO_MAP_VALUE: 17329 case PTR_TO_MEM: 17330 case PTR_TO_BUF: 17331 case PTR_TO_TP_BUFFER: 17332 /* If the new min/max/var_off satisfy the old ones and 17333 * everything else matches, we are OK. 17334 */ 17335 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 17336 range_within(rold, rcur) && 17337 tnum_in(rold->var_off, rcur->var_off) && 17338 check_ids(rold->id, rcur->id, idmap) && 17339 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 17340 case PTR_TO_PACKET_META: 17341 case PTR_TO_PACKET: 17342 /* We must have at least as much range as the old ptr 17343 * did, so that any accesses which were safe before are 17344 * still safe. This is true even if old range < old off, 17345 * since someone could have accessed through (ptr - k), or 17346 * even done ptr -= k in a register, to get a safe access. 17347 */ 17348 if (rold->range > rcur->range) 17349 return false; 17350 /* If the offsets don't match, we can't trust our alignment; 17351 * nor can we be sure that we won't fall out of range. 17352 */ 17353 if (rold->off != rcur->off) 17354 return false; 17355 /* id relations must be preserved */ 17356 if (!check_ids(rold->id, rcur->id, idmap)) 17357 return false; 17358 /* new val must satisfy old val knowledge */ 17359 return range_within(rold, rcur) && 17360 tnum_in(rold->var_off, rcur->var_off); 17361 case PTR_TO_STACK: 17362 /* two stack pointers are equal only if they're pointing to 17363 * the same stack frame, since fp-8 in foo != fp-8 in bar 17364 */ 17365 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 17366 case PTR_TO_ARENA: 17367 return true; 17368 default: 17369 return regs_exact(rold, rcur, idmap); 17370 } 17371 } 17372 17373 static struct bpf_reg_state unbound_reg; 17374 17375 static __init int unbound_reg_init(void) 17376 { 17377 __mark_reg_unknown_imprecise(&unbound_reg); 17378 unbound_reg.live |= REG_LIVE_READ; 17379 return 0; 17380 } 17381 late_initcall(unbound_reg_init); 17382 17383 static bool is_stack_all_misc(struct bpf_verifier_env *env, 17384 struct bpf_stack_state *stack) 17385 { 17386 u32 i; 17387 17388 for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) { 17389 if ((stack->slot_type[i] == STACK_MISC) || 17390 (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack)) 17391 continue; 17392 return false; 17393 } 17394 17395 return true; 17396 } 17397 17398 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env, 17399 struct bpf_stack_state *stack) 17400 { 17401 if (is_spilled_scalar_reg64(stack)) 17402 return &stack->spilled_ptr; 17403 17404 if (is_stack_all_misc(env, stack)) 17405 return &unbound_reg; 17406 17407 return NULL; 17408 } 17409 17410 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 17411 struct bpf_func_state *cur, struct bpf_idmap *idmap, 17412 enum exact_level exact) 17413 { 17414 int i, spi; 17415 17416 /* walk slots of the explored stack and ignore any additional 17417 * slots in the current stack, since explored(safe) state 17418 * didn't use them 17419 */ 17420 for (i = 0; i < old->allocated_stack; i++) { 17421 struct bpf_reg_state *old_reg, *cur_reg; 17422 17423 spi = i / BPF_REG_SIZE; 17424 17425 if (exact != NOT_EXACT && 17426 (i >= cur->allocated_stack || 17427 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 17428 cur->stack[spi].slot_type[i % BPF_REG_SIZE])) 17429 return false; 17430 17431 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) 17432 && exact == NOT_EXACT) { 17433 i += BPF_REG_SIZE - 1; 17434 /* explored state didn't use this */ 17435 continue; 17436 } 17437 17438 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 17439 continue; 17440 17441 if (env->allow_uninit_stack && 17442 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 17443 continue; 17444 17445 /* explored stack has more populated slots than current stack 17446 * and these slots were used 17447 */ 17448 if (i >= cur->allocated_stack) 17449 return false; 17450 17451 /* 64-bit scalar spill vs all slots MISC and vice versa. 17452 * Load from all slots MISC produces unbound scalar. 17453 * Construct a fake register for such stack and call 17454 * regsafe() to ensure scalar ids are compared. 17455 */ 17456 old_reg = scalar_reg_for_stack(env, &old->stack[spi]); 17457 cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]); 17458 if (old_reg && cur_reg) { 17459 if (!regsafe(env, old_reg, cur_reg, idmap, exact)) 17460 return false; 17461 i += BPF_REG_SIZE - 1; 17462 continue; 17463 } 17464 17465 /* if old state was safe with misc data in the stack 17466 * it will be safe with zero-initialized stack. 17467 * The opposite is not true 17468 */ 17469 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 17470 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 17471 continue; 17472 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 17473 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 17474 /* Ex: old explored (safe) state has STACK_SPILL in 17475 * this stack slot, but current has STACK_MISC -> 17476 * this verifier states are not equivalent, 17477 * return false to continue verification of this path 17478 */ 17479 return false; 17480 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 17481 continue; 17482 /* Both old and cur are having same slot_type */ 17483 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 17484 case STACK_SPILL: 17485 /* when explored and current stack slot are both storing 17486 * spilled registers, check that stored pointers types 17487 * are the same as well. 17488 * Ex: explored safe path could have stored 17489 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 17490 * but current path has stored: 17491 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 17492 * such verifier states are not equivalent. 17493 * return false to continue verification of this path 17494 */ 17495 if (!regsafe(env, &old->stack[spi].spilled_ptr, 17496 &cur->stack[spi].spilled_ptr, idmap, exact)) 17497 return false; 17498 break; 17499 case STACK_DYNPTR: 17500 old_reg = &old->stack[spi].spilled_ptr; 17501 cur_reg = &cur->stack[spi].spilled_ptr; 17502 if (old_reg->dynptr.type != cur_reg->dynptr.type || 17503 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 17504 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 17505 return false; 17506 break; 17507 case STACK_ITER: 17508 old_reg = &old->stack[spi].spilled_ptr; 17509 cur_reg = &cur->stack[spi].spilled_ptr; 17510 /* iter.depth is not compared between states as it 17511 * doesn't matter for correctness and would otherwise 17512 * prevent convergence; we maintain it only to prevent 17513 * infinite loop check triggering, see 17514 * iter_active_depths_differ() 17515 */ 17516 if (old_reg->iter.btf != cur_reg->iter.btf || 17517 old_reg->iter.btf_id != cur_reg->iter.btf_id || 17518 old_reg->iter.state != cur_reg->iter.state || 17519 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 17520 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 17521 return false; 17522 break; 17523 case STACK_MISC: 17524 case STACK_ZERO: 17525 case STACK_INVALID: 17526 continue; 17527 /* Ensure that new unhandled slot types return false by default */ 17528 default: 17529 return false; 17530 } 17531 } 17532 return true; 17533 } 17534 17535 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 17536 struct bpf_idmap *idmap) 17537 { 17538 int i; 17539 17540 if (old->acquired_refs != cur->acquired_refs) 17541 return false; 17542 17543 for (i = 0; i < old->acquired_refs; i++) { 17544 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 17545 return false; 17546 } 17547 17548 return true; 17549 } 17550 17551 /* compare two verifier states 17552 * 17553 * all states stored in state_list are known to be valid, since 17554 * verifier reached 'bpf_exit' instruction through them 17555 * 17556 * this function is called when verifier exploring different branches of 17557 * execution popped from the state stack. If it sees an old state that has 17558 * more strict register state and more strict stack state then this execution 17559 * branch doesn't need to be explored further, since verifier already 17560 * concluded that more strict state leads to valid finish. 17561 * 17562 * Therefore two states are equivalent if register state is more conservative 17563 * and explored stack state is more conservative than the current one. 17564 * Example: 17565 * explored current 17566 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 17567 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 17568 * 17569 * In other words if current stack state (one being explored) has more 17570 * valid slots than old one that already passed validation, it means 17571 * the verifier can stop exploring and conclude that current state is valid too 17572 * 17573 * Similarly with registers. If explored state has register type as invalid 17574 * whereas register type in current state is meaningful, it means that 17575 * the current state will reach 'bpf_exit' instruction safely 17576 */ 17577 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 17578 struct bpf_func_state *cur, enum exact_level exact) 17579 { 17580 int i; 17581 17582 if (old->callback_depth > cur->callback_depth) 17583 return false; 17584 17585 for (i = 0; i < MAX_BPF_REG; i++) 17586 if (!regsafe(env, &old->regs[i], &cur->regs[i], 17587 &env->idmap_scratch, exact)) 17588 return false; 17589 17590 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 17591 return false; 17592 17593 if (!refsafe(old, cur, &env->idmap_scratch)) 17594 return false; 17595 17596 return true; 17597 } 17598 17599 static void reset_idmap_scratch(struct bpf_verifier_env *env) 17600 { 17601 env->idmap_scratch.tmp_id_gen = env->id_gen; 17602 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 17603 } 17604 17605 static bool states_equal(struct bpf_verifier_env *env, 17606 struct bpf_verifier_state *old, 17607 struct bpf_verifier_state *cur, 17608 enum exact_level exact) 17609 { 17610 int i; 17611 17612 if (old->curframe != cur->curframe) 17613 return false; 17614 17615 reset_idmap_scratch(env); 17616 17617 /* Verification state from speculative execution simulation 17618 * must never prune a non-speculative execution one. 17619 */ 17620 if (old->speculative && !cur->speculative) 17621 return false; 17622 17623 if (old->active_lock.ptr != cur->active_lock.ptr) 17624 return false; 17625 17626 /* Old and cur active_lock's have to be either both present 17627 * or both absent. 17628 */ 17629 if (!!old->active_lock.id != !!cur->active_lock.id) 17630 return false; 17631 17632 if (old->active_lock.id && 17633 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch)) 17634 return false; 17635 17636 if (old->active_rcu_lock != cur->active_rcu_lock) 17637 return false; 17638 17639 if (old->active_preempt_lock != cur->active_preempt_lock) 17640 return false; 17641 17642 if (old->in_sleepable != cur->in_sleepable) 17643 return false; 17644 17645 /* for states to be equal callsites have to be the same 17646 * and all frame states need to be equivalent 17647 */ 17648 for (i = 0; i <= old->curframe; i++) { 17649 if (old->frame[i]->callsite != cur->frame[i]->callsite) 17650 return false; 17651 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact)) 17652 return false; 17653 } 17654 return true; 17655 } 17656 17657 /* Return 0 if no propagation happened. Return negative error code if error 17658 * happened. Otherwise, return the propagated bit. 17659 */ 17660 static int propagate_liveness_reg(struct bpf_verifier_env *env, 17661 struct bpf_reg_state *reg, 17662 struct bpf_reg_state *parent_reg) 17663 { 17664 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 17665 u8 flag = reg->live & REG_LIVE_READ; 17666 int err; 17667 17668 /* When comes here, read flags of PARENT_REG or REG could be any of 17669 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 17670 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 17671 */ 17672 if (parent_flag == REG_LIVE_READ64 || 17673 /* Or if there is no read flag from REG. */ 17674 !flag || 17675 /* Or if the read flag from REG is the same as PARENT_REG. */ 17676 parent_flag == flag) 17677 return 0; 17678 17679 err = mark_reg_read(env, reg, parent_reg, flag); 17680 if (err) 17681 return err; 17682 17683 return flag; 17684 } 17685 17686 /* A write screens off any subsequent reads; but write marks come from the 17687 * straight-line code between a state and its parent. When we arrive at an 17688 * equivalent state (jump target or such) we didn't arrive by the straight-line 17689 * code, so read marks in the state must propagate to the parent regardless 17690 * of the state's write marks. That's what 'parent == state->parent' comparison 17691 * in mark_reg_read() is for. 17692 */ 17693 static int propagate_liveness(struct bpf_verifier_env *env, 17694 const struct bpf_verifier_state *vstate, 17695 struct bpf_verifier_state *vparent) 17696 { 17697 struct bpf_reg_state *state_reg, *parent_reg; 17698 struct bpf_func_state *state, *parent; 17699 int i, frame, err = 0; 17700 17701 if (vparent->curframe != vstate->curframe) { 17702 WARN(1, "propagate_live: parent frame %d current frame %d\n", 17703 vparent->curframe, vstate->curframe); 17704 return -EFAULT; 17705 } 17706 /* Propagate read liveness of registers... */ 17707 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 17708 for (frame = 0; frame <= vstate->curframe; frame++) { 17709 parent = vparent->frame[frame]; 17710 state = vstate->frame[frame]; 17711 parent_reg = parent->regs; 17712 state_reg = state->regs; 17713 /* We don't need to worry about FP liveness, it's read-only */ 17714 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 17715 err = propagate_liveness_reg(env, &state_reg[i], 17716 &parent_reg[i]); 17717 if (err < 0) 17718 return err; 17719 if (err == REG_LIVE_READ64) 17720 mark_insn_zext(env, &parent_reg[i]); 17721 } 17722 17723 /* Propagate stack slots. */ 17724 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 17725 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 17726 parent_reg = &parent->stack[i].spilled_ptr; 17727 state_reg = &state->stack[i].spilled_ptr; 17728 err = propagate_liveness_reg(env, state_reg, 17729 parent_reg); 17730 if (err < 0) 17731 return err; 17732 } 17733 } 17734 return 0; 17735 } 17736 17737 /* find precise scalars in the previous equivalent state and 17738 * propagate them into the current state 17739 */ 17740 static int propagate_precision(struct bpf_verifier_env *env, 17741 const struct bpf_verifier_state *old) 17742 { 17743 struct bpf_reg_state *state_reg; 17744 struct bpf_func_state *state; 17745 int i, err = 0, fr; 17746 bool first; 17747 17748 for (fr = old->curframe; fr >= 0; fr--) { 17749 state = old->frame[fr]; 17750 state_reg = state->regs; 17751 first = true; 17752 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 17753 if (state_reg->type != SCALAR_VALUE || 17754 !state_reg->precise || 17755 !(state_reg->live & REG_LIVE_READ)) 17756 continue; 17757 if (env->log.level & BPF_LOG_LEVEL2) { 17758 if (first) 17759 verbose(env, "frame %d: propagating r%d", fr, i); 17760 else 17761 verbose(env, ",r%d", i); 17762 } 17763 bt_set_frame_reg(&env->bt, fr, i); 17764 first = false; 17765 } 17766 17767 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 17768 if (!is_spilled_reg(&state->stack[i])) 17769 continue; 17770 state_reg = &state->stack[i].spilled_ptr; 17771 if (state_reg->type != SCALAR_VALUE || 17772 !state_reg->precise || 17773 !(state_reg->live & REG_LIVE_READ)) 17774 continue; 17775 if (env->log.level & BPF_LOG_LEVEL2) { 17776 if (first) 17777 verbose(env, "frame %d: propagating fp%d", 17778 fr, (-i - 1) * BPF_REG_SIZE); 17779 else 17780 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 17781 } 17782 bt_set_frame_slot(&env->bt, fr, i); 17783 first = false; 17784 } 17785 if (!first) 17786 verbose(env, "\n"); 17787 } 17788 17789 err = mark_chain_precision_batch(env); 17790 if (err < 0) 17791 return err; 17792 17793 return 0; 17794 } 17795 17796 static bool states_maybe_looping(struct bpf_verifier_state *old, 17797 struct bpf_verifier_state *cur) 17798 { 17799 struct bpf_func_state *fold, *fcur; 17800 int i, fr = cur->curframe; 17801 17802 if (old->curframe != fr) 17803 return false; 17804 17805 fold = old->frame[fr]; 17806 fcur = cur->frame[fr]; 17807 for (i = 0; i < MAX_BPF_REG; i++) 17808 if (memcmp(&fold->regs[i], &fcur->regs[i], 17809 offsetof(struct bpf_reg_state, parent))) 17810 return false; 17811 return true; 17812 } 17813 17814 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 17815 { 17816 return env->insn_aux_data[insn_idx].is_iter_next; 17817 } 17818 17819 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 17820 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 17821 * states to match, which otherwise would look like an infinite loop. So while 17822 * iter_next() calls are taken care of, we still need to be careful and 17823 * prevent erroneous and too eager declaration of "ininite loop", when 17824 * iterators are involved. 17825 * 17826 * Here's a situation in pseudo-BPF assembly form: 17827 * 17828 * 0: again: ; set up iter_next() call args 17829 * 1: r1 = &it ; <CHECKPOINT HERE> 17830 * 2: call bpf_iter_num_next ; this is iter_next() call 17831 * 3: if r0 == 0 goto done 17832 * 4: ... something useful here ... 17833 * 5: goto again ; another iteration 17834 * 6: done: 17835 * 7: r1 = &it 17836 * 8: call bpf_iter_num_destroy ; clean up iter state 17837 * 9: exit 17838 * 17839 * This is a typical loop. Let's assume that we have a prune point at 1:, 17840 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 17841 * again`, assuming other heuristics don't get in a way). 17842 * 17843 * When we first time come to 1:, let's say we have some state X. We proceed 17844 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 17845 * Now we come back to validate that forked ACTIVE state. We proceed through 17846 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 17847 * are converging. But the problem is that we don't know that yet, as this 17848 * convergence has to happen at iter_next() call site only. So if nothing is 17849 * done, at 1: verifier will use bounded loop logic and declare infinite 17850 * looping (and would be *technically* correct, if not for iterator's 17851 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 17852 * don't want that. So what we do in process_iter_next_call() when we go on 17853 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 17854 * a different iteration. So when we suspect an infinite loop, we additionally 17855 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 17856 * pretend we are not looping and wait for next iter_next() call. 17857 * 17858 * This only applies to ACTIVE state. In DRAINED state we don't expect to 17859 * loop, because that would actually mean infinite loop, as DRAINED state is 17860 * "sticky", and so we'll keep returning into the same instruction with the 17861 * same state (at least in one of possible code paths). 17862 * 17863 * This approach allows to keep infinite loop heuristic even in the face of 17864 * active iterator. E.g., C snippet below is and will be detected as 17865 * inifintely looping: 17866 * 17867 * struct bpf_iter_num it; 17868 * int *p, x; 17869 * 17870 * bpf_iter_num_new(&it, 0, 10); 17871 * while ((p = bpf_iter_num_next(&t))) { 17872 * x = p; 17873 * while (x--) {} // <<-- infinite loop here 17874 * } 17875 * 17876 */ 17877 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 17878 { 17879 struct bpf_reg_state *slot, *cur_slot; 17880 struct bpf_func_state *state; 17881 int i, fr; 17882 17883 for (fr = old->curframe; fr >= 0; fr--) { 17884 state = old->frame[fr]; 17885 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 17886 if (state->stack[i].slot_type[0] != STACK_ITER) 17887 continue; 17888 17889 slot = &state->stack[i].spilled_ptr; 17890 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 17891 continue; 17892 17893 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 17894 if (cur_slot->iter.depth != slot->iter.depth) 17895 return true; 17896 } 17897 } 17898 return false; 17899 } 17900 17901 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 17902 { 17903 struct bpf_verifier_state_list *new_sl; 17904 struct bpf_verifier_state_list *sl, **pprev; 17905 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry; 17906 int i, j, n, err, states_cnt = 0; 17907 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx); 17908 bool add_new_state = force_new_state; 17909 bool force_exact; 17910 17911 /* bpf progs typically have pruning point every 4 instructions 17912 * http://vger.kernel.org/bpfconf2019.html#session-1 17913 * Do not add new state for future pruning if the verifier hasn't seen 17914 * at least 2 jumps and at least 8 instructions. 17915 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 17916 * In tests that amounts to up to 50% reduction into total verifier 17917 * memory consumption and 20% verifier time speedup. 17918 */ 17919 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 17920 env->insn_processed - env->prev_insn_processed >= 8) 17921 add_new_state = true; 17922 17923 pprev = explored_state(env, insn_idx); 17924 sl = *pprev; 17925 17926 clean_live_states(env, insn_idx, cur); 17927 17928 while (sl) { 17929 states_cnt++; 17930 if (sl->state.insn_idx != insn_idx) 17931 goto next; 17932 17933 if (sl->state.branches) { 17934 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 17935 17936 if (frame->in_async_callback_fn && 17937 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 17938 /* Different async_entry_cnt means that the verifier is 17939 * processing another entry into async callback. 17940 * Seeing the same state is not an indication of infinite 17941 * loop or infinite recursion. 17942 * But finding the same state doesn't mean that it's safe 17943 * to stop processing the current state. The previous state 17944 * hasn't yet reached bpf_exit, since state.branches > 0. 17945 * Checking in_async_callback_fn alone is not enough either. 17946 * Since the verifier still needs to catch infinite loops 17947 * inside async callbacks. 17948 */ 17949 goto skip_inf_loop_check; 17950 } 17951 /* BPF open-coded iterators loop detection is special. 17952 * states_maybe_looping() logic is too simplistic in detecting 17953 * states that *might* be equivalent, because it doesn't know 17954 * about ID remapping, so don't even perform it. 17955 * See process_iter_next_call() and iter_active_depths_differ() 17956 * for overview of the logic. When current and one of parent 17957 * states are detected as equivalent, it's a good thing: we prove 17958 * convergence and can stop simulating further iterations. 17959 * It's safe to assume that iterator loop will finish, taking into 17960 * account iter_next() contract of eventually returning 17961 * sticky NULL result. 17962 * 17963 * Note, that states have to be compared exactly in this case because 17964 * read and precision marks might not be finalized inside the loop. 17965 * E.g. as in the program below: 17966 * 17967 * 1. r7 = -16 17968 * 2. r6 = bpf_get_prandom_u32() 17969 * 3. while (bpf_iter_num_next(&fp[-8])) { 17970 * 4. if (r6 != 42) { 17971 * 5. r7 = -32 17972 * 6. r6 = bpf_get_prandom_u32() 17973 * 7. continue 17974 * 8. } 17975 * 9. r0 = r10 17976 * 10. r0 += r7 17977 * 11. r8 = *(u64 *)(r0 + 0) 17978 * 12. r6 = bpf_get_prandom_u32() 17979 * 13. } 17980 * 17981 * Here verifier would first visit path 1-3, create a checkpoint at 3 17982 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 17983 * not have read or precision mark for r7 yet, thus inexact states 17984 * comparison would discard current state with r7=-32 17985 * => unsafe memory access at 11 would not be caught. 17986 */ 17987 if (is_iter_next_insn(env, insn_idx)) { 17988 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 17989 struct bpf_func_state *cur_frame; 17990 struct bpf_reg_state *iter_state, *iter_reg; 17991 int spi; 17992 17993 cur_frame = cur->frame[cur->curframe]; 17994 /* btf_check_iter_kfuncs() enforces that 17995 * iter state pointer is always the first arg 17996 */ 17997 iter_reg = &cur_frame->regs[BPF_REG_1]; 17998 /* current state is valid due to states_equal(), 17999 * so we can assume valid iter and reg state, 18000 * no need for extra (re-)validations 18001 */ 18002 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 18003 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 18004 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 18005 update_loop_entry(cur, &sl->state); 18006 goto hit; 18007 } 18008 } 18009 goto skip_inf_loop_check; 18010 } 18011 if (is_may_goto_insn_at(env, insn_idx)) { 18012 if (sl->state.may_goto_depth != cur->may_goto_depth && 18013 states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 18014 update_loop_entry(cur, &sl->state); 18015 goto hit; 18016 } 18017 } 18018 if (calls_callback(env, insn_idx)) { 18019 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) 18020 goto hit; 18021 goto skip_inf_loop_check; 18022 } 18023 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 18024 if (states_maybe_looping(&sl->state, cur) && 18025 states_equal(env, &sl->state, cur, EXACT) && 18026 !iter_active_depths_differ(&sl->state, cur) && 18027 sl->state.may_goto_depth == cur->may_goto_depth && 18028 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 18029 verbose_linfo(env, insn_idx, "; "); 18030 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 18031 verbose(env, "cur state:"); 18032 print_verifier_state(env, cur->frame[cur->curframe], true); 18033 verbose(env, "old state:"); 18034 print_verifier_state(env, sl->state.frame[cur->curframe], true); 18035 return -EINVAL; 18036 } 18037 /* if the verifier is processing a loop, avoid adding new state 18038 * too often, since different loop iterations have distinct 18039 * states and may not help future pruning. 18040 * This threshold shouldn't be too low to make sure that 18041 * a loop with large bound will be rejected quickly. 18042 * The most abusive loop will be: 18043 * r1 += 1 18044 * if r1 < 1000000 goto pc-2 18045 * 1M insn_procssed limit / 100 == 10k peak states. 18046 * This threshold shouldn't be too high either, since states 18047 * at the end of the loop are likely to be useful in pruning. 18048 */ 18049 skip_inf_loop_check: 18050 if (!force_new_state && 18051 env->jmps_processed - env->prev_jmps_processed < 20 && 18052 env->insn_processed - env->prev_insn_processed < 100) 18053 add_new_state = false; 18054 goto miss; 18055 } 18056 /* If sl->state is a part of a loop and this loop's entry is a part of 18057 * current verification path then states have to be compared exactly. 18058 * 'force_exact' is needed to catch the following case: 18059 * 18060 * initial Here state 'succ' was processed first, 18061 * | it was eventually tracked to produce a 18062 * V state identical to 'hdr'. 18063 * .---------> hdr All branches from 'succ' had been explored 18064 * | | and thus 'succ' has its .branches == 0. 18065 * | V 18066 * | .------... Suppose states 'cur' and 'succ' correspond 18067 * | | | to the same instruction + callsites. 18068 * | V V In such case it is necessary to check 18069 * | ... ... if 'succ' and 'cur' are states_equal(). 18070 * | | | If 'succ' and 'cur' are a part of the 18071 * | V V same loop exact flag has to be set. 18072 * | succ <- cur To check if that is the case, verify 18073 * | | if loop entry of 'succ' is in current 18074 * | V DFS path. 18075 * | ... 18076 * | | 18077 * '----' 18078 * 18079 * Additional details are in the comment before get_loop_entry(). 18080 */ 18081 loop_entry = get_loop_entry(&sl->state); 18082 force_exact = loop_entry && loop_entry->branches > 0; 18083 if (states_equal(env, &sl->state, cur, force_exact ? RANGE_WITHIN : NOT_EXACT)) { 18084 if (force_exact) 18085 update_loop_entry(cur, loop_entry); 18086 hit: 18087 sl->hit_cnt++; 18088 /* reached equivalent register/stack state, 18089 * prune the search. 18090 * Registers read by the continuation are read by us. 18091 * If we have any write marks in env->cur_state, they 18092 * will prevent corresponding reads in the continuation 18093 * from reaching our parent (an explored_state). Our 18094 * own state will get the read marks recorded, but 18095 * they'll be immediately forgotten as we're pruning 18096 * this state and will pop a new one. 18097 */ 18098 err = propagate_liveness(env, &sl->state, cur); 18099 18100 /* if previous state reached the exit with precision and 18101 * current state is equivalent to it (except precision marks) 18102 * the precision needs to be propagated back in 18103 * the current state. 18104 */ 18105 if (is_jmp_point(env, env->insn_idx)) 18106 err = err ? : push_jmp_history(env, cur, 0, 0); 18107 err = err ? : propagate_precision(env, &sl->state); 18108 if (err) 18109 return err; 18110 return 1; 18111 } 18112 miss: 18113 /* when new state is not going to be added do not increase miss count. 18114 * Otherwise several loop iterations will remove the state 18115 * recorded earlier. The goal of these heuristics is to have 18116 * states from some iterations of the loop (some in the beginning 18117 * and some at the end) to help pruning. 18118 */ 18119 if (add_new_state) 18120 sl->miss_cnt++; 18121 /* heuristic to determine whether this state is beneficial 18122 * to keep checking from state equivalence point of view. 18123 * Higher numbers increase max_states_per_insn and verification time, 18124 * but do not meaningfully decrease insn_processed. 18125 * 'n' controls how many times state could miss before eviction. 18126 * Use bigger 'n' for checkpoints because evicting checkpoint states 18127 * too early would hinder iterator convergence. 18128 */ 18129 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 18130 if (sl->miss_cnt > sl->hit_cnt * n + n) { 18131 /* the state is unlikely to be useful. Remove it to 18132 * speed up verification 18133 */ 18134 *pprev = sl->next; 18135 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE && 18136 !sl->state.used_as_loop_entry) { 18137 u32 br = sl->state.branches; 18138 18139 WARN_ONCE(br, 18140 "BUG live_done but branches_to_explore %d\n", 18141 br); 18142 free_verifier_state(&sl->state, false); 18143 kfree(sl); 18144 env->peak_states--; 18145 } else { 18146 /* cannot free this state, since parentage chain may 18147 * walk it later. Add it for free_list instead to 18148 * be freed at the end of verification 18149 */ 18150 sl->next = env->free_list; 18151 env->free_list = sl; 18152 } 18153 sl = *pprev; 18154 continue; 18155 } 18156 next: 18157 pprev = &sl->next; 18158 sl = *pprev; 18159 } 18160 18161 if (env->max_states_per_insn < states_cnt) 18162 env->max_states_per_insn = states_cnt; 18163 18164 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 18165 return 0; 18166 18167 if (!add_new_state) 18168 return 0; 18169 18170 /* There were no equivalent states, remember the current one. 18171 * Technically the current state is not proven to be safe yet, 18172 * but it will either reach outer most bpf_exit (which means it's safe) 18173 * or it will be rejected. When there are no loops the verifier won't be 18174 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 18175 * again on the way to bpf_exit. 18176 * When looping the sl->state.branches will be > 0 and this state 18177 * will not be considered for equivalence until branches == 0. 18178 */ 18179 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 18180 if (!new_sl) 18181 return -ENOMEM; 18182 env->total_states++; 18183 env->peak_states++; 18184 env->prev_jmps_processed = env->jmps_processed; 18185 env->prev_insn_processed = env->insn_processed; 18186 18187 /* forget precise markings we inherited, see __mark_chain_precision */ 18188 if (env->bpf_capable) 18189 mark_all_scalars_imprecise(env, cur); 18190 18191 /* add new state to the head of linked list */ 18192 new = &new_sl->state; 18193 err = copy_verifier_state(new, cur); 18194 if (err) { 18195 free_verifier_state(new, false); 18196 kfree(new_sl); 18197 return err; 18198 } 18199 new->insn_idx = insn_idx; 18200 WARN_ONCE(new->branches != 1, 18201 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 18202 18203 cur->parent = new; 18204 cur->first_insn_idx = insn_idx; 18205 cur->dfs_depth = new->dfs_depth + 1; 18206 clear_jmp_history(cur); 18207 new_sl->next = *explored_state(env, insn_idx); 18208 *explored_state(env, insn_idx) = new_sl; 18209 /* connect new state to parentage chain. Current frame needs all 18210 * registers connected. Only r6 - r9 of the callers are alive (pushed 18211 * to the stack implicitly by JITs) so in callers' frames connect just 18212 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 18213 * the state of the call instruction (with WRITTEN set), and r0 comes 18214 * from callee with its full parentage chain, anyway. 18215 */ 18216 /* clear write marks in current state: the writes we did are not writes 18217 * our child did, so they don't screen off its reads from us. 18218 * (There are no read marks in current state, because reads always mark 18219 * their parent and current state never has children yet. Only 18220 * explored_states can get read marks.) 18221 */ 18222 for (j = 0; j <= cur->curframe; j++) { 18223 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 18224 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 18225 for (i = 0; i < BPF_REG_FP; i++) 18226 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 18227 } 18228 18229 /* all stack frames are accessible from callee, clear them all */ 18230 for (j = 0; j <= cur->curframe; j++) { 18231 struct bpf_func_state *frame = cur->frame[j]; 18232 struct bpf_func_state *newframe = new->frame[j]; 18233 18234 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 18235 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 18236 frame->stack[i].spilled_ptr.parent = 18237 &newframe->stack[i].spilled_ptr; 18238 } 18239 } 18240 return 0; 18241 } 18242 18243 /* Return true if it's OK to have the same insn return a different type. */ 18244 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 18245 { 18246 switch (base_type(type)) { 18247 case PTR_TO_CTX: 18248 case PTR_TO_SOCKET: 18249 case PTR_TO_SOCK_COMMON: 18250 case PTR_TO_TCP_SOCK: 18251 case PTR_TO_XDP_SOCK: 18252 case PTR_TO_BTF_ID: 18253 case PTR_TO_ARENA: 18254 return false; 18255 default: 18256 return true; 18257 } 18258 } 18259 18260 /* If an instruction was previously used with particular pointer types, then we 18261 * need to be careful to avoid cases such as the below, where it may be ok 18262 * for one branch accessing the pointer, but not ok for the other branch: 18263 * 18264 * R1 = sock_ptr 18265 * goto X; 18266 * ... 18267 * R1 = some_other_valid_ptr; 18268 * goto X; 18269 * ... 18270 * R2 = *(u32 *)(R1 + 0); 18271 */ 18272 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 18273 { 18274 return src != prev && (!reg_type_mismatch_ok(src) || 18275 !reg_type_mismatch_ok(prev)); 18276 } 18277 18278 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 18279 bool allow_trust_mismatch) 18280 { 18281 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 18282 18283 if (*prev_type == NOT_INIT) { 18284 /* Saw a valid insn 18285 * dst_reg = *(u32 *)(src_reg + off) 18286 * save type to validate intersecting paths 18287 */ 18288 *prev_type = type; 18289 } else if (reg_type_mismatch(type, *prev_type)) { 18290 /* Abuser program is trying to use the same insn 18291 * dst_reg = *(u32*) (src_reg + off) 18292 * with different pointer types: 18293 * src_reg == ctx in one branch and 18294 * src_reg == stack|map in some other branch. 18295 * Reject it. 18296 */ 18297 if (allow_trust_mismatch && 18298 base_type(type) == PTR_TO_BTF_ID && 18299 base_type(*prev_type) == PTR_TO_BTF_ID) { 18300 /* 18301 * Have to support a use case when one path through 18302 * the program yields TRUSTED pointer while another 18303 * is UNTRUSTED. Fallback to UNTRUSTED to generate 18304 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 18305 */ 18306 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 18307 } else { 18308 verbose(env, "same insn cannot be used with different pointers\n"); 18309 return -EINVAL; 18310 } 18311 } 18312 18313 return 0; 18314 } 18315 18316 static int do_check(struct bpf_verifier_env *env) 18317 { 18318 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 18319 struct bpf_verifier_state *state = env->cur_state; 18320 struct bpf_insn *insns = env->prog->insnsi; 18321 struct bpf_reg_state *regs; 18322 int insn_cnt = env->prog->len; 18323 bool do_print_state = false; 18324 int prev_insn_idx = -1; 18325 18326 for (;;) { 18327 bool exception_exit = false; 18328 struct bpf_insn *insn; 18329 u8 class; 18330 int err; 18331 18332 /* reset current history entry on each new instruction */ 18333 env->cur_hist_ent = NULL; 18334 18335 env->prev_insn_idx = prev_insn_idx; 18336 if (env->insn_idx >= insn_cnt) { 18337 verbose(env, "invalid insn idx %d insn_cnt %d\n", 18338 env->insn_idx, insn_cnt); 18339 return -EFAULT; 18340 } 18341 18342 insn = &insns[env->insn_idx]; 18343 class = BPF_CLASS(insn->code); 18344 18345 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 18346 verbose(env, 18347 "BPF program is too large. Processed %d insn\n", 18348 env->insn_processed); 18349 return -E2BIG; 18350 } 18351 18352 state->last_insn_idx = env->prev_insn_idx; 18353 18354 if (is_prune_point(env, env->insn_idx)) { 18355 err = is_state_visited(env, env->insn_idx); 18356 if (err < 0) 18357 return err; 18358 if (err == 1) { 18359 /* found equivalent state, can prune the search */ 18360 if (env->log.level & BPF_LOG_LEVEL) { 18361 if (do_print_state) 18362 verbose(env, "\nfrom %d to %d%s: safe\n", 18363 env->prev_insn_idx, env->insn_idx, 18364 env->cur_state->speculative ? 18365 " (speculative execution)" : ""); 18366 else 18367 verbose(env, "%d: safe\n", env->insn_idx); 18368 } 18369 goto process_bpf_exit; 18370 } 18371 } 18372 18373 if (is_jmp_point(env, env->insn_idx)) { 18374 err = push_jmp_history(env, state, 0, 0); 18375 if (err) 18376 return err; 18377 } 18378 18379 if (signal_pending(current)) 18380 return -EAGAIN; 18381 18382 if (need_resched()) 18383 cond_resched(); 18384 18385 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 18386 verbose(env, "\nfrom %d to %d%s:", 18387 env->prev_insn_idx, env->insn_idx, 18388 env->cur_state->speculative ? 18389 " (speculative execution)" : ""); 18390 print_verifier_state(env, state->frame[state->curframe], true); 18391 do_print_state = false; 18392 } 18393 18394 if (env->log.level & BPF_LOG_LEVEL) { 18395 const struct bpf_insn_cbs cbs = { 18396 .cb_call = disasm_kfunc_name, 18397 .cb_print = verbose, 18398 .private_data = env, 18399 }; 18400 18401 if (verifier_state_scratched(env)) 18402 print_insn_state(env, state->frame[state->curframe]); 18403 18404 verbose_linfo(env, env->insn_idx, "; "); 18405 env->prev_log_pos = env->log.end_pos; 18406 verbose(env, "%d: ", env->insn_idx); 18407 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 18408 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 18409 env->prev_log_pos = env->log.end_pos; 18410 } 18411 18412 if (bpf_prog_is_offloaded(env->prog->aux)) { 18413 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 18414 env->prev_insn_idx); 18415 if (err) 18416 return err; 18417 } 18418 18419 regs = cur_regs(env); 18420 sanitize_mark_insn_seen(env); 18421 prev_insn_idx = env->insn_idx; 18422 18423 if (class == BPF_ALU || class == BPF_ALU64) { 18424 err = check_alu_op(env, insn); 18425 if (err) 18426 return err; 18427 18428 } else if (class == BPF_LDX) { 18429 enum bpf_reg_type src_reg_type; 18430 18431 /* check for reserved fields is already done */ 18432 18433 /* check src operand */ 18434 err = check_reg_arg(env, insn->src_reg, SRC_OP); 18435 if (err) 18436 return err; 18437 18438 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 18439 if (err) 18440 return err; 18441 18442 src_reg_type = regs[insn->src_reg].type; 18443 18444 /* check that memory (src_reg + off) is readable, 18445 * the state of dst_reg will be updated by this func 18446 */ 18447 err = check_mem_access(env, env->insn_idx, insn->src_reg, 18448 insn->off, BPF_SIZE(insn->code), 18449 BPF_READ, insn->dst_reg, false, 18450 BPF_MODE(insn->code) == BPF_MEMSX); 18451 err = err ?: save_aux_ptr_type(env, src_reg_type, true); 18452 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], "ldx"); 18453 if (err) 18454 return err; 18455 } else if (class == BPF_STX) { 18456 enum bpf_reg_type dst_reg_type; 18457 18458 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 18459 err = check_atomic(env, env->insn_idx, insn); 18460 if (err) 18461 return err; 18462 env->insn_idx++; 18463 continue; 18464 } 18465 18466 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 18467 verbose(env, "BPF_STX uses reserved fields\n"); 18468 return -EINVAL; 18469 } 18470 18471 /* check src1 operand */ 18472 err = check_reg_arg(env, insn->src_reg, SRC_OP); 18473 if (err) 18474 return err; 18475 /* check src2 operand */ 18476 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 18477 if (err) 18478 return err; 18479 18480 dst_reg_type = regs[insn->dst_reg].type; 18481 18482 /* check that memory (dst_reg + off) is writeable */ 18483 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 18484 insn->off, BPF_SIZE(insn->code), 18485 BPF_WRITE, insn->src_reg, false, false); 18486 if (err) 18487 return err; 18488 18489 err = save_aux_ptr_type(env, dst_reg_type, false); 18490 if (err) 18491 return err; 18492 } else if (class == BPF_ST) { 18493 enum bpf_reg_type dst_reg_type; 18494 18495 if (BPF_MODE(insn->code) != BPF_MEM || 18496 insn->src_reg != BPF_REG_0) { 18497 verbose(env, "BPF_ST uses reserved fields\n"); 18498 return -EINVAL; 18499 } 18500 /* check src operand */ 18501 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 18502 if (err) 18503 return err; 18504 18505 dst_reg_type = regs[insn->dst_reg].type; 18506 18507 /* check that memory (dst_reg + off) is writeable */ 18508 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 18509 insn->off, BPF_SIZE(insn->code), 18510 BPF_WRITE, -1, false, false); 18511 if (err) 18512 return err; 18513 18514 err = save_aux_ptr_type(env, dst_reg_type, false); 18515 if (err) 18516 return err; 18517 } else if (class == BPF_JMP || class == BPF_JMP32) { 18518 u8 opcode = BPF_OP(insn->code); 18519 18520 env->jmps_processed++; 18521 if (opcode == BPF_CALL) { 18522 if (BPF_SRC(insn->code) != BPF_K || 18523 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 18524 && insn->off != 0) || 18525 (insn->src_reg != BPF_REG_0 && 18526 insn->src_reg != BPF_PSEUDO_CALL && 18527 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 18528 insn->dst_reg != BPF_REG_0 || 18529 class == BPF_JMP32) { 18530 verbose(env, "BPF_CALL uses reserved fields\n"); 18531 return -EINVAL; 18532 } 18533 18534 if (env->cur_state->active_lock.ptr) { 18535 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 18536 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 18537 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 18538 verbose(env, "function calls are not allowed while holding a lock\n"); 18539 return -EINVAL; 18540 } 18541 } 18542 if (insn->src_reg == BPF_PSEUDO_CALL) { 18543 err = check_func_call(env, insn, &env->insn_idx); 18544 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 18545 err = check_kfunc_call(env, insn, &env->insn_idx); 18546 if (!err && is_bpf_throw_kfunc(insn)) { 18547 exception_exit = true; 18548 goto process_bpf_exit_full; 18549 } 18550 } else { 18551 err = check_helper_call(env, insn, &env->insn_idx); 18552 } 18553 if (err) 18554 return err; 18555 18556 mark_reg_scratched(env, BPF_REG_0); 18557 } else if (opcode == BPF_JA) { 18558 if (BPF_SRC(insn->code) != BPF_K || 18559 insn->src_reg != BPF_REG_0 || 18560 insn->dst_reg != BPF_REG_0 || 18561 (class == BPF_JMP && insn->imm != 0) || 18562 (class == BPF_JMP32 && insn->off != 0)) { 18563 verbose(env, "BPF_JA uses reserved fields\n"); 18564 return -EINVAL; 18565 } 18566 18567 if (class == BPF_JMP) 18568 env->insn_idx += insn->off + 1; 18569 else 18570 env->insn_idx += insn->imm + 1; 18571 continue; 18572 18573 } else if (opcode == BPF_EXIT) { 18574 if (BPF_SRC(insn->code) != BPF_K || 18575 insn->imm != 0 || 18576 insn->src_reg != BPF_REG_0 || 18577 insn->dst_reg != BPF_REG_0 || 18578 class == BPF_JMP32) { 18579 verbose(env, "BPF_EXIT uses reserved fields\n"); 18580 return -EINVAL; 18581 } 18582 process_bpf_exit_full: 18583 if (env->cur_state->active_lock.ptr && !env->cur_state->curframe) { 18584 verbose(env, "bpf_spin_unlock is missing\n"); 18585 return -EINVAL; 18586 } 18587 18588 if (env->cur_state->active_rcu_lock && !env->cur_state->curframe) { 18589 verbose(env, "bpf_rcu_read_unlock is missing\n"); 18590 return -EINVAL; 18591 } 18592 18593 if (env->cur_state->active_preempt_lock && !env->cur_state->curframe) { 18594 verbose(env, "%d bpf_preempt_enable%s missing\n", 18595 env->cur_state->active_preempt_lock, 18596 env->cur_state->active_preempt_lock == 1 ? " is" : "(s) are"); 18597 return -EINVAL; 18598 } 18599 18600 /* We must do check_reference_leak here before 18601 * prepare_func_exit to handle the case when 18602 * state->curframe > 0, it may be a callback 18603 * function, for which reference_state must 18604 * match caller reference state when it exits. 18605 */ 18606 err = check_reference_leak(env, exception_exit); 18607 if (err) 18608 return err; 18609 18610 /* The side effect of the prepare_func_exit 18611 * which is being skipped is that it frees 18612 * bpf_func_state. Typically, process_bpf_exit 18613 * will only be hit with outermost exit. 18614 * copy_verifier_state in pop_stack will handle 18615 * freeing of any extra bpf_func_state left over 18616 * from not processing all nested function 18617 * exits. We also skip return code checks as 18618 * they are not needed for exceptional exits. 18619 */ 18620 if (exception_exit) 18621 goto process_bpf_exit; 18622 18623 if (state->curframe) { 18624 /* exit from nested function */ 18625 err = prepare_func_exit(env, &env->insn_idx); 18626 if (err) 18627 return err; 18628 do_print_state = true; 18629 continue; 18630 } 18631 18632 err = check_return_code(env, BPF_REG_0, "R0"); 18633 if (err) 18634 return err; 18635 process_bpf_exit: 18636 mark_verifier_state_scratched(env); 18637 update_branch_counts(env, env->cur_state); 18638 err = pop_stack(env, &prev_insn_idx, 18639 &env->insn_idx, pop_log); 18640 if (err < 0) { 18641 if (err != -ENOENT) 18642 return err; 18643 break; 18644 } else { 18645 do_print_state = true; 18646 continue; 18647 } 18648 } else { 18649 err = check_cond_jmp_op(env, insn, &env->insn_idx); 18650 if (err) 18651 return err; 18652 } 18653 } else if (class == BPF_LD) { 18654 u8 mode = BPF_MODE(insn->code); 18655 18656 if (mode == BPF_ABS || mode == BPF_IND) { 18657 err = check_ld_abs(env, insn); 18658 if (err) 18659 return err; 18660 18661 } else if (mode == BPF_IMM) { 18662 err = check_ld_imm(env, insn); 18663 if (err) 18664 return err; 18665 18666 env->insn_idx++; 18667 sanitize_mark_insn_seen(env); 18668 } else { 18669 verbose(env, "invalid BPF_LD mode\n"); 18670 return -EINVAL; 18671 } 18672 } else { 18673 verbose(env, "unknown insn class %d\n", class); 18674 return -EINVAL; 18675 } 18676 18677 env->insn_idx++; 18678 } 18679 18680 return 0; 18681 } 18682 18683 static int find_btf_percpu_datasec(struct btf *btf) 18684 { 18685 const struct btf_type *t; 18686 const char *tname; 18687 int i, n; 18688 18689 /* 18690 * Both vmlinux and module each have their own ".data..percpu" 18691 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 18692 * types to look at only module's own BTF types. 18693 */ 18694 n = btf_nr_types(btf); 18695 if (btf_is_module(btf)) 18696 i = btf_nr_types(btf_vmlinux); 18697 else 18698 i = 1; 18699 18700 for(; i < n; i++) { 18701 t = btf_type_by_id(btf, i); 18702 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 18703 continue; 18704 18705 tname = btf_name_by_offset(btf, t->name_off); 18706 if (!strcmp(tname, ".data..percpu")) 18707 return i; 18708 } 18709 18710 return -ENOENT; 18711 } 18712 18713 /* replace pseudo btf_id with kernel symbol address */ 18714 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 18715 struct bpf_insn *insn, 18716 struct bpf_insn_aux_data *aux) 18717 { 18718 const struct btf_var_secinfo *vsi; 18719 const struct btf_type *datasec; 18720 struct btf_mod_pair *btf_mod; 18721 const struct btf_type *t; 18722 const char *sym_name; 18723 bool percpu = false; 18724 u32 type, id = insn->imm; 18725 struct btf *btf; 18726 s32 datasec_id; 18727 u64 addr; 18728 int i, btf_fd, err; 18729 18730 btf_fd = insn[1].imm; 18731 if (btf_fd) { 18732 btf = btf_get_by_fd(btf_fd); 18733 if (IS_ERR(btf)) { 18734 verbose(env, "invalid module BTF object FD specified.\n"); 18735 return -EINVAL; 18736 } 18737 } else { 18738 if (!btf_vmlinux) { 18739 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 18740 return -EINVAL; 18741 } 18742 btf = btf_vmlinux; 18743 btf_get(btf); 18744 } 18745 18746 t = btf_type_by_id(btf, id); 18747 if (!t) { 18748 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 18749 err = -ENOENT; 18750 goto err_put; 18751 } 18752 18753 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 18754 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 18755 err = -EINVAL; 18756 goto err_put; 18757 } 18758 18759 sym_name = btf_name_by_offset(btf, t->name_off); 18760 addr = kallsyms_lookup_name(sym_name); 18761 if (!addr) { 18762 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 18763 sym_name); 18764 err = -ENOENT; 18765 goto err_put; 18766 } 18767 insn[0].imm = (u32)addr; 18768 insn[1].imm = addr >> 32; 18769 18770 if (btf_type_is_func(t)) { 18771 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 18772 aux->btf_var.mem_size = 0; 18773 goto check_btf; 18774 } 18775 18776 datasec_id = find_btf_percpu_datasec(btf); 18777 if (datasec_id > 0) { 18778 datasec = btf_type_by_id(btf, datasec_id); 18779 for_each_vsi(i, datasec, vsi) { 18780 if (vsi->type == id) { 18781 percpu = true; 18782 break; 18783 } 18784 } 18785 } 18786 18787 type = t->type; 18788 t = btf_type_skip_modifiers(btf, type, NULL); 18789 if (percpu) { 18790 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 18791 aux->btf_var.btf = btf; 18792 aux->btf_var.btf_id = type; 18793 } else if (!btf_type_is_struct(t)) { 18794 const struct btf_type *ret; 18795 const char *tname; 18796 u32 tsize; 18797 18798 /* resolve the type size of ksym. */ 18799 ret = btf_resolve_size(btf, t, &tsize); 18800 if (IS_ERR(ret)) { 18801 tname = btf_name_by_offset(btf, t->name_off); 18802 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 18803 tname, PTR_ERR(ret)); 18804 err = -EINVAL; 18805 goto err_put; 18806 } 18807 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 18808 aux->btf_var.mem_size = tsize; 18809 } else { 18810 aux->btf_var.reg_type = PTR_TO_BTF_ID; 18811 aux->btf_var.btf = btf; 18812 aux->btf_var.btf_id = type; 18813 } 18814 check_btf: 18815 /* check whether we recorded this BTF (and maybe module) already */ 18816 for (i = 0; i < env->used_btf_cnt; i++) { 18817 if (env->used_btfs[i].btf == btf) { 18818 btf_put(btf); 18819 return 0; 18820 } 18821 } 18822 18823 if (env->used_btf_cnt >= MAX_USED_BTFS) { 18824 err = -E2BIG; 18825 goto err_put; 18826 } 18827 18828 btf_mod = &env->used_btfs[env->used_btf_cnt]; 18829 btf_mod->btf = btf; 18830 btf_mod->module = NULL; 18831 18832 /* if we reference variables from kernel module, bump its refcount */ 18833 if (btf_is_module(btf)) { 18834 btf_mod->module = btf_try_get_module(btf); 18835 if (!btf_mod->module) { 18836 err = -ENXIO; 18837 goto err_put; 18838 } 18839 } 18840 18841 env->used_btf_cnt++; 18842 18843 return 0; 18844 err_put: 18845 btf_put(btf); 18846 return err; 18847 } 18848 18849 static bool is_tracing_prog_type(enum bpf_prog_type type) 18850 { 18851 switch (type) { 18852 case BPF_PROG_TYPE_KPROBE: 18853 case BPF_PROG_TYPE_TRACEPOINT: 18854 case BPF_PROG_TYPE_PERF_EVENT: 18855 case BPF_PROG_TYPE_RAW_TRACEPOINT: 18856 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 18857 return true; 18858 default: 18859 return false; 18860 } 18861 } 18862 18863 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 18864 struct bpf_map *map, 18865 struct bpf_prog *prog) 18866 18867 { 18868 enum bpf_prog_type prog_type = resolve_prog_type(prog); 18869 18870 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 18871 btf_record_has_field(map->record, BPF_RB_ROOT)) { 18872 if (is_tracing_prog_type(prog_type)) { 18873 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 18874 return -EINVAL; 18875 } 18876 } 18877 18878 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 18879 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 18880 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 18881 return -EINVAL; 18882 } 18883 18884 if (is_tracing_prog_type(prog_type)) { 18885 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 18886 return -EINVAL; 18887 } 18888 } 18889 18890 if (btf_record_has_field(map->record, BPF_TIMER)) { 18891 if (is_tracing_prog_type(prog_type)) { 18892 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 18893 return -EINVAL; 18894 } 18895 } 18896 18897 if (btf_record_has_field(map->record, BPF_WORKQUEUE)) { 18898 if (is_tracing_prog_type(prog_type)) { 18899 verbose(env, "tracing progs cannot use bpf_wq yet\n"); 18900 return -EINVAL; 18901 } 18902 } 18903 18904 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 18905 !bpf_offload_prog_map_match(prog, map)) { 18906 verbose(env, "offload device mismatch between prog and map\n"); 18907 return -EINVAL; 18908 } 18909 18910 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 18911 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 18912 return -EINVAL; 18913 } 18914 18915 if (prog->sleepable) 18916 switch (map->map_type) { 18917 case BPF_MAP_TYPE_HASH: 18918 case BPF_MAP_TYPE_LRU_HASH: 18919 case BPF_MAP_TYPE_ARRAY: 18920 case BPF_MAP_TYPE_PERCPU_HASH: 18921 case BPF_MAP_TYPE_PERCPU_ARRAY: 18922 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 18923 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 18924 case BPF_MAP_TYPE_HASH_OF_MAPS: 18925 case BPF_MAP_TYPE_RINGBUF: 18926 case BPF_MAP_TYPE_USER_RINGBUF: 18927 case BPF_MAP_TYPE_INODE_STORAGE: 18928 case BPF_MAP_TYPE_SK_STORAGE: 18929 case BPF_MAP_TYPE_TASK_STORAGE: 18930 case BPF_MAP_TYPE_CGRP_STORAGE: 18931 case BPF_MAP_TYPE_QUEUE: 18932 case BPF_MAP_TYPE_STACK: 18933 case BPF_MAP_TYPE_ARENA: 18934 break; 18935 default: 18936 verbose(env, 18937 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 18938 return -EINVAL; 18939 } 18940 18941 return 0; 18942 } 18943 18944 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 18945 { 18946 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 18947 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 18948 } 18949 18950 /* find and rewrite pseudo imm in ld_imm64 instructions: 18951 * 18952 * 1. if it accesses map FD, replace it with actual map pointer. 18953 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 18954 * 18955 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 18956 */ 18957 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 18958 { 18959 struct bpf_insn *insn = env->prog->insnsi; 18960 int insn_cnt = env->prog->len; 18961 int i, j, err; 18962 18963 err = bpf_prog_calc_tag(env->prog); 18964 if (err) 18965 return err; 18966 18967 for (i = 0; i < insn_cnt; i++, insn++) { 18968 if (BPF_CLASS(insn->code) == BPF_LDX && 18969 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 18970 insn->imm != 0)) { 18971 verbose(env, "BPF_LDX uses reserved fields\n"); 18972 return -EINVAL; 18973 } 18974 18975 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 18976 struct bpf_insn_aux_data *aux; 18977 struct bpf_map *map; 18978 struct fd f; 18979 u64 addr; 18980 u32 fd; 18981 18982 if (i == insn_cnt - 1 || insn[1].code != 0 || 18983 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 18984 insn[1].off != 0) { 18985 verbose(env, "invalid bpf_ld_imm64 insn\n"); 18986 return -EINVAL; 18987 } 18988 18989 if (insn[0].src_reg == 0) 18990 /* valid generic load 64-bit imm */ 18991 goto next_insn; 18992 18993 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 18994 aux = &env->insn_aux_data[i]; 18995 err = check_pseudo_btf_id(env, insn, aux); 18996 if (err) 18997 return err; 18998 goto next_insn; 18999 } 19000 19001 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 19002 aux = &env->insn_aux_data[i]; 19003 aux->ptr_type = PTR_TO_FUNC; 19004 goto next_insn; 19005 } 19006 19007 /* In final convert_pseudo_ld_imm64() step, this is 19008 * converted into regular 64-bit imm load insn. 19009 */ 19010 switch (insn[0].src_reg) { 19011 case BPF_PSEUDO_MAP_VALUE: 19012 case BPF_PSEUDO_MAP_IDX_VALUE: 19013 break; 19014 case BPF_PSEUDO_MAP_FD: 19015 case BPF_PSEUDO_MAP_IDX: 19016 if (insn[1].imm == 0) 19017 break; 19018 fallthrough; 19019 default: 19020 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 19021 return -EINVAL; 19022 } 19023 19024 switch (insn[0].src_reg) { 19025 case BPF_PSEUDO_MAP_IDX_VALUE: 19026 case BPF_PSEUDO_MAP_IDX: 19027 if (bpfptr_is_null(env->fd_array)) { 19028 verbose(env, "fd_idx without fd_array is invalid\n"); 19029 return -EPROTO; 19030 } 19031 if (copy_from_bpfptr_offset(&fd, env->fd_array, 19032 insn[0].imm * sizeof(fd), 19033 sizeof(fd))) 19034 return -EFAULT; 19035 break; 19036 default: 19037 fd = insn[0].imm; 19038 break; 19039 } 19040 19041 f = fdget(fd); 19042 map = __bpf_map_get(f); 19043 if (IS_ERR(map)) { 19044 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 19045 return PTR_ERR(map); 19046 } 19047 19048 err = check_map_prog_compatibility(env, map, env->prog); 19049 if (err) { 19050 fdput(f); 19051 return err; 19052 } 19053 19054 aux = &env->insn_aux_data[i]; 19055 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 19056 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 19057 addr = (unsigned long)map; 19058 } else { 19059 u32 off = insn[1].imm; 19060 19061 if (off >= BPF_MAX_VAR_OFF) { 19062 verbose(env, "direct value offset of %u is not allowed\n", off); 19063 fdput(f); 19064 return -EINVAL; 19065 } 19066 19067 if (!map->ops->map_direct_value_addr) { 19068 verbose(env, "no direct value access support for this map type\n"); 19069 fdput(f); 19070 return -EINVAL; 19071 } 19072 19073 err = map->ops->map_direct_value_addr(map, &addr, off); 19074 if (err) { 19075 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 19076 map->value_size, off); 19077 fdput(f); 19078 return err; 19079 } 19080 19081 aux->map_off = off; 19082 addr += off; 19083 } 19084 19085 insn[0].imm = (u32)addr; 19086 insn[1].imm = addr >> 32; 19087 19088 /* check whether we recorded this map already */ 19089 for (j = 0; j < env->used_map_cnt; j++) { 19090 if (env->used_maps[j] == map) { 19091 aux->map_index = j; 19092 fdput(f); 19093 goto next_insn; 19094 } 19095 } 19096 19097 if (env->used_map_cnt >= MAX_USED_MAPS) { 19098 verbose(env, "The total number of maps per program has reached the limit of %u\n", 19099 MAX_USED_MAPS); 19100 fdput(f); 19101 return -E2BIG; 19102 } 19103 19104 if (env->prog->sleepable) 19105 atomic64_inc(&map->sleepable_refcnt); 19106 /* hold the map. If the program is rejected by verifier, 19107 * the map will be released by release_maps() or it 19108 * will be used by the valid program until it's unloaded 19109 * and all maps are released in bpf_free_used_maps() 19110 */ 19111 bpf_map_inc(map); 19112 19113 aux->map_index = env->used_map_cnt; 19114 env->used_maps[env->used_map_cnt++] = map; 19115 19116 if (bpf_map_is_cgroup_storage(map) && 19117 bpf_cgroup_storage_assign(env->prog->aux, map)) { 19118 verbose(env, "only one cgroup storage of each type is allowed\n"); 19119 fdput(f); 19120 return -EBUSY; 19121 } 19122 if (map->map_type == BPF_MAP_TYPE_ARENA) { 19123 if (env->prog->aux->arena) { 19124 verbose(env, "Only one arena per program\n"); 19125 fdput(f); 19126 return -EBUSY; 19127 } 19128 if (!env->allow_ptr_leaks || !env->bpf_capable) { 19129 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n"); 19130 fdput(f); 19131 return -EPERM; 19132 } 19133 if (!env->prog->jit_requested) { 19134 verbose(env, "JIT is required to use arena\n"); 19135 fdput(f); 19136 return -EOPNOTSUPP; 19137 } 19138 if (!bpf_jit_supports_arena()) { 19139 verbose(env, "JIT doesn't support arena\n"); 19140 fdput(f); 19141 return -EOPNOTSUPP; 19142 } 19143 env->prog->aux->arena = (void *)map; 19144 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) { 19145 verbose(env, "arena's user address must be set via map_extra or mmap()\n"); 19146 fdput(f); 19147 return -EINVAL; 19148 } 19149 } 19150 19151 fdput(f); 19152 next_insn: 19153 insn++; 19154 i++; 19155 continue; 19156 } 19157 19158 /* Basic sanity check before we invest more work here. */ 19159 if (!bpf_opcode_in_insntable(insn->code)) { 19160 verbose(env, "unknown opcode %02x\n", insn->code); 19161 return -EINVAL; 19162 } 19163 } 19164 19165 /* now all pseudo BPF_LD_IMM64 instructions load valid 19166 * 'struct bpf_map *' into a register instead of user map_fd. 19167 * These pointers will be used later by verifier to validate map access. 19168 */ 19169 return 0; 19170 } 19171 19172 /* drop refcnt of maps used by the rejected program */ 19173 static void release_maps(struct bpf_verifier_env *env) 19174 { 19175 __bpf_free_used_maps(env->prog->aux, env->used_maps, 19176 env->used_map_cnt); 19177 } 19178 19179 /* drop refcnt of maps used by the rejected program */ 19180 static void release_btfs(struct bpf_verifier_env *env) 19181 { 19182 __bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt); 19183 } 19184 19185 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 19186 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 19187 { 19188 struct bpf_insn *insn = env->prog->insnsi; 19189 int insn_cnt = env->prog->len; 19190 int i; 19191 19192 for (i = 0; i < insn_cnt; i++, insn++) { 19193 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 19194 continue; 19195 if (insn->src_reg == BPF_PSEUDO_FUNC) 19196 continue; 19197 insn->src_reg = 0; 19198 } 19199 } 19200 19201 /* single env->prog->insni[off] instruction was replaced with the range 19202 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 19203 * [0, off) and [off, end) to new locations, so the patched range stays zero 19204 */ 19205 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 19206 struct bpf_insn_aux_data *new_data, 19207 struct bpf_prog *new_prog, u32 off, u32 cnt) 19208 { 19209 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 19210 struct bpf_insn *insn = new_prog->insnsi; 19211 u32 old_seen = old_data[off].seen; 19212 u32 prog_len; 19213 int i; 19214 19215 /* aux info at OFF always needs adjustment, no matter fast path 19216 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 19217 * original insn at old prog. 19218 */ 19219 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 19220 19221 if (cnt == 1) 19222 return; 19223 prog_len = new_prog->len; 19224 19225 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 19226 memcpy(new_data + off + cnt - 1, old_data + off, 19227 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 19228 for (i = off; i < off + cnt - 1; i++) { 19229 /* Expand insni[off]'s seen count to the patched range. */ 19230 new_data[i].seen = old_seen; 19231 new_data[i].zext_dst = insn_has_def32(env, insn + i); 19232 } 19233 env->insn_aux_data = new_data; 19234 vfree(old_data); 19235 } 19236 19237 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 19238 { 19239 int i; 19240 19241 if (len == 1) 19242 return; 19243 /* NOTE: fake 'exit' subprog should be updated as well. */ 19244 for (i = 0; i <= env->subprog_cnt; i++) { 19245 if (env->subprog_info[i].start <= off) 19246 continue; 19247 env->subprog_info[i].start += len - 1; 19248 } 19249 } 19250 19251 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 19252 { 19253 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 19254 int i, sz = prog->aux->size_poke_tab; 19255 struct bpf_jit_poke_descriptor *desc; 19256 19257 for (i = 0; i < sz; i++) { 19258 desc = &tab[i]; 19259 if (desc->insn_idx <= off) 19260 continue; 19261 desc->insn_idx += len - 1; 19262 } 19263 } 19264 19265 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 19266 const struct bpf_insn *patch, u32 len) 19267 { 19268 struct bpf_prog *new_prog; 19269 struct bpf_insn_aux_data *new_data = NULL; 19270 19271 if (len > 1) { 19272 new_data = vzalloc(array_size(env->prog->len + len - 1, 19273 sizeof(struct bpf_insn_aux_data))); 19274 if (!new_data) 19275 return NULL; 19276 } 19277 19278 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 19279 if (IS_ERR(new_prog)) { 19280 if (PTR_ERR(new_prog) == -ERANGE) 19281 verbose(env, 19282 "insn %d cannot be patched due to 16-bit range\n", 19283 env->insn_aux_data[off].orig_idx); 19284 vfree(new_data); 19285 return NULL; 19286 } 19287 adjust_insn_aux_data(env, new_data, new_prog, off, len); 19288 adjust_subprog_starts(env, off, len); 19289 adjust_poke_descs(new_prog, off, len); 19290 return new_prog; 19291 } 19292 19293 /* 19294 * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the 19295 * jump offset by 'delta'. 19296 */ 19297 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta) 19298 { 19299 struct bpf_insn *insn = prog->insnsi; 19300 u32 insn_cnt = prog->len, i; 19301 s32 imm; 19302 s16 off; 19303 19304 for (i = 0; i < insn_cnt; i++, insn++) { 19305 u8 code = insn->code; 19306 19307 if (tgt_idx <= i && i < tgt_idx + delta) 19308 continue; 19309 19310 if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) || 19311 BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT) 19312 continue; 19313 19314 if (insn->code == (BPF_JMP32 | BPF_JA)) { 19315 if (i + 1 + insn->imm != tgt_idx) 19316 continue; 19317 if (check_add_overflow(insn->imm, delta, &imm)) 19318 return -ERANGE; 19319 insn->imm = imm; 19320 } else { 19321 if (i + 1 + insn->off != tgt_idx) 19322 continue; 19323 if (check_add_overflow(insn->off, delta, &off)) 19324 return -ERANGE; 19325 insn->off = off; 19326 } 19327 } 19328 return 0; 19329 } 19330 19331 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 19332 u32 off, u32 cnt) 19333 { 19334 int i, j; 19335 19336 /* find first prog starting at or after off (first to remove) */ 19337 for (i = 0; i < env->subprog_cnt; i++) 19338 if (env->subprog_info[i].start >= off) 19339 break; 19340 /* find first prog starting at or after off + cnt (first to stay) */ 19341 for (j = i; j < env->subprog_cnt; j++) 19342 if (env->subprog_info[j].start >= off + cnt) 19343 break; 19344 /* if j doesn't start exactly at off + cnt, we are just removing 19345 * the front of previous prog 19346 */ 19347 if (env->subprog_info[j].start != off + cnt) 19348 j--; 19349 19350 if (j > i) { 19351 struct bpf_prog_aux *aux = env->prog->aux; 19352 int move; 19353 19354 /* move fake 'exit' subprog as well */ 19355 move = env->subprog_cnt + 1 - j; 19356 19357 memmove(env->subprog_info + i, 19358 env->subprog_info + j, 19359 sizeof(*env->subprog_info) * move); 19360 env->subprog_cnt -= j - i; 19361 19362 /* remove func_info */ 19363 if (aux->func_info) { 19364 move = aux->func_info_cnt - j; 19365 19366 memmove(aux->func_info + i, 19367 aux->func_info + j, 19368 sizeof(*aux->func_info) * move); 19369 aux->func_info_cnt -= j - i; 19370 /* func_info->insn_off is set after all code rewrites, 19371 * in adjust_btf_func() - no need to adjust 19372 */ 19373 } 19374 } else { 19375 /* convert i from "first prog to remove" to "first to adjust" */ 19376 if (env->subprog_info[i].start == off) 19377 i++; 19378 } 19379 19380 /* update fake 'exit' subprog as well */ 19381 for (; i <= env->subprog_cnt; i++) 19382 env->subprog_info[i].start -= cnt; 19383 19384 return 0; 19385 } 19386 19387 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 19388 u32 cnt) 19389 { 19390 struct bpf_prog *prog = env->prog; 19391 u32 i, l_off, l_cnt, nr_linfo; 19392 struct bpf_line_info *linfo; 19393 19394 nr_linfo = prog->aux->nr_linfo; 19395 if (!nr_linfo) 19396 return 0; 19397 19398 linfo = prog->aux->linfo; 19399 19400 /* find first line info to remove, count lines to be removed */ 19401 for (i = 0; i < nr_linfo; i++) 19402 if (linfo[i].insn_off >= off) 19403 break; 19404 19405 l_off = i; 19406 l_cnt = 0; 19407 for (; i < nr_linfo; i++) 19408 if (linfo[i].insn_off < off + cnt) 19409 l_cnt++; 19410 else 19411 break; 19412 19413 /* First live insn doesn't match first live linfo, it needs to "inherit" 19414 * last removed linfo. prog is already modified, so prog->len == off 19415 * means no live instructions after (tail of the program was removed). 19416 */ 19417 if (prog->len != off && l_cnt && 19418 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 19419 l_cnt--; 19420 linfo[--i].insn_off = off + cnt; 19421 } 19422 19423 /* remove the line info which refer to the removed instructions */ 19424 if (l_cnt) { 19425 memmove(linfo + l_off, linfo + i, 19426 sizeof(*linfo) * (nr_linfo - i)); 19427 19428 prog->aux->nr_linfo -= l_cnt; 19429 nr_linfo = prog->aux->nr_linfo; 19430 } 19431 19432 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 19433 for (i = l_off; i < nr_linfo; i++) 19434 linfo[i].insn_off -= cnt; 19435 19436 /* fix up all subprogs (incl. 'exit') which start >= off */ 19437 for (i = 0; i <= env->subprog_cnt; i++) 19438 if (env->subprog_info[i].linfo_idx > l_off) { 19439 /* program may have started in the removed region but 19440 * may not be fully removed 19441 */ 19442 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 19443 env->subprog_info[i].linfo_idx -= l_cnt; 19444 else 19445 env->subprog_info[i].linfo_idx = l_off; 19446 } 19447 19448 return 0; 19449 } 19450 19451 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 19452 { 19453 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 19454 unsigned int orig_prog_len = env->prog->len; 19455 int err; 19456 19457 if (bpf_prog_is_offloaded(env->prog->aux)) 19458 bpf_prog_offload_remove_insns(env, off, cnt); 19459 19460 err = bpf_remove_insns(env->prog, off, cnt); 19461 if (err) 19462 return err; 19463 19464 err = adjust_subprog_starts_after_remove(env, off, cnt); 19465 if (err) 19466 return err; 19467 19468 err = bpf_adj_linfo_after_remove(env, off, cnt); 19469 if (err) 19470 return err; 19471 19472 memmove(aux_data + off, aux_data + off + cnt, 19473 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 19474 19475 return 0; 19476 } 19477 19478 /* The verifier does more data flow analysis than llvm and will not 19479 * explore branches that are dead at run time. Malicious programs can 19480 * have dead code too. Therefore replace all dead at-run-time code 19481 * with 'ja -1'. 19482 * 19483 * Just nops are not optimal, e.g. if they would sit at the end of the 19484 * program and through another bug we would manage to jump there, then 19485 * we'd execute beyond program memory otherwise. Returning exception 19486 * code also wouldn't work since we can have subprogs where the dead 19487 * code could be located. 19488 */ 19489 static void sanitize_dead_code(struct bpf_verifier_env *env) 19490 { 19491 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 19492 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 19493 struct bpf_insn *insn = env->prog->insnsi; 19494 const int insn_cnt = env->prog->len; 19495 int i; 19496 19497 for (i = 0; i < insn_cnt; i++) { 19498 if (aux_data[i].seen) 19499 continue; 19500 memcpy(insn + i, &trap, sizeof(trap)); 19501 aux_data[i].zext_dst = false; 19502 } 19503 } 19504 19505 static bool insn_is_cond_jump(u8 code) 19506 { 19507 u8 op; 19508 19509 op = BPF_OP(code); 19510 if (BPF_CLASS(code) == BPF_JMP32) 19511 return op != BPF_JA; 19512 19513 if (BPF_CLASS(code) != BPF_JMP) 19514 return false; 19515 19516 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 19517 } 19518 19519 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 19520 { 19521 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 19522 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 19523 struct bpf_insn *insn = env->prog->insnsi; 19524 const int insn_cnt = env->prog->len; 19525 int i; 19526 19527 for (i = 0; i < insn_cnt; i++, insn++) { 19528 if (!insn_is_cond_jump(insn->code)) 19529 continue; 19530 19531 if (!aux_data[i + 1].seen) 19532 ja.off = insn->off; 19533 else if (!aux_data[i + 1 + insn->off].seen) 19534 ja.off = 0; 19535 else 19536 continue; 19537 19538 if (bpf_prog_is_offloaded(env->prog->aux)) 19539 bpf_prog_offload_replace_insn(env, i, &ja); 19540 19541 memcpy(insn, &ja, sizeof(ja)); 19542 } 19543 } 19544 19545 static int opt_remove_dead_code(struct bpf_verifier_env *env) 19546 { 19547 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 19548 int insn_cnt = env->prog->len; 19549 int i, err; 19550 19551 for (i = 0; i < insn_cnt; i++) { 19552 int j; 19553 19554 j = 0; 19555 while (i + j < insn_cnt && !aux_data[i + j].seen) 19556 j++; 19557 if (!j) 19558 continue; 19559 19560 err = verifier_remove_insns(env, i, j); 19561 if (err) 19562 return err; 19563 insn_cnt = env->prog->len; 19564 } 19565 19566 return 0; 19567 } 19568 19569 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 19570 19571 static int opt_remove_nops(struct bpf_verifier_env *env) 19572 { 19573 const struct bpf_insn ja = NOP; 19574 struct bpf_insn *insn = env->prog->insnsi; 19575 int insn_cnt = env->prog->len; 19576 int i, err; 19577 19578 for (i = 0; i < insn_cnt; i++) { 19579 if (memcmp(&insn[i], &ja, sizeof(ja))) 19580 continue; 19581 19582 err = verifier_remove_insns(env, i, 1); 19583 if (err) 19584 return err; 19585 insn_cnt--; 19586 i--; 19587 } 19588 19589 return 0; 19590 } 19591 19592 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 19593 const union bpf_attr *attr) 19594 { 19595 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 19596 struct bpf_insn_aux_data *aux = env->insn_aux_data; 19597 int i, patch_len, delta = 0, len = env->prog->len; 19598 struct bpf_insn *insns = env->prog->insnsi; 19599 struct bpf_prog *new_prog; 19600 bool rnd_hi32; 19601 19602 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 19603 zext_patch[1] = BPF_ZEXT_REG(0); 19604 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 19605 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 19606 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 19607 for (i = 0; i < len; i++) { 19608 int adj_idx = i + delta; 19609 struct bpf_insn insn; 19610 int load_reg; 19611 19612 insn = insns[adj_idx]; 19613 load_reg = insn_def_regno(&insn); 19614 if (!aux[adj_idx].zext_dst) { 19615 u8 code, class; 19616 u32 imm_rnd; 19617 19618 if (!rnd_hi32) 19619 continue; 19620 19621 code = insn.code; 19622 class = BPF_CLASS(code); 19623 if (load_reg == -1) 19624 continue; 19625 19626 /* NOTE: arg "reg" (the fourth one) is only used for 19627 * BPF_STX + SRC_OP, so it is safe to pass NULL 19628 * here. 19629 */ 19630 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 19631 if (class == BPF_LD && 19632 BPF_MODE(code) == BPF_IMM) 19633 i++; 19634 continue; 19635 } 19636 19637 /* ctx load could be transformed into wider load. */ 19638 if (class == BPF_LDX && 19639 aux[adj_idx].ptr_type == PTR_TO_CTX) 19640 continue; 19641 19642 imm_rnd = get_random_u32(); 19643 rnd_hi32_patch[0] = insn; 19644 rnd_hi32_patch[1].imm = imm_rnd; 19645 rnd_hi32_patch[3].dst_reg = load_reg; 19646 patch = rnd_hi32_patch; 19647 patch_len = 4; 19648 goto apply_patch_buffer; 19649 } 19650 19651 /* Add in an zero-extend instruction if a) the JIT has requested 19652 * it or b) it's a CMPXCHG. 19653 * 19654 * The latter is because: BPF_CMPXCHG always loads a value into 19655 * R0, therefore always zero-extends. However some archs' 19656 * equivalent instruction only does this load when the 19657 * comparison is successful. This detail of CMPXCHG is 19658 * orthogonal to the general zero-extension behaviour of the 19659 * CPU, so it's treated independently of bpf_jit_needs_zext. 19660 */ 19661 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 19662 continue; 19663 19664 /* Zero-extension is done by the caller. */ 19665 if (bpf_pseudo_kfunc_call(&insn)) 19666 continue; 19667 19668 if (WARN_ON(load_reg == -1)) { 19669 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 19670 return -EFAULT; 19671 } 19672 19673 zext_patch[0] = insn; 19674 zext_patch[1].dst_reg = load_reg; 19675 zext_patch[1].src_reg = load_reg; 19676 patch = zext_patch; 19677 patch_len = 2; 19678 apply_patch_buffer: 19679 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 19680 if (!new_prog) 19681 return -ENOMEM; 19682 env->prog = new_prog; 19683 insns = new_prog->insnsi; 19684 aux = env->insn_aux_data; 19685 delta += patch_len - 1; 19686 } 19687 19688 return 0; 19689 } 19690 19691 /* convert load instructions that access fields of a context type into a 19692 * sequence of instructions that access fields of the underlying structure: 19693 * struct __sk_buff -> struct sk_buff 19694 * struct bpf_sock_ops -> struct sock 19695 */ 19696 static int convert_ctx_accesses(struct bpf_verifier_env *env) 19697 { 19698 struct bpf_subprog_info *subprogs = env->subprog_info; 19699 const struct bpf_verifier_ops *ops = env->ops; 19700 int i, cnt, size, ctx_field_size, delta = 0, epilogue_cnt = 0; 19701 const int insn_cnt = env->prog->len; 19702 struct bpf_insn *epilogue_buf = env->epilogue_buf; 19703 struct bpf_insn *insn_buf = env->insn_buf; 19704 struct bpf_insn *insn; 19705 u32 target_size, size_default, off; 19706 struct bpf_prog *new_prog; 19707 enum bpf_access_type type; 19708 bool is_narrower_load; 19709 int epilogue_idx = 0; 19710 19711 if (ops->gen_epilogue) { 19712 epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog, 19713 -(subprogs[0].stack_depth + 8)); 19714 if (epilogue_cnt >= INSN_BUF_SIZE) { 19715 verbose(env, "bpf verifier is misconfigured\n"); 19716 return -EINVAL; 19717 } else if (epilogue_cnt) { 19718 /* Save the ARG_PTR_TO_CTX for the epilogue to use */ 19719 cnt = 0; 19720 subprogs[0].stack_depth += 8; 19721 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1, 19722 -subprogs[0].stack_depth); 19723 insn_buf[cnt++] = env->prog->insnsi[0]; 19724 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 19725 if (!new_prog) 19726 return -ENOMEM; 19727 env->prog = new_prog; 19728 delta += cnt - 1; 19729 } 19730 } 19731 19732 if (ops->gen_prologue || env->seen_direct_write) { 19733 if (!ops->gen_prologue) { 19734 verbose(env, "bpf verifier is misconfigured\n"); 19735 return -EINVAL; 19736 } 19737 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 19738 env->prog); 19739 if (cnt >= INSN_BUF_SIZE) { 19740 verbose(env, "bpf verifier is misconfigured\n"); 19741 return -EINVAL; 19742 } else if (cnt) { 19743 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 19744 if (!new_prog) 19745 return -ENOMEM; 19746 19747 env->prog = new_prog; 19748 delta += cnt - 1; 19749 } 19750 } 19751 19752 if (delta) 19753 WARN_ON(adjust_jmp_off(env->prog, 0, delta)); 19754 19755 if (bpf_prog_is_offloaded(env->prog->aux)) 19756 return 0; 19757 19758 insn = env->prog->insnsi + delta; 19759 19760 for (i = 0; i < insn_cnt; i++, insn++) { 19761 bpf_convert_ctx_access_t convert_ctx_access; 19762 u8 mode; 19763 19764 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 19765 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 19766 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 19767 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 19768 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 19769 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 19770 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 19771 type = BPF_READ; 19772 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 19773 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 19774 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 19775 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 19776 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 19777 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 19778 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 19779 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 19780 type = BPF_WRITE; 19781 } else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) || 19782 insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) && 19783 env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) { 19784 insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code); 19785 env->prog->aux->num_exentries++; 19786 continue; 19787 } else if (insn->code == (BPF_JMP | BPF_EXIT) && 19788 epilogue_cnt && 19789 i + delta < subprogs[1].start) { 19790 /* Generate epilogue for the main prog */ 19791 if (epilogue_idx) { 19792 /* jump back to the earlier generated epilogue */ 19793 insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1); 19794 cnt = 1; 19795 } else { 19796 memcpy(insn_buf, epilogue_buf, 19797 epilogue_cnt * sizeof(*epilogue_buf)); 19798 cnt = epilogue_cnt; 19799 /* epilogue_idx cannot be 0. It must have at 19800 * least one ctx ptr saving insn before the 19801 * epilogue. 19802 */ 19803 epilogue_idx = i + delta; 19804 } 19805 goto patch_insn_buf; 19806 } else { 19807 continue; 19808 } 19809 19810 if (type == BPF_WRITE && 19811 env->insn_aux_data[i + delta].sanitize_stack_spill) { 19812 struct bpf_insn patch[] = { 19813 *insn, 19814 BPF_ST_NOSPEC(), 19815 }; 19816 19817 cnt = ARRAY_SIZE(patch); 19818 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 19819 if (!new_prog) 19820 return -ENOMEM; 19821 19822 delta += cnt - 1; 19823 env->prog = new_prog; 19824 insn = new_prog->insnsi + i + delta; 19825 continue; 19826 } 19827 19828 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 19829 case PTR_TO_CTX: 19830 if (!ops->convert_ctx_access) 19831 continue; 19832 convert_ctx_access = ops->convert_ctx_access; 19833 break; 19834 case PTR_TO_SOCKET: 19835 case PTR_TO_SOCK_COMMON: 19836 convert_ctx_access = bpf_sock_convert_ctx_access; 19837 break; 19838 case PTR_TO_TCP_SOCK: 19839 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 19840 break; 19841 case PTR_TO_XDP_SOCK: 19842 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 19843 break; 19844 case PTR_TO_BTF_ID: 19845 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 19846 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 19847 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 19848 * be said once it is marked PTR_UNTRUSTED, hence we must handle 19849 * any faults for loads into such types. BPF_WRITE is disallowed 19850 * for this case. 19851 */ 19852 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 19853 if (type == BPF_READ) { 19854 if (BPF_MODE(insn->code) == BPF_MEM) 19855 insn->code = BPF_LDX | BPF_PROBE_MEM | 19856 BPF_SIZE((insn)->code); 19857 else 19858 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 19859 BPF_SIZE((insn)->code); 19860 env->prog->aux->num_exentries++; 19861 } 19862 continue; 19863 case PTR_TO_ARENA: 19864 if (BPF_MODE(insn->code) == BPF_MEMSX) { 19865 verbose(env, "sign extending loads from arena are not supported yet\n"); 19866 return -EOPNOTSUPP; 19867 } 19868 insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code); 19869 env->prog->aux->num_exentries++; 19870 continue; 19871 default: 19872 continue; 19873 } 19874 19875 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 19876 size = BPF_LDST_BYTES(insn); 19877 mode = BPF_MODE(insn->code); 19878 19879 /* If the read access is a narrower load of the field, 19880 * convert to a 4/8-byte load, to minimum program type specific 19881 * convert_ctx_access changes. If conversion is successful, 19882 * we will apply proper mask to the result. 19883 */ 19884 is_narrower_load = size < ctx_field_size; 19885 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 19886 off = insn->off; 19887 if (is_narrower_load) { 19888 u8 size_code; 19889 19890 if (type == BPF_WRITE) { 19891 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 19892 return -EINVAL; 19893 } 19894 19895 size_code = BPF_H; 19896 if (ctx_field_size == 4) 19897 size_code = BPF_W; 19898 else if (ctx_field_size == 8) 19899 size_code = BPF_DW; 19900 19901 insn->off = off & ~(size_default - 1); 19902 insn->code = BPF_LDX | BPF_MEM | size_code; 19903 } 19904 19905 target_size = 0; 19906 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 19907 &target_size); 19908 if (cnt == 0 || cnt >= INSN_BUF_SIZE || 19909 (ctx_field_size && !target_size)) { 19910 verbose(env, "bpf verifier is misconfigured\n"); 19911 return -EINVAL; 19912 } 19913 19914 if (is_narrower_load && size < target_size) { 19915 u8 shift = bpf_ctx_narrow_access_offset( 19916 off, size, size_default) * 8; 19917 if (shift && cnt + 1 >= INSN_BUF_SIZE) { 19918 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 19919 return -EINVAL; 19920 } 19921 if (ctx_field_size <= 4) { 19922 if (shift) 19923 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 19924 insn->dst_reg, 19925 shift); 19926 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 19927 (1 << size * 8) - 1); 19928 } else { 19929 if (shift) 19930 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 19931 insn->dst_reg, 19932 shift); 19933 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 19934 (1ULL << size * 8) - 1); 19935 } 19936 } 19937 if (mode == BPF_MEMSX) 19938 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 19939 insn->dst_reg, insn->dst_reg, 19940 size * 8, 0); 19941 19942 patch_insn_buf: 19943 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19944 if (!new_prog) 19945 return -ENOMEM; 19946 19947 delta += cnt - 1; 19948 19949 /* keep walking new program and skip insns we just inserted */ 19950 env->prog = new_prog; 19951 insn = new_prog->insnsi + i + delta; 19952 } 19953 19954 return 0; 19955 } 19956 19957 static int jit_subprogs(struct bpf_verifier_env *env) 19958 { 19959 struct bpf_prog *prog = env->prog, **func, *tmp; 19960 int i, j, subprog_start, subprog_end = 0, len, subprog; 19961 struct bpf_map *map_ptr; 19962 struct bpf_insn *insn; 19963 void *old_bpf_func; 19964 int err, num_exentries; 19965 19966 if (env->subprog_cnt <= 1) 19967 return 0; 19968 19969 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 19970 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 19971 continue; 19972 19973 /* Upon error here we cannot fall back to interpreter but 19974 * need a hard reject of the program. Thus -EFAULT is 19975 * propagated in any case. 19976 */ 19977 subprog = find_subprog(env, i + insn->imm + 1); 19978 if (subprog < 0) { 19979 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 19980 i + insn->imm + 1); 19981 return -EFAULT; 19982 } 19983 /* temporarily remember subprog id inside insn instead of 19984 * aux_data, since next loop will split up all insns into funcs 19985 */ 19986 insn->off = subprog; 19987 /* remember original imm in case JIT fails and fallback 19988 * to interpreter will be needed 19989 */ 19990 env->insn_aux_data[i].call_imm = insn->imm; 19991 /* point imm to __bpf_call_base+1 from JITs point of view */ 19992 insn->imm = 1; 19993 if (bpf_pseudo_func(insn)) { 19994 #if defined(MODULES_VADDR) 19995 u64 addr = MODULES_VADDR; 19996 #else 19997 u64 addr = VMALLOC_START; 19998 #endif 19999 /* jit (e.g. x86_64) may emit fewer instructions 20000 * if it learns a u32 imm is the same as a u64 imm. 20001 * Set close enough to possible prog address. 20002 */ 20003 insn[0].imm = (u32)addr; 20004 insn[1].imm = addr >> 32; 20005 } 20006 } 20007 20008 err = bpf_prog_alloc_jited_linfo(prog); 20009 if (err) 20010 goto out_undo_insn; 20011 20012 err = -ENOMEM; 20013 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 20014 if (!func) 20015 goto out_undo_insn; 20016 20017 for (i = 0; i < env->subprog_cnt; i++) { 20018 subprog_start = subprog_end; 20019 subprog_end = env->subprog_info[i + 1].start; 20020 20021 len = subprog_end - subprog_start; 20022 /* bpf_prog_run() doesn't call subprogs directly, 20023 * hence main prog stats include the runtime of subprogs. 20024 * subprogs don't have IDs and not reachable via prog_get_next_id 20025 * func[i]->stats will never be accessed and stays NULL 20026 */ 20027 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 20028 if (!func[i]) 20029 goto out_free; 20030 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 20031 len * sizeof(struct bpf_insn)); 20032 func[i]->type = prog->type; 20033 func[i]->len = len; 20034 if (bpf_prog_calc_tag(func[i])) 20035 goto out_free; 20036 func[i]->is_func = 1; 20037 func[i]->sleepable = prog->sleepable; 20038 func[i]->aux->func_idx = i; 20039 /* Below members will be freed only at prog->aux */ 20040 func[i]->aux->btf = prog->aux->btf; 20041 func[i]->aux->func_info = prog->aux->func_info; 20042 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 20043 func[i]->aux->poke_tab = prog->aux->poke_tab; 20044 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 20045 20046 for (j = 0; j < prog->aux->size_poke_tab; j++) { 20047 struct bpf_jit_poke_descriptor *poke; 20048 20049 poke = &prog->aux->poke_tab[j]; 20050 if (poke->insn_idx < subprog_end && 20051 poke->insn_idx >= subprog_start) 20052 poke->aux = func[i]->aux; 20053 } 20054 20055 func[i]->aux->name[0] = 'F'; 20056 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 20057 func[i]->jit_requested = 1; 20058 func[i]->blinding_requested = prog->blinding_requested; 20059 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 20060 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 20061 func[i]->aux->linfo = prog->aux->linfo; 20062 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 20063 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 20064 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 20065 func[i]->aux->arena = prog->aux->arena; 20066 num_exentries = 0; 20067 insn = func[i]->insnsi; 20068 for (j = 0; j < func[i]->len; j++, insn++) { 20069 if (BPF_CLASS(insn->code) == BPF_LDX && 20070 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 20071 BPF_MODE(insn->code) == BPF_PROBE_MEM32 || 20072 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 20073 num_exentries++; 20074 if ((BPF_CLASS(insn->code) == BPF_STX || 20075 BPF_CLASS(insn->code) == BPF_ST) && 20076 BPF_MODE(insn->code) == BPF_PROBE_MEM32) 20077 num_exentries++; 20078 if (BPF_CLASS(insn->code) == BPF_STX && 20079 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) 20080 num_exentries++; 20081 } 20082 func[i]->aux->num_exentries = num_exentries; 20083 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 20084 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb; 20085 if (!i) 20086 func[i]->aux->exception_boundary = env->seen_exception; 20087 func[i] = bpf_int_jit_compile(func[i]); 20088 if (!func[i]->jited) { 20089 err = -ENOTSUPP; 20090 goto out_free; 20091 } 20092 cond_resched(); 20093 } 20094 20095 /* at this point all bpf functions were successfully JITed 20096 * now populate all bpf_calls with correct addresses and 20097 * run last pass of JIT 20098 */ 20099 for (i = 0; i < env->subprog_cnt; i++) { 20100 insn = func[i]->insnsi; 20101 for (j = 0; j < func[i]->len; j++, insn++) { 20102 if (bpf_pseudo_func(insn)) { 20103 subprog = insn->off; 20104 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 20105 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 20106 continue; 20107 } 20108 if (!bpf_pseudo_call(insn)) 20109 continue; 20110 subprog = insn->off; 20111 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 20112 } 20113 20114 /* we use the aux data to keep a list of the start addresses 20115 * of the JITed images for each function in the program 20116 * 20117 * for some architectures, such as powerpc64, the imm field 20118 * might not be large enough to hold the offset of the start 20119 * address of the callee's JITed image from __bpf_call_base 20120 * 20121 * in such cases, we can lookup the start address of a callee 20122 * by using its subprog id, available from the off field of 20123 * the call instruction, as an index for this list 20124 */ 20125 func[i]->aux->func = func; 20126 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 20127 func[i]->aux->real_func_cnt = env->subprog_cnt; 20128 } 20129 for (i = 0; i < env->subprog_cnt; i++) { 20130 old_bpf_func = func[i]->bpf_func; 20131 tmp = bpf_int_jit_compile(func[i]); 20132 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 20133 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 20134 err = -ENOTSUPP; 20135 goto out_free; 20136 } 20137 cond_resched(); 20138 } 20139 20140 /* finally lock prog and jit images for all functions and 20141 * populate kallsysm. Begin at the first subprogram, since 20142 * bpf_prog_load will add the kallsyms for the main program. 20143 */ 20144 for (i = 1; i < env->subprog_cnt; i++) { 20145 err = bpf_prog_lock_ro(func[i]); 20146 if (err) 20147 goto out_free; 20148 } 20149 20150 for (i = 1; i < env->subprog_cnt; i++) 20151 bpf_prog_kallsyms_add(func[i]); 20152 20153 /* Last step: make now unused interpreter insns from main 20154 * prog consistent for later dump requests, so they can 20155 * later look the same as if they were interpreted only. 20156 */ 20157 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 20158 if (bpf_pseudo_func(insn)) { 20159 insn[0].imm = env->insn_aux_data[i].call_imm; 20160 insn[1].imm = insn->off; 20161 insn->off = 0; 20162 continue; 20163 } 20164 if (!bpf_pseudo_call(insn)) 20165 continue; 20166 insn->off = env->insn_aux_data[i].call_imm; 20167 subprog = find_subprog(env, i + insn->off + 1); 20168 insn->imm = subprog; 20169 } 20170 20171 prog->jited = 1; 20172 prog->bpf_func = func[0]->bpf_func; 20173 prog->jited_len = func[0]->jited_len; 20174 prog->aux->extable = func[0]->aux->extable; 20175 prog->aux->num_exentries = func[0]->aux->num_exentries; 20176 prog->aux->func = func; 20177 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 20178 prog->aux->real_func_cnt = env->subprog_cnt; 20179 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func; 20180 prog->aux->exception_boundary = func[0]->aux->exception_boundary; 20181 bpf_prog_jit_attempt_done(prog); 20182 return 0; 20183 out_free: 20184 /* We failed JIT'ing, so at this point we need to unregister poke 20185 * descriptors from subprogs, so that kernel is not attempting to 20186 * patch it anymore as we're freeing the subprog JIT memory. 20187 */ 20188 for (i = 0; i < prog->aux->size_poke_tab; i++) { 20189 map_ptr = prog->aux->poke_tab[i].tail_call.map; 20190 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 20191 } 20192 /* At this point we're guaranteed that poke descriptors are not 20193 * live anymore. We can just unlink its descriptor table as it's 20194 * released with the main prog. 20195 */ 20196 for (i = 0; i < env->subprog_cnt; i++) { 20197 if (!func[i]) 20198 continue; 20199 func[i]->aux->poke_tab = NULL; 20200 bpf_jit_free(func[i]); 20201 } 20202 kfree(func); 20203 out_undo_insn: 20204 /* cleanup main prog to be interpreted */ 20205 prog->jit_requested = 0; 20206 prog->blinding_requested = 0; 20207 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 20208 if (!bpf_pseudo_call(insn)) 20209 continue; 20210 insn->off = 0; 20211 insn->imm = env->insn_aux_data[i].call_imm; 20212 } 20213 bpf_prog_jit_attempt_done(prog); 20214 return err; 20215 } 20216 20217 static int fixup_call_args(struct bpf_verifier_env *env) 20218 { 20219 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 20220 struct bpf_prog *prog = env->prog; 20221 struct bpf_insn *insn = prog->insnsi; 20222 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 20223 int i, depth; 20224 #endif 20225 int err = 0; 20226 20227 if (env->prog->jit_requested && 20228 !bpf_prog_is_offloaded(env->prog->aux)) { 20229 err = jit_subprogs(env); 20230 if (err == 0) 20231 return 0; 20232 if (err == -EFAULT) 20233 return err; 20234 } 20235 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 20236 if (has_kfunc_call) { 20237 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 20238 return -EINVAL; 20239 } 20240 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 20241 /* When JIT fails the progs with bpf2bpf calls and tail_calls 20242 * have to be rejected, since interpreter doesn't support them yet. 20243 */ 20244 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 20245 return -EINVAL; 20246 } 20247 for (i = 0; i < prog->len; i++, insn++) { 20248 if (bpf_pseudo_func(insn)) { 20249 /* When JIT fails the progs with callback calls 20250 * have to be rejected, since interpreter doesn't support them yet. 20251 */ 20252 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 20253 return -EINVAL; 20254 } 20255 20256 if (!bpf_pseudo_call(insn)) 20257 continue; 20258 depth = get_callee_stack_depth(env, insn, i); 20259 if (depth < 0) 20260 return depth; 20261 bpf_patch_call_args(insn, depth); 20262 } 20263 err = 0; 20264 #endif 20265 return err; 20266 } 20267 20268 /* replace a generic kfunc with a specialized version if necessary */ 20269 static void specialize_kfunc(struct bpf_verifier_env *env, 20270 u32 func_id, u16 offset, unsigned long *addr) 20271 { 20272 struct bpf_prog *prog = env->prog; 20273 bool seen_direct_write; 20274 void *xdp_kfunc; 20275 bool is_rdonly; 20276 20277 if (bpf_dev_bound_kfunc_id(func_id)) { 20278 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 20279 if (xdp_kfunc) { 20280 *addr = (unsigned long)xdp_kfunc; 20281 return; 20282 } 20283 /* fallback to default kfunc when not supported by netdev */ 20284 } 20285 20286 if (offset) 20287 return; 20288 20289 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 20290 seen_direct_write = env->seen_direct_write; 20291 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 20292 20293 if (is_rdonly) 20294 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 20295 20296 /* restore env->seen_direct_write to its original value, since 20297 * may_access_direct_pkt_data mutates it 20298 */ 20299 env->seen_direct_write = seen_direct_write; 20300 } 20301 } 20302 20303 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 20304 u16 struct_meta_reg, 20305 u16 node_offset_reg, 20306 struct bpf_insn *insn, 20307 struct bpf_insn *insn_buf, 20308 int *cnt) 20309 { 20310 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 20311 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 20312 20313 insn_buf[0] = addr[0]; 20314 insn_buf[1] = addr[1]; 20315 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 20316 insn_buf[3] = *insn; 20317 *cnt = 4; 20318 } 20319 20320 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 20321 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 20322 { 20323 const struct bpf_kfunc_desc *desc; 20324 20325 if (!insn->imm) { 20326 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 20327 return -EINVAL; 20328 } 20329 20330 *cnt = 0; 20331 20332 /* insn->imm has the btf func_id. Replace it with an offset relative to 20333 * __bpf_call_base, unless the JIT needs to call functions that are 20334 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 20335 */ 20336 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 20337 if (!desc) { 20338 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 20339 insn->imm); 20340 return -EFAULT; 20341 } 20342 20343 if (!bpf_jit_supports_far_kfunc_call()) 20344 insn->imm = BPF_CALL_IMM(desc->addr); 20345 if (insn->off) 20346 return 0; 20347 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 20348 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 20349 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 20350 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 20351 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 20352 20353 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) { 20354 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 20355 insn_idx); 20356 return -EFAULT; 20357 } 20358 20359 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 20360 insn_buf[1] = addr[0]; 20361 insn_buf[2] = addr[1]; 20362 insn_buf[3] = *insn; 20363 *cnt = 4; 20364 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 20365 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] || 20366 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 20367 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 20368 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 20369 20370 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) { 20371 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 20372 insn_idx); 20373 return -EFAULT; 20374 } 20375 20376 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 20377 !kptr_struct_meta) { 20378 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 20379 insn_idx); 20380 return -EFAULT; 20381 } 20382 20383 insn_buf[0] = addr[0]; 20384 insn_buf[1] = addr[1]; 20385 insn_buf[2] = *insn; 20386 *cnt = 3; 20387 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 20388 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 20389 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 20390 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 20391 int struct_meta_reg = BPF_REG_3; 20392 int node_offset_reg = BPF_REG_4; 20393 20394 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 20395 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 20396 struct_meta_reg = BPF_REG_4; 20397 node_offset_reg = BPF_REG_5; 20398 } 20399 20400 if (!kptr_struct_meta) { 20401 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 20402 insn_idx); 20403 return -EFAULT; 20404 } 20405 20406 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 20407 node_offset_reg, insn, insn_buf, cnt); 20408 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 20409 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 20410 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 20411 *cnt = 1; 20412 } else if (is_bpf_wq_set_callback_impl_kfunc(desc->func_id)) { 20413 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(BPF_REG_4, (long)env->prog->aux) }; 20414 20415 insn_buf[0] = ld_addrs[0]; 20416 insn_buf[1] = ld_addrs[1]; 20417 insn_buf[2] = *insn; 20418 *cnt = 3; 20419 } 20420 return 0; 20421 } 20422 20423 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */ 20424 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len) 20425 { 20426 struct bpf_subprog_info *info = env->subprog_info; 20427 int cnt = env->subprog_cnt; 20428 struct bpf_prog *prog; 20429 20430 /* We only reserve one slot for hidden subprogs in subprog_info. */ 20431 if (env->hidden_subprog_cnt) { 20432 verbose(env, "verifier internal error: only one hidden subprog supported\n"); 20433 return -EFAULT; 20434 } 20435 /* We're not patching any existing instruction, just appending the new 20436 * ones for the hidden subprog. Hence all of the adjustment operations 20437 * in bpf_patch_insn_data are no-ops. 20438 */ 20439 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len); 20440 if (!prog) 20441 return -ENOMEM; 20442 env->prog = prog; 20443 info[cnt + 1].start = info[cnt].start; 20444 info[cnt].start = prog->len - len + 1; 20445 env->subprog_cnt++; 20446 env->hidden_subprog_cnt++; 20447 return 0; 20448 } 20449 20450 /* Do various post-verification rewrites in a single program pass. 20451 * These rewrites simplify JIT and interpreter implementations. 20452 */ 20453 static int do_misc_fixups(struct bpf_verifier_env *env) 20454 { 20455 struct bpf_prog *prog = env->prog; 20456 enum bpf_attach_type eatype = prog->expected_attach_type; 20457 enum bpf_prog_type prog_type = resolve_prog_type(prog); 20458 struct bpf_insn *insn = prog->insnsi; 20459 const struct bpf_func_proto *fn; 20460 const int insn_cnt = prog->len; 20461 const struct bpf_map_ops *ops; 20462 struct bpf_insn_aux_data *aux; 20463 struct bpf_insn *insn_buf = env->insn_buf; 20464 struct bpf_prog *new_prog; 20465 struct bpf_map *map_ptr; 20466 int i, ret, cnt, delta = 0, cur_subprog = 0; 20467 struct bpf_subprog_info *subprogs = env->subprog_info; 20468 u16 stack_depth = subprogs[cur_subprog].stack_depth; 20469 u16 stack_depth_extra = 0; 20470 20471 if (env->seen_exception && !env->exception_callback_subprog) { 20472 struct bpf_insn patch[] = { 20473 env->prog->insnsi[insn_cnt - 1], 20474 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1), 20475 BPF_EXIT_INSN(), 20476 }; 20477 20478 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch)); 20479 if (ret < 0) 20480 return ret; 20481 prog = env->prog; 20482 insn = prog->insnsi; 20483 20484 env->exception_callback_subprog = env->subprog_cnt - 1; 20485 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */ 20486 mark_subprog_exc_cb(env, env->exception_callback_subprog); 20487 } 20488 20489 for (i = 0; i < insn_cnt;) { 20490 if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) { 20491 if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) || 20492 (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) { 20493 /* convert to 32-bit mov that clears upper 32-bit */ 20494 insn->code = BPF_ALU | BPF_MOV | BPF_X; 20495 /* clear off and imm, so it's a normal 'wX = wY' from JIT pov */ 20496 insn->off = 0; 20497 insn->imm = 0; 20498 } /* cast from as(0) to as(1) should be handled by JIT */ 20499 goto next_insn; 20500 } 20501 20502 if (env->insn_aux_data[i + delta].needs_zext) 20503 /* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */ 20504 insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code); 20505 20506 /* Make divide-by-zero exceptions impossible. */ 20507 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 20508 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 20509 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 20510 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 20511 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 20512 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 20513 struct bpf_insn *patchlet; 20514 struct bpf_insn chk_and_div[] = { 20515 /* [R,W]x div 0 -> 0 */ 20516 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 20517 BPF_JNE | BPF_K, insn->src_reg, 20518 0, 2, 0), 20519 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 20520 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 20521 *insn, 20522 }; 20523 struct bpf_insn chk_and_mod[] = { 20524 /* [R,W]x mod 0 -> [R,W]x */ 20525 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 20526 BPF_JEQ | BPF_K, insn->src_reg, 20527 0, 1 + (is64 ? 0 : 1), 0), 20528 *insn, 20529 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 20530 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 20531 }; 20532 20533 patchlet = isdiv ? chk_and_div : chk_and_mod; 20534 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 20535 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 20536 20537 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 20538 if (!new_prog) 20539 return -ENOMEM; 20540 20541 delta += cnt - 1; 20542 env->prog = prog = new_prog; 20543 insn = new_prog->insnsi + i + delta; 20544 goto next_insn; 20545 } 20546 20547 /* Make it impossible to de-reference a userspace address */ 20548 if (BPF_CLASS(insn->code) == BPF_LDX && 20549 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 20550 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) { 20551 struct bpf_insn *patch = &insn_buf[0]; 20552 u64 uaddress_limit = bpf_arch_uaddress_limit(); 20553 20554 if (!uaddress_limit) 20555 goto next_insn; 20556 20557 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg); 20558 if (insn->off) 20559 *patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off); 20560 *patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32); 20561 *patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2); 20562 *patch++ = *insn; 20563 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 20564 *patch++ = BPF_MOV64_IMM(insn->dst_reg, 0); 20565 20566 cnt = patch - insn_buf; 20567 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20568 if (!new_prog) 20569 return -ENOMEM; 20570 20571 delta += cnt - 1; 20572 env->prog = prog = new_prog; 20573 insn = new_prog->insnsi + i + delta; 20574 goto next_insn; 20575 } 20576 20577 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 20578 if (BPF_CLASS(insn->code) == BPF_LD && 20579 (BPF_MODE(insn->code) == BPF_ABS || 20580 BPF_MODE(insn->code) == BPF_IND)) { 20581 cnt = env->ops->gen_ld_abs(insn, insn_buf); 20582 if (cnt == 0 || cnt >= INSN_BUF_SIZE) { 20583 verbose(env, "bpf verifier is misconfigured\n"); 20584 return -EINVAL; 20585 } 20586 20587 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20588 if (!new_prog) 20589 return -ENOMEM; 20590 20591 delta += cnt - 1; 20592 env->prog = prog = new_prog; 20593 insn = new_prog->insnsi + i + delta; 20594 goto next_insn; 20595 } 20596 20597 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 20598 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 20599 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 20600 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 20601 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 20602 struct bpf_insn *patch = &insn_buf[0]; 20603 bool issrc, isneg, isimm; 20604 u32 off_reg; 20605 20606 aux = &env->insn_aux_data[i + delta]; 20607 if (!aux->alu_state || 20608 aux->alu_state == BPF_ALU_NON_POINTER) 20609 goto next_insn; 20610 20611 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 20612 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 20613 BPF_ALU_SANITIZE_SRC; 20614 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 20615 20616 off_reg = issrc ? insn->src_reg : insn->dst_reg; 20617 if (isimm) { 20618 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 20619 } else { 20620 if (isneg) 20621 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 20622 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 20623 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 20624 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 20625 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 20626 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 20627 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 20628 } 20629 if (!issrc) 20630 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 20631 insn->src_reg = BPF_REG_AX; 20632 if (isneg) 20633 insn->code = insn->code == code_add ? 20634 code_sub : code_add; 20635 *patch++ = *insn; 20636 if (issrc && isneg && !isimm) 20637 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 20638 cnt = patch - insn_buf; 20639 20640 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20641 if (!new_prog) 20642 return -ENOMEM; 20643 20644 delta += cnt - 1; 20645 env->prog = prog = new_prog; 20646 insn = new_prog->insnsi + i + delta; 20647 goto next_insn; 20648 } 20649 20650 if (is_may_goto_insn(insn)) { 20651 int stack_off = -stack_depth - 8; 20652 20653 stack_depth_extra = 8; 20654 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off); 20655 if (insn->off >= 0) 20656 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2); 20657 else 20658 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1); 20659 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1); 20660 insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off); 20661 cnt = 4; 20662 20663 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20664 if (!new_prog) 20665 return -ENOMEM; 20666 20667 delta += cnt - 1; 20668 env->prog = prog = new_prog; 20669 insn = new_prog->insnsi + i + delta; 20670 goto next_insn; 20671 } 20672 20673 if (insn->code != (BPF_JMP | BPF_CALL)) 20674 goto next_insn; 20675 if (insn->src_reg == BPF_PSEUDO_CALL) 20676 goto next_insn; 20677 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 20678 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 20679 if (ret) 20680 return ret; 20681 if (cnt == 0) 20682 goto next_insn; 20683 20684 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20685 if (!new_prog) 20686 return -ENOMEM; 20687 20688 delta += cnt - 1; 20689 env->prog = prog = new_prog; 20690 insn = new_prog->insnsi + i + delta; 20691 goto next_insn; 20692 } 20693 20694 /* Skip inlining the helper call if the JIT does it. */ 20695 if (bpf_jit_inlines_helper_call(insn->imm)) 20696 goto next_insn; 20697 20698 if (insn->imm == BPF_FUNC_get_route_realm) 20699 prog->dst_needed = 1; 20700 if (insn->imm == BPF_FUNC_get_prandom_u32) 20701 bpf_user_rnd_init_once(); 20702 if (insn->imm == BPF_FUNC_override_return) 20703 prog->kprobe_override = 1; 20704 if (insn->imm == BPF_FUNC_tail_call) { 20705 /* If we tail call into other programs, we 20706 * cannot make any assumptions since they can 20707 * be replaced dynamically during runtime in 20708 * the program array. 20709 */ 20710 prog->cb_access = 1; 20711 if (!allow_tail_call_in_subprogs(env)) 20712 prog->aux->stack_depth = MAX_BPF_STACK; 20713 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 20714 20715 /* mark bpf_tail_call as different opcode to avoid 20716 * conditional branch in the interpreter for every normal 20717 * call and to prevent accidental JITing by JIT compiler 20718 * that doesn't support bpf_tail_call yet 20719 */ 20720 insn->imm = 0; 20721 insn->code = BPF_JMP | BPF_TAIL_CALL; 20722 20723 aux = &env->insn_aux_data[i + delta]; 20724 if (env->bpf_capable && !prog->blinding_requested && 20725 prog->jit_requested && 20726 !bpf_map_key_poisoned(aux) && 20727 !bpf_map_ptr_poisoned(aux) && 20728 !bpf_map_ptr_unpriv(aux)) { 20729 struct bpf_jit_poke_descriptor desc = { 20730 .reason = BPF_POKE_REASON_TAIL_CALL, 20731 .tail_call.map = aux->map_ptr_state.map_ptr, 20732 .tail_call.key = bpf_map_key_immediate(aux), 20733 .insn_idx = i + delta, 20734 }; 20735 20736 ret = bpf_jit_add_poke_descriptor(prog, &desc); 20737 if (ret < 0) { 20738 verbose(env, "adding tail call poke descriptor failed\n"); 20739 return ret; 20740 } 20741 20742 insn->imm = ret + 1; 20743 goto next_insn; 20744 } 20745 20746 if (!bpf_map_ptr_unpriv(aux)) 20747 goto next_insn; 20748 20749 /* instead of changing every JIT dealing with tail_call 20750 * emit two extra insns: 20751 * if (index >= max_entries) goto out; 20752 * index &= array->index_mask; 20753 * to avoid out-of-bounds cpu speculation 20754 */ 20755 if (bpf_map_ptr_poisoned(aux)) { 20756 verbose(env, "tail_call abusing map_ptr\n"); 20757 return -EINVAL; 20758 } 20759 20760 map_ptr = aux->map_ptr_state.map_ptr; 20761 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 20762 map_ptr->max_entries, 2); 20763 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 20764 container_of(map_ptr, 20765 struct bpf_array, 20766 map)->index_mask); 20767 insn_buf[2] = *insn; 20768 cnt = 3; 20769 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20770 if (!new_prog) 20771 return -ENOMEM; 20772 20773 delta += cnt - 1; 20774 env->prog = prog = new_prog; 20775 insn = new_prog->insnsi + i + delta; 20776 goto next_insn; 20777 } 20778 20779 if (insn->imm == BPF_FUNC_timer_set_callback) { 20780 /* The verifier will process callback_fn as many times as necessary 20781 * with different maps and the register states prepared by 20782 * set_timer_callback_state will be accurate. 20783 * 20784 * The following use case is valid: 20785 * map1 is shared by prog1, prog2, prog3. 20786 * prog1 calls bpf_timer_init for some map1 elements 20787 * prog2 calls bpf_timer_set_callback for some map1 elements. 20788 * Those that were not bpf_timer_init-ed will return -EINVAL. 20789 * prog3 calls bpf_timer_start for some map1 elements. 20790 * Those that were not both bpf_timer_init-ed and 20791 * bpf_timer_set_callback-ed will return -EINVAL. 20792 */ 20793 struct bpf_insn ld_addrs[2] = { 20794 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 20795 }; 20796 20797 insn_buf[0] = ld_addrs[0]; 20798 insn_buf[1] = ld_addrs[1]; 20799 insn_buf[2] = *insn; 20800 cnt = 3; 20801 20802 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20803 if (!new_prog) 20804 return -ENOMEM; 20805 20806 delta += cnt - 1; 20807 env->prog = prog = new_prog; 20808 insn = new_prog->insnsi + i + delta; 20809 goto patch_call_imm; 20810 } 20811 20812 if (is_storage_get_function(insn->imm)) { 20813 if (!in_sleepable(env) || 20814 env->insn_aux_data[i + delta].storage_get_func_atomic) 20815 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 20816 else 20817 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 20818 insn_buf[1] = *insn; 20819 cnt = 2; 20820 20821 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20822 if (!new_prog) 20823 return -ENOMEM; 20824 20825 delta += cnt - 1; 20826 env->prog = prog = new_prog; 20827 insn = new_prog->insnsi + i + delta; 20828 goto patch_call_imm; 20829 } 20830 20831 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */ 20832 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) { 20833 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data, 20834 * bpf_mem_alloc() returns a ptr to the percpu data ptr. 20835 */ 20836 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0); 20837 insn_buf[1] = *insn; 20838 cnt = 2; 20839 20840 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20841 if (!new_prog) 20842 return -ENOMEM; 20843 20844 delta += cnt - 1; 20845 env->prog = prog = new_prog; 20846 insn = new_prog->insnsi + i + delta; 20847 goto patch_call_imm; 20848 } 20849 20850 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 20851 * and other inlining handlers are currently limited to 64 bit 20852 * only. 20853 */ 20854 if (prog->jit_requested && BITS_PER_LONG == 64 && 20855 (insn->imm == BPF_FUNC_map_lookup_elem || 20856 insn->imm == BPF_FUNC_map_update_elem || 20857 insn->imm == BPF_FUNC_map_delete_elem || 20858 insn->imm == BPF_FUNC_map_push_elem || 20859 insn->imm == BPF_FUNC_map_pop_elem || 20860 insn->imm == BPF_FUNC_map_peek_elem || 20861 insn->imm == BPF_FUNC_redirect_map || 20862 insn->imm == BPF_FUNC_for_each_map_elem || 20863 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 20864 aux = &env->insn_aux_data[i + delta]; 20865 if (bpf_map_ptr_poisoned(aux)) 20866 goto patch_call_imm; 20867 20868 map_ptr = aux->map_ptr_state.map_ptr; 20869 ops = map_ptr->ops; 20870 if (insn->imm == BPF_FUNC_map_lookup_elem && 20871 ops->map_gen_lookup) { 20872 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 20873 if (cnt == -EOPNOTSUPP) 20874 goto patch_map_ops_generic; 20875 if (cnt <= 0 || cnt >= INSN_BUF_SIZE) { 20876 verbose(env, "bpf verifier is misconfigured\n"); 20877 return -EINVAL; 20878 } 20879 20880 new_prog = bpf_patch_insn_data(env, i + delta, 20881 insn_buf, cnt); 20882 if (!new_prog) 20883 return -ENOMEM; 20884 20885 delta += cnt - 1; 20886 env->prog = prog = new_prog; 20887 insn = new_prog->insnsi + i + delta; 20888 goto next_insn; 20889 } 20890 20891 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 20892 (void *(*)(struct bpf_map *map, void *key))NULL)); 20893 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 20894 (long (*)(struct bpf_map *map, void *key))NULL)); 20895 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 20896 (long (*)(struct bpf_map *map, void *key, void *value, 20897 u64 flags))NULL)); 20898 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 20899 (long (*)(struct bpf_map *map, void *value, 20900 u64 flags))NULL)); 20901 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 20902 (long (*)(struct bpf_map *map, void *value))NULL)); 20903 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 20904 (long (*)(struct bpf_map *map, void *value))NULL)); 20905 BUILD_BUG_ON(!__same_type(ops->map_redirect, 20906 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 20907 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 20908 (long (*)(struct bpf_map *map, 20909 bpf_callback_t callback_fn, 20910 void *callback_ctx, 20911 u64 flags))NULL)); 20912 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 20913 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 20914 20915 patch_map_ops_generic: 20916 switch (insn->imm) { 20917 case BPF_FUNC_map_lookup_elem: 20918 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 20919 goto next_insn; 20920 case BPF_FUNC_map_update_elem: 20921 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 20922 goto next_insn; 20923 case BPF_FUNC_map_delete_elem: 20924 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 20925 goto next_insn; 20926 case BPF_FUNC_map_push_elem: 20927 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 20928 goto next_insn; 20929 case BPF_FUNC_map_pop_elem: 20930 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 20931 goto next_insn; 20932 case BPF_FUNC_map_peek_elem: 20933 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 20934 goto next_insn; 20935 case BPF_FUNC_redirect_map: 20936 insn->imm = BPF_CALL_IMM(ops->map_redirect); 20937 goto next_insn; 20938 case BPF_FUNC_for_each_map_elem: 20939 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 20940 goto next_insn; 20941 case BPF_FUNC_map_lookup_percpu_elem: 20942 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 20943 goto next_insn; 20944 } 20945 20946 goto patch_call_imm; 20947 } 20948 20949 /* Implement bpf_jiffies64 inline. */ 20950 if (prog->jit_requested && BITS_PER_LONG == 64 && 20951 insn->imm == BPF_FUNC_jiffies64) { 20952 struct bpf_insn ld_jiffies_addr[2] = { 20953 BPF_LD_IMM64(BPF_REG_0, 20954 (unsigned long)&jiffies), 20955 }; 20956 20957 insn_buf[0] = ld_jiffies_addr[0]; 20958 insn_buf[1] = ld_jiffies_addr[1]; 20959 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 20960 BPF_REG_0, 0); 20961 cnt = 3; 20962 20963 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 20964 cnt); 20965 if (!new_prog) 20966 return -ENOMEM; 20967 20968 delta += cnt - 1; 20969 env->prog = prog = new_prog; 20970 insn = new_prog->insnsi + i + delta; 20971 goto next_insn; 20972 } 20973 20974 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML) 20975 /* Implement bpf_get_smp_processor_id() inline. */ 20976 if (insn->imm == BPF_FUNC_get_smp_processor_id && 20977 verifier_inlines_helper_call(env, insn->imm)) { 20978 /* BPF_FUNC_get_smp_processor_id inlining is an 20979 * optimization, so if pcpu_hot.cpu_number is ever 20980 * changed in some incompatible and hard to support 20981 * way, it's fine to back out this inlining logic 20982 */ 20983 insn_buf[0] = BPF_MOV32_IMM(BPF_REG_0, (u32)(unsigned long)&pcpu_hot.cpu_number); 20984 insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0); 20985 insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0); 20986 cnt = 3; 20987 20988 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20989 if (!new_prog) 20990 return -ENOMEM; 20991 20992 delta += cnt - 1; 20993 env->prog = prog = new_prog; 20994 insn = new_prog->insnsi + i + delta; 20995 goto next_insn; 20996 } 20997 #endif 20998 /* Implement bpf_get_func_arg inline. */ 20999 if (prog_type == BPF_PROG_TYPE_TRACING && 21000 insn->imm == BPF_FUNC_get_func_arg) { 21001 /* Load nr_args from ctx - 8 */ 21002 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 21003 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 21004 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 21005 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 21006 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 21007 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 21008 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 21009 insn_buf[7] = BPF_JMP_A(1); 21010 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 21011 cnt = 9; 21012 21013 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21014 if (!new_prog) 21015 return -ENOMEM; 21016 21017 delta += cnt - 1; 21018 env->prog = prog = new_prog; 21019 insn = new_prog->insnsi + i + delta; 21020 goto next_insn; 21021 } 21022 21023 /* Implement bpf_get_func_ret inline. */ 21024 if (prog_type == BPF_PROG_TYPE_TRACING && 21025 insn->imm == BPF_FUNC_get_func_ret) { 21026 if (eatype == BPF_TRACE_FEXIT || 21027 eatype == BPF_MODIFY_RETURN) { 21028 /* Load nr_args from ctx - 8 */ 21029 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 21030 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 21031 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 21032 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 21033 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 21034 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 21035 cnt = 6; 21036 } else { 21037 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 21038 cnt = 1; 21039 } 21040 21041 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21042 if (!new_prog) 21043 return -ENOMEM; 21044 21045 delta += cnt - 1; 21046 env->prog = prog = new_prog; 21047 insn = new_prog->insnsi + i + delta; 21048 goto next_insn; 21049 } 21050 21051 /* Implement get_func_arg_cnt inline. */ 21052 if (prog_type == BPF_PROG_TYPE_TRACING && 21053 insn->imm == BPF_FUNC_get_func_arg_cnt) { 21054 /* Load nr_args from ctx - 8 */ 21055 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 21056 21057 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 21058 if (!new_prog) 21059 return -ENOMEM; 21060 21061 env->prog = prog = new_prog; 21062 insn = new_prog->insnsi + i + delta; 21063 goto next_insn; 21064 } 21065 21066 /* Implement bpf_get_func_ip inline. */ 21067 if (prog_type == BPF_PROG_TYPE_TRACING && 21068 insn->imm == BPF_FUNC_get_func_ip) { 21069 /* Load IP address from ctx - 16 */ 21070 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 21071 21072 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 21073 if (!new_prog) 21074 return -ENOMEM; 21075 21076 env->prog = prog = new_prog; 21077 insn = new_prog->insnsi + i + delta; 21078 goto next_insn; 21079 } 21080 21081 /* Implement bpf_get_branch_snapshot inline. */ 21082 if (IS_ENABLED(CONFIG_PERF_EVENTS) && 21083 prog->jit_requested && BITS_PER_LONG == 64 && 21084 insn->imm == BPF_FUNC_get_branch_snapshot) { 21085 /* We are dealing with the following func protos: 21086 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags); 21087 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt); 21088 */ 21089 const u32 br_entry_size = sizeof(struct perf_branch_entry); 21090 21091 /* struct perf_branch_entry is part of UAPI and is 21092 * used as an array element, so extremely unlikely to 21093 * ever grow or shrink 21094 */ 21095 BUILD_BUG_ON(br_entry_size != 24); 21096 21097 /* if (unlikely(flags)) return -EINVAL */ 21098 insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7); 21099 21100 /* Transform size (bytes) into number of entries (cnt = size / 24). 21101 * But to avoid expensive division instruction, we implement 21102 * divide-by-3 through multiplication, followed by further 21103 * division by 8 through 3-bit right shift. 21104 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr., 21105 * p. 227, chapter "Unsigned Division by 3" for details and proofs. 21106 * 21107 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab. 21108 */ 21109 insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab); 21110 insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0); 21111 insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36); 21112 21113 /* call perf_snapshot_branch_stack implementation */ 21114 insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack)); 21115 /* if (entry_cnt == 0) return -ENOENT */ 21116 insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4); 21117 /* return entry_cnt * sizeof(struct perf_branch_entry) */ 21118 insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size); 21119 insn_buf[7] = BPF_JMP_A(3); 21120 /* return -EINVAL; */ 21121 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 21122 insn_buf[9] = BPF_JMP_A(1); 21123 /* return -ENOENT; */ 21124 insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT); 21125 cnt = 11; 21126 21127 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21128 if (!new_prog) 21129 return -ENOMEM; 21130 21131 delta += cnt - 1; 21132 env->prog = prog = new_prog; 21133 insn = new_prog->insnsi + i + delta; 21134 continue; 21135 } 21136 21137 /* Implement bpf_kptr_xchg inline */ 21138 if (prog->jit_requested && BITS_PER_LONG == 64 && 21139 insn->imm == BPF_FUNC_kptr_xchg && 21140 bpf_jit_supports_ptr_xchg()) { 21141 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2); 21142 insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0); 21143 cnt = 2; 21144 21145 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21146 if (!new_prog) 21147 return -ENOMEM; 21148 21149 delta += cnt - 1; 21150 env->prog = prog = new_prog; 21151 insn = new_prog->insnsi + i + delta; 21152 goto next_insn; 21153 } 21154 patch_call_imm: 21155 fn = env->ops->get_func_proto(insn->imm, env->prog); 21156 /* all functions that have prototype and verifier allowed 21157 * programs to call them, must be real in-kernel functions 21158 */ 21159 if (!fn->func) { 21160 verbose(env, 21161 "kernel subsystem misconfigured func %s#%d\n", 21162 func_id_name(insn->imm), insn->imm); 21163 return -EFAULT; 21164 } 21165 insn->imm = fn->func - __bpf_call_base; 21166 next_insn: 21167 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 21168 subprogs[cur_subprog].stack_depth += stack_depth_extra; 21169 subprogs[cur_subprog].stack_extra = stack_depth_extra; 21170 cur_subprog++; 21171 stack_depth = subprogs[cur_subprog].stack_depth; 21172 stack_depth_extra = 0; 21173 } 21174 i++; 21175 insn++; 21176 } 21177 21178 env->prog->aux->stack_depth = subprogs[0].stack_depth; 21179 for (i = 0; i < env->subprog_cnt; i++) { 21180 int subprog_start = subprogs[i].start; 21181 int stack_slots = subprogs[i].stack_extra / 8; 21182 21183 if (!stack_slots) 21184 continue; 21185 if (stack_slots > 1) { 21186 verbose(env, "verifier bug: stack_slots supports may_goto only\n"); 21187 return -EFAULT; 21188 } 21189 21190 /* Add ST insn to subprog prologue to init extra stack */ 21191 insn_buf[0] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, 21192 -subprogs[i].stack_depth, BPF_MAX_LOOPS); 21193 /* Copy first actual insn to preserve it */ 21194 insn_buf[1] = env->prog->insnsi[subprog_start]; 21195 21196 new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, 2); 21197 if (!new_prog) 21198 return -ENOMEM; 21199 env->prog = prog = new_prog; 21200 /* 21201 * If may_goto is a first insn of a prog there could be a jmp 21202 * insn that points to it, hence adjust all such jmps to point 21203 * to insn after BPF_ST that inits may_goto count. 21204 * Adjustment will succeed because bpf_patch_insn_data() didn't fail. 21205 */ 21206 WARN_ON(adjust_jmp_off(env->prog, subprog_start, 1)); 21207 } 21208 21209 /* Since poke tab is now finalized, publish aux to tracker. */ 21210 for (i = 0; i < prog->aux->size_poke_tab; i++) { 21211 map_ptr = prog->aux->poke_tab[i].tail_call.map; 21212 if (!map_ptr->ops->map_poke_track || 21213 !map_ptr->ops->map_poke_untrack || 21214 !map_ptr->ops->map_poke_run) { 21215 verbose(env, "bpf verifier is misconfigured\n"); 21216 return -EINVAL; 21217 } 21218 21219 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 21220 if (ret < 0) { 21221 verbose(env, "tracking tail call prog failed\n"); 21222 return ret; 21223 } 21224 } 21225 21226 sort_kfunc_descs_by_imm_off(env->prog); 21227 21228 return 0; 21229 } 21230 21231 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 21232 int position, 21233 s32 stack_base, 21234 u32 callback_subprogno, 21235 u32 *total_cnt) 21236 { 21237 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 21238 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 21239 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 21240 int reg_loop_max = BPF_REG_6; 21241 int reg_loop_cnt = BPF_REG_7; 21242 int reg_loop_ctx = BPF_REG_8; 21243 21244 struct bpf_insn *insn_buf = env->insn_buf; 21245 struct bpf_prog *new_prog; 21246 u32 callback_start; 21247 u32 call_insn_offset; 21248 s32 callback_offset; 21249 u32 cnt = 0; 21250 21251 /* This represents an inlined version of bpf_iter.c:bpf_loop, 21252 * be careful to modify this code in sync. 21253 */ 21254 21255 /* Return error and jump to the end of the patch if 21256 * expected number of iterations is too big. 21257 */ 21258 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2); 21259 insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG); 21260 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16); 21261 /* spill R6, R7, R8 to use these as loop vars */ 21262 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset); 21263 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset); 21264 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset); 21265 /* initialize loop vars */ 21266 insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1); 21267 insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0); 21268 insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3); 21269 /* loop header, 21270 * if reg_loop_cnt >= reg_loop_max skip the loop body 21271 */ 21272 insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5); 21273 /* callback call, 21274 * correct callback offset would be set after patching 21275 */ 21276 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt); 21277 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx); 21278 insn_buf[cnt++] = BPF_CALL_REL(0); 21279 /* increment loop counter */ 21280 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1); 21281 /* jump to loop header if callback returned 0 */ 21282 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6); 21283 /* return value of bpf_loop, 21284 * set R0 to the number of iterations 21285 */ 21286 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt); 21287 /* restore original values of R6, R7, R8 */ 21288 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset); 21289 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset); 21290 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset); 21291 21292 *total_cnt = cnt; 21293 new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt); 21294 if (!new_prog) 21295 return new_prog; 21296 21297 /* callback start is known only after patching */ 21298 callback_start = env->subprog_info[callback_subprogno].start; 21299 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 21300 call_insn_offset = position + 12; 21301 callback_offset = callback_start - call_insn_offset - 1; 21302 new_prog->insnsi[call_insn_offset].imm = callback_offset; 21303 21304 return new_prog; 21305 } 21306 21307 static bool is_bpf_loop_call(struct bpf_insn *insn) 21308 { 21309 return insn->code == (BPF_JMP | BPF_CALL) && 21310 insn->src_reg == 0 && 21311 insn->imm == BPF_FUNC_loop; 21312 } 21313 21314 /* For all sub-programs in the program (including main) check 21315 * insn_aux_data to see if there are bpf_loop calls that require 21316 * inlining. If such calls are found the calls are replaced with a 21317 * sequence of instructions produced by `inline_bpf_loop` function and 21318 * subprog stack_depth is increased by the size of 3 registers. 21319 * This stack space is used to spill values of the R6, R7, R8. These 21320 * registers are used to store the loop bound, counter and context 21321 * variables. 21322 */ 21323 static int optimize_bpf_loop(struct bpf_verifier_env *env) 21324 { 21325 struct bpf_subprog_info *subprogs = env->subprog_info; 21326 int i, cur_subprog = 0, cnt, delta = 0; 21327 struct bpf_insn *insn = env->prog->insnsi; 21328 int insn_cnt = env->prog->len; 21329 u16 stack_depth = subprogs[cur_subprog].stack_depth; 21330 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 21331 u16 stack_depth_extra = 0; 21332 21333 for (i = 0; i < insn_cnt; i++, insn++) { 21334 struct bpf_loop_inline_state *inline_state = 21335 &env->insn_aux_data[i + delta].loop_inline_state; 21336 21337 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 21338 struct bpf_prog *new_prog; 21339 21340 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 21341 new_prog = inline_bpf_loop(env, 21342 i + delta, 21343 -(stack_depth + stack_depth_extra), 21344 inline_state->callback_subprogno, 21345 &cnt); 21346 if (!new_prog) 21347 return -ENOMEM; 21348 21349 delta += cnt - 1; 21350 env->prog = new_prog; 21351 insn = new_prog->insnsi + i + delta; 21352 } 21353 21354 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 21355 subprogs[cur_subprog].stack_depth += stack_depth_extra; 21356 cur_subprog++; 21357 stack_depth = subprogs[cur_subprog].stack_depth; 21358 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 21359 stack_depth_extra = 0; 21360 } 21361 } 21362 21363 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 21364 21365 return 0; 21366 } 21367 21368 /* Remove unnecessary spill/fill pairs, members of fastcall pattern, 21369 * adjust subprograms stack depth when possible. 21370 */ 21371 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env) 21372 { 21373 struct bpf_subprog_info *subprog = env->subprog_info; 21374 struct bpf_insn_aux_data *aux = env->insn_aux_data; 21375 struct bpf_insn *insn = env->prog->insnsi; 21376 int insn_cnt = env->prog->len; 21377 u32 spills_num; 21378 bool modified = false; 21379 int i, j; 21380 21381 for (i = 0; i < insn_cnt; i++, insn++) { 21382 if (aux[i].fastcall_spills_num > 0) { 21383 spills_num = aux[i].fastcall_spills_num; 21384 /* NOPs would be removed by opt_remove_nops() */ 21385 for (j = 1; j <= spills_num; ++j) { 21386 *(insn - j) = NOP; 21387 *(insn + j) = NOP; 21388 } 21389 modified = true; 21390 } 21391 if ((subprog + 1)->start == i + 1) { 21392 if (modified && !subprog->keep_fastcall_stack) 21393 subprog->stack_depth = -subprog->fastcall_stack_off; 21394 subprog++; 21395 modified = false; 21396 } 21397 } 21398 21399 return 0; 21400 } 21401 21402 static void free_states(struct bpf_verifier_env *env) 21403 { 21404 struct bpf_verifier_state_list *sl, *sln; 21405 int i; 21406 21407 sl = env->free_list; 21408 while (sl) { 21409 sln = sl->next; 21410 free_verifier_state(&sl->state, false); 21411 kfree(sl); 21412 sl = sln; 21413 } 21414 env->free_list = NULL; 21415 21416 if (!env->explored_states) 21417 return; 21418 21419 for (i = 0; i < state_htab_size(env); i++) { 21420 sl = env->explored_states[i]; 21421 21422 while (sl) { 21423 sln = sl->next; 21424 free_verifier_state(&sl->state, false); 21425 kfree(sl); 21426 sl = sln; 21427 } 21428 env->explored_states[i] = NULL; 21429 } 21430 } 21431 21432 static int do_check_common(struct bpf_verifier_env *env, int subprog) 21433 { 21434 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 21435 struct bpf_subprog_info *sub = subprog_info(env, subprog); 21436 struct bpf_verifier_state *state; 21437 struct bpf_reg_state *regs; 21438 int ret, i; 21439 21440 env->prev_linfo = NULL; 21441 env->pass_cnt++; 21442 21443 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 21444 if (!state) 21445 return -ENOMEM; 21446 state->curframe = 0; 21447 state->speculative = false; 21448 state->branches = 1; 21449 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 21450 if (!state->frame[0]) { 21451 kfree(state); 21452 return -ENOMEM; 21453 } 21454 env->cur_state = state; 21455 init_func_state(env, state->frame[0], 21456 BPF_MAIN_FUNC /* callsite */, 21457 0 /* frameno */, 21458 subprog); 21459 state->first_insn_idx = env->subprog_info[subprog].start; 21460 state->last_insn_idx = -1; 21461 21462 regs = state->frame[state->curframe]->regs; 21463 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 21464 const char *sub_name = subprog_name(env, subprog); 21465 struct bpf_subprog_arg_info *arg; 21466 struct bpf_reg_state *reg; 21467 21468 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 21469 ret = btf_prepare_func_args(env, subprog); 21470 if (ret) 21471 goto out; 21472 21473 if (subprog_is_exc_cb(env, subprog)) { 21474 state->frame[0]->in_exception_callback_fn = true; 21475 /* We have already ensured that the callback returns an integer, just 21476 * like all global subprogs. We need to determine it only has a single 21477 * scalar argument. 21478 */ 21479 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 21480 verbose(env, "exception cb only supports single integer argument\n"); 21481 ret = -EINVAL; 21482 goto out; 21483 } 21484 } 21485 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) { 21486 arg = &sub->args[i - BPF_REG_1]; 21487 reg = ®s[i]; 21488 21489 if (arg->arg_type == ARG_PTR_TO_CTX) { 21490 reg->type = PTR_TO_CTX; 21491 mark_reg_known_zero(env, regs, i); 21492 } else if (arg->arg_type == ARG_ANYTHING) { 21493 reg->type = SCALAR_VALUE; 21494 mark_reg_unknown(env, regs, i); 21495 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 21496 /* assume unspecial LOCAL dynptr type */ 21497 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen); 21498 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 21499 reg->type = PTR_TO_MEM; 21500 if (arg->arg_type & PTR_MAYBE_NULL) 21501 reg->type |= PTR_MAYBE_NULL; 21502 mark_reg_known_zero(env, regs, i); 21503 reg->mem_size = arg->mem_size; 21504 reg->id = ++env->id_gen; 21505 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 21506 reg->type = PTR_TO_BTF_ID; 21507 if (arg->arg_type & PTR_MAYBE_NULL) 21508 reg->type |= PTR_MAYBE_NULL; 21509 if (arg->arg_type & PTR_UNTRUSTED) 21510 reg->type |= PTR_UNTRUSTED; 21511 if (arg->arg_type & PTR_TRUSTED) 21512 reg->type |= PTR_TRUSTED; 21513 mark_reg_known_zero(env, regs, i); 21514 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */ 21515 reg->btf_id = arg->btf_id; 21516 reg->id = ++env->id_gen; 21517 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 21518 /* caller can pass either PTR_TO_ARENA or SCALAR */ 21519 mark_reg_unknown(env, regs, i); 21520 } else { 21521 WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n", 21522 i - BPF_REG_1, arg->arg_type); 21523 ret = -EFAULT; 21524 goto out; 21525 } 21526 } 21527 } else { 21528 /* if main BPF program has associated BTF info, validate that 21529 * it's matching expected signature, and otherwise mark BTF 21530 * info for main program as unreliable 21531 */ 21532 if (env->prog->aux->func_info_aux) { 21533 ret = btf_prepare_func_args(env, 0); 21534 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) 21535 env->prog->aux->func_info_aux[0].unreliable = true; 21536 } 21537 21538 /* 1st arg to a function */ 21539 regs[BPF_REG_1].type = PTR_TO_CTX; 21540 mark_reg_known_zero(env, regs, BPF_REG_1); 21541 } 21542 21543 ret = do_check(env); 21544 out: 21545 /* check for NULL is necessary, since cur_state can be freed inside 21546 * do_check() under memory pressure. 21547 */ 21548 if (env->cur_state) { 21549 free_verifier_state(env->cur_state, true); 21550 env->cur_state = NULL; 21551 } 21552 while (!pop_stack(env, NULL, NULL, false)); 21553 if (!ret && pop_log) 21554 bpf_vlog_reset(&env->log, 0); 21555 free_states(env); 21556 return ret; 21557 } 21558 21559 /* Lazily verify all global functions based on their BTF, if they are called 21560 * from main BPF program or any of subprograms transitively. 21561 * BPF global subprogs called from dead code are not validated. 21562 * All callable global functions must pass verification. 21563 * Otherwise the whole program is rejected. 21564 * Consider: 21565 * int bar(int); 21566 * int foo(int f) 21567 * { 21568 * return bar(f); 21569 * } 21570 * int bar(int b) 21571 * { 21572 * ... 21573 * } 21574 * foo() will be verified first for R1=any_scalar_value. During verification it 21575 * will be assumed that bar() already verified successfully and call to bar() 21576 * from foo() will be checked for type match only. Later bar() will be verified 21577 * independently to check that it's safe for R1=any_scalar_value. 21578 */ 21579 static int do_check_subprogs(struct bpf_verifier_env *env) 21580 { 21581 struct bpf_prog_aux *aux = env->prog->aux; 21582 struct bpf_func_info_aux *sub_aux; 21583 int i, ret, new_cnt; 21584 21585 if (!aux->func_info) 21586 return 0; 21587 21588 /* exception callback is presumed to be always called */ 21589 if (env->exception_callback_subprog) 21590 subprog_aux(env, env->exception_callback_subprog)->called = true; 21591 21592 again: 21593 new_cnt = 0; 21594 for (i = 1; i < env->subprog_cnt; i++) { 21595 if (!subprog_is_global(env, i)) 21596 continue; 21597 21598 sub_aux = subprog_aux(env, i); 21599 if (!sub_aux->called || sub_aux->verified) 21600 continue; 21601 21602 env->insn_idx = env->subprog_info[i].start; 21603 WARN_ON_ONCE(env->insn_idx == 0); 21604 ret = do_check_common(env, i); 21605 if (ret) { 21606 return ret; 21607 } else if (env->log.level & BPF_LOG_LEVEL) { 21608 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 21609 i, subprog_name(env, i)); 21610 } 21611 21612 /* We verified new global subprog, it might have called some 21613 * more global subprogs that we haven't verified yet, so we 21614 * need to do another pass over subprogs to verify those. 21615 */ 21616 sub_aux->verified = true; 21617 new_cnt++; 21618 } 21619 21620 /* We can't loop forever as we verify at least one global subprog on 21621 * each pass. 21622 */ 21623 if (new_cnt) 21624 goto again; 21625 21626 return 0; 21627 } 21628 21629 static int do_check_main(struct bpf_verifier_env *env) 21630 { 21631 int ret; 21632 21633 env->insn_idx = 0; 21634 ret = do_check_common(env, 0); 21635 if (!ret) 21636 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 21637 return ret; 21638 } 21639 21640 21641 static void print_verification_stats(struct bpf_verifier_env *env) 21642 { 21643 int i; 21644 21645 if (env->log.level & BPF_LOG_STATS) { 21646 verbose(env, "verification time %lld usec\n", 21647 div_u64(env->verification_time, 1000)); 21648 verbose(env, "stack depth "); 21649 for (i = 0; i < env->subprog_cnt; i++) { 21650 u32 depth = env->subprog_info[i].stack_depth; 21651 21652 verbose(env, "%d", depth); 21653 if (i + 1 < env->subprog_cnt) 21654 verbose(env, "+"); 21655 } 21656 verbose(env, "\n"); 21657 } 21658 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 21659 "total_states %d peak_states %d mark_read %d\n", 21660 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 21661 env->max_states_per_insn, env->total_states, 21662 env->peak_states, env->longest_mark_read_walk); 21663 } 21664 21665 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 21666 { 21667 const struct btf_type *t, *func_proto; 21668 const struct bpf_struct_ops_desc *st_ops_desc; 21669 const struct bpf_struct_ops *st_ops; 21670 const struct btf_member *member; 21671 struct bpf_prog *prog = env->prog; 21672 u32 btf_id, member_idx; 21673 struct btf *btf; 21674 const char *mname; 21675 int err; 21676 21677 if (!prog->gpl_compatible) { 21678 verbose(env, "struct ops programs must have a GPL compatible license\n"); 21679 return -EINVAL; 21680 } 21681 21682 if (!prog->aux->attach_btf_id) 21683 return -ENOTSUPP; 21684 21685 btf = prog->aux->attach_btf; 21686 if (btf_is_module(btf)) { 21687 /* Make sure st_ops is valid through the lifetime of env */ 21688 env->attach_btf_mod = btf_try_get_module(btf); 21689 if (!env->attach_btf_mod) { 21690 verbose(env, "struct_ops module %s is not found\n", 21691 btf_get_name(btf)); 21692 return -ENOTSUPP; 21693 } 21694 } 21695 21696 btf_id = prog->aux->attach_btf_id; 21697 st_ops_desc = bpf_struct_ops_find(btf, btf_id); 21698 if (!st_ops_desc) { 21699 verbose(env, "attach_btf_id %u is not a supported struct\n", 21700 btf_id); 21701 return -ENOTSUPP; 21702 } 21703 st_ops = st_ops_desc->st_ops; 21704 21705 t = st_ops_desc->type; 21706 member_idx = prog->expected_attach_type; 21707 if (member_idx >= btf_type_vlen(t)) { 21708 verbose(env, "attach to invalid member idx %u of struct %s\n", 21709 member_idx, st_ops->name); 21710 return -EINVAL; 21711 } 21712 21713 member = &btf_type_member(t)[member_idx]; 21714 mname = btf_name_by_offset(btf, member->name_off); 21715 func_proto = btf_type_resolve_func_ptr(btf, member->type, 21716 NULL); 21717 if (!func_proto) { 21718 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 21719 mname, member_idx, st_ops->name); 21720 return -EINVAL; 21721 } 21722 21723 err = bpf_struct_ops_supported(st_ops, __btf_member_bit_offset(t, member) / 8); 21724 if (err) { 21725 verbose(env, "attach to unsupported member %s of struct %s\n", 21726 mname, st_ops->name); 21727 return err; 21728 } 21729 21730 if (st_ops->check_member) { 21731 err = st_ops->check_member(t, member, prog); 21732 21733 if (err) { 21734 verbose(env, "attach to unsupported member %s of struct %s\n", 21735 mname, st_ops->name); 21736 return err; 21737 } 21738 } 21739 21740 /* btf_ctx_access() used this to provide argument type info */ 21741 prog->aux->ctx_arg_info = 21742 st_ops_desc->arg_info[member_idx].info; 21743 prog->aux->ctx_arg_info_size = 21744 st_ops_desc->arg_info[member_idx].cnt; 21745 21746 prog->aux->attach_func_proto = func_proto; 21747 prog->aux->attach_func_name = mname; 21748 env->ops = st_ops->verifier_ops; 21749 21750 return 0; 21751 } 21752 #define SECURITY_PREFIX "security_" 21753 21754 static int check_attach_modify_return(unsigned long addr, const char *func_name) 21755 { 21756 if (within_error_injection_list(addr) || 21757 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 21758 return 0; 21759 21760 return -EINVAL; 21761 } 21762 21763 /* list of non-sleepable functions that are otherwise on 21764 * ALLOW_ERROR_INJECTION list 21765 */ 21766 BTF_SET_START(btf_non_sleepable_error_inject) 21767 /* Three functions below can be called from sleepable and non-sleepable context. 21768 * Assume non-sleepable from bpf safety point of view. 21769 */ 21770 BTF_ID(func, __filemap_add_folio) 21771 #ifdef CONFIG_FAIL_PAGE_ALLOC 21772 BTF_ID(func, should_fail_alloc_page) 21773 #endif 21774 #ifdef CONFIG_FAILSLAB 21775 BTF_ID(func, should_failslab) 21776 #endif 21777 BTF_SET_END(btf_non_sleepable_error_inject) 21778 21779 static int check_non_sleepable_error_inject(u32 btf_id) 21780 { 21781 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 21782 } 21783 21784 int bpf_check_attach_target(struct bpf_verifier_log *log, 21785 const struct bpf_prog *prog, 21786 const struct bpf_prog *tgt_prog, 21787 u32 btf_id, 21788 struct bpf_attach_target_info *tgt_info) 21789 { 21790 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 21791 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 21792 const char prefix[] = "btf_trace_"; 21793 int ret = 0, subprog = -1, i; 21794 const struct btf_type *t; 21795 bool conservative = true; 21796 const char *tname; 21797 struct btf *btf; 21798 long addr = 0; 21799 struct module *mod = NULL; 21800 21801 if (!btf_id) { 21802 bpf_log(log, "Tracing programs must provide btf_id\n"); 21803 return -EINVAL; 21804 } 21805 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 21806 if (!btf) { 21807 bpf_log(log, 21808 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 21809 return -EINVAL; 21810 } 21811 t = btf_type_by_id(btf, btf_id); 21812 if (!t) { 21813 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 21814 return -EINVAL; 21815 } 21816 tname = btf_name_by_offset(btf, t->name_off); 21817 if (!tname) { 21818 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 21819 return -EINVAL; 21820 } 21821 if (tgt_prog) { 21822 struct bpf_prog_aux *aux = tgt_prog->aux; 21823 21824 if (bpf_prog_is_dev_bound(prog->aux) && 21825 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 21826 bpf_log(log, "Target program bound device mismatch"); 21827 return -EINVAL; 21828 } 21829 21830 for (i = 0; i < aux->func_info_cnt; i++) 21831 if (aux->func_info[i].type_id == btf_id) { 21832 subprog = i; 21833 break; 21834 } 21835 if (subprog == -1) { 21836 bpf_log(log, "Subprog %s doesn't exist\n", tname); 21837 return -EINVAL; 21838 } 21839 if (aux->func && aux->func[subprog]->aux->exception_cb) { 21840 bpf_log(log, 21841 "%s programs cannot attach to exception callback\n", 21842 prog_extension ? "Extension" : "FENTRY/FEXIT"); 21843 return -EINVAL; 21844 } 21845 conservative = aux->func_info_aux[subprog].unreliable; 21846 if (prog_extension) { 21847 if (conservative) { 21848 bpf_log(log, 21849 "Cannot replace static functions\n"); 21850 return -EINVAL; 21851 } 21852 if (!prog->jit_requested) { 21853 bpf_log(log, 21854 "Extension programs should be JITed\n"); 21855 return -EINVAL; 21856 } 21857 } 21858 if (!tgt_prog->jited) { 21859 bpf_log(log, "Can attach to only JITed progs\n"); 21860 return -EINVAL; 21861 } 21862 if (prog_tracing) { 21863 if (aux->attach_tracing_prog) { 21864 /* 21865 * Target program is an fentry/fexit which is already attached 21866 * to another tracing program. More levels of nesting 21867 * attachment are not allowed. 21868 */ 21869 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 21870 return -EINVAL; 21871 } 21872 } else if (tgt_prog->type == prog->type) { 21873 /* 21874 * To avoid potential call chain cycles, prevent attaching of a 21875 * program extension to another extension. It's ok to attach 21876 * fentry/fexit to extension program. 21877 */ 21878 bpf_log(log, "Cannot recursively attach\n"); 21879 return -EINVAL; 21880 } 21881 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 21882 prog_extension && 21883 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 21884 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 21885 /* Program extensions can extend all program types 21886 * except fentry/fexit. The reason is the following. 21887 * The fentry/fexit programs are used for performance 21888 * analysis, stats and can be attached to any program 21889 * type. When extension program is replacing XDP function 21890 * it is necessary to allow performance analysis of all 21891 * functions. Both original XDP program and its program 21892 * extension. Hence attaching fentry/fexit to 21893 * BPF_PROG_TYPE_EXT is allowed. If extending of 21894 * fentry/fexit was allowed it would be possible to create 21895 * long call chain fentry->extension->fentry->extension 21896 * beyond reasonable stack size. Hence extending fentry 21897 * is not allowed. 21898 */ 21899 bpf_log(log, "Cannot extend fentry/fexit\n"); 21900 return -EINVAL; 21901 } 21902 } else { 21903 if (prog_extension) { 21904 bpf_log(log, "Cannot replace kernel functions\n"); 21905 return -EINVAL; 21906 } 21907 } 21908 21909 switch (prog->expected_attach_type) { 21910 case BPF_TRACE_RAW_TP: 21911 if (tgt_prog) { 21912 bpf_log(log, 21913 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 21914 return -EINVAL; 21915 } 21916 if (!btf_type_is_typedef(t)) { 21917 bpf_log(log, "attach_btf_id %u is not a typedef\n", 21918 btf_id); 21919 return -EINVAL; 21920 } 21921 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 21922 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 21923 btf_id, tname); 21924 return -EINVAL; 21925 } 21926 tname += sizeof(prefix) - 1; 21927 t = btf_type_by_id(btf, t->type); 21928 if (!btf_type_is_ptr(t)) 21929 /* should never happen in valid vmlinux build */ 21930 return -EINVAL; 21931 t = btf_type_by_id(btf, t->type); 21932 if (!btf_type_is_func_proto(t)) 21933 /* should never happen in valid vmlinux build */ 21934 return -EINVAL; 21935 21936 break; 21937 case BPF_TRACE_ITER: 21938 if (!btf_type_is_func(t)) { 21939 bpf_log(log, "attach_btf_id %u is not a function\n", 21940 btf_id); 21941 return -EINVAL; 21942 } 21943 t = btf_type_by_id(btf, t->type); 21944 if (!btf_type_is_func_proto(t)) 21945 return -EINVAL; 21946 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 21947 if (ret) 21948 return ret; 21949 break; 21950 default: 21951 if (!prog_extension) 21952 return -EINVAL; 21953 fallthrough; 21954 case BPF_MODIFY_RETURN: 21955 case BPF_LSM_MAC: 21956 case BPF_LSM_CGROUP: 21957 case BPF_TRACE_FENTRY: 21958 case BPF_TRACE_FEXIT: 21959 if (!btf_type_is_func(t)) { 21960 bpf_log(log, "attach_btf_id %u is not a function\n", 21961 btf_id); 21962 return -EINVAL; 21963 } 21964 if (prog_extension && 21965 btf_check_type_match(log, prog, btf, t)) 21966 return -EINVAL; 21967 t = btf_type_by_id(btf, t->type); 21968 if (!btf_type_is_func_proto(t)) 21969 return -EINVAL; 21970 21971 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 21972 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 21973 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 21974 return -EINVAL; 21975 21976 if (tgt_prog && conservative) 21977 t = NULL; 21978 21979 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 21980 if (ret < 0) 21981 return ret; 21982 21983 if (tgt_prog) { 21984 if (subprog == 0) 21985 addr = (long) tgt_prog->bpf_func; 21986 else 21987 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 21988 } else { 21989 if (btf_is_module(btf)) { 21990 mod = btf_try_get_module(btf); 21991 if (mod) 21992 addr = find_kallsyms_symbol_value(mod, tname); 21993 else 21994 addr = 0; 21995 } else { 21996 addr = kallsyms_lookup_name(tname); 21997 } 21998 if (!addr) { 21999 module_put(mod); 22000 bpf_log(log, 22001 "The address of function %s cannot be found\n", 22002 tname); 22003 return -ENOENT; 22004 } 22005 } 22006 22007 if (prog->sleepable) { 22008 ret = -EINVAL; 22009 switch (prog->type) { 22010 case BPF_PROG_TYPE_TRACING: 22011 22012 /* fentry/fexit/fmod_ret progs can be sleepable if they are 22013 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 22014 */ 22015 if (!check_non_sleepable_error_inject(btf_id) && 22016 within_error_injection_list(addr)) 22017 ret = 0; 22018 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 22019 * in the fmodret id set with the KF_SLEEPABLE flag. 22020 */ 22021 else { 22022 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 22023 prog); 22024 22025 if (flags && (*flags & KF_SLEEPABLE)) 22026 ret = 0; 22027 } 22028 break; 22029 case BPF_PROG_TYPE_LSM: 22030 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 22031 * Only some of them are sleepable. 22032 */ 22033 if (bpf_lsm_is_sleepable_hook(btf_id)) 22034 ret = 0; 22035 break; 22036 default: 22037 break; 22038 } 22039 if (ret) { 22040 module_put(mod); 22041 bpf_log(log, "%s is not sleepable\n", tname); 22042 return ret; 22043 } 22044 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 22045 if (tgt_prog) { 22046 module_put(mod); 22047 bpf_log(log, "can't modify return codes of BPF programs\n"); 22048 return -EINVAL; 22049 } 22050 ret = -EINVAL; 22051 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 22052 !check_attach_modify_return(addr, tname)) 22053 ret = 0; 22054 if (ret) { 22055 module_put(mod); 22056 bpf_log(log, "%s() is not modifiable\n", tname); 22057 return ret; 22058 } 22059 } 22060 22061 break; 22062 } 22063 tgt_info->tgt_addr = addr; 22064 tgt_info->tgt_name = tname; 22065 tgt_info->tgt_type = t; 22066 tgt_info->tgt_mod = mod; 22067 return 0; 22068 } 22069 22070 BTF_SET_START(btf_id_deny) 22071 BTF_ID_UNUSED 22072 #ifdef CONFIG_SMP 22073 BTF_ID(func, migrate_disable) 22074 BTF_ID(func, migrate_enable) 22075 #endif 22076 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 22077 BTF_ID(func, rcu_read_unlock_strict) 22078 #endif 22079 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 22080 BTF_ID(func, preempt_count_add) 22081 BTF_ID(func, preempt_count_sub) 22082 #endif 22083 #ifdef CONFIG_PREEMPT_RCU 22084 BTF_ID(func, __rcu_read_lock) 22085 BTF_ID(func, __rcu_read_unlock) 22086 #endif 22087 BTF_SET_END(btf_id_deny) 22088 22089 static bool can_be_sleepable(struct bpf_prog *prog) 22090 { 22091 if (prog->type == BPF_PROG_TYPE_TRACING) { 22092 switch (prog->expected_attach_type) { 22093 case BPF_TRACE_FENTRY: 22094 case BPF_TRACE_FEXIT: 22095 case BPF_MODIFY_RETURN: 22096 case BPF_TRACE_ITER: 22097 return true; 22098 default: 22099 return false; 22100 } 22101 } 22102 return prog->type == BPF_PROG_TYPE_LSM || 22103 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 22104 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 22105 } 22106 22107 static int check_attach_btf_id(struct bpf_verifier_env *env) 22108 { 22109 struct bpf_prog *prog = env->prog; 22110 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 22111 struct bpf_attach_target_info tgt_info = {}; 22112 u32 btf_id = prog->aux->attach_btf_id; 22113 struct bpf_trampoline *tr; 22114 int ret; 22115 u64 key; 22116 22117 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 22118 if (prog->sleepable) 22119 /* attach_btf_id checked to be zero already */ 22120 return 0; 22121 verbose(env, "Syscall programs can only be sleepable\n"); 22122 return -EINVAL; 22123 } 22124 22125 if (prog->sleepable && !can_be_sleepable(prog)) { 22126 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 22127 return -EINVAL; 22128 } 22129 22130 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 22131 return check_struct_ops_btf_id(env); 22132 22133 if (prog->type != BPF_PROG_TYPE_TRACING && 22134 prog->type != BPF_PROG_TYPE_LSM && 22135 prog->type != BPF_PROG_TYPE_EXT) 22136 return 0; 22137 22138 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 22139 if (ret) 22140 return ret; 22141 22142 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 22143 /* to make freplace equivalent to their targets, they need to 22144 * inherit env->ops and expected_attach_type for the rest of the 22145 * verification 22146 */ 22147 env->ops = bpf_verifier_ops[tgt_prog->type]; 22148 prog->expected_attach_type = tgt_prog->expected_attach_type; 22149 } 22150 22151 /* store info about the attachment target that will be used later */ 22152 prog->aux->attach_func_proto = tgt_info.tgt_type; 22153 prog->aux->attach_func_name = tgt_info.tgt_name; 22154 prog->aux->mod = tgt_info.tgt_mod; 22155 22156 if (tgt_prog) { 22157 prog->aux->saved_dst_prog_type = tgt_prog->type; 22158 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 22159 } 22160 22161 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 22162 prog->aux->attach_btf_trace = true; 22163 return 0; 22164 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 22165 if (!bpf_iter_prog_supported(prog)) 22166 return -EINVAL; 22167 return 0; 22168 } 22169 22170 if (prog->type == BPF_PROG_TYPE_LSM) { 22171 ret = bpf_lsm_verify_prog(&env->log, prog); 22172 if (ret < 0) 22173 return ret; 22174 } else if (prog->type == BPF_PROG_TYPE_TRACING && 22175 btf_id_set_contains(&btf_id_deny, btf_id)) { 22176 return -EINVAL; 22177 } 22178 22179 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 22180 tr = bpf_trampoline_get(key, &tgt_info); 22181 if (!tr) 22182 return -ENOMEM; 22183 22184 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 22185 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 22186 22187 prog->aux->dst_trampoline = tr; 22188 return 0; 22189 } 22190 22191 struct btf *bpf_get_btf_vmlinux(void) 22192 { 22193 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 22194 mutex_lock(&bpf_verifier_lock); 22195 if (!btf_vmlinux) 22196 btf_vmlinux = btf_parse_vmlinux(); 22197 mutex_unlock(&bpf_verifier_lock); 22198 } 22199 return btf_vmlinux; 22200 } 22201 22202 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 22203 { 22204 u64 start_time = ktime_get_ns(); 22205 struct bpf_verifier_env *env; 22206 int i, len, ret = -EINVAL, err; 22207 u32 log_true_size; 22208 bool is_priv; 22209 22210 /* no program is valid */ 22211 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 22212 return -EINVAL; 22213 22214 /* 'struct bpf_verifier_env' can be global, but since it's not small, 22215 * allocate/free it every time bpf_check() is called 22216 */ 22217 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 22218 if (!env) 22219 return -ENOMEM; 22220 22221 env->bt.env = env; 22222 22223 len = (*prog)->len; 22224 env->insn_aux_data = 22225 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 22226 ret = -ENOMEM; 22227 if (!env->insn_aux_data) 22228 goto err_free_env; 22229 for (i = 0; i < len; i++) 22230 env->insn_aux_data[i].orig_idx = i; 22231 env->prog = *prog; 22232 env->ops = bpf_verifier_ops[env->prog->type]; 22233 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 22234 22235 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 22236 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 22237 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 22238 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 22239 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 22240 22241 bpf_get_btf_vmlinux(); 22242 22243 /* grab the mutex to protect few globals used by verifier */ 22244 if (!is_priv) 22245 mutex_lock(&bpf_verifier_lock); 22246 22247 /* user could have requested verbose verifier output 22248 * and supplied buffer to store the verification trace 22249 */ 22250 ret = bpf_vlog_init(&env->log, attr->log_level, 22251 (char __user *) (unsigned long) attr->log_buf, 22252 attr->log_size); 22253 if (ret) 22254 goto err_unlock; 22255 22256 mark_verifier_state_clean(env); 22257 22258 if (IS_ERR(btf_vmlinux)) { 22259 /* Either gcc or pahole or kernel are broken. */ 22260 verbose(env, "in-kernel BTF is malformed\n"); 22261 ret = PTR_ERR(btf_vmlinux); 22262 goto skip_full_check; 22263 } 22264 22265 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 22266 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 22267 env->strict_alignment = true; 22268 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 22269 env->strict_alignment = false; 22270 22271 if (is_priv) 22272 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 22273 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 22274 22275 env->explored_states = kvcalloc(state_htab_size(env), 22276 sizeof(struct bpf_verifier_state_list *), 22277 GFP_USER); 22278 ret = -ENOMEM; 22279 if (!env->explored_states) 22280 goto skip_full_check; 22281 22282 ret = check_btf_info_early(env, attr, uattr); 22283 if (ret < 0) 22284 goto skip_full_check; 22285 22286 ret = add_subprog_and_kfunc(env); 22287 if (ret < 0) 22288 goto skip_full_check; 22289 22290 ret = check_subprogs(env); 22291 if (ret < 0) 22292 goto skip_full_check; 22293 22294 ret = check_btf_info(env, attr, uattr); 22295 if (ret < 0) 22296 goto skip_full_check; 22297 22298 ret = check_attach_btf_id(env); 22299 if (ret) 22300 goto skip_full_check; 22301 22302 ret = resolve_pseudo_ldimm64(env); 22303 if (ret < 0) 22304 goto skip_full_check; 22305 22306 if (bpf_prog_is_offloaded(env->prog->aux)) { 22307 ret = bpf_prog_offload_verifier_prep(env->prog); 22308 if (ret) 22309 goto skip_full_check; 22310 } 22311 22312 ret = check_cfg(env); 22313 if (ret < 0) 22314 goto skip_full_check; 22315 22316 ret = mark_fastcall_patterns(env); 22317 if (ret < 0) 22318 goto skip_full_check; 22319 22320 ret = do_check_main(env); 22321 ret = ret ?: do_check_subprogs(env); 22322 22323 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 22324 ret = bpf_prog_offload_finalize(env); 22325 22326 skip_full_check: 22327 kvfree(env->explored_states); 22328 22329 /* might decrease stack depth, keep it before passes that 22330 * allocate additional slots. 22331 */ 22332 if (ret == 0) 22333 ret = remove_fastcall_spills_fills(env); 22334 22335 if (ret == 0) 22336 ret = check_max_stack_depth(env); 22337 22338 /* instruction rewrites happen after this point */ 22339 if (ret == 0) 22340 ret = optimize_bpf_loop(env); 22341 22342 if (is_priv) { 22343 if (ret == 0) 22344 opt_hard_wire_dead_code_branches(env); 22345 if (ret == 0) 22346 ret = opt_remove_dead_code(env); 22347 if (ret == 0) 22348 ret = opt_remove_nops(env); 22349 } else { 22350 if (ret == 0) 22351 sanitize_dead_code(env); 22352 } 22353 22354 if (ret == 0) 22355 /* program is valid, convert *(u32*)(ctx + off) accesses */ 22356 ret = convert_ctx_accesses(env); 22357 22358 if (ret == 0) 22359 ret = do_misc_fixups(env); 22360 22361 /* do 32-bit optimization after insn patching has done so those patched 22362 * insns could be handled correctly. 22363 */ 22364 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 22365 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 22366 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 22367 : false; 22368 } 22369 22370 if (ret == 0) 22371 ret = fixup_call_args(env); 22372 22373 env->verification_time = ktime_get_ns() - start_time; 22374 print_verification_stats(env); 22375 env->prog->aux->verified_insns = env->insn_processed; 22376 22377 /* preserve original error even if log finalization is successful */ 22378 err = bpf_vlog_finalize(&env->log, &log_true_size); 22379 if (err) 22380 ret = err; 22381 22382 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 22383 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 22384 &log_true_size, sizeof(log_true_size))) { 22385 ret = -EFAULT; 22386 goto err_release_maps; 22387 } 22388 22389 if (ret) 22390 goto err_release_maps; 22391 22392 if (env->used_map_cnt) { 22393 /* if program passed verifier, update used_maps in bpf_prog_info */ 22394 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 22395 sizeof(env->used_maps[0]), 22396 GFP_KERNEL); 22397 22398 if (!env->prog->aux->used_maps) { 22399 ret = -ENOMEM; 22400 goto err_release_maps; 22401 } 22402 22403 memcpy(env->prog->aux->used_maps, env->used_maps, 22404 sizeof(env->used_maps[0]) * env->used_map_cnt); 22405 env->prog->aux->used_map_cnt = env->used_map_cnt; 22406 } 22407 if (env->used_btf_cnt) { 22408 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 22409 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 22410 sizeof(env->used_btfs[0]), 22411 GFP_KERNEL); 22412 if (!env->prog->aux->used_btfs) { 22413 ret = -ENOMEM; 22414 goto err_release_maps; 22415 } 22416 22417 memcpy(env->prog->aux->used_btfs, env->used_btfs, 22418 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 22419 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 22420 } 22421 if (env->used_map_cnt || env->used_btf_cnt) { 22422 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 22423 * bpf_ld_imm64 instructions 22424 */ 22425 convert_pseudo_ld_imm64(env); 22426 } 22427 22428 adjust_btf_func(env); 22429 22430 err_release_maps: 22431 if (!env->prog->aux->used_maps) 22432 /* if we didn't copy map pointers into bpf_prog_info, release 22433 * them now. Otherwise free_used_maps() will release them. 22434 */ 22435 release_maps(env); 22436 if (!env->prog->aux->used_btfs) 22437 release_btfs(env); 22438 22439 /* extension progs temporarily inherit the attach_type of their targets 22440 for verification purposes, so set it back to zero before returning 22441 */ 22442 if (env->prog->type == BPF_PROG_TYPE_EXT) 22443 env->prog->expected_attach_type = 0; 22444 22445 *prog = env->prog; 22446 22447 module_put(env->attach_btf_mod); 22448 err_unlock: 22449 if (!is_priv) 22450 mutex_unlock(&bpf_verifier_lock); 22451 vfree(env->insn_aux_data); 22452 err_free_env: 22453 kfree(env); 22454 return ret; 22455 } 22456