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 #include <linux/trace_events.h> 32 #include <linux/kallsyms.h> 33 34 #include "disasm.h" 35 36 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 37 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \ 38 [_id] = & _name ## _verifier_ops, 39 #define BPF_MAP_TYPE(_id, _ops) 40 #define BPF_LINK_TYPE(_id, _name) 41 #include <linux/bpf_types.h> 42 #undef BPF_PROG_TYPE 43 #undef BPF_MAP_TYPE 44 #undef BPF_LINK_TYPE 45 }; 46 47 struct bpf_mem_alloc bpf_global_percpu_ma; 48 static bool bpf_global_percpu_ma_set; 49 50 /* bpf_check() is a static code analyzer that walks eBPF program 51 * instruction by instruction and updates register/stack state. 52 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 53 * 54 * The first pass is depth-first-search to check that the program is a DAG. 55 * It rejects the following programs: 56 * - larger than BPF_MAXINSNS insns 57 * - if loop is present (detected via back-edge) 58 * - unreachable insns exist (shouldn't be a forest. program = one function) 59 * - out of bounds or malformed jumps 60 * The second pass is all possible path descent from the 1st insn. 61 * Since it's analyzing all paths through the program, the length of the 62 * analysis is limited to 64k insn, which may be hit even if total number of 63 * insn is less then 4K, but there are too many branches that change stack/regs. 64 * Number of 'branches to be analyzed' is limited to 1k 65 * 66 * On entry to each instruction, each register has a type, and the instruction 67 * changes the types of the registers depending on instruction semantics. 68 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 69 * copied to R1. 70 * 71 * All registers are 64-bit. 72 * R0 - return register 73 * R1-R5 argument passing registers 74 * R6-R9 callee saved registers 75 * R10 - frame pointer read-only 76 * 77 * At the start of BPF program the register R1 contains a pointer to bpf_context 78 * and has type PTR_TO_CTX. 79 * 80 * Verifier tracks arithmetic operations on pointers in case: 81 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 82 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 83 * 1st insn copies R10 (which has FRAME_PTR) type into R1 84 * and 2nd arithmetic instruction is pattern matched to recognize 85 * that it wants to construct a pointer to some element within stack. 86 * So after 2nd insn, the register R1 has type PTR_TO_STACK 87 * (and -20 constant is saved for further stack bounds checking). 88 * Meaning that this reg is a pointer to stack plus known immediate constant. 89 * 90 * Most of the time the registers have SCALAR_VALUE type, which 91 * means the register has some value, but it's not a valid pointer. 92 * (like pointer plus pointer becomes SCALAR_VALUE type) 93 * 94 * When verifier sees load or store instructions the type of base register 95 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 96 * four pointer types recognized by check_mem_access() function. 97 * 98 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 99 * and the range of [ptr, ptr + map's value_size) is accessible. 100 * 101 * registers used to pass values to function calls are checked against 102 * function argument constraints. 103 * 104 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 105 * It means that the register type passed to this function must be 106 * PTR_TO_STACK and it will be used inside the function as 107 * 'pointer to map element key' 108 * 109 * For example the argument constraints for bpf_map_lookup_elem(): 110 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 111 * .arg1_type = ARG_CONST_MAP_PTR, 112 * .arg2_type = ARG_PTR_TO_MAP_KEY, 113 * 114 * ret_type says that this function returns 'pointer to map elem value or null' 115 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 116 * 2nd argument should be a pointer to stack, which will be used inside 117 * the helper function as a pointer to map element key. 118 * 119 * On the kernel side the helper function looks like: 120 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 121 * { 122 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 123 * void *key = (void *) (unsigned long) r2; 124 * void *value; 125 * 126 * here kernel can access 'key' and 'map' pointers safely, knowing that 127 * [key, key + map->key_size) bytes are valid and were initialized on 128 * the stack of eBPF program. 129 * } 130 * 131 * Corresponding eBPF program may look like: 132 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 133 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 134 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 135 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 136 * here verifier looks at prototype of map_lookup_elem() and sees: 137 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 138 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 139 * 140 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 141 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 142 * and were initialized prior to this call. 143 * If it's ok, then verifier allows this BPF_CALL insn and looks at 144 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 145 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 146 * returns either pointer to map value or NULL. 147 * 148 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 149 * insn, the register holding that pointer in the true branch changes state to 150 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 151 * branch. See check_cond_jmp_op(). 152 * 153 * After the call R0 is set to return type of the function and registers R1-R5 154 * are set to NOT_INIT to indicate that they are no longer readable. 155 * 156 * The following reference types represent a potential reference to a kernel 157 * resource which, after first being allocated, must be checked and freed by 158 * the BPF program: 159 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 160 * 161 * When the verifier sees a helper call return a reference type, it allocates a 162 * pointer id for the reference and stores it in the current function state. 163 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 164 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 165 * passes through a NULL-check conditional. For the branch wherein the state is 166 * changed to CONST_IMM, the verifier releases the reference. 167 * 168 * For each helper function that allocates a reference, such as 169 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 170 * bpf_sk_release(). When a reference type passes into the release function, 171 * the verifier also releases the reference. If any unchecked or unreleased 172 * reference remains at the end of the program, the verifier rejects it. 173 */ 174 175 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 176 struct bpf_verifier_stack_elem { 177 /* verifier state is 'st' 178 * before processing instruction 'insn_idx' 179 * and after processing instruction 'prev_insn_idx' 180 */ 181 struct bpf_verifier_state st; 182 int insn_idx; 183 int prev_insn_idx; 184 struct bpf_verifier_stack_elem *next; 185 /* length of verifier log at the time this state was pushed on stack */ 186 u32 log_pos; 187 }; 188 189 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192 190 #define BPF_COMPLEXITY_LIMIT_STATES 64 191 192 #define BPF_MAP_KEY_POISON (1ULL << 63) 193 #define BPF_MAP_KEY_SEEN (1ULL << 62) 194 195 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE 512 196 197 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx); 198 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id); 199 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 200 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 201 static int ref_set_non_owning(struct bpf_verifier_env *env, 202 struct bpf_reg_state *reg); 203 static void specialize_kfunc(struct bpf_verifier_env *env, 204 u32 func_id, u16 offset, unsigned long *addr); 205 static bool is_trusted_reg(const struct bpf_reg_state *reg); 206 207 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 208 { 209 return aux->map_ptr_state.poison; 210 } 211 212 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 213 { 214 return aux->map_ptr_state.unpriv; 215 } 216 217 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 218 struct bpf_map *map, 219 bool unpriv, bool poison) 220 { 221 unpriv |= bpf_map_ptr_unpriv(aux); 222 aux->map_ptr_state.unpriv = unpriv; 223 aux->map_ptr_state.poison = poison; 224 aux->map_ptr_state.map_ptr = map; 225 } 226 227 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 228 { 229 return aux->map_key_state & BPF_MAP_KEY_POISON; 230 } 231 232 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 233 { 234 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 235 } 236 237 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 238 { 239 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 240 } 241 242 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 243 { 244 bool poisoned = bpf_map_key_poisoned(aux); 245 246 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 247 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 248 } 249 250 static bool bpf_helper_call(const struct bpf_insn *insn) 251 { 252 return insn->code == (BPF_JMP | BPF_CALL) && 253 insn->src_reg == 0; 254 } 255 256 static bool bpf_pseudo_call(const struct bpf_insn *insn) 257 { 258 return insn->code == (BPF_JMP | BPF_CALL) && 259 insn->src_reg == BPF_PSEUDO_CALL; 260 } 261 262 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 263 { 264 return insn->code == (BPF_JMP | BPF_CALL) && 265 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 266 } 267 268 struct bpf_call_arg_meta { 269 struct bpf_map *map_ptr; 270 bool raw_mode; 271 bool pkt_access; 272 u8 release_regno; 273 int regno; 274 int access_size; 275 int mem_size; 276 u64 msize_max_value; 277 int ref_obj_id; 278 int dynptr_id; 279 int map_uid; 280 int func_id; 281 struct btf *btf; 282 u32 btf_id; 283 struct btf *ret_btf; 284 u32 ret_btf_id; 285 u32 subprogno; 286 struct btf_field *kptr_field; 287 }; 288 289 struct bpf_kfunc_call_arg_meta { 290 /* In parameters */ 291 struct btf *btf; 292 u32 func_id; 293 u32 kfunc_flags; 294 const struct btf_type *func_proto; 295 const char *func_name; 296 /* Out parameters */ 297 u32 ref_obj_id; 298 u8 release_regno; 299 bool r0_rdonly; 300 u32 ret_btf_id; 301 u64 r0_size; 302 u32 subprogno; 303 struct { 304 u64 value; 305 bool found; 306 } arg_constant; 307 308 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling, 309 * generally to pass info about user-defined local kptr types to later 310 * verification logic 311 * bpf_obj_drop/bpf_percpu_obj_drop 312 * Record the local kptr type to be drop'd 313 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type) 314 * Record the local kptr type to be refcount_incr'd and use 315 * arg_owning_ref to determine whether refcount_acquire should be 316 * fallible 317 */ 318 struct btf *arg_btf; 319 u32 arg_btf_id; 320 bool arg_owning_ref; 321 322 struct { 323 struct btf_field *field; 324 } arg_list_head; 325 struct { 326 struct btf_field *field; 327 } arg_rbtree_root; 328 struct { 329 enum bpf_dynptr_type type; 330 u32 id; 331 u32 ref_obj_id; 332 } initialized_dynptr; 333 struct { 334 u8 spi; 335 u8 frameno; 336 } iter; 337 struct { 338 struct bpf_map *ptr; 339 int uid; 340 } map; 341 u64 mem_size; 342 }; 343 344 struct btf *btf_vmlinux; 345 346 static const char *btf_type_name(const struct btf *btf, u32 id) 347 { 348 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 349 } 350 351 static DEFINE_MUTEX(bpf_verifier_lock); 352 static DEFINE_MUTEX(bpf_percpu_ma_lock); 353 354 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 355 { 356 struct bpf_verifier_env *env = private_data; 357 va_list args; 358 359 if (!bpf_verifier_log_needed(&env->log)) 360 return; 361 362 va_start(args, fmt); 363 bpf_verifier_vlog(&env->log, fmt, args); 364 va_end(args); 365 } 366 367 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 368 struct bpf_reg_state *reg, 369 struct bpf_retval_range range, const char *ctx, 370 const char *reg_name) 371 { 372 bool unknown = true; 373 374 verbose(env, "%s the register %s has", ctx, reg_name); 375 if (reg->smin_value > S64_MIN) { 376 verbose(env, " smin=%lld", reg->smin_value); 377 unknown = false; 378 } 379 if (reg->smax_value < S64_MAX) { 380 verbose(env, " smax=%lld", reg->smax_value); 381 unknown = false; 382 } 383 if (unknown) 384 verbose(env, " unknown scalar value"); 385 verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval); 386 } 387 388 static bool reg_not_null(const struct bpf_reg_state *reg) 389 { 390 enum bpf_reg_type type; 391 392 type = reg->type; 393 if (type_may_be_null(type)) 394 return false; 395 396 type = base_type(type); 397 return type == PTR_TO_SOCKET || 398 type == PTR_TO_TCP_SOCK || 399 type == PTR_TO_MAP_VALUE || 400 type == PTR_TO_MAP_KEY || 401 type == PTR_TO_SOCK_COMMON || 402 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) || 403 type == PTR_TO_MEM; 404 } 405 406 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 407 { 408 struct btf_record *rec = NULL; 409 struct btf_struct_meta *meta; 410 411 if (reg->type == PTR_TO_MAP_VALUE) { 412 rec = reg->map_ptr->record; 413 } else if (type_is_ptr_alloc_obj(reg->type)) { 414 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 415 if (meta) 416 rec = meta->record; 417 } 418 return rec; 419 } 420 421 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog) 422 { 423 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 424 425 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 426 } 427 428 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog) 429 { 430 struct bpf_func_info *info; 431 432 if (!env->prog->aux->func_info) 433 return ""; 434 435 info = &env->prog->aux->func_info[subprog]; 436 return btf_type_name(env->prog->aux->btf, info->type_id); 437 } 438 439 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog) 440 { 441 struct bpf_subprog_info *info = subprog_info(env, subprog); 442 443 info->is_cb = true; 444 info->is_async_cb = true; 445 info->is_exception_cb = true; 446 } 447 448 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog) 449 { 450 return subprog_info(env, subprog)->is_exception_cb; 451 } 452 453 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 454 { 455 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK); 456 } 457 458 static bool type_is_rdonly_mem(u32 type) 459 { 460 return type & MEM_RDONLY; 461 } 462 463 static bool is_acquire_function(enum bpf_func_id func_id, 464 const struct bpf_map *map) 465 { 466 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 467 468 if (func_id == BPF_FUNC_sk_lookup_tcp || 469 func_id == BPF_FUNC_sk_lookup_udp || 470 func_id == BPF_FUNC_skc_lookup_tcp || 471 func_id == BPF_FUNC_ringbuf_reserve || 472 func_id == BPF_FUNC_kptr_xchg) 473 return true; 474 475 if (func_id == BPF_FUNC_map_lookup_elem && 476 (map_type == BPF_MAP_TYPE_SOCKMAP || 477 map_type == BPF_MAP_TYPE_SOCKHASH)) 478 return true; 479 480 return false; 481 } 482 483 static bool is_ptr_cast_function(enum bpf_func_id func_id) 484 { 485 return func_id == BPF_FUNC_tcp_sock || 486 func_id == BPF_FUNC_sk_fullsock || 487 func_id == BPF_FUNC_skc_to_tcp_sock || 488 func_id == BPF_FUNC_skc_to_tcp6_sock || 489 func_id == BPF_FUNC_skc_to_udp6_sock || 490 func_id == BPF_FUNC_skc_to_mptcp_sock || 491 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 492 func_id == BPF_FUNC_skc_to_tcp_request_sock; 493 } 494 495 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 496 { 497 return func_id == BPF_FUNC_dynptr_data; 498 } 499 500 static bool is_sync_callback_calling_kfunc(u32 btf_id); 501 static bool is_async_callback_calling_kfunc(u32 btf_id); 502 static bool is_callback_calling_kfunc(u32 btf_id); 503 static bool is_bpf_throw_kfunc(struct bpf_insn *insn); 504 505 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id); 506 507 static bool is_sync_callback_calling_function(enum bpf_func_id func_id) 508 { 509 return func_id == BPF_FUNC_for_each_map_elem || 510 func_id == BPF_FUNC_find_vma || 511 func_id == BPF_FUNC_loop || 512 func_id == BPF_FUNC_user_ringbuf_drain; 513 } 514 515 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 516 { 517 return func_id == BPF_FUNC_timer_set_callback; 518 } 519 520 static bool is_callback_calling_function(enum bpf_func_id func_id) 521 { 522 return is_sync_callback_calling_function(func_id) || 523 is_async_callback_calling_function(func_id); 524 } 525 526 static bool is_sync_callback_calling_insn(struct bpf_insn *insn) 527 { 528 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) || 529 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm)); 530 } 531 532 static bool is_async_callback_calling_insn(struct bpf_insn *insn) 533 { 534 return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) || 535 (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm)); 536 } 537 538 static bool is_may_goto_insn(struct bpf_insn *insn) 539 { 540 return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO; 541 } 542 543 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx) 544 { 545 return is_may_goto_insn(&env->prog->insnsi[insn_idx]); 546 } 547 548 static bool is_storage_get_function(enum bpf_func_id func_id) 549 { 550 return func_id == BPF_FUNC_sk_storage_get || 551 func_id == BPF_FUNC_inode_storage_get || 552 func_id == BPF_FUNC_task_storage_get || 553 func_id == BPF_FUNC_cgrp_storage_get; 554 } 555 556 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 557 const struct bpf_map *map) 558 { 559 int ref_obj_uses = 0; 560 561 if (is_ptr_cast_function(func_id)) 562 ref_obj_uses++; 563 if (is_acquire_function(func_id, map)) 564 ref_obj_uses++; 565 if (is_dynptr_ref_function(func_id)) 566 ref_obj_uses++; 567 568 return ref_obj_uses > 1; 569 } 570 571 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 572 { 573 return BPF_CLASS(insn->code) == BPF_STX && 574 BPF_MODE(insn->code) == BPF_ATOMIC && 575 insn->imm == BPF_CMPXCHG; 576 } 577 578 static int __get_spi(s32 off) 579 { 580 return (-off - 1) / BPF_REG_SIZE; 581 } 582 583 static struct bpf_func_state *func(struct bpf_verifier_env *env, 584 const struct bpf_reg_state *reg) 585 { 586 struct bpf_verifier_state *cur = env->cur_state; 587 588 return cur->frame[reg->frameno]; 589 } 590 591 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 592 { 593 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 594 595 /* We need to check that slots between [spi - nr_slots + 1, spi] are 596 * within [0, allocated_stack). 597 * 598 * Please note that the spi grows downwards. For example, a dynptr 599 * takes the size of two stack slots; the first slot will be at 600 * spi and the second slot will be at spi - 1. 601 */ 602 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 603 } 604 605 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 606 const char *obj_kind, int nr_slots) 607 { 608 int off, spi; 609 610 if (!tnum_is_const(reg->var_off)) { 611 verbose(env, "%s has to be at a constant offset\n", obj_kind); 612 return -EINVAL; 613 } 614 615 off = reg->off + reg->var_off.value; 616 if (off % BPF_REG_SIZE) { 617 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 618 return -EINVAL; 619 } 620 621 spi = __get_spi(off); 622 if (spi + 1 < nr_slots) { 623 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 624 return -EINVAL; 625 } 626 627 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots)) 628 return -ERANGE; 629 return spi; 630 } 631 632 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 633 { 634 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 635 } 636 637 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 638 { 639 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 640 } 641 642 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 643 { 644 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 645 case DYNPTR_TYPE_LOCAL: 646 return BPF_DYNPTR_TYPE_LOCAL; 647 case DYNPTR_TYPE_RINGBUF: 648 return BPF_DYNPTR_TYPE_RINGBUF; 649 case DYNPTR_TYPE_SKB: 650 return BPF_DYNPTR_TYPE_SKB; 651 case DYNPTR_TYPE_XDP: 652 return BPF_DYNPTR_TYPE_XDP; 653 default: 654 return BPF_DYNPTR_TYPE_INVALID; 655 } 656 } 657 658 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 659 { 660 switch (type) { 661 case BPF_DYNPTR_TYPE_LOCAL: 662 return DYNPTR_TYPE_LOCAL; 663 case BPF_DYNPTR_TYPE_RINGBUF: 664 return DYNPTR_TYPE_RINGBUF; 665 case BPF_DYNPTR_TYPE_SKB: 666 return DYNPTR_TYPE_SKB; 667 case BPF_DYNPTR_TYPE_XDP: 668 return DYNPTR_TYPE_XDP; 669 default: 670 return 0; 671 } 672 } 673 674 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 675 { 676 return type == BPF_DYNPTR_TYPE_RINGBUF; 677 } 678 679 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 680 enum bpf_dynptr_type type, 681 bool first_slot, int dynptr_id); 682 683 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 684 struct bpf_reg_state *reg); 685 686 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 687 struct bpf_reg_state *sreg1, 688 struct bpf_reg_state *sreg2, 689 enum bpf_dynptr_type type) 690 { 691 int id = ++env->id_gen; 692 693 __mark_dynptr_reg(sreg1, type, true, id); 694 __mark_dynptr_reg(sreg2, type, false, id); 695 } 696 697 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 698 struct bpf_reg_state *reg, 699 enum bpf_dynptr_type type) 700 { 701 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 702 } 703 704 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 705 struct bpf_func_state *state, int spi); 706 707 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 708 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id) 709 { 710 struct bpf_func_state *state = func(env, reg); 711 enum bpf_dynptr_type type; 712 int spi, i, err; 713 714 spi = dynptr_get_spi(env, reg); 715 if (spi < 0) 716 return spi; 717 718 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 719 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 720 * to ensure that for the following example: 721 * [d1][d1][d2][d2] 722 * spi 3 2 1 0 723 * So marking spi = 2 should lead to destruction of both d1 and d2. In 724 * case they do belong to same dynptr, second call won't see slot_type 725 * as STACK_DYNPTR and will simply skip destruction. 726 */ 727 err = destroy_if_dynptr_stack_slot(env, state, spi); 728 if (err) 729 return err; 730 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 731 if (err) 732 return err; 733 734 for (i = 0; i < BPF_REG_SIZE; i++) { 735 state->stack[spi].slot_type[i] = STACK_DYNPTR; 736 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 737 } 738 739 type = arg_to_dynptr_type(arg_type); 740 if (type == BPF_DYNPTR_TYPE_INVALID) 741 return -EINVAL; 742 743 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 744 &state->stack[spi - 1].spilled_ptr, type); 745 746 if (dynptr_type_refcounted(type)) { 747 /* The id is used to track proper releasing */ 748 int id; 749 750 if (clone_ref_obj_id) 751 id = clone_ref_obj_id; 752 else 753 id = acquire_reference_state(env, insn_idx); 754 755 if (id < 0) 756 return id; 757 758 state->stack[spi].spilled_ptr.ref_obj_id = id; 759 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 760 } 761 762 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 763 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 764 765 return 0; 766 } 767 768 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi) 769 { 770 int i; 771 772 for (i = 0; i < BPF_REG_SIZE; i++) { 773 state->stack[spi].slot_type[i] = STACK_INVALID; 774 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 775 } 776 777 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 778 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 779 780 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot? 781 * 782 * While we don't allow reading STACK_INVALID, it is still possible to 783 * do <8 byte writes marking some but not all slots as STACK_MISC. Then, 784 * helpers or insns can do partial read of that part without failing, 785 * but check_stack_range_initialized, check_stack_read_var_off, and 786 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of 787 * the slot conservatively. Hence we need to prevent those liveness 788 * marking walks. 789 * 790 * This was not a problem before because STACK_INVALID is only set by 791 * default (where the default reg state has its reg->parent as NULL), or 792 * in clean_live_states after REG_LIVE_DONE (at which point 793 * mark_reg_read won't walk reg->parent chain), but not randomly during 794 * verifier state exploration (like we did above). Hence, for our case 795 * parentage chain will still be live (i.e. reg->parent may be 796 * non-NULL), while earlier reg->parent was NULL, so we need 797 * REG_LIVE_WRITTEN to screen off read marker propagation when it is 798 * done later on reads or by mark_dynptr_read as well to unnecessary 799 * mark registers in verifier state. 800 */ 801 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 802 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 803 } 804 805 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 806 { 807 struct bpf_func_state *state = func(env, reg); 808 int spi, ref_obj_id, i; 809 810 spi = dynptr_get_spi(env, reg); 811 if (spi < 0) 812 return spi; 813 814 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 815 invalidate_dynptr(env, state, spi); 816 return 0; 817 } 818 819 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 820 821 /* If the dynptr has a ref_obj_id, then we need to invalidate 822 * two things: 823 * 824 * 1) Any dynptrs with a matching ref_obj_id (clones) 825 * 2) Any slices derived from this dynptr. 826 */ 827 828 /* Invalidate any slices associated with this dynptr */ 829 WARN_ON_ONCE(release_reference(env, ref_obj_id)); 830 831 /* Invalidate any dynptr clones */ 832 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) { 833 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id) 834 continue; 835 836 /* it should always be the case that if the ref obj id 837 * matches then the stack slot also belongs to a 838 * dynptr 839 */ 840 if (state->stack[i].slot_type[0] != STACK_DYNPTR) { 841 verbose(env, "verifier internal error: misconfigured ref_obj_id\n"); 842 return -EFAULT; 843 } 844 if (state->stack[i].spilled_ptr.dynptr.first_slot) 845 invalidate_dynptr(env, state, i); 846 } 847 848 return 0; 849 } 850 851 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 852 struct bpf_reg_state *reg); 853 854 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 855 { 856 if (!env->allow_ptr_leaks) 857 __mark_reg_not_init(env, reg); 858 else 859 __mark_reg_unknown(env, reg); 860 } 861 862 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 863 struct bpf_func_state *state, int spi) 864 { 865 struct bpf_func_state *fstate; 866 struct bpf_reg_state *dreg; 867 int i, dynptr_id; 868 869 /* We always ensure that STACK_DYNPTR is never set partially, 870 * hence just checking for slot_type[0] is enough. This is 871 * different for STACK_SPILL, where it may be only set for 872 * 1 byte, so code has to use is_spilled_reg. 873 */ 874 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 875 return 0; 876 877 /* Reposition spi to first slot */ 878 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 879 spi = spi + 1; 880 881 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 882 verbose(env, "cannot overwrite referenced dynptr\n"); 883 return -EINVAL; 884 } 885 886 mark_stack_slot_scratched(env, spi); 887 mark_stack_slot_scratched(env, spi - 1); 888 889 /* Writing partially to one dynptr stack slot destroys both. */ 890 for (i = 0; i < BPF_REG_SIZE; i++) { 891 state->stack[spi].slot_type[i] = STACK_INVALID; 892 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 893 } 894 895 dynptr_id = state->stack[spi].spilled_ptr.id; 896 /* Invalidate any slices associated with this dynptr */ 897 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 898 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 899 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 900 continue; 901 if (dreg->dynptr_id == dynptr_id) 902 mark_reg_invalid(env, dreg); 903 })); 904 905 /* Do not release reference state, we are destroying dynptr on stack, 906 * not using some helper to release it. Just reset register. 907 */ 908 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 909 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 910 911 /* Same reason as unmark_stack_slots_dynptr above */ 912 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 913 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 914 915 return 0; 916 } 917 918 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 919 { 920 int spi; 921 922 if (reg->type == CONST_PTR_TO_DYNPTR) 923 return false; 924 925 spi = dynptr_get_spi(env, reg); 926 927 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 928 * error because this just means the stack state hasn't been updated yet. 929 * We will do check_mem_access to check and update stack bounds later. 930 */ 931 if (spi < 0 && spi != -ERANGE) 932 return false; 933 934 /* We don't need to check if the stack slots are marked by previous 935 * dynptr initializations because we allow overwriting existing unreferenced 936 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 937 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 938 * touching are completely destructed before we reinitialize them for a new 939 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 940 * instead of delaying it until the end where the user will get "Unreleased 941 * reference" error. 942 */ 943 return true; 944 } 945 946 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 947 { 948 struct bpf_func_state *state = func(env, reg); 949 int i, spi; 950 951 /* This already represents first slot of initialized bpf_dynptr. 952 * 953 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 954 * check_func_arg_reg_off's logic, so we don't need to check its 955 * offset and alignment. 956 */ 957 if (reg->type == CONST_PTR_TO_DYNPTR) 958 return true; 959 960 spi = dynptr_get_spi(env, reg); 961 if (spi < 0) 962 return false; 963 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 964 return false; 965 966 for (i = 0; i < BPF_REG_SIZE; i++) { 967 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 968 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 969 return false; 970 } 971 972 return true; 973 } 974 975 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 976 enum bpf_arg_type arg_type) 977 { 978 struct bpf_func_state *state = func(env, reg); 979 enum bpf_dynptr_type dynptr_type; 980 int spi; 981 982 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 983 if (arg_type == ARG_PTR_TO_DYNPTR) 984 return true; 985 986 dynptr_type = arg_to_dynptr_type(arg_type); 987 if (reg->type == CONST_PTR_TO_DYNPTR) { 988 return reg->dynptr.type == dynptr_type; 989 } else { 990 spi = dynptr_get_spi(env, reg); 991 if (spi < 0) 992 return false; 993 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 994 } 995 } 996 997 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 998 999 static bool in_rcu_cs(struct bpf_verifier_env *env); 1000 1001 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta); 1002 1003 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 1004 struct bpf_kfunc_call_arg_meta *meta, 1005 struct bpf_reg_state *reg, int insn_idx, 1006 struct btf *btf, u32 btf_id, int nr_slots) 1007 { 1008 struct bpf_func_state *state = func(env, reg); 1009 int spi, i, j, id; 1010 1011 spi = iter_get_spi(env, reg, nr_slots); 1012 if (spi < 0) 1013 return spi; 1014 1015 id = acquire_reference_state(env, insn_idx); 1016 if (id < 0) 1017 return id; 1018 1019 for (i = 0; i < nr_slots; i++) { 1020 struct bpf_stack_state *slot = &state->stack[spi - i]; 1021 struct bpf_reg_state *st = &slot->spilled_ptr; 1022 1023 __mark_reg_known_zero(st); 1024 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1025 if (is_kfunc_rcu_protected(meta)) { 1026 if (in_rcu_cs(env)) 1027 st->type |= MEM_RCU; 1028 else 1029 st->type |= PTR_UNTRUSTED; 1030 } 1031 st->live |= REG_LIVE_WRITTEN; 1032 st->ref_obj_id = i == 0 ? id : 0; 1033 st->iter.btf = btf; 1034 st->iter.btf_id = btf_id; 1035 st->iter.state = BPF_ITER_STATE_ACTIVE; 1036 st->iter.depth = 0; 1037 1038 for (j = 0; j < BPF_REG_SIZE; j++) 1039 slot->slot_type[j] = STACK_ITER; 1040 1041 mark_stack_slot_scratched(env, spi - i); 1042 } 1043 1044 return 0; 1045 } 1046 1047 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 1048 struct bpf_reg_state *reg, int nr_slots) 1049 { 1050 struct bpf_func_state *state = func(env, reg); 1051 int spi, i, j; 1052 1053 spi = iter_get_spi(env, reg, nr_slots); 1054 if (spi < 0) 1055 return spi; 1056 1057 for (i = 0; i < nr_slots; i++) { 1058 struct bpf_stack_state *slot = &state->stack[spi - i]; 1059 struct bpf_reg_state *st = &slot->spilled_ptr; 1060 1061 if (i == 0) 1062 WARN_ON_ONCE(release_reference(env, st->ref_obj_id)); 1063 1064 __mark_reg_not_init(env, st); 1065 1066 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1067 st->live |= REG_LIVE_WRITTEN; 1068 1069 for (j = 0; j < BPF_REG_SIZE; j++) 1070 slot->slot_type[j] = STACK_INVALID; 1071 1072 mark_stack_slot_scratched(env, spi - i); 1073 } 1074 1075 return 0; 1076 } 1077 1078 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1079 struct bpf_reg_state *reg, int nr_slots) 1080 { 1081 struct bpf_func_state *state = func(env, reg); 1082 int spi, i, j; 1083 1084 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1085 * will do check_mem_access to check and update stack bounds later, so 1086 * return true for that case. 1087 */ 1088 spi = iter_get_spi(env, reg, nr_slots); 1089 if (spi == -ERANGE) 1090 return true; 1091 if (spi < 0) 1092 return false; 1093 1094 for (i = 0; i < nr_slots; i++) { 1095 struct bpf_stack_state *slot = &state->stack[spi - i]; 1096 1097 for (j = 0; j < BPF_REG_SIZE; j++) 1098 if (slot->slot_type[j] == STACK_ITER) 1099 return false; 1100 } 1101 1102 return true; 1103 } 1104 1105 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1106 struct btf *btf, u32 btf_id, int nr_slots) 1107 { 1108 struct bpf_func_state *state = func(env, reg); 1109 int spi, i, j; 1110 1111 spi = iter_get_spi(env, reg, nr_slots); 1112 if (spi < 0) 1113 return -EINVAL; 1114 1115 for (i = 0; i < nr_slots; i++) { 1116 struct bpf_stack_state *slot = &state->stack[spi - i]; 1117 struct bpf_reg_state *st = &slot->spilled_ptr; 1118 1119 if (st->type & PTR_UNTRUSTED) 1120 return -EPROTO; 1121 /* only main (first) slot has ref_obj_id set */ 1122 if (i == 0 && !st->ref_obj_id) 1123 return -EINVAL; 1124 if (i != 0 && st->ref_obj_id) 1125 return -EINVAL; 1126 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1127 return -EINVAL; 1128 1129 for (j = 0; j < BPF_REG_SIZE; j++) 1130 if (slot->slot_type[j] != STACK_ITER) 1131 return -EINVAL; 1132 } 1133 1134 return 0; 1135 } 1136 1137 /* Check if given stack slot is "special": 1138 * - spilled register state (STACK_SPILL); 1139 * - dynptr state (STACK_DYNPTR); 1140 * - iter state (STACK_ITER). 1141 */ 1142 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1143 { 1144 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1145 1146 switch (type) { 1147 case STACK_SPILL: 1148 case STACK_DYNPTR: 1149 case STACK_ITER: 1150 return true; 1151 case STACK_INVALID: 1152 case STACK_MISC: 1153 case STACK_ZERO: 1154 return false; 1155 default: 1156 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1157 return true; 1158 } 1159 } 1160 1161 /* The reg state of a pointer or a bounded scalar was saved when 1162 * it was spilled to the stack. 1163 */ 1164 static bool is_spilled_reg(const struct bpf_stack_state *stack) 1165 { 1166 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1167 } 1168 1169 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack) 1170 { 1171 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL && 1172 stack->spilled_ptr.type == SCALAR_VALUE; 1173 } 1174 1175 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack) 1176 { 1177 return stack->slot_type[0] == STACK_SPILL && 1178 stack->spilled_ptr.type == SCALAR_VALUE; 1179 } 1180 1181 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which 1182 * case they are equivalent, or it's STACK_ZERO, in which case we preserve 1183 * more precise STACK_ZERO. 1184 * Note, in uprivileged mode leaving STACK_INVALID is wrong, so we take 1185 * env->allow_ptr_leaks into account and force STACK_MISC, if necessary. 1186 */ 1187 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype) 1188 { 1189 if (*stype == STACK_ZERO) 1190 return; 1191 if (env->allow_ptr_leaks && *stype == STACK_INVALID) 1192 return; 1193 *stype = STACK_MISC; 1194 } 1195 1196 static void scrub_spilled_slot(u8 *stype) 1197 { 1198 if (*stype != STACK_INVALID) 1199 *stype = STACK_MISC; 1200 } 1201 1202 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1203 * small to hold src. This is different from krealloc since we don't want to preserve 1204 * the contents of dst. 1205 * 1206 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1207 * not be allocated. 1208 */ 1209 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1210 { 1211 size_t alloc_bytes; 1212 void *orig = dst; 1213 size_t bytes; 1214 1215 if (ZERO_OR_NULL_PTR(src)) 1216 goto out; 1217 1218 if (unlikely(check_mul_overflow(n, size, &bytes))) 1219 return NULL; 1220 1221 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1222 dst = krealloc(orig, alloc_bytes, flags); 1223 if (!dst) { 1224 kfree(orig); 1225 return NULL; 1226 } 1227 1228 memcpy(dst, src, bytes); 1229 out: 1230 return dst ? dst : ZERO_SIZE_PTR; 1231 } 1232 1233 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1234 * small to hold new_n items. new items are zeroed out if the array grows. 1235 * 1236 * Contrary to krealloc_array, does not free arr if new_n is zero. 1237 */ 1238 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1239 { 1240 size_t alloc_size; 1241 void *new_arr; 1242 1243 if (!new_n || old_n == new_n) 1244 goto out; 1245 1246 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1247 new_arr = krealloc(arr, alloc_size, GFP_KERNEL); 1248 if (!new_arr) { 1249 kfree(arr); 1250 return NULL; 1251 } 1252 arr = new_arr; 1253 1254 if (new_n > old_n) 1255 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1256 1257 out: 1258 return arr ? arr : ZERO_SIZE_PTR; 1259 } 1260 1261 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1262 { 1263 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1264 sizeof(struct bpf_reference_state), GFP_KERNEL); 1265 if (!dst->refs) 1266 return -ENOMEM; 1267 1268 dst->acquired_refs = src->acquired_refs; 1269 return 0; 1270 } 1271 1272 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1273 { 1274 size_t n = src->allocated_stack / BPF_REG_SIZE; 1275 1276 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1277 GFP_KERNEL); 1278 if (!dst->stack) 1279 return -ENOMEM; 1280 1281 dst->allocated_stack = src->allocated_stack; 1282 return 0; 1283 } 1284 1285 static int resize_reference_state(struct bpf_func_state *state, size_t n) 1286 { 1287 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1288 sizeof(struct bpf_reference_state)); 1289 if (!state->refs) 1290 return -ENOMEM; 1291 1292 state->acquired_refs = n; 1293 return 0; 1294 } 1295 1296 /* Possibly update state->allocated_stack to be at least size bytes. Also 1297 * possibly update the function's high-water mark in its bpf_subprog_info. 1298 */ 1299 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) 1300 { 1301 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n; 1302 1303 /* The stack size is always a multiple of BPF_REG_SIZE. */ 1304 size = round_up(size, BPF_REG_SIZE); 1305 n = size / BPF_REG_SIZE; 1306 1307 if (old_n >= n) 1308 return 0; 1309 1310 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1311 if (!state->stack) 1312 return -ENOMEM; 1313 1314 state->allocated_stack = size; 1315 1316 /* update known max for given subprogram */ 1317 if (env->subprog_info[state->subprogno].stack_depth < size) 1318 env->subprog_info[state->subprogno].stack_depth = size; 1319 1320 return 0; 1321 } 1322 1323 /* Acquire a pointer id from the env and update the state->refs to include 1324 * this new pointer reference. 1325 * On success, returns a valid pointer id to associate with the register 1326 * On failure, returns a negative errno. 1327 */ 1328 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1329 { 1330 struct bpf_func_state *state = cur_func(env); 1331 int new_ofs = state->acquired_refs; 1332 int id, err; 1333 1334 err = resize_reference_state(state, state->acquired_refs + 1); 1335 if (err) 1336 return err; 1337 id = ++env->id_gen; 1338 state->refs[new_ofs].id = id; 1339 state->refs[new_ofs].insn_idx = insn_idx; 1340 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0; 1341 1342 return id; 1343 } 1344 1345 /* release function corresponding to acquire_reference_state(). Idempotent. */ 1346 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 1347 { 1348 int i, last_idx; 1349 1350 last_idx = state->acquired_refs - 1; 1351 for (i = 0; i < state->acquired_refs; i++) { 1352 if (state->refs[i].id == ptr_id) { 1353 /* Cannot release caller references in callbacks */ 1354 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 1355 return -EINVAL; 1356 if (last_idx && i != last_idx) 1357 memcpy(&state->refs[i], &state->refs[last_idx], 1358 sizeof(*state->refs)); 1359 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1360 state->acquired_refs--; 1361 return 0; 1362 } 1363 } 1364 return -EINVAL; 1365 } 1366 1367 static void free_func_state(struct bpf_func_state *state) 1368 { 1369 if (!state) 1370 return; 1371 kfree(state->refs); 1372 kfree(state->stack); 1373 kfree(state); 1374 } 1375 1376 static void clear_jmp_history(struct bpf_verifier_state *state) 1377 { 1378 kfree(state->jmp_history); 1379 state->jmp_history = NULL; 1380 state->jmp_history_cnt = 0; 1381 } 1382 1383 static void free_verifier_state(struct bpf_verifier_state *state, 1384 bool free_self) 1385 { 1386 int i; 1387 1388 for (i = 0; i <= state->curframe; i++) { 1389 free_func_state(state->frame[i]); 1390 state->frame[i] = NULL; 1391 } 1392 clear_jmp_history(state); 1393 if (free_self) 1394 kfree(state); 1395 } 1396 1397 /* copy verifier state from src to dst growing dst stack space 1398 * when necessary to accommodate larger src stack 1399 */ 1400 static int copy_func_state(struct bpf_func_state *dst, 1401 const struct bpf_func_state *src) 1402 { 1403 int err; 1404 1405 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 1406 err = copy_reference_state(dst, src); 1407 if (err) 1408 return err; 1409 return copy_stack_state(dst, src); 1410 } 1411 1412 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1413 const struct bpf_verifier_state *src) 1414 { 1415 struct bpf_func_state *dst; 1416 int i, err; 1417 1418 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1419 src->jmp_history_cnt, sizeof(*dst_state->jmp_history), 1420 GFP_USER); 1421 if (!dst_state->jmp_history) 1422 return -ENOMEM; 1423 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1424 1425 /* if dst has more stack frames then src frame, free them, this is also 1426 * necessary in case of exceptional exits using bpf_throw. 1427 */ 1428 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1429 free_func_state(dst_state->frame[i]); 1430 dst_state->frame[i] = NULL; 1431 } 1432 dst_state->speculative = src->speculative; 1433 dst_state->active_rcu_lock = src->active_rcu_lock; 1434 dst_state->active_preempt_lock = src->active_preempt_lock; 1435 dst_state->in_sleepable = src->in_sleepable; 1436 dst_state->curframe = src->curframe; 1437 dst_state->active_lock.ptr = src->active_lock.ptr; 1438 dst_state->active_lock.id = src->active_lock.id; 1439 dst_state->branches = src->branches; 1440 dst_state->parent = src->parent; 1441 dst_state->first_insn_idx = src->first_insn_idx; 1442 dst_state->last_insn_idx = src->last_insn_idx; 1443 dst_state->dfs_depth = src->dfs_depth; 1444 dst_state->callback_unroll_depth = src->callback_unroll_depth; 1445 dst_state->used_as_loop_entry = src->used_as_loop_entry; 1446 dst_state->may_goto_depth = src->may_goto_depth; 1447 for (i = 0; i <= src->curframe; i++) { 1448 dst = dst_state->frame[i]; 1449 if (!dst) { 1450 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1451 if (!dst) 1452 return -ENOMEM; 1453 dst_state->frame[i] = dst; 1454 } 1455 err = copy_func_state(dst, src->frame[i]); 1456 if (err) 1457 return err; 1458 } 1459 return 0; 1460 } 1461 1462 static u32 state_htab_size(struct bpf_verifier_env *env) 1463 { 1464 return env->prog->len; 1465 } 1466 1467 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx) 1468 { 1469 struct bpf_verifier_state *cur = env->cur_state; 1470 struct bpf_func_state *state = cur->frame[cur->curframe]; 1471 1472 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 1473 } 1474 1475 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b) 1476 { 1477 int fr; 1478 1479 if (a->curframe != b->curframe) 1480 return false; 1481 1482 for (fr = a->curframe; fr >= 0; fr--) 1483 if (a->frame[fr]->callsite != b->frame[fr]->callsite) 1484 return false; 1485 1486 return true; 1487 } 1488 1489 /* Open coded iterators allow back-edges in the state graph in order to 1490 * check unbounded loops that iterators. 1491 * 1492 * In is_state_visited() it is necessary to know if explored states are 1493 * part of some loops in order to decide whether non-exact states 1494 * comparison could be used: 1495 * - non-exact states comparison establishes sub-state relation and uses 1496 * read and precision marks to do so, these marks are propagated from 1497 * children states and thus are not guaranteed to be final in a loop; 1498 * - exact states comparison just checks if current and explored states 1499 * are identical (and thus form a back-edge). 1500 * 1501 * Paper "A New Algorithm for Identifying Loops in Decompilation" 1502 * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient 1503 * algorithm for loop structure detection and gives an overview of 1504 * relevant terminology. It also has helpful illustrations. 1505 * 1506 * [1] https://api.semanticscholar.org/CorpusID:15784067 1507 * 1508 * We use a similar algorithm but because loop nested structure is 1509 * irrelevant for verifier ours is significantly simpler and resembles 1510 * strongly connected components algorithm from Sedgewick's textbook. 1511 * 1512 * Define topmost loop entry as a first node of the loop traversed in a 1513 * depth first search starting from initial state. The goal of the loop 1514 * tracking algorithm is to associate topmost loop entries with states 1515 * derived from these entries. 1516 * 1517 * For each step in the DFS states traversal algorithm needs to identify 1518 * the following situations: 1519 * 1520 * initial initial initial 1521 * | | | 1522 * V V V 1523 * ... ... .---------> hdr 1524 * | | | | 1525 * V V | V 1526 * cur .-> succ | .------... 1527 * | | | | | | 1528 * V | V | V V 1529 * succ '-- cur | ... ... 1530 * | | | 1531 * | V V 1532 * | succ <- cur 1533 * | | 1534 * | V 1535 * | ... 1536 * | | 1537 * '----' 1538 * 1539 * (A) successor state of cur (B) successor state of cur or it's entry 1540 * not yet traversed are in current DFS path, thus cur and succ 1541 * are members of the same outermost loop 1542 * 1543 * initial initial 1544 * | | 1545 * V V 1546 * ... ... 1547 * | | 1548 * V V 1549 * .------... .------... 1550 * | | | | 1551 * V V V V 1552 * .-> hdr ... ... ... 1553 * | | | | | 1554 * | V V V V 1555 * | succ <- cur succ <- cur 1556 * | | | 1557 * | V V 1558 * | ... ... 1559 * | | | 1560 * '----' exit 1561 * 1562 * (C) successor state of cur is a part of some loop but this loop 1563 * does not include cur or successor state is not in a loop at all. 1564 * 1565 * Algorithm could be described as the following python code: 1566 * 1567 * traversed = set() # Set of traversed nodes 1568 * entries = {} # Mapping from node to loop entry 1569 * depths = {} # Depth level assigned to graph node 1570 * path = set() # Current DFS path 1571 * 1572 * # Find outermost loop entry known for n 1573 * def get_loop_entry(n): 1574 * h = entries.get(n, None) 1575 * while h in entries and entries[h] != h: 1576 * h = entries[h] 1577 * return h 1578 * 1579 * # Update n's loop entry if h's outermost entry comes 1580 * # before n's outermost entry in current DFS path. 1581 * def update_loop_entry(n, h): 1582 * n1 = get_loop_entry(n) or n 1583 * h1 = get_loop_entry(h) or h 1584 * if h1 in path and depths[h1] <= depths[n1]: 1585 * entries[n] = h1 1586 * 1587 * def dfs(n, depth): 1588 * traversed.add(n) 1589 * path.add(n) 1590 * depths[n] = depth 1591 * for succ in G.successors(n): 1592 * if succ not in traversed: 1593 * # Case A: explore succ and update cur's loop entry 1594 * # only if succ's entry is in current DFS path. 1595 * dfs(succ, depth + 1) 1596 * h = get_loop_entry(succ) 1597 * update_loop_entry(n, h) 1598 * else: 1599 * # Case B or C depending on `h1 in path` check in update_loop_entry(). 1600 * update_loop_entry(n, succ) 1601 * path.remove(n) 1602 * 1603 * To adapt this algorithm for use with verifier: 1604 * - use st->branch == 0 as a signal that DFS of succ had been finished 1605 * and cur's loop entry has to be updated (case A), handle this in 1606 * update_branch_counts(); 1607 * - use st->branch > 0 as a signal that st is in the current DFS path; 1608 * - handle cases B and C in is_state_visited(); 1609 * - update topmost loop entry for intermediate states in get_loop_entry(). 1610 */ 1611 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st) 1612 { 1613 struct bpf_verifier_state *topmost = st->loop_entry, *old; 1614 1615 while (topmost && topmost->loop_entry && topmost != topmost->loop_entry) 1616 topmost = topmost->loop_entry; 1617 /* Update loop entries for intermediate states to avoid this 1618 * traversal in future get_loop_entry() calls. 1619 */ 1620 while (st && st->loop_entry != topmost) { 1621 old = st->loop_entry; 1622 st->loop_entry = topmost; 1623 st = old; 1624 } 1625 return topmost; 1626 } 1627 1628 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr) 1629 { 1630 struct bpf_verifier_state *cur1, *hdr1; 1631 1632 cur1 = get_loop_entry(cur) ?: cur; 1633 hdr1 = get_loop_entry(hdr) ?: hdr; 1634 /* The head1->branches check decides between cases B and C in 1635 * comment for get_loop_entry(). If hdr1->branches == 0 then 1636 * head's topmost loop entry is not in current DFS path, 1637 * hence 'cur' and 'hdr' are not in the same loop and there is 1638 * no need to update cur->loop_entry. 1639 */ 1640 if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) { 1641 cur->loop_entry = hdr; 1642 hdr->used_as_loop_entry = true; 1643 } 1644 } 1645 1646 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1647 { 1648 while (st) { 1649 u32 br = --st->branches; 1650 1651 /* br == 0 signals that DFS exploration for 'st' is finished, 1652 * thus it is necessary to update parent's loop entry if it 1653 * turned out that st is a part of some loop. 1654 * This is a part of 'case A' in get_loop_entry() comment. 1655 */ 1656 if (br == 0 && st->parent && st->loop_entry) 1657 update_loop_entry(st->parent, st->loop_entry); 1658 1659 /* WARN_ON(br > 1) technically makes sense here, 1660 * but see comment in push_stack(), hence: 1661 */ 1662 WARN_ONCE((int)br < 0, 1663 "BUG update_branch_counts:branches_to_explore=%d\n", 1664 br); 1665 if (br) 1666 break; 1667 st = st->parent; 1668 } 1669 } 1670 1671 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1672 int *insn_idx, bool pop_log) 1673 { 1674 struct bpf_verifier_state *cur = env->cur_state; 1675 struct bpf_verifier_stack_elem *elem, *head = env->head; 1676 int err; 1677 1678 if (env->head == NULL) 1679 return -ENOENT; 1680 1681 if (cur) { 1682 err = copy_verifier_state(cur, &head->st); 1683 if (err) 1684 return err; 1685 } 1686 if (pop_log) 1687 bpf_vlog_reset(&env->log, head->log_pos); 1688 if (insn_idx) 1689 *insn_idx = head->insn_idx; 1690 if (prev_insn_idx) 1691 *prev_insn_idx = head->prev_insn_idx; 1692 elem = head->next; 1693 free_verifier_state(&head->st, false); 1694 kfree(head); 1695 env->head = elem; 1696 env->stack_size--; 1697 return 0; 1698 } 1699 1700 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1701 int insn_idx, int prev_insn_idx, 1702 bool speculative) 1703 { 1704 struct bpf_verifier_state *cur = env->cur_state; 1705 struct bpf_verifier_stack_elem *elem; 1706 int err; 1707 1708 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1709 if (!elem) 1710 goto err; 1711 1712 elem->insn_idx = insn_idx; 1713 elem->prev_insn_idx = prev_insn_idx; 1714 elem->next = env->head; 1715 elem->log_pos = env->log.end_pos; 1716 env->head = elem; 1717 env->stack_size++; 1718 err = copy_verifier_state(&elem->st, cur); 1719 if (err) 1720 goto err; 1721 elem->st.speculative |= speculative; 1722 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1723 verbose(env, "The sequence of %d jumps is too complex.\n", 1724 env->stack_size); 1725 goto err; 1726 } 1727 if (elem->st.parent) { 1728 ++elem->st.parent->branches; 1729 /* WARN_ON(branches > 2) technically makes sense here, 1730 * but 1731 * 1. speculative states will bump 'branches' for non-branch 1732 * instructions 1733 * 2. is_state_visited() heuristics may decide not to create 1734 * a new state for a sequence of branches and all such current 1735 * and cloned states will be pointing to a single parent state 1736 * which might have large 'branches' count. 1737 */ 1738 } 1739 return &elem->st; 1740 err: 1741 free_verifier_state(env->cur_state, true); 1742 env->cur_state = NULL; 1743 /* pop all elements and return */ 1744 while (!pop_stack(env, NULL, NULL, false)); 1745 return NULL; 1746 } 1747 1748 #define CALLER_SAVED_REGS 6 1749 static const int caller_saved[CALLER_SAVED_REGS] = { 1750 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1751 }; 1752 1753 /* This helper doesn't clear reg->id */ 1754 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1755 { 1756 reg->var_off = tnum_const(imm); 1757 reg->smin_value = (s64)imm; 1758 reg->smax_value = (s64)imm; 1759 reg->umin_value = imm; 1760 reg->umax_value = imm; 1761 1762 reg->s32_min_value = (s32)imm; 1763 reg->s32_max_value = (s32)imm; 1764 reg->u32_min_value = (u32)imm; 1765 reg->u32_max_value = (u32)imm; 1766 } 1767 1768 /* Mark the unknown part of a register (variable offset or scalar value) as 1769 * known to have the value @imm. 1770 */ 1771 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1772 { 1773 /* Clear off and union(map_ptr, range) */ 1774 memset(((u8 *)reg) + sizeof(reg->type), 0, 1775 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1776 reg->id = 0; 1777 reg->ref_obj_id = 0; 1778 ___mark_reg_known(reg, imm); 1779 } 1780 1781 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1782 { 1783 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1784 reg->s32_min_value = (s32)imm; 1785 reg->s32_max_value = (s32)imm; 1786 reg->u32_min_value = (u32)imm; 1787 reg->u32_max_value = (u32)imm; 1788 } 1789 1790 /* Mark the 'variable offset' part of a register as zero. This should be 1791 * used only on registers holding a pointer type. 1792 */ 1793 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1794 { 1795 __mark_reg_known(reg, 0); 1796 } 1797 1798 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1799 { 1800 __mark_reg_known(reg, 0); 1801 reg->type = SCALAR_VALUE; 1802 /* all scalars are assumed imprecise initially (unless unprivileged, 1803 * in which case everything is forced to be precise) 1804 */ 1805 reg->precise = !env->bpf_capable; 1806 } 1807 1808 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1809 struct bpf_reg_state *regs, u32 regno) 1810 { 1811 if (WARN_ON(regno >= MAX_BPF_REG)) { 1812 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1813 /* Something bad happened, let's kill all regs */ 1814 for (regno = 0; regno < MAX_BPF_REG; regno++) 1815 __mark_reg_not_init(env, regs + regno); 1816 return; 1817 } 1818 __mark_reg_known_zero(regs + regno); 1819 } 1820 1821 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1822 bool first_slot, int dynptr_id) 1823 { 1824 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1825 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1826 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1827 */ 1828 __mark_reg_known_zero(reg); 1829 reg->type = CONST_PTR_TO_DYNPTR; 1830 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1831 reg->id = dynptr_id; 1832 reg->dynptr.type = type; 1833 reg->dynptr.first_slot = first_slot; 1834 } 1835 1836 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1837 { 1838 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1839 const struct bpf_map *map = reg->map_ptr; 1840 1841 if (map->inner_map_meta) { 1842 reg->type = CONST_PTR_TO_MAP; 1843 reg->map_ptr = map->inner_map_meta; 1844 /* transfer reg's id which is unique for every map_lookup_elem 1845 * as UID of the inner map. 1846 */ 1847 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 1848 reg->map_uid = reg->id; 1849 if (btf_record_has_field(map->inner_map_meta->record, BPF_WORKQUEUE)) 1850 reg->map_uid = reg->id; 1851 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1852 reg->type = PTR_TO_XDP_SOCK; 1853 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1854 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1855 reg->type = PTR_TO_SOCKET; 1856 } else { 1857 reg->type = PTR_TO_MAP_VALUE; 1858 } 1859 return; 1860 } 1861 1862 reg->type &= ~PTR_MAYBE_NULL; 1863 } 1864 1865 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 1866 struct btf_field_graph_root *ds_head) 1867 { 1868 __mark_reg_known_zero(®s[regno]); 1869 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 1870 regs[regno].btf = ds_head->btf; 1871 regs[regno].btf_id = ds_head->value_btf_id; 1872 regs[regno].off = ds_head->node_offset; 1873 } 1874 1875 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1876 { 1877 return type_is_pkt_pointer(reg->type); 1878 } 1879 1880 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1881 { 1882 return reg_is_pkt_pointer(reg) || 1883 reg->type == PTR_TO_PACKET_END; 1884 } 1885 1886 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 1887 { 1888 return base_type(reg->type) == PTR_TO_MEM && 1889 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP); 1890 } 1891 1892 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1893 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1894 enum bpf_reg_type which) 1895 { 1896 /* The register can already have a range from prior markings. 1897 * This is fine as long as it hasn't been advanced from its 1898 * origin. 1899 */ 1900 return reg->type == which && 1901 reg->id == 0 && 1902 reg->off == 0 && 1903 tnum_equals_const(reg->var_off, 0); 1904 } 1905 1906 /* Reset the min/max bounds of a register */ 1907 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1908 { 1909 reg->smin_value = S64_MIN; 1910 reg->smax_value = S64_MAX; 1911 reg->umin_value = 0; 1912 reg->umax_value = U64_MAX; 1913 1914 reg->s32_min_value = S32_MIN; 1915 reg->s32_max_value = S32_MAX; 1916 reg->u32_min_value = 0; 1917 reg->u32_max_value = U32_MAX; 1918 } 1919 1920 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1921 { 1922 reg->smin_value = S64_MIN; 1923 reg->smax_value = S64_MAX; 1924 reg->umin_value = 0; 1925 reg->umax_value = U64_MAX; 1926 } 1927 1928 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1929 { 1930 reg->s32_min_value = S32_MIN; 1931 reg->s32_max_value = S32_MAX; 1932 reg->u32_min_value = 0; 1933 reg->u32_max_value = U32_MAX; 1934 } 1935 1936 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1937 { 1938 struct tnum var32_off = tnum_subreg(reg->var_off); 1939 1940 /* min signed is max(sign bit) | min(other bits) */ 1941 reg->s32_min_value = max_t(s32, reg->s32_min_value, 1942 var32_off.value | (var32_off.mask & S32_MIN)); 1943 /* max signed is min(sign bit) | max(other bits) */ 1944 reg->s32_max_value = min_t(s32, reg->s32_max_value, 1945 var32_off.value | (var32_off.mask & S32_MAX)); 1946 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 1947 reg->u32_max_value = min(reg->u32_max_value, 1948 (u32)(var32_off.value | var32_off.mask)); 1949 } 1950 1951 static void __update_reg64_bounds(struct bpf_reg_state *reg) 1952 { 1953 /* min signed is max(sign bit) | min(other bits) */ 1954 reg->smin_value = max_t(s64, reg->smin_value, 1955 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 1956 /* max signed is min(sign bit) | max(other bits) */ 1957 reg->smax_value = min_t(s64, reg->smax_value, 1958 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 1959 reg->umin_value = max(reg->umin_value, reg->var_off.value); 1960 reg->umax_value = min(reg->umax_value, 1961 reg->var_off.value | reg->var_off.mask); 1962 } 1963 1964 static void __update_reg_bounds(struct bpf_reg_state *reg) 1965 { 1966 __update_reg32_bounds(reg); 1967 __update_reg64_bounds(reg); 1968 } 1969 1970 /* Uses signed min/max values to inform unsigned, and vice-versa */ 1971 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 1972 { 1973 /* If upper 32 bits of u64/s64 range don't change, we can use lower 32 1974 * bits to improve our u32/s32 boundaries. 1975 * 1976 * E.g., the case where we have upper 32 bits as zero ([10, 20] in 1977 * u64) is pretty trivial, it's obvious that in u32 we'll also have 1978 * [10, 20] range. But this property holds for any 64-bit range as 1979 * long as upper 32 bits in that entire range of values stay the same. 1980 * 1981 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311] 1982 * in decimal) has the same upper 32 bits throughout all the values in 1983 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15]) 1984 * range. 1985 * 1986 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32, 1987 * following the rules outlined below about u64/s64 correspondence 1988 * (which equally applies to u32 vs s32 correspondence). In general it 1989 * depends on actual hexadecimal values of 32-bit range. They can form 1990 * only valid u32, or only valid s32 ranges in some cases. 1991 * 1992 * So we use all these insights to derive bounds for subregisters here. 1993 */ 1994 if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) { 1995 /* u64 to u32 casting preserves validity of low 32 bits as 1996 * a range, if upper 32 bits are the same 1997 */ 1998 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value); 1999 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value); 2000 2001 if ((s32)reg->umin_value <= (s32)reg->umax_value) { 2002 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 2003 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 2004 } 2005 } 2006 if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) { 2007 /* low 32 bits should form a proper u32 range */ 2008 if ((u32)reg->smin_value <= (u32)reg->smax_value) { 2009 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value); 2010 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value); 2011 } 2012 /* low 32 bits should form a proper s32 range */ 2013 if ((s32)reg->smin_value <= (s32)reg->smax_value) { 2014 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 2015 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 2016 } 2017 } 2018 /* Special case where upper bits form a small sequence of two 2019 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to 2020 * 0x00000000 is also valid), while lower bits form a proper s32 range 2021 * going from negative numbers to positive numbers. E.g., let's say we 2022 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]). 2023 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff, 2024 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits, 2025 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]). 2026 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in 2027 * upper 32 bits. As a random example, s64 range 2028 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range 2029 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister. 2030 */ 2031 if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) && 2032 (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) { 2033 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 2034 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 2035 } 2036 if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) && 2037 (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) { 2038 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 2039 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 2040 } 2041 /* if u32 range forms a valid s32 range (due to matching sign bit), 2042 * try to learn from that 2043 */ 2044 if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) { 2045 reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value); 2046 reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value); 2047 } 2048 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2049 * are the same, so combine. This works even in the negative case, e.g. 2050 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2051 */ 2052 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2053 reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value); 2054 reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value); 2055 } 2056 } 2057 2058 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 2059 { 2060 /* If u64 range forms a valid s64 range (due to matching sign bit), 2061 * try to learn from that. Let's do a bit of ASCII art to see when 2062 * this is happening. Let's take u64 range first: 2063 * 2064 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2065 * |-------------------------------|--------------------------------| 2066 * 2067 * Valid u64 range is formed when umin and umax are anywhere in the 2068 * range [0, U64_MAX], and umin <= umax. u64 case is simple and 2069 * straightforward. Let's see how s64 range maps onto the same range 2070 * of values, annotated below the line for comparison: 2071 * 2072 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2073 * |-------------------------------|--------------------------------| 2074 * 0 S64_MAX S64_MIN -1 2075 * 2076 * So s64 values basically start in the middle and they are logically 2077 * contiguous to the right of it, wrapping around from -1 to 0, and 2078 * then finishing as S64_MAX (0x7fffffffffffffff) right before 2079 * S64_MIN. We can try drawing the continuity of u64 vs s64 values 2080 * more visually as mapped to sign-agnostic range of hex values. 2081 * 2082 * u64 start u64 end 2083 * _______________________________________________________________ 2084 * / \ 2085 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2086 * |-------------------------------|--------------------------------| 2087 * 0 S64_MAX S64_MIN -1 2088 * / \ 2089 * >------------------------------ -------------------------------> 2090 * s64 continues... s64 end s64 start s64 "midpoint" 2091 * 2092 * What this means is that, in general, we can't always derive 2093 * something new about u64 from any random s64 range, and vice versa. 2094 * 2095 * But we can do that in two particular cases. One is when entire 2096 * u64/s64 range is *entirely* contained within left half of the above 2097 * diagram or when it is *entirely* contained in the right half. I.e.: 2098 * 2099 * |-------------------------------|--------------------------------| 2100 * ^ ^ ^ ^ 2101 * A B C D 2102 * 2103 * [A, B] and [C, D] are contained entirely in their respective halves 2104 * and form valid contiguous ranges as both u64 and s64 values. [A, B] 2105 * will be non-negative both as u64 and s64 (and in fact it will be 2106 * identical ranges no matter the signedness). [C, D] treated as s64 2107 * will be a range of negative values, while in u64 it will be 2108 * non-negative range of values larger than 0x8000000000000000. 2109 * 2110 * Now, any other range here can't be represented in both u64 and s64 2111 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid 2112 * contiguous u64 ranges, but they are discontinuous in s64. [B, C] 2113 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX], 2114 * for example. Similarly, valid s64 range [D, A] (going from negative 2115 * to positive values), would be two separate [D, U64_MAX] and [0, A] 2116 * ranges as u64. Currently reg_state can't represent two segments per 2117 * numeric domain, so in such situations we can only derive maximal 2118 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64). 2119 * 2120 * So we use these facts to derive umin/umax from smin/smax and vice 2121 * versa only if they stay within the same "half". This is equivalent 2122 * to checking sign bit: lower half will have sign bit as zero, upper 2123 * half have sign bit 1. Below in code we simplify this by just 2124 * casting umin/umax as smin/smax and checking if they form valid 2125 * range, and vice versa. Those are equivalent checks. 2126 */ 2127 if ((s64)reg->umin_value <= (s64)reg->umax_value) { 2128 reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value); 2129 reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value); 2130 } 2131 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2132 * are the same, so combine. This works even in the negative case, e.g. 2133 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2134 */ 2135 if ((u64)reg->smin_value <= (u64)reg->smax_value) { 2136 reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); 2137 reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); 2138 } 2139 } 2140 2141 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg) 2142 { 2143 /* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit 2144 * values on both sides of 64-bit range in hope to have tighter range. 2145 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from 2146 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff]. 2147 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound 2148 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of 2149 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a 2150 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff]. 2151 * We just need to make sure that derived bounds we are intersecting 2152 * with are well-formed ranges in respective s64 or u64 domain, just 2153 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments. 2154 */ 2155 __u64 new_umin, new_umax; 2156 __s64 new_smin, new_smax; 2157 2158 /* u32 -> u64 tightening, it's always well-formed */ 2159 new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value; 2160 new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value; 2161 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2162 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2163 /* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */ 2164 new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value; 2165 new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value; 2166 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2167 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2168 2169 /* if s32 can be treated as valid u32 range, we can use it as well */ 2170 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2171 /* s32 -> u64 tightening */ 2172 new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value; 2173 new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value; 2174 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2175 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2176 /* s32 -> s64 tightening */ 2177 new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value; 2178 new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value; 2179 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2180 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2181 } 2182 2183 /* Here we would like to handle a special case after sign extending load, 2184 * when upper bits for a 64-bit range are all 1s or all 0s. 2185 * 2186 * Upper bits are all 1s when register is in a range: 2187 * [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff] 2188 * Upper bits are all 0s when register is in a range: 2189 * [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff] 2190 * Together this forms are continuous range: 2191 * [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff] 2192 * 2193 * Now, suppose that register range is in fact tighter: 2194 * [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R) 2195 * Also suppose that it's 32-bit range is positive, 2196 * meaning that lower 32-bits of the full 64-bit register 2197 * are in the range: 2198 * [0x0000_0000, 0x7fff_ffff] (W) 2199 * 2200 * If this happens, then any value in a range: 2201 * [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff] 2202 * is smaller than a lowest bound of the range (R): 2203 * 0xffff_ffff_8000_0000 2204 * which means that upper bits of the full 64-bit register 2205 * can't be all 1s, when lower bits are in range (W). 2206 * 2207 * Note that: 2208 * - 0xffff_ffff_8000_0000 == (s64)S32_MIN 2209 * - 0x0000_0000_7fff_ffff == (s64)S32_MAX 2210 * These relations are used in the conditions below. 2211 */ 2212 if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) { 2213 reg->smin_value = reg->s32_min_value; 2214 reg->smax_value = reg->s32_max_value; 2215 reg->umin_value = reg->s32_min_value; 2216 reg->umax_value = reg->s32_max_value; 2217 reg->var_off = tnum_intersect(reg->var_off, 2218 tnum_range(reg->smin_value, reg->smax_value)); 2219 } 2220 } 2221 2222 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2223 { 2224 __reg32_deduce_bounds(reg); 2225 __reg64_deduce_bounds(reg); 2226 __reg_deduce_mixed_bounds(reg); 2227 } 2228 2229 /* Attempts to improve var_off based on unsigned min/max information */ 2230 static void __reg_bound_offset(struct bpf_reg_state *reg) 2231 { 2232 struct tnum var64_off = tnum_intersect(reg->var_off, 2233 tnum_range(reg->umin_value, 2234 reg->umax_value)); 2235 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2236 tnum_range(reg->u32_min_value, 2237 reg->u32_max_value)); 2238 2239 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2240 } 2241 2242 static void reg_bounds_sync(struct bpf_reg_state *reg) 2243 { 2244 /* We might have learned new bounds from the var_off. */ 2245 __update_reg_bounds(reg); 2246 /* We might have learned something about the sign bit. */ 2247 __reg_deduce_bounds(reg); 2248 __reg_deduce_bounds(reg); 2249 /* We might have learned some bits from the bounds. */ 2250 __reg_bound_offset(reg); 2251 /* Intersecting with the old var_off might have improved our bounds 2252 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2253 * then new var_off is (0; 0x7f...fc) which improves our umax. 2254 */ 2255 __update_reg_bounds(reg); 2256 } 2257 2258 static int reg_bounds_sanity_check(struct bpf_verifier_env *env, 2259 struct bpf_reg_state *reg, const char *ctx) 2260 { 2261 const char *msg; 2262 2263 if (reg->umin_value > reg->umax_value || 2264 reg->smin_value > reg->smax_value || 2265 reg->u32_min_value > reg->u32_max_value || 2266 reg->s32_min_value > reg->s32_max_value) { 2267 msg = "range bounds violation"; 2268 goto out; 2269 } 2270 2271 if (tnum_is_const(reg->var_off)) { 2272 u64 uval = reg->var_off.value; 2273 s64 sval = (s64)uval; 2274 2275 if (reg->umin_value != uval || reg->umax_value != uval || 2276 reg->smin_value != sval || reg->smax_value != sval) { 2277 msg = "const tnum out of sync with range bounds"; 2278 goto out; 2279 } 2280 } 2281 2282 if (tnum_subreg_is_const(reg->var_off)) { 2283 u32 uval32 = tnum_subreg(reg->var_off).value; 2284 s32 sval32 = (s32)uval32; 2285 2286 if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 || 2287 reg->s32_min_value != sval32 || reg->s32_max_value != sval32) { 2288 msg = "const subreg tnum out of sync with range bounds"; 2289 goto out; 2290 } 2291 } 2292 2293 return 0; 2294 out: 2295 verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] " 2296 "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n", 2297 ctx, msg, reg->umin_value, reg->umax_value, 2298 reg->smin_value, reg->smax_value, 2299 reg->u32_min_value, reg->u32_max_value, 2300 reg->s32_min_value, reg->s32_max_value, 2301 reg->var_off.value, reg->var_off.mask); 2302 if (env->test_reg_invariants) 2303 return -EFAULT; 2304 __mark_reg_unbounded(reg); 2305 return 0; 2306 } 2307 2308 static bool __reg32_bound_s64(s32 a) 2309 { 2310 return a >= 0 && a <= S32_MAX; 2311 } 2312 2313 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 2314 { 2315 reg->umin_value = reg->u32_min_value; 2316 reg->umax_value = reg->u32_max_value; 2317 2318 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 2319 * be positive otherwise set to worse case bounds and refine later 2320 * from tnum. 2321 */ 2322 if (__reg32_bound_s64(reg->s32_min_value) && 2323 __reg32_bound_s64(reg->s32_max_value)) { 2324 reg->smin_value = reg->s32_min_value; 2325 reg->smax_value = reg->s32_max_value; 2326 } else { 2327 reg->smin_value = 0; 2328 reg->smax_value = U32_MAX; 2329 } 2330 } 2331 2332 /* Mark a register as having a completely unknown (scalar) value. */ 2333 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg) 2334 { 2335 /* 2336 * Clear type, off, and union(map_ptr, range) and 2337 * padding between 'type' and union 2338 */ 2339 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2340 reg->type = SCALAR_VALUE; 2341 reg->id = 0; 2342 reg->ref_obj_id = 0; 2343 reg->var_off = tnum_unknown; 2344 reg->frameno = 0; 2345 reg->precise = false; 2346 __mark_reg_unbounded(reg); 2347 } 2348 2349 /* Mark a register as having a completely unknown (scalar) value, 2350 * initialize .precise as true when not bpf capable. 2351 */ 2352 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2353 struct bpf_reg_state *reg) 2354 { 2355 __mark_reg_unknown_imprecise(reg); 2356 reg->precise = !env->bpf_capable; 2357 } 2358 2359 static void mark_reg_unknown(struct bpf_verifier_env *env, 2360 struct bpf_reg_state *regs, u32 regno) 2361 { 2362 if (WARN_ON(regno >= MAX_BPF_REG)) { 2363 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 2364 /* Something bad happened, let's kill all regs except FP */ 2365 for (regno = 0; regno < BPF_REG_FP; regno++) 2366 __mark_reg_not_init(env, regs + regno); 2367 return; 2368 } 2369 __mark_reg_unknown(env, regs + regno); 2370 } 2371 2372 static int __mark_reg_s32_range(struct bpf_verifier_env *env, 2373 struct bpf_reg_state *regs, 2374 u32 regno, 2375 s32 s32_min, 2376 s32 s32_max) 2377 { 2378 struct bpf_reg_state *reg = regs + regno; 2379 2380 reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min); 2381 reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max); 2382 2383 reg->smin_value = max_t(s64, reg->smin_value, s32_min); 2384 reg->smax_value = min_t(s64, reg->smax_value, s32_max); 2385 2386 reg_bounds_sync(reg); 2387 2388 return reg_bounds_sanity_check(env, reg, "s32_range"); 2389 } 2390 2391 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 2392 struct bpf_reg_state *reg) 2393 { 2394 __mark_reg_unknown(env, reg); 2395 reg->type = NOT_INIT; 2396 } 2397 2398 static void mark_reg_not_init(struct bpf_verifier_env *env, 2399 struct bpf_reg_state *regs, u32 regno) 2400 { 2401 if (WARN_ON(regno >= MAX_BPF_REG)) { 2402 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 2403 /* Something bad happened, let's kill all regs except FP */ 2404 for (regno = 0; regno < BPF_REG_FP; regno++) 2405 __mark_reg_not_init(env, regs + regno); 2406 return; 2407 } 2408 __mark_reg_not_init(env, regs + regno); 2409 } 2410 2411 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 2412 struct bpf_reg_state *regs, u32 regno, 2413 enum bpf_reg_type reg_type, 2414 struct btf *btf, u32 btf_id, 2415 enum bpf_type_flag flag) 2416 { 2417 if (reg_type == SCALAR_VALUE) { 2418 mark_reg_unknown(env, regs, regno); 2419 return; 2420 } 2421 mark_reg_known_zero(env, regs, regno); 2422 regs[regno].type = PTR_TO_BTF_ID | flag; 2423 regs[regno].btf = btf; 2424 regs[regno].btf_id = btf_id; 2425 if (type_may_be_null(flag)) 2426 regs[regno].id = ++env->id_gen; 2427 } 2428 2429 #define DEF_NOT_SUBREG (0) 2430 static void init_reg_state(struct bpf_verifier_env *env, 2431 struct bpf_func_state *state) 2432 { 2433 struct bpf_reg_state *regs = state->regs; 2434 int i; 2435 2436 for (i = 0; i < MAX_BPF_REG; i++) { 2437 mark_reg_not_init(env, regs, i); 2438 regs[i].live = REG_LIVE_NONE; 2439 regs[i].parent = NULL; 2440 regs[i].subreg_def = DEF_NOT_SUBREG; 2441 } 2442 2443 /* frame pointer */ 2444 regs[BPF_REG_FP].type = PTR_TO_STACK; 2445 mark_reg_known_zero(env, regs, BPF_REG_FP); 2446 regs[BPF_REG_FP].frameno = state->frameno; 2447 } 2448 2449 static struct bpf_retval_range retval_range(s32 minval, s32 maxval) 2450 { 2451 return (struct bpf_retval_range){ minval, maxval }; 2452 } 2453 2454 #define BPF_MAIN_FUNC (-1) 2455 static void init_func_state(struct bpf_verifier_env *env, 2456 struct bpf_func_state *state, 2457 int callsite, int frameno, int subprogno) 2458 { 2459 state->callsite = callsite; 2460 state->frameno = frameno; 2461 state->subprogno = subprogno; 2462 state->callback_ret_range = retval_range(0, 0); 2463 init_reg_state(env, state); 2464 mark_verifier_state_scratched(env); 2465 } 2466 2467 /* Similar to push_stack(), but for async callbacks */ 2468 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2469 int insn_idx, int prev_insn_idx, 2470 int subprog, bool is_sleepable) 2471 { 2472 struct bpf_verifier_stack_elem *elem; 2473 struct bpf_func_state *frame; 2474 2475 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2476 if (!elem) 2477 goto err; 2478 2479 elem->insn_idx = insn_idx; 2480 elem->prev_insn_idx = prev_insn_idx; 2481 elem->next = env->head; 2482 elem->log_pos = env->log.end_pos; 2483 env->head = elem; 2484 env->stack_size++; 2485 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2486 verbose(env, 2487 "The sequence of %d jumps is too complex for async cb.\n", 2488 env->stack_size); 2489 goto err; 2490 } 2491 /* Unlike push_stack() do not copy_verifier_state(). 2492 * The caller state doesn't matter. 2493 * This is async callback. It starts in a fresh stack. 2494 * Initialize it similar to do_check_common(). 2495 */ 2496 elem->st.branches = 1; 2497 elem->st.in_sleepable = is_sleepable; 2498 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 2499 if (!frame) 2500 goto err; 2501 init_func_state(env, frame, 2502 BPF_MAIN_FUNC /* callsite */, 2503 0 /* frameno within this callchain */, 2504 subprog /* subprog number within this prog */); 2505 elem->st.frame[0] = frame; 2506 return &elem->st; 2507 err: 2508 free_verifier_state(env->cur_state, true); 2509 env->cur_state = NULL; 2510 /* pop all elements and return */ 2511 while (!pop_stack(env, NULL, NULL, false)); 2512 return NULL; 2513 } 2514 2515 2516 enum reg_arg_type { 2517 SRC_OP, /* register is used as source operand */ 2518 DST_OP, /* register is used as destination operand */ 2519 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2520 }; 2521 2522 static int cmp_subprogs(const void *a, const void *b) 2523 { 2524 return ((struct bpf_subprog_info *)a)->start - 2525 ((struct bpf_subprog_info *)b)->start; 2526 } 2527 2528 static int find_subprog(struct bpf_verifier_env *env, int off) 2529 { 2530 struct bpf_subprog_info *p; 2531 2532 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 2533 sizeof(env->subprog_info[0]), cmp_subprogs); 2534 if (!p) 2535 return -ENOENT; 2536 return p - env->subprog_info; 2537 2538 } 2539 2540 static int add_subprog(struct bpf_verifier_env *env, int off) 2541 { 2542 int insn_cnt = env->prog->len; 2543 int ret; 2544 2545 if (off >= insn_cnt || off < 0) { 2546 verbose(env, "call to invalid destination\n"); 2547 return -EINVAL; 2548 } 2549 ret = find_subprog(env, off); 2550 if (ret >= 0) 2551 return ret; 2552 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2553 verbose(env, "too many subprograms\n"); 2554 return -E2BIG; 2555 } 2556 /* determine subprog starts. The end is one before the next starts */ 2557 env->subprog_info[env->subprog_cnt++].start = off; 2558 sort(env->subprog_info, env->subprog_cnt, 2559 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2560 return env->subprog_cnt - 1; 2561 } 2562 2563 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env) 2564 { 2565 struct bpf_prog_aux *aux = env->prog->aux; 2566 struct btf *btf = aux->btf; 2567 const struct btf_type *t; 2568 u32 main_btf_id, id; 2569 const char *name; 2570 int ret, i; 2571 2572 /* Non-zero func_info_cnt implies valid btf */ 2573 if (!aux->func_info_cnt) 2574 return 0; 2575 main_btf_id = aux->func_info[0].type_id; 2576 2577 t = btf_type_by_id(btf, main_btf_id); 2578 if (!t) { 2579 verbose(env, "invalid btf id for main subprog in func_info\n"); 2580 return -EINVAL; 2581 } 2582 2583 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:"); 2584 if (IS_ERR(name)) { 2585 ret = PTR_ERR(name); 2586 /* If there is no tag present, there is no exception callback */ 2587 if (ret == -ENOENT) 2588 ret = 0; 2589 else if (ret == -EEXIST) 2590 verbose(env, "multiple exception callback tags for main subprog\n"); 2591 return ret; 2592 } 2593 2594 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC); 2595 if (ret < 0) { 2596 verbose(env, "exception callback '%s' could not be found in BTF\n", name); 2597 return ret; 2598 } 2599 id = ret; 2600 t = btf_type_by_id(btf, id); 2601 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) { 2602 verbose(env, "exception callback '%s' must have global linkage\n", name); 2603 return -EINVAL; 2604 } 2605 ret = 0; 2606 for (i = 0; i < aux->func_info_cnt; i++) { 2607 if (aux->func_info[i].type_id != id) 2608 continue; 2609 ret = aux->func_info[i].insn_off; 2610 /* Further func_info and subprog checks will also happen 2611 * later, so assume this is the right insn_off for now. 2612 */ 2613 if (!ret) { 2614 verbose(env, "invalid exception callback insn_off in func_info: 0\n"); 2615 ret = -EINVAL; 2616 } 2617 } 2618 if (!ret) { 2619 verbose(env, "exception callback type id not found in func_info\n"); 2620 ret = -EINVAL; 2621 } 2622 return ret; 2623 } 2624 2625 #define MAX_KFUNC_DESCS 256 2626 #define MAX_KFUNC_BTFS 256 2627 2628 struct bpf_kfunc_desc { 2629 struct btf_func_model func_model; 2630 u32 func_id; 2631 s32 imm; 2632 u16 offset; 2633 unsigned long addr; 2634 }; 2635 2636 struct bpf_kfunc_btf { 2637 struct btf *btf; 2638 struct module *module; 2639 u16 offset; 2640 }; 2641 2642 struct bpf_kfunc_desc_tab { 2643 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during 2644 * verification. JITs do lookups by bpf_insn, where func_id may not be 2645 * available, therefore at the end of verification do_misc_fixups() 2646 * sorts this by imm and offset. 2647 */ 2648 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 2649 u32 nr_descs; 2650 }; 2651 2652 struct bpf_kfunc_btf_tab { 2653 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2654 u32 nr_descs; 2655 }; 2656 2657 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2658 { 2659 const struct bpf_kfunc_desc *d0 = a; 2660 const struct bpf_kfunc_desc *d1 = b; 2661 2662 /* func_id is not greater than BTF_MAX_TYPE */ 2663 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2664 } 2665 2666 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2667 { 2668 const struct bpf_kfunc_btf *d0 = a; 2669 const struct bpf_kfunc_btf *d1 = b; 2670 2671 return d0->offset - d1->offset; 2672 } 2673 2674 static const struct bpf_kfunc_desc * 2675 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2676 { 2677 struct bpf_kfunc_desc desc = { 2678 .func_id = func_id, 2679 .offset = offset, 2680 }; 2681 struct bpf_kfunc_desc_tab *tab; 2682 2683 tab = prog->aux->kfunc_tab; 2684 return bsearch(&desc, tab->descs, tab->nr_descs, 2685 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2686 } 2687 2688 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2689 u16 btf_fd_idx, u8 **func_addr) 2690 { 2691 const struct bpf_kfunc_desc *desc; 2692 2693 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2694 if (!desc) 2695 return -EFAULT; 2696 2697 *func_addr = (u8 *)desc->addr; 2698 return 0; 2699 } 2700 2701 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2702 s16 offset) 2703 { 2704 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2705 struct bpf_kfunc_btf_tab *tab; 2706 struct bpf_kfunc_btf *b; 2707 struct module *mod; 2708 struct btf *btf; 2709 int btf_fd; 2710 2711 tab = env->prog->aux->kfunc_btf_tab; 2712 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2713 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2714 if (!b) { 2715 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2716 verbose(env, "too many different module BTFs\n"); 2717 return ERR_PTR(-E2BIG); 2718 } 2719 2720 if (bpfptr_is_null(env->fd_array)) { 2721 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2722 return ERR_PTR(-EPROTO); 2723 } 2724 2725 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2726 offset * sizeof(btf_fd), 2727 sizeof(btf_fd))) 2728 return ERR_PTR(-EFAULT); 2729 2730 btf = btf_get_by_fd(btf_fd); 2731 if (IS_ERR(btf)) { 2732 verbose(env, "invalid module BTF fd specified\n"); 2733 return btf; 2734 } 2735 2736 if (!btf_is_module(btf)) { 2737 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2738 btf_put(btf); 2739 return ERR_PTR(-EINVAL); 2740 } 2741 2742 mod = btf_try_get_module(btf); 2743 if (!mod) { 2744 btf_put(btf); 2745 return ERR_PTR(-ENXIO); 2746 } 2747 2748 b = &tab->descs[tab->nr_descs++]; 2749 b->btf = btf; 2750 b->module = mod; 2751 b->offset = offset; 2752 2753 /* sort() reorders entries by value, so b may no longer point 2754 * to the right entry after this 2755 */ 2756 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2757 kfunc_btf_cmp_by_off, NULL); 2758 } else { 2759 btf = b->btf; 2760 } 2761 2762 return btf; 2763 } 2764 2765 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2766 { 2767 if (!tab) 2768 return; 2769 2770 while (tab->nr_descs--) { 2771 module_put(tab->descs[tab->nr_descs].module); 2772 btf_put(tab->descs[tab->nr_descs].btf); 2773 } 2774 kfree(tab); 2775 } 2776 2777 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2778 { 2779 if (offset) { 2780 if (offset < 0) { 2781 /* In the future, this can be allowed to increase limit 2782 * of fd index into fd_array, interpreted as u16. 2783 */ 2784 verbose(env, "negative offset disallowed for kernel module function call\n"); 2785 return ERR_PTR(-EINVAL); 2786 } 2787 2788 return __find_kfunc_desc_btf(env, offset); 2789 } 2790 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2791 } 2792 2793 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 2794 { 2795 const struct btf_type *func, *func_proto; 2796 struct bpf_kfunc_btf_tab *btf_tab; 2797 struct bpf_kfunc_desc_tab *tab; 2798 struct bpf_prog_aux *prog_aux; 2799 struct bpf_kfunc_desc *desc; 2800 const char *func_name; 2801 struct btf *desc_btf; 2802 unsigned long call_imm; 2803 unsigned long addr; 2804 int err; 2805 2806 prog_aux = env->prog->aux; 2807 tab = prog_aux->kfunc_tab; 2808 btf_tab = prog_aux->kfunc_btf_tab; 2809 if (!tab) { 2810 if (!btf_vmlinux) { 2811 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2812 return -ENOTSUPP; 2813 } 2814 2815 if (!env->prog->jit_requested) { 2816 verbose(env, "JIT is required for calling kernel function\n"); 2817 return -ENOTSUPP; 2818 } 2819 2820 if (!bpf_jit_supports_kfunc_call()) { 2821 verbose(env, "JIT does not support calling kernel function\n"); 2822 return -ENOTSUPP; 2823 } 2824 2825 if (!env->prog->gpl_compatible) { 2826 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2827 return -EINVAL; 2828 } 2829 2830 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 2831 if (!tab) 2832 return -ENOMEM; 2833 prog_aux->kfunc_tab = tab; 2834 } 2835 2836 /* func_id == 0 is always invalid, but instead of returning an error, be 2837 * conservative and wait until the code elimination pass before returning 2838 * error, so that invalid calls that get pruned out can be in BPF programs 2839 * loaded from userspace. It is also required that offset be untouched 2840 * for such calls. 2841 */ 2842 if (!func_id && !offset) 2843 return 0; 2844 2845 if (!btf_tab && offset) { 2846 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 2847 if (!btf_tab) 2848 return -ENOMEM; 2849 prog_aux->kfunc_btf_tab = btf_tab; 2850 } 2851 2852 desc_btf = find_kfunc_desc_btf(env, offset); 2853 if (IS_ERR(desc_btf)) { 2854 verbose(env, "failed to find BTF for kernel function\n"); 2855 return PTR_ERR(desc_btf); 2856 } 2857 2858 if (find_kfunc_desc(env->prog, func_id, offset)) 2859 return 0; 2860 2861 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2862 verbose(env, "too many different kernel function calls\n"); 2863 return -E2BIG; 2864 } 2865 2866 func = btf_type_by_id(desc_btf, func_id); 2867 if (!func || !btf_type_is_func(func)) { 2868 verbose(env, "kernel btf_id %u is not a function\n", 2869 func_id); 2870 return -EINVAL; 2871 } 2872 func_proto = btf_type_by_id(desc_btf, func->type); 2873 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2874 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 2875 func_id); 2876 return -EINVAL; 2877 } 2878 2879 func_name = btf_name_by_offset(desc_btf, func->name_off); 2880 addr = kallsyms_lookup_name(func_name); 2881 if (!addr) { 2882 verbose(env, "cannot find address for kernel function %s\n", 2883 func_name); 2884 return -EINVAL; 2885 } 2886 specialize_kfunc(env, func_id, offset, &addr); 2887 2888 if (bpf_jit_supports_far_kfunc_call()) { 2889 call_imm = func_id; 2890 } else { 2891 call_imm = BPF_CALL_IMM(addr); 2892 /* Check whether the relative offset overflows desc->imm */ 2893 if ((unsigned long)(s32)call_imm != call_imm) { 2894 verbose(env, "address of kernel function %s is out of range\n", 2895 func_name); 2896 return -EINVAL; 2897 } 2898 } 2899 2900 if (bpf_dev_bound_kfunc_id(func_id)) { 2901 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2902 if (err) 2903 return err; 2904 } 2905 2906 desc = &tab->descs[tab->nr_descs++]; 2907 desc->func_id = func_id; 2908 desc->imm = call_imm; 2909 desc->offset = offset; 2910 desc->addr = addr; 2911 err = btf_distill_func_proto(&env->log, desc_btf, 2912 func_proto, func_name, 2913 &desc->func_model); 2914 if (!err) 2915 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2916 kfunc_desc_cmp_by_id_off, NULL); 2917 return err; 2918 } 2919 2920 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b) 2921 { 2922 const struct bpf_kfunc_desc *d0 = a; 2923 const struct bpf_kfunc_desc *d1 = b; 2924 2925 if (d0->imm != d1->imm) 2926 return d0->imm < d1->imm ? -1 : 1; 2927 if (d0->offset != d1->offset) 2928 return d0->offset < d1->offset ? -1 : 1; 2929 return 0; 2930 } 2931 2932 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog) 2933 { 2934 struct bpf_kfunc_desc_tab *tab; 2935 2936 tab = prog->aux->kfunc_tab; 2937 if (!tab) 2938 return; 2939 2940 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2941 kfunc_desc_cmp_by_imm_off, NULL); 2942 } 2943 2944 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2945 { 2946 return !!prog->aux->kfunc_tab; 2947 } 2948 2949 const struct btf_func_model * 2950 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 2951 const struct bpf_insn *insn) 2952 { 2953 const struct bpf_kfunc_desc desc = { 2954 .imm = insn->imm, 2955 .offset = insn->off, 2956 }; 2957 const struct bpf_kfunc_desc *res; 2958 struct bpf_kfunc_desc_tab *tab; 2959 2960 tab = prog->aux->kfunc_tab; 2961 res = bsearch(&desc, tab->descs, tab->nr_descs, 2962 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off); 2963 2964 return res ? &res->func_model : NULL; 2965 } 2966 2967 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 2968 { 2969 struct bpf_subprog_info *subprog = env->subprog_info; 2970 int i, ret, insn_cnt = env->prog->len, ex_cb_insn; 2971 struct bpf_insn *insn = env->prog->insnsi; 2972 2973 /* Add entry function. */ 2974 ret = add_subprog(env, 0); 2975 if (ret) 2976 return ret; 2977 2978 for (i = 0; i < insn_cnt; i++, insn++) { 2979 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 2980 !bpf_pseudo_kfunc_call(insn)) 2981 continue; 2982 2983 if (!env->bpf_capable) { 2984 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2985 return -EPERM; 2986 } 2987 2988 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 2989 ret = add_subprog(env, i + insn->imm + 1); 2990 else 2991 ret = add_kfunc_call(env, insn->imm, insn->off); 2992 2993 if (ret < 0) 2994 return ret; 2995 } 2996 2997 ret = bpf_find_exception_callback_insn_off(env); 2998 if (ret < 0) 2999 return ret; 3000 ex_cb_insn = ret; 3001 3002 /* If ex_cb_insn > 0, this means that the main program has a subprog 3003 * marked using BTF decl tag to serve as the exception callback. 3004 */ 3005 if (ex_cb_insn) { 3006 ret = add_subprog(env, ex_cb_insn); 3007 if (ret < 0) 3008 return ret; 3009 for (i = 1; i < env->subprog_cnt; i++) { 3010 if (env->subprog_info[i].start != ex_cb_insn) 3011 continue; 3012 env->exception_callback_subprog = i; 3013 mark_subprog_exc_cb(env, i); 3014 break; 3015 } 3016 } 3017 3018 /* Add a fake 'exit' subprog which could simplify subprog iteration 3019 * logic. 'subprog_cnt' should not be increased. 3020 */ 3021 subprog[env->subprog_cnt].start = insn_cnt; 3022 3023 if (env->log.level & BPF_LOG_LEVEL2) 3024 for (i = 0; i < env->subprog_cnt; i++) 3025 verbose(env, "func#%d @%d\n", i, subprog[i].start); 3026 3027 return 0; 3028 } 3029 3030 static int check_subprogs(struct bpf_verifier_env *env) 3031 { 3032 int i, subprog_start, subprog_end, off, cur_subprog = 0; 3033 struct bpf_subprog_info *subprog = env->subprog_info; 3034 struct bpf_insn *insn = env->prog->insnsi; 3035 int insn_cnt = env->prog->len; 3036 3037 /* now check that all jumps are within the same subprog */ 3038 subprog_start = subprog[cur_subprog].start; 3039 subprog_end = subprog[cur_subprog + 1].start; 3040 for (i = 0; i < insn_cnt; i++) { 3041 u8 code = insn[i].code; 3042 3043 if (code == (BPF_JMP | BPF_CALL) && 3044 insn[i].src_reg == 0 && 3045 insn[i].imm == BPF_FUNC_tail_call) { 3046 subprog[cur_subprog].has_tail_call = true; 3047 subprog[cur_subprog].tail_call_reachable = true; 3048 } 3049 if (BPF_CLASS(code) == BPF_LD && 3050 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 3051 subprog[cur_subprog].has_ld_abs = true; 3052 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 3053 goto next; 3054 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 3055 goto next; 3056 if (code == (BPF_JMP32 | BPF_JA)) 3057 off = i + insn[i].imm + 1; 3058 else 3059 off = i + insn[i].off + 1; 3060 if (off < subprog_start || off >= subprog_end) { 3061 verbose(env, "jump out of range from insn %d to %d\n", i, off); 3062 return -EINVAL; 3063 } 3064 next: 3065 if (i == subprog_end - 1) { 3066 /* to avoid fall-through from one subprog into another 3067 * the last insn of the subprog should be either exit 3068 * or unconditional jump back or bpf_throw call 3069 */ 3070 if (code != (BPF_JMP | BPF_EXIT) && 3071 code != (BPF_JMP32 | BPF_JA) && 3072 code != (BPF_JMP | BPF_JA)) { 3073 verbose(env, "last insn is not an exit or jmp\n"); 3074 return -EINVAL; 3075 } 3076 subprog_start = subprog_end; 3077 cur_subprog++; 3078 if (cur_subprog < env->subprog_cnt) 3079 subprog_end = subprog[cur_subprog + 1].start; 3080 } 3081 } 3082 return 0; 3083 } 3084 3085 /* Parentage chain of this register (or stack slot) should take care of all 3086 * issues like callee-saved registers, stack slot allocation time, etc. 3087 */ 3088 static int mark_reg_read(struct bpf_verifier_env *env, 3089 const struct bpf_reg_state *state, 3090 struct bpf_reg_state *parent, u8 flag) 3091 { 3092 bool writes = parent == state->parent; /* Observe write marks */ 3093 int cnt = 0; 3094 3095 while (parent) { 3096 /* if read wasn't screened by an earlier write ... */ 3097 if (writes && state->live & REG_LIVE_WRITTEN) 3098 break; 3099 if (parent->live & REG_LIVE_DONE) { 3100 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 3101 reg_type_str(env, parent->type), 3102 parent->var_off.value, parent->off); 3103 return -EFAULT; 3104 } 3105 /* The first condition is more likely to be true than the 3106 * second, checked it first. 3107 */ 3108 if ((parent->live & REG_LIVE_READ) == flag || 3109 parent->live & REG_LIVE_READ64) 3110 /* The parentage chain never changes and 3111 * this parent was already marked as LIVE_READ. 3112 * There is no need to keep walking the chain again and 3113 * keep re-marking all parents as LIVE_READ. 3114 * This case happens when the same register is read 3115 * multiple times without writes into it in-between. 3116 * Also, if parent has the stronger REG_LIVE_READ64 set, 3117 * then no need to set the weak REG_LIVE_READ32. 3118 */ 3119 break; 3120 /* ... then we depend on parent's value */ 3121 parent->live |= flag; 3122 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 3123 if (flag == REG_LIVE_READ64) 3124 parent->live &= ~REG_LIVE_READ32; 3125 state = parent; 3126 parent = state->parent; 3127 writes = true; 3128 cnt++; 3129 } 3130 3131 if (env->longest_mark_read_walk < cnt) 3132 env->longest_mark_read_walk = cnt; 3133 return 0; 3134 } 3135 3136 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3137 { 3138 struct bpf_func_state *state = func(env, reg); 3139 int spi, ret; 3140 3141 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 3142 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 3143 * check_kfunc_call. 3144 */ 3145 if (reg->type == CONST_PTR_TO_DYNPTR) 3146 return 0; 3147 spi = dynptr_get_spi(env, reg); 3148 if (spi < 0) 3149 return spi; 3150 /* Caller ensures dynptr is valid and initialized, which means spi is in 3151 * bounds and spi is the first dynptr slot. Simply mark stack slot as 3152 * read. 3153 */ 3154 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr, 3155 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64); 3156 if (ret) 3157 return ret; 3158 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr, 3159 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64); 3160 } 3161 3162 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3163 int spi, int nr_slots) 3164 { 3165 struct bpf_func_state *state = func(env, reg); 3166 int err, i; 3167 3168 for (i = 0; i < nr_slots; i++) { 3169 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr; 3170 3171 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64); 3172 if (err) 3173 return err; 3174 3175 mark_stack_slot_scratched(env, spi - i); 3176 } 3177 3178 return 0; 3179 } 3180 3181 /* This function is supposed to be used by the following 32-bit optimization 3182 * code only. It returns TRUE if the source or destination register operates 3183 * on 64-bit, otherwise return FALSE. 3184 */ 3185 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 3186 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 3187 { 3188 u8 code, class, op; 3189 3190 code = insn->code; 3191 class = BPF_CLASS(code); 3192 op = BPF_OP(code); 3193 if (class == BPF_JMP) { 3194 /* BPF_EXIT for "main" will reach here. Return TRUE 3195 * conservatively. 3196 */ 3197 if (op == BPF_EXIT) 3198 return true; 3199 if (op == BPF_CALL) { 3200 /* BPF to BPF call will reach here because of marking 3201 * caller saved clobber with DST_OP_NO_MARK for which we 3202 * don't care the register def because they are anyway 3203 * marked as NOT_INIT already. 3204 */ 3205 if (insn->src_reg == BPF_PSEUDO_CALL) 3206 return false; 3207 /* Helper call will reach here because of arg type 3208 * check, conservatively return TRUE. 3209 */ 3210 if (t == SRC_OP) 3211 return true; 3212 3213 return false; 3214 } 3215 } 3216 3217 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3218 return false; 3219 3220 if (class == BPF_ALU64 || class == BPF_JMP || 3221 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3222 return true; 3223 3224 if (class == BPF_ALU || class == BPF_JMP32) 3225 return false; 3226 3227 if (class == BPF_LDX) { 3228 if (t != SRC_OP) 3229 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX; 3230 /* LDX source must be ptr. */ 3231 return true; 3232 } 3233 3234 if (class == BPF_STX) { 3235 /* BPF_STX (including atomic variants) has multiple source 3236 * operands, one of which is a ptr. Check whether the caller is 3237 * asking about it. 3238 */ 3239 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3240 return true; 3241 return BPF_SIZE(code) == BPF_DW; 3242 } 3243 3244 if (class == BPF_LD) { 3245 u8 mode = BPF_MODE(code); 3246 3247 /* LD_IMM64 */ 3248 if (mode == BPF_IMM) 3249 return true; 3250 3251 /* Both LD_IND and LD_ABS return 32-bit data. */ 3252 if (t != SRC_OP) 3253 return false; 3254 3255 /* Implicit ctx ptr. */ 3256 if (regno == BPF_REG_6) 3257 return true; 3258 3259 /* Explicit source could be any width. */ 3260 return true; 3261 } 3262 3263 if (class == BPF_ST) 3264 /* The only source register for BPF_ST is a ptr. */ 3265 return true; 3266 3267 /* Conservatively return true at default. */ 3268 return true; 3269 } 3270 3271 /* Return the regno defined by the insn, or -1. */ 3272 static int insn_def_regno(const struct bpf_insn *insn) 3273 { 3274 switch (BPF_CLASS(insn->code)) { 3275 case BPF_JMP: 3276 case BPF_JMP32: 3277 case BPF_ST: 3278 return -1; 3279 case BPF_STX: 3280 if ((BPF_MODE(insn->code) == BPF_ATOMIC || 3281 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) && 3282 (insn->imm & BPF_FETCH)) { 3283 if (insn->imm == BPF_CMPXCHG) 3284 return BPF_REG_0; 3285 else 3286 return insn->src_reg; 3287 } else { 3288 return -1; 3289 } 3290 default: 3291 return insn->dst_reg; 3292 } 3293 } 3294 3295 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 3296 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 3297 { 3298 int dst_reg = insn_def_regno(insn); 3299 3300 if (dst_reg == -1) 3301 return false; 3302 3303 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 3304 } 3305 3306 static void mark_insn_zext(struct bpf_verifier_env *env, 3307 struct bpf_reg_state *reg) 3308 { 3309 s32 def_idx = reg->subreg_def; 3310 3311 if (def_idx == DEF_NOT_SUBREG) 3312 return; 3313 3314 env->insn_aux_data[def_idx - 1].zext_dst = true; 3315 /* The dst will be zero extended, so won't be sub-register anymore. */ 3316 reg->subreg_def = DEF_NOT_SUBREG; 3317 } 3318 3319 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno, 3320 enum reg_arg_type t) 3321 { 3322 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3323 struct bpf_reg_state *reg; 3324 bool rw64; 3325 3326 if (regno >= MAX_BPF_REG) { 3327 verbose(env, "R%d is invalid\n", regno); 3328 return -EINVAL; 3329 } 3330 3331 mark_reg_scratched(env, regno); 3332 3333 reg = ®s[regno]; 3334 rw64 = is_reg64(env, insn, regno, reg, t); 3335 if (t == SRC_OP) { 3336 /* check whether register used as source operand can be read */ 3337 if (reg->type == NOT_INIT) { 3338 verbose(env, "R%d !read_ok\n", regno); 3339 return -EACCES; 3340 } 3341 /* We don't need to worry about FP liveness because it's read-only */ 3342 if (regno == BPF_REG_FP) 3343 return 0; 3344 3345 if (rw64) 3346 mark_insn_zext(env, reg); 3347 3348 return mark_reg_read(env, reg, reg->parent, 3349 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 3350 } else { 3351 /* check whether register used as dest operand can be written to */ 3352 if (regno == BPF_REG_FP) { 3353 verbose(env, "frame pointer is read only\n"); 3354 return -EACCES; 3355 } 3356 reg->live |= REG_LIVE_WRITTEN; 3357 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3358 if (t == DST_OP) 3359 mark_reg_unknown(env, regs, regno); 3360 } 3361 return 0; 3362 } 3363 3364 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3365 enum reg_arg_type t) 3366 { 3367 struct bpf_verifier_state *vstate = env->cur_state; 3368 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3369 3370 return __check_reg_arg(env, state->regs, regno, t); 3371 } 3372 3373 static int insn_stack_access_flags(int frameno, int spi) 3374 { 3375 return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno; 3376 } 3377 3378 static int insn_stack_access_spi(int insn_flags) 3379 { 3380 return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK; 3381 } 3382 3383 static int insn_stack_access_frameno(int insn_flags) 3384 { 3385 return insn_flags & INSN_F_FRAMENO_MASK; 3386 } 3387 3388 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 3389 { 3390 env->insn_aux_data[idx].jmp_point = true; 3391 } 3392 3393 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 3394 { 3395 return env->insn_aux_data[insn_idx].jmp_point; 3396 } 3397 3398 #define LR_FRAMENO_BITS 3 3399 #define LR_SPI_BITS 6 3400 #define LR_ENTRY_BITS (LR_SPI_BITS + LR_FRAMENO_BITS + 1) 3401 #define LR_SIZE_BITS 4 3402 #define LR_FRAMENO_MASK ((1ull << LR_FRAMENO_BITS) - 1) 3403 #define LR_SPI_MASK ((1ull << LR_SPI_BITS) - 1) 3404 #define LR_SIZE_MASK ((1ull << LR_SIZE_BITS) - 1) 3405 #define LR_SPI_OFF LR_FRAMENO_BITS 3406 #define LR_IS_REG_OFF (LR_SPI_BITS + LR_FRAMENO_BITS) 3407 #define LINKED_REGS_MAX 6 3408 3409 struct linked_reg { 3410 u8 frameno; 3411 union { 3412 u8 spi; 3413 u8 regno; 3414 }; 3415 bool is_reg; 3416 }; 3417 3418 struct linked_regs { 3419 int cnt; 3420 struct linked_reg entries[LINKED_REGS_MAX]; 3421 }; 3422 3423 static struct linked_reg *linked_regs_push(struct linked_regs *s) 3424 { 3425 if (s->cnt < LINKED_REGS_MAX) 3426 return &s->entries[s->cnt++]; 3427 3428 return NULL; 3429 } 3430 3431 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track 3432 * number of elements currently in stack. 3433 * Pack one history entry for linked registers as 10 bits in the following format: 3434 * - 3-bits frameno 3435 * - 6-bits spi_or_reg 3436 * - 1-bit is_reg 3437 */ 3438 static u64 linked_regs_pack(struct linked_regs *s) 3439 { 3440 u64 val = 0; 3441 int i; 3442 3443 for (i = 0; i < s->cnt; ++i) { 3444 struct linked_reg *e = &s->entries[i]; 3445 u64 tmp = 0; 3446 3447 tmp |= e->frameno; 3448 tmp |= e->spi << LR_SPI_OFF; 3449 tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF; 3450 3451 val <<= LR_ENTRY_BITS; 3452 val |= tmp; 3453 } 3454 val <<= LR_SIZE_BITS; 3455 val |= s->cnt; 3456 return val; 3457 } 3458 3459 static void linked_regs_unpack(u64 val, struct linked_regs *s) 3460 { 3461 int i; 3462 3463 s->cnt = val & LR_SIZE_MASK; 3464 val >>= LR_SIZE_BITS; 3465 3466 for (i = 0; i < s->cnt; ++i) { 3467 struct linked_reg *e = &s->entries[i]; 3468 3469 e->frameno = val & LR_FRAMENO_MASK; 3470 e->spi = (val >> LR_SPI_OFF) & LR_SPI_MASK; 3471 e->is_reg = (val >> LR_IS_REG_OFF) & 0x1; 3472 val >>= LR_ENTRY_BITS; 3473 } 3474 } 3475 3476 /* for any branch, call, exit record the history of jmps in the given state */ 3477 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur, 3478 int insn_flags, u64 linked_regs) 3479 { 3480 u32 cnt = cur->jmp_history_cnt; 3481 struct bpf_jmp_history_entry *p; 3482 size_t alloc_size; 3483 3484 /* combine instruction flags if we already recorded this instruction */ 3485 if (env->cur_hist_ent) { 3486 /* atomic instructions push insn_flags twice, for READ and 3487 * WRITE sides, but they should agree on stack slot 3488 */ 3489 WARN_ONCE((env->cur_hist_ent->flags & insn_flags) && 3490 (env->cur_hist_ent->flags & insn_flags) != insn_flags, 3491 "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n", 3492 env->insn_idx, env->cur_hist_ent->flags, insn_flags); 3493 env->cur_hist_ent->flags |= insn_flags; 3494 WARN_ONCE(env->cur_hist_ent->linked_regs != 0, 3495 "verifier insn history bug: insn_idx %d linked_regs != 0: %#llx\n", 3496 env->insn_idx, env->cur_hist_ent->linked_regs); 3497 env->cur_hist_ent->linked_regs = linked_regs; 3498 return 0; 3499 } 3500 3501 cnt++; 3502 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 3503 p = krealloc(cur->jmp_history, alloc_size, GFP_USER); 3504 if (!p) 3505 return -ENOMEM; 3506 cur->jmp_history = p; 3507 3508 p = &cur->jmp_history[cnt - 1]; 3509 p->idx = env->insn_idx; 3510 p->prev_idx = env->prev_insn_idx; 3511 p->flags = insn_flags; 3512 p->linked_regs = linked_regs; 3513 cur->jmp_history_cnt = cnt; 3514 env->cur_hist_ent = p; 3515 3516 return 0; 3517 } 3518 3519 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st, 3520 u32 hist_end, int insn_idx) 3521 { 3522 if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx) 3523 return &st->jmp_history[hist_end - 1]; 3524 return NULL; 3525 } 3526 3527 /* Backtrack one insn at a time. If idx is not at the top of recorded 3528 * history then previous instruction came from straight line execution. 3529 * Return -ENOENT if we exhausted all instructions within given state. 3530 * 3531 * It's legal to have a bit of a looping with the same starting and ending 3532 * insn index within the same state, e.g.: 3->4->5->3, so just because current 3533 * instruction index is the same as state's first_idx doesn't mean we are 3534 * done. If there is still some jump history left, we should keep going. We 3535 * need to take into account that we might have a jump history between given 3536 * state's parent and itself, due to checkpointing. In this case, we'll have 3537 * history entry recording a jump from last instruction of parent state and 3538 * first instruction of given state. 3539 */ 3540 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 3541 u32 *history) 3542 { 3543 u32 cnt = *history; 3544 3545 if (i == st->first_insn_idx) { 3546 if (cnt == 0) 3547 return -ENOENT; 3548 if (cnt == 1 && st->jmp_history[0].idx == i) 3549 return -ENOENT; 3550 } 3551 3552 if (cnt && st->jmp_history[cnt - 1].idx == i) { 3553 i = st->jmp_history[cnt - 1].prev_idx; 3554 (*history)--; 3555 } else { 3556 i--; 3557 } 3558 return i; 3559 } 3560 3561 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3562 { 3563 const struct btf_type *func; 3564 struct btf *desc_btf; 3565 3566 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3567 return NULL; 3568 3569 desc_btf = find_kfunc_desc_btf(data, insn->off); 3570 if (IS_ERR(desc_btf)) 3571 return "<error>"; 3572 3573 func = btf_type_by_id(desc_btf, insn->imm); 3574 return btf_name_by_offset(desc_btf, func->name_off); 3575 } 3576 3577 static inline void bt_init(struct backtrack_state *bt, u32 frame) 3578 { 3579 bt->frame = frame; 3580 } 3581 3582 static inline void bt_reset(struct backtrack_state *bt) 3583 { 3584 struct bpf_verifier_env *env = bt->env; 3585 3586 memset(bt, 0, sizeof(*bt)); 3587 bt->env = env; 3588 } 3589 3590 static inline u32 bt_empty(struct backtrack_state *bt) 3591 { 3592 u64 mask = 0; 3593 int i; 3594 3595 for (i = 0; i <= bt->frame; i++) 3596 mask |= bt->reg_masks[i] | bt->stack_masks[i]; 3597 3598 return mask == 0; 3599 } 3600 3601 static inline int bt_subprog_enter(struct backtrack_state *bt) 3602 { 3603 if (bt->frame == MAX_CALL_FRAMES - 1) { 3604 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame); 3605 WARN_ONCE(1, "verifier backtracking bug"); 3606 return -EFAULT; 3607 } 3608 bt->frame++; 3609 return 0; 3610 } 3611 3612 static inline int bt_subprog_exit(struct backtrack_state *bt) 3613 { 3614 if (bt->frame == 0) { 3615 verbose(bt->env, "BUG subprog exit from frame 0\n"); 3616 WARN_ONCE(1, "verifier backtracking bug"); 3617 return -EFAULT; 3618 } 3619 bt->frame--; 3620 return 0; 3621 } 3622 3623 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3624 { 3625 bt->reg_masks[frame] |= 1 << reg; 3626 } 3627 3628 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3629 { 3630 bt->reg_masks[frame] &= ~(1 << reg); 3631 } 3632 3633 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg) 3634 { 3635 bt_set_frame_reg(bt, bt->frame, reg); 3636 } 3637 3638 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg) 3639 { 3640 bt_clear_frame_reg(bt, bt->frame, reg); 3641 } 3642 3643 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3644 { 3645 bt->stack_masks[frame] |= 1ull << slot; 3646 } 3647 3648 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3649 { 3650 bt->stack_masks[frame] &= ~(1ull << slot); 3651 } 3652 3653 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame) 3654 { 3655 return bt->reg_masks[frame]; 3656 } 3657 3658 static inline u32 bt_reg_mask(struct backtrack_state *bt) 3659 { 3660 return bt->reg_masks[bt->frame]; 3661 } 3662 3663 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame) 3664 { 3665 return bt->stack_masks[frame]; 3666 } 3667 3668 static inline u64 bt_stack_mask(struct backtrack_state *bt) 3669 { 3670 return bt->stack_masks[bt->frame]; 3671 } 3672 3673 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg) 3674 { 3675 return bt->reg_masks[bt->frame] & (1 << reg); 3676 } 3677 3678 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg) 3679 { 3680 return bt->reg_masks[frame] & (1 << reg); 3681 } 3682 3683 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot) 3684 { 3685 return bt->stack_masks[frame] & (1ull << slot); 3686 } 3687 3688 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */ 3689 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask) 3690 { 3691 DECLARE_BITMAP(mask, 64); 3692 bool first = true; 3693 int i, n; 3694 3695 buf[0] = '\0'; 3696 3697 bitmap_from_u64(mask, reg_mask); 3698 for_each_set_bit(i, mask, 32) { 3699 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i); 3700 first = false; 3701 buf += n; 3702 buf_sz -= n; 3703 if (buf_sz < 0) 3704 break; 3705 } 3706 } 3707 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */ 3708 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask) 3709 { 3710 DECLARE_BITMAP(mask, 64); 3711 bool first = true; 3712 int i, n; 3713 3714 buf[0] = '\0'; 3715 3716 bitmap_from_u64(mask, stack_mask); 3717 for_each_set_bit(i, mask, 64) { 3718 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8); 3719 first = false; 3720 buf += n; 3721 buf_sz -= n; 3722 if (buf_sz < 0) 3723 break; 3724 } 3725 } 3726 3727 /* If any register R in hist->linked_regs is marked as precise in bt, 3728 * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs. 3729 */ 3730 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist) 3731 { 3732 struct linked_regs linked_regs; 3733 bool some_precise = false; 3734 int i; 3735 3736 if (!hist || hist->linked_regs == 0) 3737 return; 3738 3739 linked_regs_unpack(hist->linked_regs, &linked_regs); 3740 for (i = 0; i < linked_regs.cnt; ++i) { 3741 struct linked_reg *e = &linked_regs.entries[i]; 3742 3743 if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) || 3744 (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) { 3745 some_precise = true; 3746 break; 3747 } 3748 } 3749 3750 if (!some_precise) 3751 return; 3752 3753 for (i = 0; i < linked_regs.cnt; ++i) { 3754 struct linked_reg *e = &linked_regs.entries[i]; 3755 3756 if (e->is_reg) 3757 bt_set_frame_reg(bt, e->frameno, e->regno); 3758 else 3759 bt_set_frame_slot(bt, e->frameno, e->spi); 3760 } 3761 } 3762 3763 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx); 3764 3765 /* For given verifier state backtrack_insn() is called from the last insn to 3766 * the first insn. Its purpose is to compute a bitmask of registers and 3767 * stack slots that needs precision in the parent verifier state. 3768 * 3769 * @idx is an index of the instruction we are currently processing; 3770 * @subseq_idx is an index of the subsequent instruction that: 3771 * - *would be* executed next, if jump history is viewed in forward order; 3772 * - *was* processed previously during backtracking. 3773 */ 3774 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx, 3775 struct bpf_jmp_history_entry *hist, struct backtrack_state *bt) 3776 { 3777 const struct bpf_insn_cbs cbs = { 3778 .cb_call = disasm_kfunc_name, 3779 .cb_print = verbose, 3780 .private_data = env, 3781 }; 3782 struct bpf_insn *insn = env->prog->insnsi + idx; 3783 u8 class = BPF_CLASS(insn->code); 3784 u8 opcode = BPF_OP(insn->code); 3785 u8 mode = BPF_MODE(insn->code); 3786 u32 dreg = insn->dst_reg; 3787 u32 sreg = insn->src_reg; 3788 u32 spi, i, fr; 3789 3790 if (insn->code == 0) 3791 return 0; 3792 if (env->log.level & BPF_LOG_LEVEL2) { 3793 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt)); 3794 verbose(env, "mark_precise: frame%d: regs=%s ", 3795 bt->frame, env->tmp_str_buf); 3796 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt)); 3797 verbose(env, "stack=%s before ", env->tmp_str_buf); 3798 verbose(env, "%d: ", idx); 3799 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3800 } 3801 3802 /* If there is a history record that some registers gained range at this insn, 3803 * propagate precision marks to those registers, so that bt_is_reg_set() 3804 * accounts for these registers. 3805 */ 3806 bt_sync_linked_regs(bt, hist); 3807 3808 if (class == BPF_ALU || class == BPF_ALU64) { 3809 if (!bt_is_reg_set(bt, dreg)) 3810 return 0; 3811 if (opcode == BPF_END || opcode == BPF_NEG) { 3812 /* sreg is reserved and unused 3813 * dreg still need precision before this insn 3814 */ 3815 return 0; 3816 } else if (opcode == BPF_MOV) { 3817 if (BPF_SRC(insn->code) == BPF_X) { 3818 /* dreg = sreg or dreg = (s8, s16, s32)sreg 3819 * dreg needs precision after this insn 3820 * sreg needs precision before this insn 3821 */ 3822 bt_clear_reg(bt, dreg); 3823 if (sreg != BPF_REG_FP) 3824 bt_set_reg(bt, sreg); 3825 } else { 3826 /* dreg = K 3827 * dreg needs precision after this insn. 3828 * Corresponding register is already marked 3829 * as precise=true in this verifier state. 3830 * No further markings in parent are necessary 3831 */ 3832 bt_clear_reg(bt, dreg); 3833 } 3834 } else { 3835 if (BPF_SRC(insn->code) == BPF_X) { 3836 /* dreg += sreg 3837 * both dreg and sreg need precision 3838 * before this insn 3839 */ 3840 if (sreg != BPF_REG_FP) 3841 bt_set_reg(bt, sreg); 3842 } /* else dreg += K 3843 * dreg still needs precision before this insn 3844 */ 3845 } 3846 } else if (class == BPF_LDX) { 3847 if (!bt_is_reg_set(bt, dreg)) 3848 return 0; 3849 bt_clear_reg(bt, dreg); 3850 3851 /* scalars can only be spilled into stack w/o losing precision. 3852 * Load from any other memory can be zero extended. 3853 * The desire to keep that precision is already indicated 3854 * by 'precise' mark in corresponding register of this state. 3855 * No further tracking necessary. 3856 */ 3857 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 3858 return 0; 3859 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 3860 * that [fp - off] slot contains scalar that needs to be 3861 * tracked with precision 3862 */ 3863 spi = insn_stack_access_spi(hist->flags); 3864 fr = insn_stack_access_frameno(hist->flags); 3865 bt_set_frame_slot(bt, fr, spi); 3866 } else if (class == BPF_STX || class == BPF_ST) { 3867 if (bt_is_reg_set(bt, dreg)) 3868 /* stx & st shouldn't be using _scalar_ dst_reg 3869 * to access memory. It means backtracking 3870 * encountered a case of pointer subtraction. 3871 */ 3872 return -ENOTSUPP; 3873 /* scalars can only be spilled into stack */ 3874 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 3875 return 0; 3876 spi = insn_stack_access_spi(hist->flags); 3877 fr = insn_stack_access_frameno(hist->flags); 3878 if (!bt_is_frame_slot_set(bt, fr, spi)) 3879 return 0; 3880 bt_clear_frame_slot(bt, fr, spi); 3881 if (class == BPF_STX) 3882 bt_set_reg(bt, sreg); 3883 } else if (class == BPF_JMP || class == BPF_JMP32) { 3884 if (bpf_pseudo_call(insn)) { 3885 int subprog_insn_idx, subprog; 3886 3887 subprog_insn_idx = idx + insn->imm + 1; 3888 subprog = find_subprog(env, subprog_insn_idx); 3889 if (subprog < 0) 3890 return -EFAULT; 3891 3892 if (subprog_is_global(env, subprog)) { 3893 /* check that jump history doesn't have any 3894 * extra instructions from subprog; the next 3895 * instruction after call to global subprog 3896 * should be literally next instruction in 3897 * caller program 3898 */ 3899 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug"); 3900 /* r1-r5 are invalidated after subprog call, 3901 * so for global func call it shouldn't be set 3902 * anymore 3903 */ 3904 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3905 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3906 WARN_ONCE(1, "verifier backtracking bug"); 3907 return -EFAULT; 3908 } 3909 /* global subprog always sets R0 */ 3910 bt_clear_reg(bt, BPF_REG_0); 3911 return 0; 3912 } else { 3913 /* static subprog call instruction, which 3914 * means that we are exiting current subprog, 3915 * so only r1-r5 could be still requested as 3916 * precise, r0 and r6-r10 or any stack slot in 3917 * the current frame should be zero by now 3918 */ 3919 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3920 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3921 WARN_ONCE(1, "verifier backtracking bug"); 3922 return -EFAULT; 3923 } 3924 /* we are now tracking register spills correctly, 3925 * so any instance of leftover slots is a bug 3926 */ 3927 if (bt_stack_mask(bt) != 0) { 3928 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt)); 3929 WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)"); 3930 return -EFAULT; 3931 } 3932 /* propagate r1-r5 to the caller */ 3933 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 3934 if (bt_is_reg_set(bt, i)) { 3935 bt_clear_reg(bt, i); 3936 bt_set_frame_reg(bt, bt->frame - 1, i); 3937 } 3938 } 3939 if (bt_subprog_exit(bt)) 3940 return -EFAULT; 3941 return 0; 3942 } 3943 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) { 3944 /* exit from callback subprog to callback-calling helper or 3945 * kfunc call. Use idx/subseq_idx check to discern it from 3946 * straight line code backtracking. 3947 * Unlike the subprog call handling above, we shouldn't 3948 * propagate precision of r1-r5 (if any requested), as they are 3949 * not actually arguments passed directly to callback subprogs 3950 */ 3951 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3952 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3953 WARN_ONCE(1, "verifier backtracking bug"); 3954 return -EFAULT; 3955 } 3956 if (bt_stack_mask(bt) != 0) { 3957 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt)); 3958 WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)"); 3959 return -EFAULT; 3960 } 3961 /* clear r1-r5 in callback subprog's mask */ 3962 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3963 bt_clear_reg(bt, i); 3964 if (bt_subprog_exit(bt)) 3965 return -EFAULT; 3966 return 0; 3967 } else if (opcode == BPF_CALL) { 3968 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 3969 * catch this error later. Make backtracking conservative 3970 * with ENOTSUPP. 3971 */ 3972 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 3973 return -ENOTSUPP; 3974 /* regular helper call sets R0 */ 3975 bt_clear_reg(bt, BPF_REG_0); 3976 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3977 /* if backtracing was looking for registers R1-R5 3978 * they should have been found already. 3979 */ 3980 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3981 WARN_ONCE(1, "verifier backtracking bug"); 3982 return -EFAULT; 3983 } 3984 } else if (opcode == BPF_EXIT) { 3985 bool r0_precise; 3986 3987 /* Backtracking to a nested function call, 'idx' is a part of 3988 * the inner frame 'subseq_idx' is a part of the outer frame. 3989 * In case of a regular function call, instructions giving 3990 * precision to registers R1-R5 should have been found already. 3991 * In case of a callback, it is ok to have R1-R5 marked for 3992 * backtracking, as these registers are set by the function 3993 * invoking callback. 3994 */ 3995 if (subseq_idx >= 0 && calls_callback(env, subseq_idx)) 3996 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3997 bt_clear_reg(bt, i); 3998 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3999 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 4000 WARN_ONCE(1, "verifier backtracking bug"); 4001 return -EFAULT; 4002 } 4003 4004 /* BPF_EXIT in subprog or callback always returns 4005 * right after the call instruction, so by checking 4006 * whether the instruction at subseq_idx-1 is subprog 4007 * call or not we can distinguish actual exit from 4008 * *subprog* from exit from *callback*. In the former 4009 * case, we need to propagate r0 precision, if 4010 * necessary. In the former we never do that. 4011 */ 4012 r0_precise = subseq_idx - 1 >= 0 && 4013 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) && 4014 bt_is_reg_set(bt, BPF_REG_0); 4015 4016 bt_clear_reg(bt, BPF_REG_0); 4017 if (bt_subprog_enter(bt)) 4018 return -EFAULT; 4019 4020 if (r0_precise) 4021 bt_set_reg(bt, BPF_REG_0); 4022 /* r6-r9 and stack slots will stay set in caller frame 4023 * bitmasks until we return back from callee(s) 4024 */ 4025 return 0; 4026 } else if (BPF_SRC(insn->code) == BPF_X) { 4027 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg)) 4028 return 0; 4029 /* dreg <cond> sreg 4030 * Both dreg and sreg need precision before 4031 * this insn. If only sreg was marked precise 4032 * before it would be equally necessary to 4033 * propagate it to dreg. 4034 */ 4035 bt_set_reg(bt, dreg); 4036 bt_set_reg(bt, sreg); 4037 } else if (BPF_SRC(insn->code) == BPF_K) { 4038 /* dreg <cond> K 4039 * Only dreg still needs precision before 4040 * this insn, so for the K-based conditional 4041 * there is nothing new to be marked. 4042 */ 4043 } 4044 } else if (class == BPF_LD) { 4045 if (!bt_is_reg_set(bt, dreg)) 4046 return 0; 4047 bt_clear_reg(bt, dreg); 4048 /* It's ld_imm64 or ld_abs or ld_ind. 4049 * For ld_imm64 no further tracking of precision 4050 * into parent is necessary 4051 */ 4052 if (mode == BPF_IND || mode == BPF_ABS) 4053 /* to be analyzed */ 4054 return -ENOTSUPP; 4055 } 4056 /* Propagate precision marks to linked registers, to account for 4057 * registers marked as precise in this function. 4058 */ 4059 bt_sync_linked_regs(bt, hist); 4060 return 0; 4061 } 4062 4063 /* the scalar precision tracking algorithm: 4064 * . at the start all registers have precise=false. 4065 * . scalar ranges are tracked as normal through alu and jmp insns. 4066 * . once precise value of the scalar register is used in: 4067 * . ptr + scalar alu 4068 * . if (scalar cond K|scalar) 4069 * . helper_call(.., scalar, ...) where ARG_CONST is expected 4070 * backtrack through the verifier states and mark all registers and 4071 * stack slots with spilled constants that these scalar regisers 4072 * should be precise. 4073 * . during state pruning two registers (or spilled stack slots) 4074 * are equivalent if both are not precise. 4075 * 4076 * Note the verifier cannot simply walk register parentage chain, 4077 * since many different registers and stack slots could have been 4078 * used to compute single precise scalar. 4079 * 4080 * The approach of starting with precise=true for all registers and then 4081 * backtrack to mark a register as not precise when the verifier detects 4082 * that program doesn't care about specific value (e.g., when helper 4083 * takes register as ARG_ANYTHING parameter) is not safe. 4084 * 4085 * It's ok to walk single parentage chain of the verifier states. 4086 * It's possible that this backtracking will go all the way till 1st insn. 4087 * All other branches will be explored for needing precision later. 4088 * 4089 * The backtracking needs to deal with cases like: 4090 * 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) 4091 * r9 -= r8 4092 * r5 = r9 4093 * if r5 > 0x79f goto pc+7 4094 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 4095 * r5 += 1 4096 * ... 4097 * call bpf_perf_event_output#25 4098 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 4099 * 4100 * and this case: 4101 * r6 = 1 4102 * call foo // uses callee's r6 inside to compute r0 4103 * r0 += r6 4104 * if r0 == 0 goto 4105 * 4106 * to track above reg_mask/stack_mask needs to be independent for each frame. 4107 * 4108 * Also if parent's curframe > frame where backtracking started, 4109 * the verifier need to mark registers in both frames, otherwise callees 4110 * may incorrectly prune callers. This is similar to 4111 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 4112 * 4113 * For now backtracking falls back into conservative marking. 4114 */ 4115 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 4116 struct bpf_verifier_state *st) 4117 { 4118 struct bpf_func_state *func; 4119 struct bpf_reg_state *reg; 4120 int i, j; 4121 4122 if (env->log.level & BPF_LOG_LEVEL2) { 4123 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n", 4124 st->curframe); 4125 } 4126 4127 /* big hammer: mark all scalars precise in this path. 4128 * pop_stack may still get !precise scalars. 4129 * We also skip current state and go straight to first parent state, 4130 * because precision markings in current non-checkpointed state are 4131 * not needed. See why in the comment in __mark_chain_precision below. 4132 */ 4133 for (st = st->parent; st; st = st->parent) { 4134 for (i = 0; i <= st->curframe; i++) { 4135 func = st->frame[i]; 4136 for (j = 0; j < BPF_REG_FP; j++) { 4137 reg = &func->regs[j]; 4138 if (reg->type != SCALAR_VALUE || reg->precise) 4139 continue; 4140 reg->precise = true; 4141 if (env->log.level & BPF_LOG_LEVEL2) { 4142 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n", 4143 i, j); 4144 } 4145 } 4146 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 4147 if (!is_spilled_reg(&func->stack[j])) 4148 continue; 4149 reg = &func->stack[j].spilled_ptr; 4150 if (reg->type != SCALAR_VALUE || reg->precise) 4151 continue; 4152 reg->precise = true; 4153 if (env->log.level & BPF_LOG_LEVEL2) { 4154 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n", 4155 i, -(j + 1) * 8); 4156 } 4157 } 4158 } 4159 } 4160 } 4161 4162 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 4163 { 4164 struct bpf_func_state *func; 4165 struct bpf_reg_state *reg; 4166 int i, j; 4167 4168 for (i = 0; i <= st->curframe; i++) { 4169 func = st->frame[i]; 4170 for (j = 0; j < BPF_REG_FP; j++) { 4171 reg = &func->regs[j]; 4172 if (reg->type != SCALAR_VALUE) 4173 continue; 4174 reg->precise = false; 4175 } 4176 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 4177 if (!is_spilled_reg(&func->stack[j])) 4178 continue; 4179 reg = &func->stack[j].spilled_ptr; 4180 if (reg->type != SCALAR_VALUE) 4181 continue; 4182 reg->precise = false; 4183 } 4184 } 4185 } 4186 4187 /* 4188 * __mark_chain_precision() backtracks BPF program instruction sequence and 4189 * chain of verifier states making sure that register *regno* (if regno >= 0) 4190 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 4191 * SCALARS, as well as any other registers and slots that contribute to 4192 * a tracked state of given registers/stack slots, depending on specific BPF 4193 * assembly instructions (see backtrack_insns() for exact instruction handling 4194 * logic). This backtracking relies on recorded jmp_history and is able to 4195 * traverse entire chain of parent states. This process ends only when all the 4196 * necessary registers/slots and their transitive dependencies are marked as 4197 * precise. 4198 * 4199 * One important and subtle aspect is that precise marks *do not matter* in 4200 * the currently verified state (current state). It is important to understand 4201 * why this is the case. 4202 * 4203 * First, note that current state is the state that is not yet "checkpointed", 4204 * i.e., it is not yet put into env->explored_states, and it has no children 4205 * states as well. It's ephemeral, and can end up either a) being discarded if 4206 * compatible explored state is found at some point or BPF_EXIT instruction is 4207 * reached or b) checkpointed and put into env->explored_states, branching out 4208 * into one or more children states. 4209 * 4210 * In the former case, precise markings in current state are completely 4211 * ignored by state comparison code (see regsafe() for details). Only 4212 * checkpointed ("old") state precise markings are important, and if old 4213 * state's register/slot is precise, regsafe() assumes current state's 4214 * register/slot as precise and checks value ranges exactly and precisely. If 4215 * states turn out to be compatible, current state's necessary precise 4216 * markings and any required parent states' precise markings are enforced 4217 * after the fact with propagate_precision() logic, after the fact. But it's 4218 * important to realize that in this case, even after marking current state 4219 * registers/slots as precise, we immediately discard current state. So what 4220 * actually matters is any of the precise markings propagated into current 4221 * state's parent states, which are always checkpointed (due to b) case above). 4222 * As such, for scenario a) it doesn't matter if current state has precise 4223 * markings set or not. 4224 * 4225 * Now, for the scenario b), checkpointing and forking into child(ren) 4226 * state(s). Note that before current state gets to checkpointing step, any 4227 * processed instruction always assumes precise SCALAR register/slot 4228 * knowledge: if precise value or range is useful to prune jump branch, BPF 4229 * verifier takes this opportunity enthusiastically. Similarly, when 4230 * register's value is used to calculate offset or memory address, exact 4231 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 4232 * what we mentioned above about state comparison ignoring precise markings 4233 * during state comparison, BPF verifier ignores and also assumes precise 4234 * markings *at will* during instruction verification process. But as verifier 4235 * assumes precision, it also propagates any precision dependencies across 4236 * parent states, which are not yet finalized, so can be further restricted 4237 * based on new knowledge gained from restrictions enforced by their children 4238 * states. This is so that once those parent states are finalized, i.e., when 4239 * they have no more active children state, state comparison logic in 4240 * is_state_visited() would enforce strict and precise SCALAR ranges, if 4241 * required for correctness. 4242 * 4243 * To build a bit more intuition, note also that once a state is checkpointed, 4244 * the path we took to get to that state is not important. This is crucial 4245 * property for state pruning. When state is checkpointed and finalized at 4246 * some instruction index, it can be correctly and safely used to "short 4247 * circuit" any *compatible* state that reaches exactly the same instruction 4248 * index. I.e., if we jumped to that instruction from a completely different 4249 * code path than original finalized state was derived from, it doesn't 4250 * matter, current state can be discarded because from that instruction 4251 * forward having a compatible state will ensure we will safely reach the 4252 * exit. States describe preconditions for further exploration, but completely 4253 * forget the history of how we got here. 4254 * 4255 * This also means that even if we needed precise SCALAR range to get to 4256 * finalized state, but from that point forward *that same* SCALAR register is 4257 * never used in a precise context (i.e., it's precise value is not needed for 4258 * correctness), it's correct and safe to mark such register as "imprecise" 4259 * (i.e., precise marking set to false). This is what we rely on when we do 4260 * not set precise marking in current state. If no child state requires 4261 * precision for any given SCALAR register, it's safe to dictate that it can 4262 * be imprecise. If any child state does require this register to be precise, 4263 * we'll mark it precise later retroactively during precise markings 4264 * propagation from child state to parent states. 4265 * 4266 * Skipping precise marking setting in current state is a mild version of 4267 * relying on the above observation. But we can utilize this property even 4268 * more aggressively by proactively forgetting any precise marking in the 4269 * current state (which we inherited from the parent state), right before we 4270 * checkpoint it and branch off into new child state. This is done by 4271 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 4272 * finalized states which help in short circuiting more future states. 4273 */ 4274 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno) 4275 { 4276 struct backtrack_state *bt = &env->bt; 4277 struct bpf_verifier_state *st = env->cur_state; 4278 int first_idx = st->first_insn_idx; 4279 int last_idx = env->insn_idx; 4280 int subseq_idx = -1; 4281 struct bpf_func_state *func; 4282 struct bpf_reg_state *reg; 4283 bool skip_first = true; 4284 int i, fr, err; 4285 4286 if (!env->bpf_capable) 4287 return 0; 4288 4289 /* set frame number from which we are starting to backtrack */ 4290 bt_init(bt, env->cur_state->curframe); 4291 4292 /* Do sanity checks against current state of register and/or stack 4293 * slot, but don't set precise flag in current state, as precision 4294 * tracking in the current state is unnecessary. 4295 */ 4296 func = st->frame[bt->frame]; 4297 if (regno >= 0) { 4298 reg = &func->regs[regno]; 4299 if (reg->type != SCALAR_VALUE) { 4300 WARN_ONCE(1, "backtracing misuse"); 4301 return -EFAULT; 4302 } 4303 bt_set_reg(bt, regno); 4304 } 4305 4306 if (bt_empty(bt)) 4307 return 0; 4308 4309 for (;;) { 4310 DECLARE_BITMAP(mask, 64); 4311 u32 history = st->jmp_history_cnt; 4312 struct bpf_jmp_history_entry *hist; 4313 4314 if (env->log.level & BPF_LOG_LEVEL2) { 4315 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n", 4316 bt->frame, last_idx, first_idx, subseq_idx); 4317 } 4318 4319 if (last_idx < 0) { 4320 /* we are at the entry into subprog, which 4321 * is expected for global funcs, but only if 4322 * requested precise registers are R1-R5 4323 * (which are global func's input arguments) 4324 */ 4325 if (st->curframe == 0 && 4326 st->frame[0]->subprogno > 0 && 4327 st->frame[0]->callsite == BPF_MAIN_FUNC && 4328 bt_stack_mask(bt) == 0 && 4329 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) { 4330 bitmap_from_u64(mask, bt_reg_mask(bt)); 4331 for_each_set_bit(i, mask, 32) { 4332 reg = &st->frame[0]->regs[i]; 4333 bt_clear_reg(bt, i); 4334 if (reg->type == SCALAR_VALUE) 4335 reg->precise = true; 4336 } 4337 return 0; 4338 } 4339 4340 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n", 4341 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt)); 4342 WARN_ONCE(1, "verifier backtracking bug"); 4343 return -EFAULT; 4344 } 4345 4346 for (i = last_idx;;) { 4347 if (skip_first) { 4348 err = 0; 4349 skip_first = false; 4350 } else { 4351 hist = get_jmp_hist_entry(st, history, i); 4352 err = backtrack_insn(env, i, subseq_idx, hist, bt); 4353 } 4354 if (err == -ENOTSUPP) { 4355 mark_all_scalars_precise(env, env->cur_state); 4356 bt_reset(bt); 4357 return 0; 4358 } else if (err) { 4359 return err; 4360 } 4361 if (bt_empty(bt)) 4362 /* Found assignment(s) into tracked register in this state. 4363 * Since this state is already marked, just return. 4364 * Nothing to be tracked further in the parent state. 4365 */ 4366 return 0; 4367 subseq_idx = i; 4368 i = get_prev_insn_idx(st, i, &history); 4369 if (i == -ENOENT) 4370 break; 4371 if (i >= env->prog->len) { 4372 /* This can happen if backtracking reached insn 0 4373 * and there are still reg_mask or stack_mask 4374 * to backtrack. 4375 * It means the backtracking missed the spot where 4376 * particular register was initialized with a constant. 4377 */ 4378 verbose(env, "BUG backtracking idx %d\n", i); 4379 WARN_ONCE(1, "verifier backtracking bug"); 4380 return -EFAULT; 4381 } 4382 } 4383 st = st->parent; 4384 if (!st) 4385 break; 4386 4387 for (fr = bt->frame; fr >= 0; fr--) { 4388 func = st->frame[fr]; 4389 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4390 for_each_set_bit(i, mask, 32) { 4391 reg = &func->regs[i]; 4392 if (reg->type != SCALAR_VALUE) { 4393 bt_clear_frame_reg(bt, fr, i); 4394 continue; 4395 } 4396 if (reg->precise) 4397 bt_clear_frame_reg(bt, fr, i); 4398 else 4399 reg->precise = true; 4400 } 4401 4402 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4403 for_each_set_bit(i, mask, 64) { 4404 if (i >= func->allocated_stack / BPF_REG_SIZE) { 4405 verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n", 4406 i, func->allocated_stack / BPF_REG_SIZE); 4407 WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)"); 4408 return -EFAULT; 4409 } 4410 4411 if (!is_spilled_scalar_reg(&func->stack[i])) { 4412 bt_clear_frame_slot(bt, fr, i); 4413 continue; 4414 } 4415 reg = &func->stack[i].spilled_ptr; 4416 if (reg->precise) 4417 bt_clear_frame_slot(bt, fr, i); 4418 else 4419 reg->precise = true; 4420 } 4421 if (env->log.level & BPF_LOG_LEVEL2) { 4422 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4423 bt_frame_reg_mask(bt, fr)); 4424 verbose(env, "mark_precise: frame%d: parent state regs=%s ", 4425 fr, env->tmp_str_buf); 4426 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4427 bt_frame_stack_mask(bt, fr)); 4428 verbose(env, "stack=%s: ", env->tmp_str_buf); 4429 print_verifier_state(env, func, true); 4430 } 4431 } 4432 4433 if (bt_empty(bt)) 4434 return 0; 4435 4436 subseq_idx = first_idx; 4437 last_idx = st->last_insn_idx; 4438 first_idx = st->first_insn_idx; 4439 } 4440 4441 /* if we still have requested precise regs or slots, we missed 4442 * something (e.g., stack access through non-r10 register), so 4443 * fallback to marking all precise 4444 */ 4445 if (!bt_empty(bt)) { 4446 mark_all_scalars_precise(env, env->cur_state); 4447 bt_reset(bt); 4448 } 4449 4450 return 0; 4451 } 4452 4453 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 4454 { 4455 return __mark_chain_precision(env, regno); 4456 } 4457 4458 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 4459 * desired reg and stack masks across all relevant frames 4460 */ 4461 static int mark_chain_precision_batch(struct bpf_verifier_env *env) 4462 { 4463 return __mark_chain_precision(env, -1); 4464 } 4465 4466 static bool is_spillable_regtype(enum bpf_reg_type type) 4467 { 4468 switch (base_type(type)) { 4469 case PTR_TO_MAP_VALUE: 4470 case PTR_TO_STACK: 4471 case PTR_TO_CTX: 4472 case PTR_TO_PACKET: 4473 case PTR_TO_PACKET_META: 4474 case PTR_TO_PACKET_END: 4475 case PTR_TO_FLOW_KEYS: 4476 case CONST_PTR_TO_MAP: 4477 case PTR_TO_SOCKET: 4478 case PTR_TO_SOCK_COMMON: 4479 case PTR_TO_TCP_SOCK: 4480 case PTR_TO_XDP_SOCK: 4481 case PTR_TO_BTF_ID: 4482 case PTR_TO_BUF: 4483 case PTR_TO_MEM: 4484 case PTR_TO_FUNC: 4485 case PTR_TO_MAP_KEY: 4486 case PTR_TO_ARENA: 4487 return true; 4488 default: 4489 return false; 4490 } 4491 } 4492 4493 /* Does this register contain a constant zero? */ 4494 static bool register_is_null(struct bpf_reg_state *reg) 4495 { 4496 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 4497 } 4498 4499 /* check if register is a constant scalar value */ 4500 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32) 4501 { 4502 return reg->type == SCALAR_VALUE && 4503 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off); 4504 } 4505 4506 /* assuming is_reg_const() is true, return constant value of a register */ 4507 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32) 4508 { 4509 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value; 4510 } 4511 4512 static bool __is_pointer_value(bool allow_ptr_leaks, 4513 const struct bpf_reg_state *reg) 4514 { 4515 if (allow_ptr_leaks) 4516 return false; 4517 4518 return reg->type != SCALAR_VALUE; 4519 } 4520 4521 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env, 4522 struct bpf_reg_state *src_reg) 4523 { 4524 if (src_reg->type != SCALAR_VALUE) 4525 return; 4526 4527 if (src_reg->id & BPF_ADD_CONST) { 4528 /* 4529 * The verifier is processing rX = rY insn and 4530 * rY->id has special linked register already. 4531 * Cleared it, since multiple rX += const are not supported. 4532 */ 4533 src_reg->id = 0; 4534 src_reg->off = 0; 4535 } 4536 4537 if (!src_reg->id && !tnum_is_const(src_reg->var_off)) 4538 /* Ensure that src_reg has a valid ID that will be copied to 4539 * dst_reg and then will be used by sync_linked_regs() to 4540 * propagate min/max range. 4541 */ 4542 src_reg->id = ++env->id_gen; 4543 } 4544 4545 /* Copy src state preserving dst->parent and dst->live fields */ 4546 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 4547 { 4548 struct bpf_reg_state *parent = dst->parent; 4549 enum bpf_reg_liveness live = dst->live; 4550 4551 *dst = *src; 4552 dst->parent = parent; 4553 dst->live = live; 4554 } 4555 4556 static void save_register_state(struct bpf_verifier_env *env, 4557 struct bpf_func_state *state, 4558 int spi, struct bpf_reg_state *reg, 4559 int size) 4560 { 4561 int i; 4562 4563 copy_register_state(&state->stack[spi].spilled_ptr, reg); 4564 if (size == BPF_REG_SIZE) 4565 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4566 4567 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 4568 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 4569 4570 /* size < 8 bytes spill */ 4571 for (; i; i--) 4572 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]); 4573 } 4574 4575 static bool is_bpf_st_mem(struct bpf_insn *insn) 4576 { 4577 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 4578 } 4579 4580 static int get_reg_width(struct bpf_reg_state *reg) 4581 { 4582 return fls64(reg->umax_value); 4583 } 4584 4585 /* See comment for mark_fastcall_pattern_for_call() */ 4586 static void check_fastcall_stack_contract(struct bpf_verifier_env *env, 4587 struct bpf_func_state *state, int insn_idx, int off) 4588 { 4589 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 4590 struct bpf_insn_aux_data *aux = env->insn_aux_data; 4591 int i; 4592 4593 if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern) 4594 return; 4595 /* access to the region [max_stack_depth .. fastcall_stack_off) 4596 * from something that is not a part of the fastcall pattern, 4597 * disable fastcall rewrites for current subprogram by setting 4598 * fastcall_stack_off to a value smaller than any possible offset. 4599 */ 4600 subprog->fastcall_stack_off = S16_MIN; 4601 /* reset fastcall aux flags within subprogram, 4602 * happens at most once per subprogram 4603 */ 4604 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 4605 aux[i].fastcall_spills_num = 0; 4606 aux[i].fastcall_pattern = 0; 4607 } 4608 } 4609 4610 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 4611 * stack boundary and alignment are checked in check_mem_access() 4612 */ 4613 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 4614 /* stack frame we're writing to */ 4615 struct bpf_func_state *state, 4616 int off, int size, int value_regno, 4617 int insn_idx) 4618 { 4619 struct bpf_func_state *cur; /* state of the current function */ 4620 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 4621 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4622 struct bpf_reg_state *reg = NULL; 4623 int insn_flags = insn_stack_access_flags(state->frameno, spi); 4624 4625 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 4626 * so it's aligned access and [off, off + size) are within stack limits 4627 */ 4628 if (!env->allow_ptr_leaks && 4629 is_spilled_reg(&state->stack[spi]) && 4630 size != BPF_REG_SIZE) { 4631 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 4632 return -EACCES; 4633 } 4634 4635 cur = env->cur_state->frame[env->cur_state->curframe]; 4636 if (value_regno >= 0) 4637 reg = &cur->regs[value_regno]; 4638 if (!env->bypass_spec_v4) { 4639 bool sanitize = reg && is_spillable_regtype(reg->type); 4640 4641 for (i = 0; i < size; i++) { 4642 u8 type = state->stack[spi].slot_type[i]; 4643 4644 if (type != STACK_MISC && type != STACK_ZERO) { 4645 sanitize = true; 4646 break; 4647 } 4648 } 4649 4650 if (sanitize) 4651 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 4652 } 4653 4654 err = destroy_if_dynptr_stack_slot(env, state, spi); 4655 if (err) 4656 return err; 4657 4658 check_fastcall_stack_contract(env, state, insn_idx, off); 4659 mark_stack_slot_scratched(env, spi); 4660 if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) { 4661 bool reg_value_fits; 4662 4663 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size; 4664 /* Make sure that reg had an ID to build a relation on spill. */ 4665 if (reg_value_fits) 4666 assign_scalar_id_before_mov(env, reg); 4667 save_register_state(env, state, spi, reg, size); 4668 /* Break the relation on a narrowing spill. */ 4669 if (!reg_value_fits) 4670 state->stack[spi].spilled_ptr.id = 0; 4671 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 4672 env->bpf_capable) { 4673 struct bpf_reg_state *tmp_reg = &env->fake_reg[0]; 4674 4675 memset(tmp_reg, 0, sizeof(*tmp_reg)); 4676 __mark_reg_known(tmp_reg, insn->imm); 4677 tmp_reg->type = SCALAR_VALUE; 4678 save_register_state(env, state, spi, tmp_reg, size); 4679 } else if (reg && is_spillable_regtype(reg->type)) { 4680 /* register containing pointer is being spilled into stack */ 4681 if (size != BPF_REG_SIZE) { 4682 verbose_linfo(env, insn_idx, "; "); 4683 verbose(env, "invalid size of register spill\n"); 4684 return -EACCES; 4685 } 4686 if (state != cur && reg->type == PTR_TO_STACK) { 4687 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4688 return -EINVAL; 4689 } 4690 save_register_state(env, state, spi, reg, size); 4691 } else { 4692 u8 type = STACK_MISC; 4693 4694 /* regular write of data into stack destroys any spilled ptr */ 4695 state->stack[spi].spilled_ptr.type = NOT_INIT; 4696 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 4697 if (is_stack_slot_special(&state->stack[spi])) 4698 for (i = 0; i < BPF_REG_SIZE; i++) 4699 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 4700 4701 /* only mark the slot as written if all 8 bytes were written 4702 * otherwise read propagation may incorrectly stop too soon 4703 * when stack slots are partially written. 4704 * This heuristic means that read propagation will be 4705 * conservative, since it will add reg_live_read marks 4706 * to stack slots all the way to first state when programs 4707 * writes+reads less than 8 bytes 4708 */ 4709 if (size == BPF_REG_SIZE) 4710 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4711 4712 /* when we zero initialize stack slots mark them as such */ 4713 if ((reg && register_is_null(reg)) || 4714 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4715 /* STACK_ZERO case happened because register spill 4716 * wasn't properly aligned at the stack slot boundary, 4717 * so it's not a register spill anymore; force 4718 * originating register to be precise to make 4719 * STACK_ZERO correct for subsequent states 4720 */ 4721 err = mark_chain_precision(env, value_regno); 4722 if (err) 4723 return err; 4724 type = STACK_ZERO; 4725 } 4726 4727 /* Mark slots affected by this stack write. */ 4728 for (i = 0; i < size; i++) 4729 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 4730 insn_flags = 0; /* not a register spill */ 4731 } 4732 4733 if (insn_flags) 4734 return push_jmp_history(env, env->cur_state, insn_flags, 0); 4735 return 0; 4736 } 4737 4738 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 4739 * known to contain a variable offset. 4740 * This function checks whether the write is permitted and conservatively 4741 * tracks the effects of the write, considering that each stack slot in the 4742 * dynamic range is potentially written to. 4743 * 4744 * 'off' includes 'regno->off'. 4745 * 'value_regno' can be -1, meaning that an unknown value is being written to 4746 * the stack. 4747 * 4748 * Spilled pointers in range are not marked as written because we don't know 4749 * what's going to be actually written. This means that read propagation for 4750 * future reads cannot be terminated by this write. 4751 * 4752 * For privileged programs, uninitialized stack slots are considered 4753 * initialized by this write (even though we don't know exactly what offsets 4754 * are going to be written to). The idea is that we don't want the verifier to 4755 * reject future reads that access slots written to through variable offsets. 4756 */ 4757 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4758 /* func where register points to */ 4759 struct bpf_func_state *state, 4760 int ptr_regno, int off, int size, 4761 int value_regno, int insn_idx) 4762 { 4763 struct bpf_func_state *cur; /* state of the current function */ 4764 int min_off, max_off; 4765 int i, err; 4766 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 4767 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4768 bool writing_zero = false; 4769 /* set if the fact that we're writing a zero is used to let any 4770 * stack slots remain STACK_ZERO 4771 */ 4772 bool zero_used = false; 4773 4774 cur = env->cur_state->frame[env->cur_state->curframe]; 4775 ptr_reg = &cur->regs[ptr_regno]; 4776 min_off = ptr_reg->smin_value + off; 4777 max_off = ptr_reg->smax_value + off + size; 4778 if (value_regno >= 0) 4779 value_reg = &cur->regs[value_regno]; 4780 if ((value_reg && register_is_null(value_reg)) || 4781 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4782 writing_zero = true; 4783 4784 for (i = min_off; i < max_off; i++) { 4785 int spi; 4786 4787 spi = __get_spi(i); 4788 err = destroy_if_dynptr_stack_slot(env, state, spi); 4789 if (err) 4790 return err; 4791 } 4792 4793 check_fastcall_stack_contract(env, state, insn_idx, min_off); 4794 /* Variable offset writes destroy any spilled pointers in range. */ 4795 for (i = min_off; i < max_off; i++) { 4796 u8 new_type, *stype; 4797 int slot, spi; 4798 4799 slot = -i - 1; 4800 spi = slot / BPF_REG_SIZE; 4801 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4802 mark_stack_slot_scratched(env, spi); 4803 4804 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4805 /* Reject the write if range we may write to has not 4806 * been initialized beforehand. If we didn't reject 4807 * here, the ptr status would be erased below (even 4808 * though not all slots are actually overwritten), 4809 * possibly opening the door to leaks. 4810 * 4811 * We do however catch STACK_INVALID case below, and 4812 * only allow reading possibly uninitialized memory 4813 * later for CAP_PERFMON, as the write may not happen to 4814 * that slot. 4815 */ 4816 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4817 insn_idx, i); 4818 return -EINVAL; 4819 } 4820 4821 /* If writing_zero and the spi slot contains a spill of value 0, 4822 * maintain the spill type. 4823 */ 4824 if (writing_zero && *stype == STACK_SPILL && 4825 is_spilled_scalar_reg(&state->stack[spi])) { 4826 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr; 4827 4828 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) { 4829 zero_used = true; 4830 continue; 4831 } 4832 } 4833 4834 /* Erase all other spilled pointers. */ 4835 state->stack[spi].spilled_ptr.type = NOT_INIT; 4836 4837 /* Update the slot type. */ 4838 new_type = STACK_MISC; 4839 if (writing_zero && *stype == STACK_ZERO) { 4840 new_type = STACK_ZERO; 4841 zero_used = true; 4842 } 4843 /* If the slot is STACK_INVALID, we check whether it's OK to 4844 * pretend that it will be initialized by this write. The slot 4845 * might not actually be written to, and so if we mark it as 4846 * initialized future reads might leak uninitialized memory. 4847 * For privileged programs, we will accept such reads to slots 4848 * that may or may not be written because, if we're reject 4849 * them, the error would be too confusing. 4850 */ 4851 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4852 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4853 insn_idx, i); 4854 return -EINVAL; 4855 } 4856 *stype = new_type; 4857 } 4858 if (zero_used) { 4859 /* backtracking doesn't work for STACK_ZERO yet. */ 4860 err = mark_chain_precision(env, value_regno); 4861 if (err) 4862 return err; 4863 } 4864 return 0; 4865 } 4866 4867 /* When register 'dst_regno' is assigned some values from stack[min_off, 4868 * max_off), we set the register's type according to the types of the 4869 * respective stack slots. If all the stack values are known to be zeros, then 4870 * so is the destination reg. Otherwise, the register is considered to be 4871 * SCALAR. This function does not deal with register filling; the caller must 4872 * ensure that all spilled registers in the stack range have been marked as 4873 * read. 4874 */ 4875 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4876 /* func where src register points to */ 4877 struct bpf_func_state *ptr_state, 4878 int min_off, int max_off, int dst_regno) 4879 { 4880 struct bpf_verifier_state *vstate = env->cur_state; 4881 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4882 int i, slot, spi; 4883 u8 *stype; 4884 int zeros = 0; 4885 4886 for (i = min_off; i < max_off; i++) { 4887 slot = -i - 1; 4888 spi = slot / BPF_REG_SIZE; 4889 mark_stack_slot_scratched(env, spi); 4890 stype = ptr_state->stack[spi].slot_type; 4891 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4892 break; 4893 zeros++; 4894 } 4895 if (zeros == max_off - min_off) { 4896 /* Any access_size read into register is zero extended, 4897 * so the whole register == const_zero. 4898 */ 4899 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4900 } else { 4901 /* have read misc data from the stack */ 4902 mark_reg_unknown(env, state->regs, dst_regno); 4903 } 4904 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4905 } 4906 4907 /* Read the stack at 'off' and put the results into the register indicated by 4908 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4909 * spilled reg. 4910 * 4911 * 'dst_regno' can be -1, meaning that the read value is not going to a 4912 * register. 4913 * 4914 * The access is assumed to be within the current stack bounds. 4915 */ 4916 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4917 /* func where src register points to */ 4918 struct bpf_func_state *reg_state, 4919 int off, int size, int dst_regno) 4920 { 4921 struct bpf_verifier_state *vstate = env->cur_state; 4922 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4923 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4924 struct bpf_reg_state *reg; 4925 u8 *stype, type; 4926 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi); 4927 4928 stype = reg_state->stack[spi].slot_type; 4929 reg = ®_state->stack[spi].spilled_ptr; 4930 4931 mark_stack_slot_scratched(env, spi); 4932 check_fastcall_stack_contract(env, state, env->insn_idx, off); 4933 4934 if (is_spilled_reg(®_state->stack[spi])) { 4935 u8 spill_size = 1; 4936 4937 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4938 spill_size++; 4939 4940 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4941 if (reg->type != SCALAR_VALUE) { 4942 verbose_linfo(env, env->insn_idx, "; "); 4943 verbose(env, "invalid size of register fill\n"); 4944 return -EACCES; 4945 } 4946 4947 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4948 if (dst_regno < 0) 4949 return 0; 4950 4951 if (size <= spill_size && 4952 bpf_stack_narrow_access_ok(off, size, spill_size)) { 4953 /* The earlier check_reg_arg() has decided the 4954 * subreg_def for this insn. Save it first. 4955 */ 4956 s32 subreg_def = state->regs[dst_regno].subreg_def; 4957 4958 copy_register_state(&state->regs[dst_regno], reg); 4959 state->regs[dst_regno].subreg_def = subreg_def; 4960 4961 /* Break the relation on a narrowing fill. 4962 * coerce_reg_to_size will adjust the boundaries. 4963 */ 4964 if (get_reg_width(reg) > size * BITS_PER_BYTE) 4965 state->regs[dst_regno].id = 0; 4966 } else { 4967 int spill_cnt = 0, zero_cnt = 0; 4968 4969 for (i = 0; i < size; i++) { 4970 type = stype[(slot - i) % BPF_REG_SIZE]; 4971 if (type == STACK_SPILL) { 4972 spill_cnt++; 4973 continue; 4974 } 4975 if (type == STACK_MISC) 4976 continue; 4977 if (type == STACK_ZERO) { 4978 zero_cnt++; 4979 continue; 4980 } 4981 if (type == STACK_INVALID && env->allow_uninit_stack) 4982 continue; 4983 verbose(env, "invalid read from stack off %d+%d size %d\n", 4984 off, i, size); 4985 return -EACCES; 4986 } 4987 4988 if (spill_cnt == size && 4989 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 4990 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4991 /* this IS register fill, so keep insn_flags */ 4992 } else if (zero_cnt == size) { 4993 /* similarly to mark_reg_stack_read(), preserve zeroes */ 4994 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4995 insn_flags = 0; /* not restoring original register state */ 4996 } else { 4997 mark_reg_unknown(env, state->regs, dst_regno); 4998 insn_flags = 0; /* not restoring original register state */ 4999 } 5000 } 5001 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 5002 } else if (dst_regno >= 0) { 5003 /* restore register state from stack */ 5004 copy_register_state(&state->regs[dst_regno], reg); 5005 /* mark reg as written since spilled pointer state likely 5006 * has its liveness marks cleared by is_state_visited() 5007 * which resets stack/reg liveness for state transitions 5008 */ 5009 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 5010 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 5011 /* If dst_regno==-1, the caller is asking us whether 5012 * it is acceptable to use this value as a SCALAR_VALUE 5013 * (e.g. for XADD). 5014 * We must not allow unprivileged callers to do that 5015 * with spilled pointers. 5016 */ 5017 verbose(env, "leaking pointer from stack off %d\n", 5018 off); 5019 return -EACCES; 5020 } 5021 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 5022 } else { 5023 for (i = 0; i < size; i++) { 5024 type = stype[(slot - i) % BPF_REG_SIZE]; 5025 if (type == STACK_MISC) 5026 continue; 5027 if (type == STACK_ZERO) 5028 continue; 5029 if (type == STACK_INVALID && env->allow_uninit_stack) 5030 continue; 5031 verbose(env, "invalid read from stack off %d+%d size %d\n", 5032 off, i, size); 5033 return -EACCES; 5034 } 5035 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 5036 if (dst_regno >= 0) 5037 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 5038 insn_flags = 0; /* we are not restoring spilled register */ 5039 } 5040 if (insn_flags) 5041 return push_jmp_history(env, env->cur_state, insn_flags, 0); 5042 return 0; 5043 } 5044 5045 enum bpf_access_src { 5046 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 5047 ACCESS_HELPER = 2, /* the access is performed by a helper */ 5048 }; 5049 5050 static int check_stack_range_initialized(struct bpf_verifier_env *env, 5051 int regno, int off, int access_size, 5052 bool zero_size_allowed, 5053 enum bpf_access_src type, 5054 struct bpf_call_arg_meta *meta); 5055 5056 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 5057 { 5058 return cur_regs(env) + regno; 5059 } 5060 5061 /* Read the stack at 'ptr_regno + off' and put the result into the register 5062 * 'dst_regno'. 5063 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 5064 * but not its variable offset. 5065 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 5066 * 5067 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 5068 * filling registers (i.e. reads of spilled register cannot be detected when 5069 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 5070 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 5071 * offset; for a fixed offset check_stack_read_fixed_off should be used 5072 * instead. 5073 */ 5074 static int check_stack_read_var_off(struct bpf_verifier_env *env, 5075 int ptr_regno, int off, int size, int dst_regno) 5076 { 5077 /* The state of the source register. */ 5078 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5079 struct bpf_func_state *ptr_state = func(env, reg); 5080 int err; 5081 int min_off, max_off; 5082 5083 /* Note that we pass a NULL meta, so raw access will not be permitted. 5084 */ 5085 err = check_stack_range_initialized(env, ptr_regno, off, size, 5086 false, ACCESS_DIRECT, NULL); 5087 if (err) 5088 return err; 5089 5090 min_off = reg->smin_value + off; 5091 max_off = reg->smax_value + off; 5092 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 5093 check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off); 5094 return 0; 5095 } 5096 5097 /* check_stack_read dispatches to check_stack_read_fixed_off or 5098 * check_stack_read_var_off. 5099 * 5100 * The caller must ensure that the offset falls within the allocated stack 5101 * bounds. 5102 * 5103 * 'dst_regno' is a register which will receive the value from the stack. It 5104 * can be -1, meaning that the read value is not going to a register. 5105 */ 5106 static int check_stack_read(struct bpf_verifier_env *env, 5107 int ptr_regno, int off, int size, 5108 int dst_regno) 5109 { 5110 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5111 struct bpf_func_state *state = func(env, reg); 5112 int err; 5113 /* Some accesses are only permitted with a static offset. */ 5114 bool var_off = !tnum_is_const(reg->var_off); 5115 5116 /* The offset is required to be static when reads don't go to a 5117 * register, in order to not leak pointers (see 5118 * check_stack_read_fixed_off). 5119 */ 5120 if (dst_regno < 0 && var_off) { 5121 char tn_buf[48]; 5122 5123 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5124 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 5125 tn_buf, off, size); 5126 return -EACCES; 5127 } 5128 /* Variable offset is prohibited for unprivileged mode for simplicity 5129 * since it requires corresponding support in Spectre masking for stack 5130 * ALU. See also retrieve_ptr_limit(). The check in 5131 * check_stack_access_for_ptr_arithmetic() called by 5132 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 5133 * with variable offsets, therefore no check is required here. Further, 5134 * just checking it here would be insufficient as speculative stack 5135 * writes could still lead to unsafe speculative behaviour. 5136 */ 5137 if (!var_off) { 5138 off += reg->var_off.value; 5139 err = check_stack_read_fixed_off(env, state, off, size, 5140 dst_regno); 5141 } else { 5142 /* Variable offset stack reads need more conservative handling 5143 * than fixed offset ones. Note that dst_regno >= 0 on this 5144 * branch. 5145 */ 5146 err = check_stack_read_var_off(env, ptr_regno, off, size, 5147 dst_regno); 5148 } 5149 return err; 5150 } 5151 5152 5153 /* check_stack_write dispatches to check_stack_write_fixed_off or 5154 * check_stack_write_var_off. 5155 * 5156 * 'ptr_regno' is the register used as a pointer into the stack. 5157 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 5158 * 'value_regno' is the register whose value we're writing to the stack. It can 5159 * be -1, meaning that we're not writing from a register. 5160 * 5161 * The caller must ensure that the offset falls within the maximum stack size. 5162 */ 5163 static int check_stack_write(struct bpf_verifier_env *env, 5164 int ptr_regno, int off, int size, 5165 int value_regno, int insn_idx) 5166 { 5167 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5168 struct bpf_func_state *state = func(env, reg); 5169 int err; 5170 5171 if (tnum_is_const(reg->var_off)) { 5172 off += reg->var_off.value; 5173 err = check_stack_write_fixed_off(env, state, off, size, 5174 value_regno, insn_idx); 5175 } else { 5176 /* Variable offset stack reads need more conservative handling 5177 * than fixed offset ones. 5178 */ 5179 err = check_stack_write_var_off(env, state, 5180 ptr_regno, off, size, 5181 value_regno, insn_idx); 5182 } 5183 return err; 5184 } 5185 5186 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 5187 int off, int size, enum bpf_access_type type) 5188 { 5189 struct bpf_reg_state *regs = cur_regs(env); 5190 struct bpf_map *map = regs[regno].map_ptr; 5191 u32 cap = bpf_map_flags_to_cap(map); 5192 5193 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 5194 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 5195 map->value_size, off, size); 5196 return -EACCES; 5197 } 5198 5199 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 5200 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 5201 map->value_size, off, size); 5202 return -EACCES; 5203 } 5204 5205 return 0; 5206 } 5207 5208 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 5209 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 5210 int off, int size, u32 mem_size, 5211 bool zero_size_allowed) 5212 { 5213 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 5214 struct bpf_reg_state *reg; 5215 5216 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 5217 return 0; 5218 5219 reg = &cur_regs(env)[regno]; 5220 switch (reg->type) { 5221 case PTR_TO_MAP_KEY: 5222 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 5223 mem_size, off, size); 5224 break; 5225 case PTR_TO_MAP_VALUE: 5226 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 5227 mem_size, off, size); 5228 break; 5229 case PTR_TO_PACKET: 5230 case PTR_TO_PACKET_META: 5231 case PTR_TO_PACKET_END: 5232 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 5233 off, size, regno, reg->id, off, mem_size); 5234 break; 5235 case PTR_TO_MEM: 5236 default: 5237 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 5238 mem_size, off, size); 5239 } 5240 5241 return -EACCES; 5242 } 5243 5244 /* check read/write into a memory region with possible variable offset */ 5245 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 5246 int off, int size, u32 mem_size, 5247 bool zero_size_allowed) 5248 { 5249 struct bpf_verifier_state *vstate = env->cur_state; 5250 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5251 struct bpf_reg_state *reg = &state->regs[regno]; 5252 int err; 5253 5254 /* We may have adjusted the register pointing to memory region, so we 5255 * need to try adding each of min_value and max_value to off 5256 * to make sure our theoretical access will be safe. 5257 * 5258 * The minimum value is only important with signed 5259 * comparisons where we can't assume the floor of a 5260 * value is 0. If we are using signed variables for our 5261 * index'es we need to make sure that whatever we use 5262 * will have a set floor within our range. 5263 */ 5264 if (reg->smin_value < 0 && 5265 (reg->smin_value == S64_MIN || 5266 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5267 reg->smin_value + off < 0)) { 5268 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5269 regno); 5270 return -EACCES; 5271 } 5272 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5273 mem_size, zero_size_allowed); 5274 if (err) { 5275 verbose(env, "R%d min value is outside of the allowed memory range\n", 5276 regno); 5277 return err; 5278 } 5279 5280 /* If we haven't set a max value then we need to bail since we can't be 5281 * sure we won't do bad things. 5282 * If reg->umax_value + off could overflow, treat that as unbounded too. 5283 */ 5284 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5285 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5286 regno); 5287 return -EACCES; 5288 } 5289 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5290 mem_size, zero_size_allowed); 5291 if (err) { 5292 verbose(env, "R%d max value is outside of the allowed memory range\n", 5293 regno); 5294 return err; 5295 } 5296 5297 return 0; 5298 } 5299 5300 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5301 const struct bpf_reg_state *reg, int regno, 5302 bool fixed_off_ok) 5303 { 5304 /* Access to this pointer-typed register or passing it to a helper 5305 * is only allowed in its original, unmodified form. 5306 */ 5307 5308 if (reg->off < 0) { 5309 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5310 reg_type_str(env, reg->type), regno, reg->off); 5311 return -EACCES; 5312 } 5313 5314 if (!fixed_off_ok && reg->off) { 5315 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5316 reg_type_str(env, reg->type), regno, reg->off); 5317 return -EACCES; 5318 } 5319 5320 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5321 char tn_buf[48]; 5322 5323 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5324 verbose(env, "variable %s access var_off=%s disallowed\n", 5325 reg_type_str(env, reg->type), tn_buf); 5326 return -EACCES; 5327 } 5328 5329 return 0; 5330 } 5331 5332 static int check_ptr_off_reg(struct bpf_verifier_env *env, 5333 const struct bpf_reg_state *reg, int regno) 5334 { 5335 return __check_ptr_off_reg(env, reg, regno, false); 5336 } 5337 5338 static int map_kptr_match_type(struct bpf_verifier_env *env, 5339 struct btf_field *kptr_field, 5340 struct bpf_reg_state *reg, u32 regno) 5341 { 5342 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5343 int perm_flags; 5344 const char *reg_name = ""; 5345 5346 if (btf_is_kernel(reg->btf)) { 5347 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5348 5349 /* Only unreferenced case accepts untrusted pointers */ 5350 if (kptr_field->type == BPF_KPTR_UNREF) 5351 perm_flags |= PTR_UNTRUSTED; 5352 } else { 5353 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5354 if (kptr_field->type == BPF_KPTR_PERCPU) 5355 perm_flags |= MEM_PERCPU; 5356 } 5357 5358 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5359 goto bad_type; 5360 5361 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5362 reg_name = btf_type_name(reg->btf, reg->btf_id); 5363 5364 /* For ref_ptr case, release function check should ensure we get one 5365 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5366 * normal store of unreferenced kptr, we must ensure var_off is zero. 5367 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5368 * reg->off and reg->ref_obj_id are not needed here. 5369 */ 5370 if (__check_ptr_off_reg(env, reg, regno, true)) 5371 return -EACCES; 5372 5373 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5374 * we also need to take into account the reg->off. 5375 * 5376 * We want to support cases like: 5377 * 5378 * struct foo { 5379 * struct bar br; 5380 * struct baz bz; 5381 * }; 5382 * 5383 * struct foo *v; 5384 * v = func(); // PTR_TO_BTF_ID 5385 * val->foo = v; // reg->off is zero, btf and btf_id match type 5386 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5387 * // first member type of struct after comparison fails 5388 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5389 * // to match type 5390 * 5391 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5392 * is zero. We must also ensure that btf_struct_ids_match does not walk 5393 * the struct to match type against first member of struct, i.e. reject 5394 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5395 * strict mode to true for type match. 5396 */ 5397 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5398 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5399 kptr_field->type != BPF_KPTR_UNREF)) 5400 goto bad_type; 5401 return 0; 5402 bad_type: 5403 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5404 reg_type_str(env, reg->type), reg_name); 5405 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5406 if (kptr_field->type == BPF_KPTR_UNREF) 5407 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5408 targ_name); 5409 else 5410 verbose(env, "\n"); 5411 return -EINVAL; 5412 } 5413 5414 static bool in_sleepable(struct bpf_verifier_env *env) 5415 { 5416 return env->prog->sleepable || 5417 (env->cur_state && env->cur_state->in_sleepable); 5418 } 5419 5420 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5421 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5422 */ 5423 static bool in_rcu_cs(struct bpf_verifier_env *env) 5424 { 5425 return env->cur_state->active_rcu_lock || 5426 env->cur_state->active_lock.ptr || 5427 !in_sleepable(env); 5428 } 5429 5430 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5431 BTF_SET_START(rcu_protected_types) 5432 BTF_ID(struct, prog_test_ref_kfunc) 5433 #ifdef CONFIG_CGROUPS 5434 BTF_ID(struct, cgroup) 5435 #endif 5436 #ifdef CONFIG_BPF_JIT 5437 BTF_ID(struct, bpf_cpumask) 5438 #endif 5439 BTF_ID(struct, task_struct) 5440 BTF_ID(struct, bpf_crypto_ctx) 5441 BTF_SET_END(rcu_protected_types) 5442 5443 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5444 { 5445 if (!btf_is_kernel(btf)) 5446 return true; 5447 return btf_id_set_contains(&rcu_protected_types, btf_id); 5448 } 5449 5450 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 5451 { 5452 struct btf_struct_meta *meta; 5453 5454 if (btf_is_kernel(kptr_field->kptr.btf)) 5455 return NULL; 5456 5457 meta = btf_find_struct_meta(kptr_field->kptr.btf, 5458 kptr_field->kptr.btf_id); 5459 5460 return meta ? meta->record : NULL; 5461 } 5462 5463 static bool rcu_safe_kptr(const struct btf_field *field) 5464 { 5465 const struct btf_field_kptr *kptr = &field->kptr; 5466 5467 return field->type == BPF_KPTR_PERCPU || 5468 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 5469 } 5470 5471 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 5472 { 5473 struct btf_record *rec; 5474 u32 ret; 5475 5476 ret = PTR_MAYBE_NULL; 5477 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 5478 ret |= MEM_RCU; 5479 if (kptr_field->type == BPF_KPTR_PERCPU) 5480 ret |= MEM_PERCPU; 5481 else if (!btf_is_kernel(kptr_field->kptr.btf)) 5482 ret |= MEM_ALLOC; 5483 5484 rec = kptr_pointee_btf_record(kptr_field); 5485 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 5486 ret |= NON_OWN_REF; 5487 } else { 5488 ret |= PTR_UNTRUSTED; 5489 } 5490 5491 return ret; 5492 } 5493 5494 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5495 int value_regno, int insn_idx, 5496 struct btf_field *kptr_field) 5497 { 5498 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5499 int class = BPF_CLASS(insn->code); 5500 struct bpf_reg_state *val_reg; 5501 5502 /* Things we already checked for in check_map_access and caller: 5503 * - Reject cases where variable offset may touch kptr 5504 * - size of access (must be BPF_DW) 5505 * - tnum_is_const(reg->var_off) 5506 * - kptr_field->offset == off + reg->var_off.value 5507 */ 5508 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5509 if (BPF_MODE(insn->code) != BPF_MEM) { 5510 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5511 return -EACCES; 5512 } 5513 5514 /* We only allow loading referenced kptr, since it will be marked as 5515 * untrusted, similar to unreferenced kptr. 5516 */ 5517 if (class != BPF_LDX && 5518 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 5519 verbose(env, "store to referenced kptr disallowed\n"); 5520 return -EACCES; 5521 } 5522 5523 if (class == BPF_LDX) { 5524 val_reg = reg_state(env, value_regno); 5525 /* We can simply mark the value_regno receiving the pointer 5526 * value from map as PTR_TO_BTF_ID, with the correct type. 5527 */ 5528 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5529 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field)); 5530 } else if (class == BPF_STX) { 5531 val_reg = reg_state(env, value_regno); 5532 if (!register_is_null(val_reg) && 5533 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5534 return -EACCES; 5535 } else if (class == BPF_ST) { 5536 if (insn->imm) { 5537 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5538 kptr_field->offset); 5539 return -EACCES; 5540 } 5541 } else { 5542 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5543 return -EACCES; 5544 } 5545 return 0; 5546 } 5547 5548 /* check read/write into a map element with possible variable offset */ 5549 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5550 int off, int size, bool zero_size_allowed, 5551 enum bpf_access_src src) 5552 { 5553 struct bpf_verifier_state *vstate = env->cur_state; 5554 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5555 struct bpf_reg_state *reg = &state->regs[regno]; 5556 struct bpf_map *map = reg->map_ptr; 5557 struct btf_record *rec; 5558 int err, i; 5559 5560 err = check_mem_region_access(env, regno, off, size, map->value_size, 5561 zero_size_allowed); 5562 if (err) 5563 return err; 5564 5565 if (IS_ERR_OR_NULL(map->record)) 5566 return 0; 5567 rec = map->record; 5568 for (i = 0; i < rec->cnt; i++) { 5569 struct btf_field *field = &rec->fields[i]; 5570 u32 p = field->offset; 5571 5572 /* If any part of a field can be touched by load/store, reject 5573 * this program. To check that [x1, x2) overlaps with [y1, y2), 5574 * it is sufficient to check x1 < y2 && y1 < x2. 5575 */ 5576 if (reg->smin_value + off < p + field->size && 5577 p < reg->umax_value + off + size) { 5578 switch (field->type) { 5579 case BPF_KPTR_UNREF: 5580 case BPF_KPTR_REF: 5581 case BPF_KPTR_PERCPU: 5582 if (src != ACCESS_DIRECT) { 5583 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 5584 return -EACCES; 5585 } 5586 if (!tnum_is_const(reg->var_off)) { 5587 verbose(env, "kptr access cannot have variable offset\n"); 5588 return -EACCES; 5589 } 5590 if (p != off + reg->var_off.value) { 5591 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 5592 p, off + reg->var_off.value); 5593 return -EACCES; 5594 } 5595 if (size != bpf_size_to_bytes(BPF_DW)) { 5596 verbose(env, "kptr access size must be BPF_DW\n"); 5597 return -EACCES; 5598 } 5599 break; 5600 default: 5601 verbose(env, "%s cannot be accessed directly by load/store\n", 5602 btf_field_type_name(field->type)); 5603 return -EACCES; 5604 } 5605 } 5606 } 5607 return 0; 5608 } 5609 5610 #define MAX_PACKET_OFF 0xffff 5611 5612 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5613 const struct bpf_call_arg_meta *meta, 5614 enum bpf_access_type t) 5615 { 5616 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5617 5618 switch (prog_type) { 5619 /* Program types only with direct read access go here! */ 5620 case BPF_PROG_TYPE_LWT_IN: 5621 case BPF_PROG_TYPE_LWT_OUT: 5622 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5623 case BPF_PROG_TYPE_SK_REUSEPORT: 5624 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5625 case BPF_PROG_TYPE_CGROUP_SKB: 5626 if (t == BPF_WRITE) 5627 return false; 5628 fallthrough; 5629 5630 /* Program types with direct read + write access go here! */ 5631 case BPF_PROG_TYPE_SCHED_CLS: 5632 case BPF_PROG_TYPE_SCHED_ACT: 5633 case BPF_PROG_TYPE_XDP: 5634 case BPF_PROG_TYPE_LWT_XMIT: 5635 case BPF_PROG_TYPE_SK_SKB: 5636 case BPF_PROG_TYPE_SK_MSG: 5637 if (meta) 5638 return meta->pkt_access; 5639 5640 env->seen_direct_write = true; 5641 return true; 5642 5643 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5644 if (t == BPF_WRITE) 5645 env->seen_direct_write = true; 5646 5647 return true; 5648 5649 default: 5650 return false; 5651 } 5652 } 5653 5654 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5655 int size, bool zero_size_allowed) 5656 { 5657 struct bpf_reg_state *regs = cur_regs(env); 5658 struct bpf_reg_state *reg = ®s[regno]; 5659 int err; 5660 5661 /* We may have added a variable offset to the packet pointer; but any 5662 * reg->range we have comes after that. We are only checking the fixed 5663 * offset. 5664 */ 5665 5666 /* We don't allow negative numbers, because we aren't tracking enough 5667 * detail to prove they're safe. 5668 */ 5669 if (reg->smin_value < 0) { 5670 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5671 regno); 5672 return -EACCES; 5673 } 5674 5675 err = reg->range < 0 ? -EINVAL : 5676 __check_mem_access(env, regno, off, size, reg->range, 5677 zero_size_allowed); 5678 if (err) { 5679 verbose(env, "R%d offset is outside of the packet\n", regno); 5680 return err; 5681 } 5682 5683 /* __check_mem_access has made sure "off + size - 1" is within u16. 5684 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5685 * otherwise find_good_pkt_pointers would have refused to set range info 5686 * that __check_mem_access would have rejected this pkt access. 5687 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5688 */ 5689 env->prog->aux->max_pkt_offset = 5690 max_t(u32, env->prog->aux->max_pkt_offset, 5691 off + reg->umax_value + size - 1); 5692 5693 return err; 5694 } 5695 5696 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5697 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5698 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5699 struct btf **btf, u32 *btf_id, bool *is_retval, bool is_ldsx) 5700 { 5701 struct bpf_insn_access_aux info = { 5702 .reg_type = *reg_type, 5703 .log = &env->log, 5704 .is_retval = false, 5705 .is_ldsx = is_ldsx, 5706 }; 5707 5708 if (env->ops->is_valid_access && 5709 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5710 /* A non zero info.ctx_field_size indicates that this field is a 5711 * candidate for later verifier transformation to load the whole 5712 * field and then apply a mask when accessed with a narrower 5713 * access than actual ctx access size. A zero info.ctx_field_size 5714 * will only allow for whole field access and rejects any other 5715 * type of narrower access. 5716 */ 5717 *reg_type = info.reg_type; 5718 *is_retval = info.is_retval; 5719 5720 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5721 *btf = info.btf; 5722 *btf_id = info.btf_id; 5723 } else { 5724 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5725 } 5726 /* remember the offset of last byte accessed in ctx */ 5727 if (env->prog->aux->max_ctx_offset < off + size) 5728 env->prog->aux->max_ctx_offset = off + size; 5729 return 0; 5730 } 5731 5732 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5733 return -EACCES; 5734 } 5735 5736 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5737 int size) 5738 { 5739 if (size < 0 || off < 0 || 5740 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5741 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5742 off, size); 5743 return -EACCES; 5744 } 5745 return 0; 5746 } 5747 5748 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5749 u32 regno, int off, int size, 5750 enum bpf_access_type t) 5751 { 5752 struct bpf_reg_state *regs = cur_regs(env); 5753 struct bpf_reg_state *reg = ®s[regno]; 5754 struct bpf_insn_access_aux info = {}; 5755 bool valid; 5756 5757 if (reg->smin_value < 0) { 5758 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5759 regno); 5760 return -EACCES; 5761 } 5762 5763 switch (reg->type) { 5764 case PTR_TO_SOCK_COMMON: 5765 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5766 break; 5767 case PTR_TO_SOCKET: 5768 valid = bpf_sock_is_valid_access(off, size, t, &info); 5769 break; 5770 case PTR_TO_TCP_SOCK: 5771 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5772 break; 5773 case PTR_TO_XDP_SOCK: 5774 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5775 break; 5776 default: 5777 valid = false; 5778 } 5779 5780 5781 if (valid) { 5782 env->insn_aux_data[insn_idx].ctx_field_size = 5783 info.ctx_field_size; 5784 return 0; 5785 } 5786 5787 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5788 regno, reg_type_str(env, reg->type), off, size); 5789 5790 return -EACCES; 5791 } 5792 5793 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5794 { 5795 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5796 } 5797 5798 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5799 { 5800 const struct bpf_reg_state *reg = reg_state(env, regno); 5801 5802 return reg->type == PTR_TO_CTX; 5803 } 5804 5805 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5806 { 5807 const struct bpf_reg_state *reg = reg_state(env, regno); 5808 5809 return type_is_sk_pointer(reg->type); 5810 } 5811 5812 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5813 { 5814 const struct bpf_reg_state *reg = reg_state(env, regno); 5815 5816 return type_is_pkt_pointer(reg->type); 5817 } 5818 5819 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5820 { 5821 const struct bpf_reg_state *reg = reg_state(env, regno); 5822 5823 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5824 return reg->type == PTR_TO_FLOW_KEYS; 5825 } 5826 5827 static bool is_arena_reg(struct bpf_verifier_env *env, int regno) 5828 { 5829 const struct bpf_reg_state *reg = reg_state(env, regno); 5830 5831 return reg->type == PTR_TO_ARENA; 5832 } 5833 5834 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5835 #ifdef CONFIG_NET 5836 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5837 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5838 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5839 #endif 5840 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5841 }; 5842 5843 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5844 { 5845 /* A referenced register is always trusted. */ 5846 if (reg->ref_obj_id) 5847 return true; 5848 5849 /* Types listed in the reg2btf_ids are always trusted */ 5850 if (reg2btf_ids[base_type(reg->type)] && 5851 !bpf_type_has_unsafe_modifiers(reg->type)) 5852 return true; 5853 5854 /* If a register is not referenced, it is trusted if it has the 5855 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5856 * other type modifiers may be safe, but we elect to take an opt-in 5857 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5858 * not. 5859 * 5860 * Eventually, we should make PTR_TRUSTED the single source of truth 5861 * for whether a register is trusted. 5862 */ 5863 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5864 !bpf_type_has_unsafe_modifiers(reg->type); 5865 } 5866 5867 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5868 { 5869 return reg->type & MEM_RCU; 5870 } 5871 5872 static void clear_trusted_flags(enum bpf_type_flag *flag) 5873 { 5874 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5875 } 5876 5877 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5878 const struct bpf_reg_state *reg, 5879 int off, int size, bool strict) 5880 { 5881 struct tnum reg_off; 5882 int ip_align; 5883 5884 /* Byte size accesses are always allowed. */ 5885 if (!strict || size == 1) 5886 return 0; 5887 5888 /* For platforms that do not have a Kconfig enabling 5889 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5890 * NET_IP_ALIGN is universally set to '2'. And on platforms 5891 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5892 * to this code only in strict mode where we want to emulate 5893 * the NET_IP_ALIGN==2 checking. Therefore use an 5894 * unconditional IP align value of '2'. 5895 */ 5896 ip_align = 2; 5897 5898 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5899 if (!tnum_is_aligned(reg_off, size)) { 5900 char tn_buf[48]; 5901 5902 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5903 verbose(env, 5904 "misaligned packet access off %d+%s+%d+%d size %d\n", 5905 ip_align, tn_buf, reg->off, off, size); 5906 return -EACCES; 5907 } 5908 5909 return 0; 5910 } 5911 5912 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5913 const struct bpf_reg_state *reg, 5914 const char *pointer_desc, 5915 int off, int size, bool strict) 5916 { 5917 struct tnum reg_off; 5918 5919 /* Byte size accesses are always allowed. */ 5920 if (!strict || size == 1) 5921 return 0; 5922 5923 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5924 if (!tnum_is_aligned(reg_off, size)) { 5925 char tn_buf[48]; 5926 5927 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5928 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5929 pointer_desc, tn_buf, reg->off, off, size); 5930 return -EACCES; 5931 } 5932 5933 return 0; 5934 } 5935 5936 static int check_ptr_alignment(struct bpf_verifier_env *env, 5937 const struct bpf_reg_state *reg, int off, 5938 int size, bool strict_alignment_once) 5939 { 5940 bool strict = env->strict_alignment || strict_alignment_once; 5941 const char *pointer_desc = ""; 5942 5943 switch (reg->type) { 5944 case PTR_TO_PACKET: 5945 case PTR_TO_PACKET_META: 5946 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5947 * right in front, treat it the very same way. 5948 */ 5949 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5950 case PTR_TO_FLOW_KEYS: 5951 pointer_desc = "flow keys "; 5952 break; 5953 case PTR_TO_MAP_KEY: 5954 pointer_desc = "key "; 5955 break; 5956 case PTR_TO_MAP_VALUE: 5957 pointer_desc = "value "; 5958 break; 5959 case PTR_TO_CTX: 5960 pointer_desc = "context "; 5961 break; 5962 case PTR_TO_STACK: 5963 pointer_desc = "stack "; 5964 /* The stack spill tracking logic in check_stack_write_fixed_off() 5965 * and check_stack_read_fixed_off() relies on stack accesses being 5966 * aligned. 5967 */ 5968 strict = true; 5969 break; 5970 case PTR_TO_SOCKET: 5971 pointer_desc = "sock "; 5972 break; 5973 case PTR_TO_SOCK_COMMON: 5974 pointer_desc = "sock_common "; 5975 break; 5976 case PTR_TO_TCP_SOCK: 5977 pointer_desc = "tcp_sock "; 5978 break; 5979 case PTR_TO_XDP_SOCK: 5980 pointer_desc = "xdp_sock "; 5981 break; 5982 case PTR_TO_ARENA: 5983 return 0; 5984 default: 5985 break; 5986 } 5987 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5988 strict); 5989 } 5990 5991 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth) 5992 { 5993 if (env->prog->jit_requested) 5994 return round_up(stack_depth, 16); 5995 5996 /* round up to 32-bytes, since this is granularity 5997 * of interpreter stack size 5998 */ 5999 return round_up(max_t(u32, stack_depth, 1), 32); 6000 } 6001 6002 /* starting from main bpf function walk all instructions of the function 6003 * and recursively walk all callees that given function can call. 6004 * Ignore jump and exit insns. 6005 * Since recursion is prevented by check_cfg() this algorithm 6006 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 6007 */ 6008 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx) 6009 { 6010 struct bpf_subprog_info *subprog = env->subprog_info; 6011 struct bpf_insn *insn = env->prog->insnsi; 6012 int depth = 0, frame = 0, i, subprog_end; 6013 bool tail_call_reachable = false; 6014 int ret_insn[MAX_CALL_FRAMES]; 6015 int ret_prog[MAX_CALL_FRAMES]; 6016 int j; 6017 6018 i = subprog[idx].start; 6019 process_func: 6020 /* protect against potential stack overflow that might happen when 6021 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 6022 * depth for such case down to 256 so that the worst case scenario 6023 * would result in 8k stack size (32 which is tailcall limit * 256 = 6024 * 8k). 6025 * 6026 * To get the idea what might happen, see an example: 6027 * func1 -> sub rsp, 128 6028 * subfunc1 -> sub rsp, 256 6029 * tailcall1 -> add rsp, 256 6030 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 6031 * subfunc2 -> sub rsp, 64 6032 * subfunc22 -> sub rsp, 128 6033 * tailcall2 -> add rsp, 128 6034 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 6035 * 6036 * tailcall will unwind the current stack frame but it will not get rid 6037 * of caller's stack as shown on the example above. 6038 */ 6039 if (idx && subprog[idx].has_tail_call && depth >= 256) { 6040 verbose(env, 6041 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 6042 depth); 6043 return -EACCES; 6044 } 6045 depth += round_up_stack_depth(env, subprog[idx].stack_depth); 6046 if (depth > MAX_BPF_STACK) { 6047 verbose(env, "combined stack size of %d calls is %d. Too large\n", 6048 frame + 1, depth); 6049 return -EACCES; 6050 } 6051 continue_func: 6052 subprog_end = subprog[idx + 1].start; 6053 for (; i < subprog_end; i++) { 6054 int next_insn, sidx; 6055 6056 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 6057 bool err = false; 6058 6059 if (!is_bpf_throw_kfunc(insn + i)) 6060 continue; 6061 if (subprog[idx].is_cb) 6062 err = true; 6063 for (int c = 0; c < frame && !err; c++) { 6064 if (subprog[ret_prog[c]].is_cb) { 6065 err = true; 6066 break; 6067 } 6068 } 6069 if (!err) 6070 continue; 6071 verbose(env, 6072 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 6073 i, idx); 6074 return -EINVAL; 6075 } 6076 6077 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 6078 continue; 6079 /* remember insn and function to return to */ 6080 ret_insn[frame] = i + 1; 6081 ret_prog[frame] = idx; 6082 6083 /* find the callee */ 6084 next_insn = i + insn[i].imm + 1; 6085 sidx = find_subprog(env, next_insn); 6086 if (sidx < 0) { 6087 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 6088 next_insn); 6089 return -EFAULT; 6090 } 6091 if (subprog[sidx].is_async_cb) { 6092 if (subprog[sidx].has_tail_call) { 6093 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 6094 return -EFAULT; 6095 } 6096 /* async callbacks don't increase bpf prog stack size unless called directly */ 6097 if (!bpf_pseudo_call(insn + i)) 6098 continue; 6099 if (subprog[sidx].is_exception_cb) { 6100 verbose(env, "insn %d cannot call exception cb directly\n", i); 6101 return -EINVAL; 6102 } 6103 } 6104 i = next_insn; 6105 idx = sidx; 6106 6107 if (subprog[idx].has_tail_call) 6108 tail_call_reachable = true; 6109 6110 frame++; 6111 if (frame >= MAX_CALL_FRAMES) { 6112 verbose(env, "the call stack of %d frames is too deep !\n", 6113 frame); 6114 return -E2BIG; 6115 } 6116 goto process_func; 6117 } 6118 /* if tail call got detected across bpf2bpf calls then mark each of the 6119 * currently present subprog frames as tail call reachable subprogs; 6120 * this info will be utilized by JIT so that we will be preserving the 6121 * tail call counter throughout bpf2bpf calls combined with tailcalls 6122 */ 6123 if (tail_call_reachable) 6124 for (j = 0; j < frame; j++) { 6125 if (subprog[ret_prog[j]].is_exception_cb) { 6126 verbose(env, "cannot tail call within exception cb\n"); 6127 return -EINVAL; 6128 } 6129 subprog[ret_prog[j]].tail_call_reachable = true; 6130 } 6131 if (subprog[0].tail_call_reachable) 6132 env->prog->aux->tail_call_reachable = true; 6133 6134 /* end of for() loop means the last insn of the 'subprog' 6135 * was reached. Doesn't matter whether it was JA or EXIT 6136 */ 6137 if (frame == 0) 6138 return 0; 6139 depth -= round_up_stack_depth(env, subprog[idx].stack_depth); 6140 frame--; 6141 i = ret_insn[frame]; 6142 idx = ret_prog[frame]; 6143 goto continue_func; 6144 } 6145 6146 static int check_max_stack_depth(struct bpf_verifier_env *env) 6147 { 6148 struct bpf_subprog_info *si = env->subprog_info; 6149 int ret; 6150 6151 for (int i = 0; i < env->subprog_cnt; i++) { 6152 if (!i || si[i].is_async_cb) { 6153 ret = check_max_stack_depth_subprog(env, i); 6154 if (ret < 0) 6155 return ret; 6156 } 6157 continue; 6158 } 6159 return 0; 6160 } 6161 6162 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 6163 static int get_callee_stack_depth(struct bpf_verifier_env *env, 6164 const struct bpf_insn *insn, int idx) 6165 { 6166 int start = idx + insn->imm + 1, subprog; 6167 6168 subprog = find_subprog(env, start); 6169 if (subprog < 0) { 6170 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 6171 start); 6172 return -EFAULT; 6173 } 6174 return env->subprog_info[subprog].stack_depth; 6175 } 6176 #endif 6177 6178 static int __check_buffer_access(struct bpf_verifier_env *env, 6179 const char *buf_info, 6180 const struct bpf_reg_state *reg, 6181 int regno, int off, int size) 6182 { 6183 if (off < 0) { 6184 verbose(env, 6185 "R%d invalid %s buffer access: off=%d, size=%d\n", 6186 regno, buf_info, off, size); 6187 return -EACCES; 6188 } 6189 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6190 char tn_buf[48]; 6191 6192 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6193 verbose(env, 6194 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 6195 regno, off, tn_buf); 6196 return -EACCES; 6197 } 6198 6199 return 0; 6200 } 6201 6202 static int check_tp_buffer_access(struct bpf_verifier_env *env, 6203 const struct bpf_reg_state *reg, 6204 int regno, int off, int size) 6205 { 6206 int err; 6207 6208 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 6209 if (err) 6210 return err; 6211 6212 if (off + size > env->prog->aux->max_tp_access) 6213 env->prog->aux->max_tp_access = off + size; 6214 6215 return 0; 6216 } 6217 6218 static int check_buffer_access(struct bpf_verifier_env *env, 6219 const struct bpf_reg_state *reg, 6220 int regno, int off, int size, 6221 bool zero_size_allowed, 6222 u32 *max_access) 6223 { 6224 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 6225 int err; 6226 6227 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 6228 if (err) 6229 return err; 6230 6231 if (off + size > *max_access) 6232 *max_access = off + size; 6233 6234 return 0; 6235 } 6236 6237 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 6238 static void zext_32_to_64(struct bpf_reg_state *reg) 6239 { 6240 reg->var_off = tnum_subreg(reg->var_off); 6241 __reg_assign_32_into_64(reg); 6242 } 6243 6244 /* truncate register to smaller size (in bytes) 6245 * must be called with size < BPF_REG_SIZE 6246 */ 6247 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 6248 { 6249 u64 mask; 6250 6251 /* clear high bits in bit representation */ 6252 reg->var_off = tnum_cast(reg->var_off, size); 6253 6254 /* fix arithmetic bounds */ 6255 mask = ((u64)1 << (size * 8)) - 1; 6256 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 6257 reg->umin_value &= mask; 6258 reg->umax_value &= mask; 6259 } else { 6260 reg->umin_value = 0; 6261 reg->umax_value = mask; 6262 } 6263 reg->smin_value = reg->umin_value; 6264 reg->smax_value = reg->umax_value; 6265 6266 /* If size is smaller than 32bit register the 32bit register 6267 * values are also truncated so we push 64-bit bounds into 6268 * 32-bit bounds. Above were truncated < 32-bits already. 6269 */ 6270 if (size < 4) 6271 __mark_reg32_unbounded(reg); 6272 6273 reg_bounds_sync(reg); 6274 } 6275 6276 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 6277 { 6278 if (size == 1) { 6279 reg->smin_value = reg->s32_min_value = S8_MIN; 6280 reg->smax_value = reg->s32_max_value = S8_MAX; 6281 } else if (size == 2) { 6282 reg->smin_value = reg->s32_min_value = S16_MIN; 6283 reg->smax_value = reg->s32_max_value = S16_MAX; 6284 } else { 6285 /* size == 4 */ 6286 reg->smin_value = reg->s32_min_value = S32_MIN; 6287 reg->smax_value = reg->s32_max_value = S32_MAX; 6288 } 6289 reg->umin_value = reg->u32_min_value = 0; 6290 reg->umax_value = U64_MAX; 6291 reg->u32_max_value = U32_MAX; 6292 reg->var_off = tnum_unknown; 6293 } 6294 6295 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6296 { 6297 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6298 u64 top_smax_value, top_smin_value; 6299 u64 num_bits = size * 8; 6300 6301 if (tnum_is_const(reg->var_off)) { 6302 u64_cval = reg->var_off.value; 6303 if (size == 1) 6304 reg->var_off = tnum_const((s8)u64_cval); 6305 else if (size == 2) 6306 reg->var_off = tnum_const((s16)u64_cval); 6307 else 6308 /* size == 4 */ 6309 reg->var_off = tnum_const((s32)u64_cval); 6310 6311 u64_cval = reg->var_off.value; 6312 reg->smax_value = reg->smin_value = u64_cval; 6313 reg->umax_value = reg->umin_value = u64_cval; 6314 reg->s32_max_value = reg->s32_min_value = u64_cval; 6315 reg->u32_max_value = reg->u32_min_value = u64_cval; 6316 return; 6317 } 6318 6319 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6320 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6321 6322 if (top_smax_value != top_smin_value) 6323 goto out; 6324 6325 /* find the s64_min and s64_min after sign extension */ 6326 if (size == 1) { 6327 init_s64_max = (s8)reg->smax_value; 6328 init_s64_min = (s8)reg->smin_value; 6329 } else if (size == 2) { 6330 init_s64_max = (s16)reg->smax_value; 6331 init_s64_min = (s16)reg->smin_value; 6332 } else { 6333 init_s64_max = (s32)reg->smax_value; 6334 init_s64_min = (s32)reg->smin_value; 6335 } 6336 6337 s64_max = max(init_s64_max, init_s64_min); 6338 s64_min = min(init_s64_max, init_s64_min); 6339 6340 /* both of s64_max/s64_min positive or negative */ 6341 if ((s64_max >= 0) == (s64_min >= 0)) { 6342 reg->s32_min_value = reg->smin_value = s64_min; 6343 reg->s32_max_value = reg->smax_value = s64_max; 6344 reg->u32_min_value = reg->umin_value = s64_min; 6345 reg->u32_max_value = reg->umax_value = s64_max; 6346 reg->var_off = tnum_range(s64_min, s64_max); 6347 return; 6348 } 6349 6350 out: 6351 set_sext64_default_val(reg, size); 6352 } 6353 6354 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6355 { 6356 if (size == 1) { 6357 reg->s32_min_value = S8_MIN; 6358 reg->s32_max_value = S8_MAX; 6359 } else { 6360 /* size == 2 */ 6361 reg->s32_min_value = S16_MIN; 6362 reg->s32_max_value = S16_MAX; 6363 } 6364 reg->u32_min_value = 0; 6365 reg->u32_max_value = U32_MAX; 6366 reg->var_off = tnum_subreg(tnum_unknown); 6367 } 6368 6369 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6370 { 6371 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6372 u32 top_smax_value, top_smin_value; 6373 u32 num_bits = size * 8; 6374 6375 if (tnum_is_const(reg->var_off)) { 6376 u32_val = reg->var_off.value; 6377 if (size == 1) 6378 reg->var_off = tnum_const((s8)u32_val); 6379 else 6380 reg->var_off = tnum_const((s16)u32_val); 6381 6382 u32_val = reg->var_off.value; 6383 reg->s32_min_value = reg->s32_max_value = u32_val; 6384 reg->u32_min_value = reg->u32_max_value = u32_val; 6385 return; 6386 } 6387 6388 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 6389 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 6390 6391 if (top_smax_value != top_smin_value) 6392 goto out; 6393 6394 /* find the s32_min and s32_min after sign extension */ 6395 if (size == 1) { 6396 init_s32_max = (s8)reg->s32_max_value; 6397 init_s32_min = (s8)reg->s32_min_value; 6398 } else { 6399 /* size == 2 */ 6400 init_s32_max = (s16)reg->s32_max_value; 6401 init_s32_min = (s16)reg->s32_min_value; 6402 } 6403 s32_max = max(init_s32_max, init_s32_min); 6404 s32_min = min(init_s32_max, init_s32_min); 6405 6406 if ((s32_min >= 0) == (s32_max >= 0)) { 6407 reg->s32_min_value = s32_min; 6408 reg->s32_max_value = s32_max; 6409 reg->u32_min_value = (u32)s32_min; 6410 reg->u32_max_value = (u32)s32_max; 6411 reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max)); 6412 return; 6413 } 6414 6415 out: 6416 set_sext32_default_val(reg, size); 6417 } 6418 6419 static bool bpf_map_is_rdonly(const struct bpf_map *map) 6420 { 6421 /* A map is considered read-only if the following condition are true: 6422 * 6423 * 1) BPF program side cannot change any of the map content. The 6424 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6425 * and was set at map creation time. 6426 * 2) The map value(s) have been initialized from user space by a 6427 * loader and then "frozen", such that no new map update/delete 6428 * operations from syscall side are possible for the rest of 6429 * the map's lifetime from that point onwards. 6430 * 3) Any parallel/pending map update/delete operations from syscall 6431 * side have been completed. Only after that point, it's safe to 6432 * assume that map value(s) are immutable. 6433 */ 6434 return (map->map_flags & BPF_F_RDONLY_PROG) && 6435 READ_ONCE(map->frozen) && 6436 !bpf_map_write_active(map); 6437 } 6438 6439 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6440 bool is_ldsx) 6441 { 6442 void *ptr; 6443 u64 addr; 6444 int err; 6445 6446 err = map->ops->map_direct_value_addr(map, &addr, off); 6447 if (err) 6448 return err; 6449 ptr = (void *)(long)addr + off; 6450 6451 switch (size) { 6452 case sizeof(u8): 6453 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6454 break; 6455 case sizeof(u16): 6456 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6457 break; 6458 case sizeof(u32): 6459 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6460 break; 6461 case sizeof(u64): 6462 *val = *(u64 *)ptr; 6463 break; 6464 default: 6465 return -EINVAL; 6466 } 6467 return 0; 6468 } 6469 6470 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6471 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6472 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6473 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null) 6474 6475 /* 6476 * Allow list few fields as RCU trusted or full trusted. 6477 * This logic doesn't allow mix tagging and will be removed once GCC supports 6478 * btf_type_tag. 6479 */ 6480 6481 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6482 BTF_TYPE_SAFE_RCU(struct task_struct) { 6483 const cpumask_t *cpus_ptr; 6484 struct css_set __rcu *cgroups; 6485 struct task_struct __rcu *real_parent; 6486 struct task_struct *group_leader; 6487 }; 6488 6489 BTF_TYPE_SAFE_RCU(struct cgroup) { 6490 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6491 struct kernfs_node *kn; 6492 }; 6493 6494 BTF_TYPE_SAFE_RCU(struct css_set) { 6495 struct cgroup *dfl_cgrp; 6496 }; 6497 6498 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6499 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6500 struct file __rcu *exe_file; 6501 }; 6502 6503 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6504 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6505 */ 6506 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6507 struct sock *sk; 6508 }; 6509 6510 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6511 struct sock *sk; 6512 }; 6513 6514 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6515 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6516 struct seq_file *seq; 6517 }; 6518 6519 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6520 struct bpf_iter_meta *meta; 6521 struct task_struct *task; 6522 }; 6523 6524 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6525 struct file *file; 6526 }; 6527 6528 BTF_TYPE_SAFE_TRUSTED(struct file) { 6529 struct inode *f_inode; 6530 }; 6531 6532 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 6533 /* no negative dentry-s in places where bpf can see it */ 6534 struct inode *d_inode; 6535 }; 6536 6537 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) { 6538 struct sock *sk; 6539 }; 6540 6541 static bool type_is_rcu(struct bpf_verifier_env *env, 6542 struct bpf_reg_state *reg, 6543 const char *field_name, u32 btf_id) 6544 { 6545 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6546 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6547 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6548 6549 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6550 } 6551 6552 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6553 struct bpf_reg_state *reg, 6554 const char *field_name, u32 btf_id) 6555 { 6556 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6557 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6558 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6559 6560 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6561 } 6562 6563 static bool type_is_trusted(struct bpf_verifier_env *env, 6564 struct bpf_reg_state *reg, 6565 const char *field_name, u32 btf_id) 6566 { 6567 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 6568 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6569 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6570 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6571 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 6572 6573 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6574 } 6575 6576 static bool type_is_trusted_or_null(struct bpf_verifier_env *env, 6577 struct bpf_reg_state *reg, 6578 const char *field_name, u32 btf_id) 6579 { 6580 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)); 6581 6582 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, 6583 "__safe_trusted_or_null"); 6584 } 6585 6586 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6587 struct bpf_reg_state *regs, 6588 int regno, int off, int size, 6589 enum bpf_access_type atype, 6590 int value_regno) 6591 { 6592 struct bpf_reg_state *reg = regs + regno; 6593 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6594 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6595 const char *field_name = NULL; 6596 enum bpf_type_flag flag = 0; 6597 u32 btf_id = 0; 6598 int ret; 6599 6600 if (!env->allow_ptr_leaks) { 6601 verbose(env, 6602 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6603 tname); 6604 return -EPERM; 6605 } 6606 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6607 verbose(env, 6608 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6609 tname); 6610 return -EINVAL; 6611 } 6612 if (off < 0) { 6613 verbose(env, 6614 "R%d is ptr_%s invalid negative access: off=%d\n", 6615 regno, tname, off); 6616 return -EACCES; 6617 } 6618 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6619 char tn_buf[48]; 6620 6621 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6622 verbose(env, 6623 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6624 regno, tname, off, tn_buf); 6625 return -EACCES; 6626 } 6627 6628 if (reg->type & MEM_USER) { 6629 verbose(env, 6630 "R%d is ptr_%s access user memory: off=%d\n", 6631 regno, tname, off); 6632 return -EACCES; 6633 } 6634 6635 if (reg->type & MEM_PERCPU) { 6636 verbose(env, 6637 "R%d is ptr_%s access percpu memory: off=%d\n", 6638 regno, tname, off); 6639 return -EACCES; 6640 } 6641 6642 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6643 if (!btf_is_kernel(reg->btf)) { 6644 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 6645 return -EFAULT; 6646 } 6647 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6648 } else { 6649 /* Writes are permitted with default btf_struct_access for 6650 * program allocated objects (which always have ref_obj_id > 0), 6651 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6652 */ 6653 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6654 verbose(env, "only read is supported\n"); 6655 return -EACCES; 6656 } 6657 6658 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6659 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 6660 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 6661 return -EFAULT; 6662 } 6663 6664 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6665 } 6666 6667 if (ret < 0) 6668 return ret; 6669 6670 if (ret != PTR_TO_BTF_ID) { 6671 /* just mark; */ 6672 6673 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6674 /* If this is an untrusted pointer, all pointers formed by walking it 6675 * also inherit the untrusted flag. 6676 */ 6677 flag = PTR_UNTRUSTED; 6678 6679 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6680 /* By default any pointer obtained from walking a trusted pointer is no 6681 * longer trusted, unless the field being accessed has explicitly been 6682 * marked as inheriting its parent's state of trust (either full or RCU). 6683 * For example: 6684 * 'cgroups' pointer is untrusted if task->cgroups dereference 6685 * happened in a sleepable program outside of bpf_rcu_read_lock() 6686 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6687 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6688 * 6689 * A regular RCU-protected pointer with __rcu tag can also be deemed 6690 * trusted if we are in an RCU CS. Such pointer can be NULL. 6691 */ 6692 if (type_is_trusted(env, reg, field_name, btf_id)) { 6693 flag |= PTR_TRUSTED; 6694 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) { 6695 flag |= PTR_TRUSTED | PTR_MAYBE_NULL; 6696 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6697 if (type_is_rcu(env, reg, field_name, btf_id)) { 6698 /* ignore __rcu tag and mark it MEM_RCU */ 6699 flag |= MEM_RCU; 6700 } else if (flag & MEM_RCU || 6701 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6702 /* __rcu tagged pointers can be NULL */ 6703 flag |= MEM_RCU | PTR_MAYBE_NULL; 6704 6705 /* We always trust them */ 6706 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6707 flag & PTR_UNTRUSTED) 6708 flag &= ~PTR_UNTRUSTED; 6709 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6710 /* keep as-is */ 6711 } else { 6712 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6713 clear_trusted_flags(&flag); 6714 } 6715 } else { 6716 /* 6717 * If not in RCU CS or MEM_RCU pointer can be NULL then 6718 * aggressively mark as untrusted otherwise such 6719 * pointers will be plain PTR_TO_BTF_ID without flags 6720 * and will be allowed to be passed into helpers for 6721 * compat reasons. 6722 */ 6723 flag = PTR_UNTRUSTED; 6724 } 6725 } else { 6726 /* Old compat. Deprecated */ 6727 clear_trusted_flags(&flag); 6728 } 6729 6730 if (atype == BPF_READ && value_regno >= 0) 6731 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6732 6733 return 0; 6734 } 6735 6736 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6737 struct bpf_reg_state *regs, 6738 int regno, int off, int size, 6739 enum bpf_access_type atype, 6740 int value_regno) 6741 { 6742 struct bpf_reg_state *reg = regs + regno; 6743 struct bpf_map *map = reg->map_ptr; 6744 struct bpf_reg_state map_reg; 6745 enum bpf_type_flag flag = 0; 6746 const struct btf_type *t; 6747 const char *tname; 6748 u32 btf_id; 6749 int ret; 6750 6751 if (!btf_vmlinux) { 6752 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6753 return -ENOTSUPP; 6754 } 6755 6756 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6757 verbose(env, "map_ptr access not supported for map type %d\n", 6758 map->map_type); 6759 return -ENOTSUPP; 6760 } 6761 6762 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6763 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6764 6765 if (!env->allow_ptr_leaks) { 6766 verbose(env, 6767 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6768 tname); 6769 return -EPERM; 6770 } 6771 6772 if (off < 0) { 6773 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6774 regno, tname, off); 6775 return -EACCES; 6776 } 6777 6778 if (atype != BPF_READ) { 6779 verbose(env, "only read from %s is supported\n", tname); 6780 return -EACCES; 6781 } 6782 6783 /* Simulate access to a PTR_TO_BTF_ID */ 6784 memset(&map_reg, 0, sizeof(map_reg)); 6785 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6786 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6787 if (ret < 0) 6788 return ret; 6789 6790 if (value_regno >= 0) 6791 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6792 6793 return 0; 6794 } 6795 6796 /* Check that the stack access at the given offset is within bounds. The 6797 * maximum valid offset is -1. 6798 * 6799 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6800 * -state->allocated_stack for reads. 6801 */ 6802 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 6803 s64 off, 6804 struct bpf_func_state *state, 6805 enum bpf_access_type t) 6806 { 6807 int min_valid_off; 6808 6809 if (t == BPF_WRITE || env->allow_uninit_stack) 6810 min_valid_off = -MAX_BPF_STACK; 6811 else 6812 min_valid_off = -state->allocated_stack; 6813 6814 if (off < min_valid_off || off > -1) 6815 return -EACCES; 6816 return 0; 6817 } 6818 6819 /* Check that the stack access at 'regno + off' falls within the maximum stack 6820 * bounds. 6821 * 6822 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6823 */ 6824 static int check_stack_access_within_bounds( 6825 struct bpf_verifier_env *env, 6826 int regno, int off, int access_size, 6827 enum bpf_access_src src, enum bpf_access_type type) 6828 { 6829 struct bpf_reg_state *regs = cur_regs(env); 6830 struct bpf_reg_state *reg = regs + regno; 6831 struct bpf_func_state *state = func(env, reg); 6832 s64 min_off, max_off; 6833 int err; 6834 char *err_extra; 6835 6836 if (src == ACCESS_HELPER) 6837 /* We don't know if helpers are reading or writing (or both). */ 6838 err_extra = " indirect access to"; 6839 else if (type == BPF_READ) 6840 err_extra = " read from"; 6841 else 6842 err_extra = " write to"; 6843 6844 if (tnum_is_const(reg->var_off)) { 6845 min_off = (s64)reg->var_off.value + off; 6846 max_off = min_off + access_size; 6847 } else { 6848 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6849 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6850 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6851 err_extra, regno); 6852 return -EACCES; 6853 } 6854 min_off = reg->smin_value + off; 6855 max_off = reg->smax_value + off + access_size; 6856 } 6857 6858 err = check_stack_slot_within_bounds(env, min_off, state, type); 6859 if (!err && max_off > 0) 6860 err = -EINVAL; /* out of stack access into non-negative offsets */ 6861 if (!err && access_size < 0) 6862 /* access_size should not be negative (or overflow an int); others checks 6863 * along the way should have prevented such an access. 6864 */ 6865 err = -EFAULT; /* invalid negative access size; integer overflow? */ 6866 6867 if (err) { 6868 if (tnum_is_const(reg->var_off)) { 6869 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 6870 err_extra, regno, off, access_size); 6871 } else { 6872 char tn_buf[48]; 6873 6874 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6875 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n", 6876 err_extra, regno, tn_buf, off, access_size); 6877 } 6878 return err; 6879 } 6880 6881 /* Note that there is no stack access with offset zero, so the needed stack 6882 * size is -min_off, not -min_off+1. 6883 */ 6884 return grow_stack_state(env, state, -min_off /* size */); 6885 } 6886 6887 static bool get_func_retval_range(struct bpf_prog *prog, 6888 struct bpf_retval_range *range) 6889 { 6890 if (prog->type == BPF_PROG_TYPE_LSM && 6891 prog->expected_attach_type == BPF_LSM_MAC && 6892 !bpf_lsm_get_retval_range(prog, range)) { 6893 return true; 6894 } 6895 return false; 6896 } 6897 6898 /* check whether memory at (regno + off) is accessible for t = (read | write) 6899 * if t==write, value_regno is a register which value is stored into memory 6900 * if t==read, value_regno is a register which will receive the value from memory 6901 * if t==write && value_regno==-1, some unknown value is stored into memory 6902 * if t==read && value_regno==-1, don't care what we read from memory 6903 */ 6904 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6905 int off, int bpf_size, enum bpf_access_type t, 6906 int value_regno, bool strict_alignment_once, bool is_ldsx) 6907 { 6908 struct bpf_reg_state *regs = cur_regs(env); 6909 struct bpf_reg_state *reg = regs + regno; 6910 int size, err = 0; 6911 6912 size = bpf_size_to_bytes(bpf_size); 6913 if (size < 0) 6914 return size; 6915 6916 /* alignment checks will add in reg->off themselves */ 6917 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6918 if (err) 6919 return err; 6920 6921 /* for access checks, reg->off is just part of off */ 6922 off += reg->off; 6923 6924 if (reg->type == PTR_TO_MAP_KEY) { 6925 if (t == BPF_WRITE) { 6926 verbose(env, "write to change key R%d not allowed\n", regno); 6927 return -EACCES; 6928 } 6929 6930 err = check_mem_region_access(env, regno, off, size, 6931 reg->map_ptr->key_size, false); 6932 if (err) 6933 return err; 6934 if (value_regno >= 0) 6935 mark_reg_unknown(env, regs, value_regno); 6936 } else if (reg->type == PTR_TO_MAP_VALUE) { 6937 struct btf_field *kptr_field = NULL; 6938 6939 if (t == BPF_WRITE && value_regno >= 0 && 6940 is_pointer_value(env, value_regno)) { 6941 verbose(env, "R%d leaks addr into map\n", value_regno); 6942 return -EACCES; 6943 } 6944 err = check_map_access_type(env, regno, off, size, t); 6945 if (err) 6946 return err; 6947 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6948 if (err) 6949 return err; 6950 if (tnum_is_const(reg->var_off)) 6951 kptr_field = btf_record_find(reg->map_ptr->record, 6952 off + reg->var_off.value, BPF_KPTR); 6953 if (kptr_field) { 6954 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6955 } else if (t == BPF_READ && value_regno >= 0) { 6956 struct bpf_map *map = reg->map_ptr; 6957 6958 /* if map is read-only, track its contents as scalars */ 6959 if (tnum_is_const(reg->var_off) && 6960 bpf_map_is_rdonly(map) && 6961 map->ops->map_direct_value_addr) { 6962 int map_off = off + reg->var_off.value; 6963 u64 val = 0; 6964 6965 err = bpf_map_direct_read(map, map_off, size, 6966 &val, is_ldsx); 6967 if (err) 6968 return err; 6969 6970 regs[value_regno].type = SCALAR_VALUE; 6971 __mark_reg_known(®s[value_regno], val); 6972 } else { 6973 mark_reg_unknown(env, regs, value_regno); 6974 } 6975 } 6976 } else if (base_type(reg->type) == PTR_TO_MEM) { 6977 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6978 6979 if (type_may_be_null(reg->type)) { 6980 verbose(env, "R%d invalid mem access '%s'\n", regno, 6981 reg_type_str(env, reg->type)); 6982 return -EACCES; 6983 } 6984 6985 if (t == BPF_WRITE && rdonly_mem) { 6986 verbose(env, "R%d cannot write into %s\n", 6987 regno, reg_type_str(env, reg->type)); 6988 return -EACCES; 6989 } 6990 6991 if (t == BPF_WRITE && value_regno >= 0 && 6992 is_pointer_value(env, value_regno)) { 6993 verbose(env, "R%d leaks addr into mem\n", value_regno); 6994 return -EACCES; 6995 } 6996 6997 err = check_mem_region_access(env, regno, off, size, 6998 reg->mem_size, false); 6999 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 7000 mark_reg_unknown(env, regs, value_regno); 7001 } else if (reg->type == PTR_TO_CTX) { 7002 bool is_retval = false; 7003 struct bpf_retval_range range; 7004 enum bpf_reg_type reg_type = SCALAR_VALUE; 7005 struct btf *btf = NULL; 7006 u32 btf_id = 0; 7007 7008 if (t == BPF_WRITE && value_regno >= 0 && 7009 is_pointer_value(env, value_regno)) { 7010 verbose(env, "R%d leaks addr into ctx\n", value_regno); 7011 return -EACCES; 7012 } 7013 7014 err = check_ptr_off_reg(env, reg, regno); 7015 if (err < 0) 7016 return err; 7017 7018 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 7019 &btf_id, &is_retval, is_ldsx); 7020 if (err) 7021 verbose_linfo(env, insn_idx, "; "); 7022 if (!err && t == BPF_READ && value_regno >= 0) { 7023 /* ctx access returns either a scalar, or a 7024 * PTR_TO_PACKET[_META,_END]. In the latter 7025 * case, we know the offset is zero. 7026 */ 7027 if (reg_type == SCALAR_VALUE) { 7028 if (is_retval && get_func_retval_range(env->prog, &range)) { 7029 err = __mark_reg_s32_range(env, regs, value_regno, 7030 range.minval, range.maxval); 7031 if (err) 7032 return err; 7033 } else { 7034 mark_reg_unknown(env, regs, value_regno); 7035 } 7036 } else { 7037 mark_reg_known_zero(env, regs, 7038 value_regno); 7039 if (type_may_be_null(reg_type)) 7040 regs[value_regno].id = ++env->id_gen; 7041 /* A load of ctx field could have different 7042 * actual load size with the one encoded in the 7043 * insn. When the dst is PTR, it is for sure not 7044 * a sub-register. 7045 */ 7046 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 7047 if (base_type(reg_type) == PTR_TO_BTF_ID) { 7048 regs[value_regno].btf = btf; 7049 regs[value_regno].btf_id = btf_id; 7050 } 7051 } 7052 regs[value_regno].type = reg_type; 7053 } 7054 7055 } else if (reg->type == PTR_TO_STACK) { 7056 /* Basic bounds checks. */ 7057 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 7058 if (err) 7059 return err; 7060 7061 if (t == BPF_READ) 7062 err = check_stack_read(env, regno, off, size, 7063 value_regno); 7064 else 7065 err = check_stack_write(env, regno, off, size, 7066 value_regno, insn_idx); 7067 } else if (reg_is_pkt_pointer(reg)) { 7068 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 7069 verbose(env, "cannot write into packet\n"); 7070 return -EACCES; 7071 } 7072 if (t == BPF_WRITE && value_regno >= 0 && 7073 is_pointer_value(env, value_regno)) { 7074 verbose(env, "R%d leaks addr into packet\n", 7075 value_regno); 7076 return -EACCES; 7077 } 7078 err = check_packet_access(env, regno, off, size, false); 7079 if (!err && t == BPF_READ && value_regno >= 0) 7080 mark_reg_unknown(env, regs, value_regno); 7081 } else if (reg->type == PTR_TO_FLOW_KEYS) { 7082 if (t == BPF_WRITE && value_regno >= 0 && 7083 is_pointer_value(env, value_regno)) { 7084 verbose(env, "R%d leaks addr into flow keys\n", 7085 value_regno); 7086 return -EACCES; 7087 } 7088 7089 err = check_flow_keys_access(env, off, size); 7090 if (!err && t == BPF_READ && value_regno >= 0) 7091 mark_reg_unknown(env, regs, value_regno); 7092 } else if (type_is_sk_pointer(reg->type)) { 7093 if (t == BPF_WRITE) { 7094 verbose(env, "R%d cannot write into %s\n", 7095 regno, reg_type_str(env, reg->type)); 7096 return -EACCES; 7097 } 7098 err = check_sock_access(env, insn_idx, regno, off, size, t); 7099 if (!err && value_regno >= 0) 7100 mark_reg_unknown(env, regs, value_regno); 7101 } else if (reg->type == PTR_TO_TP_BUFFER) { 7102 err = check_tp_buffer_access(env, reg, regno, off, size); 7103 if (!err && t == BPF_READ && value_regno >= 0) 7104 mark_reg_unknown(env, regs, value_regno); 7105 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 7106 !type_may_be_null(reg->type)) { 7107 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 7108 value_regno); 7109 } else if (reg->type == CONST_PTR_TO_MAP) { 7110 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 7111 value_regno); 7112 } else if (base_type(reg->type) == PTR_TO_BUF) { 7113 bool rdonly_mem = type_is_rdonly_mem(reg->type); 7114 u32 *max_access; 7115 7116 if (rdonly_mem) { 7117 if (t == BPF_WRITE) { 7118 verbose(env, "R%d cannot write into %s\n", 7119 regno, reg_type_str(env, reg->type)); 7120 return -EACCES; 7121 } 7122 max_access = &env->prog->aux->max_rdonly_access; 7123 } else { 7124 max_access = &env->prog->aux->max_rdwr_access; 7125 } 7126 7127 err = check_buffer_access(env, reg, regno, off, size, false, 7128 max_access); 7129 7130 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 7131 mark_reg_unknown(env, regs, value_regno); 7132 } else if (reg->type == PTR_TO_ARENA) { 7133 if (t == BPF_READ && value_regno >= 0) 7134 mark_reg_unknown(env, regs, value_regno); 7135 } else { 7136 verbose(env, "R%d invalid mem access '%s'\n", regno, 7137 reg_type_str(env, reg->type)); 7138 return -EACCES; 7139 } 7140 7141 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 7142 regs[value_regno].type == SCALAR_VALUE) { 7143 if (!is_ldsx) 7144 /* b/h/w load zero-extends, mark upper bits as known 0 */ 7145 coerce_reg_to_size(®s[value_regno], size); 7146 else 7147 coerce_reg_to_size_sx(®s[value_regno], size); 7148 } 7149 return err; 7150 } 7151 7152 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 7153 bool allow_trust_mismatch); 7154 7155 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 7156 { 7157 int load_reg; 7158 int err; 7159 7160 switch (insn->imm) { 7161 case BPF_ADD: 7162 case BPF_ADD | BPF_FETCH: 7163 case BPF_AND: 7164 case BPF_AND | BPF_FETCH: 7165 case BPF_OR: 7166 case BPF_OR | BPF_FETCH: 7167 case BPF_XOR: 7168 case BPF_XOR | BPF_FETCH: 7169 case BPF_XCHG: 7170 case BPF_CMPXCHG: 7171 break; 7172 default: 7173 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 7174 return -EINVAL; 7175 } 7176 7177 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 7178 verbose(env, "invalid atomic operand size\n"); 7179 return -EINVAL; 7180 } 7181 7182 /* check src1 operand */ 7183 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7184 if (err) 7185 return err; 7186 7187 /* check src2 operand */ 7188 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 7189 if (err) 7190 return err; 7191 7192 if (insn->imm == BPF_CMPXCHG) { 7193 /* Check comparison of R0 with memory location */ 7194 const u32 aux_reg = BPF_REG_0; 7195 7196 err = check_reg_arg(env, aux_reg, SRC_OP); 7197 if (err) 7198 return err; 7199 7200 if (is_pointer_value(env, aux_reg)) { 7201 verbose(env, "R%d leaks addr into mem\n", aux_reg); 7202 return -EACCES; 7203 } 7204 } 7205 7206 if (is_pointer_value(env, insn->src_reg)) { 7207 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 7208 return -EACCES; 7209 } 7210 7211 if (is_ctx_reg(env, insn->dst_reg) || 7212 is_pkt_reg(env, insn->dst_reg) || 7213 is_flow_key_reg(env, insn->dst_reg) || 7214 is_sk_reg(env, insn->dst_reg) || 7215 (is_arena_reg(env, insn->dst_reg) && !bpf_jit_supports_insn(insn, true))) { 7216 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 7217 insn->dst_reg, 7218 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 7219 return -EACCES; 7220 } 7221 7222 if (insn->imm & BPF_FETCH) { 7223 if (insn->imm == BPF_CMPXCHG) 7224 load_reg = BPF_REG_0; 7225 else 7226 load_reg = insn->src_reg; 7227 7228 /* check and record load of old value */ 7229 err = check_reg_arg(env, load_reg, DST_OP); 7230 if (err) 7231 return err; 7232 } else { 7233 /* This instruction accesses a memory location but doesn't 7234 * actually load it into a register. 7235 */ 7236 load_reg = -1; 7237 } 7238 7239 /* Check whether we can read the memory, with second call for fetch 7240 * case to simulate the register fill. 7241 */ 7242 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7243 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 7244 if (!err && load_reg >= 0) 7245 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7246 BPF_SIZE(insn->code), BPF_READ, load_reg, 7247 true, false); 7248 if (err) 7249 return err; 7250 7251 if (is_arena_reg(env, insn->dst_reg)) { 7252 err = save_aux_ptr_type(env, PTR_TO_ARENA, false); 7253 if (err) 7254 return err; 7255 } 7256 /* Check whether we can write into the same memory. */ 7257 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7258 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 7259 if (err) 7260 return err; 7261 return 0; 7262 } 7263 7264 /* When register 'regno' is used to read the stack (either directly or through 7265 * a helper function) make sure that it's within stack boundary and, depending 7266 * on the access type and privileges, that all elements of the stack are 7267 * initialized. 7268 * 7269 * 'off' includes 'regno->off', but not its dynamic part (if any). 7270 * 7271 * All registers that have been spilled on the stack in the slots within the 7272 * read offsets are marked as read. 7273 */ 7274 static int check_stack_range_initialized( 7275 struct bpf_verifier_env *env, int regno, int off, 7276 int access_size, bool zero_size_allowed, 7277 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 7278 { 7279 struct bpf_reg_state *reg = reg_state(env, regno); 7280 struct bpf_func_state *state = func(env, reg); 7281 int err, min_off, max_off, i, j, slot, spi; 7282 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 7283 enum bpf_access_type bounds_check_type; 7284 /* Some accesses can write anything into the stack, others are 7285 * read-only. 7286 */ 7287 bool clobber = false; 7288 7289 if (access_size == 0 && !zero_size_allowed) { 7290 verbose(env, "invalid zero-sized read\n"); 7291 return -EACCES; 7292 } 7293 7294 if (type == ACCESS_HELPER) { 7295 /* The bounds checks for writes are more permissive than for 7296 * reads. However, if raw_mode is not set, we'll do extra 7297 * checks below. 7298 */ 7299 bounds_check_type = BPF_WRITE; 7300 clobber = true; 7301 } else { 7302 bounds_check_type = BPF_READ; 7303 } 7304 err = check_stack_access_within_bounds(env, regno, off, access_size, 7305 type, bounds_check_type); 7306 if (err) 7307 return err; 7308 7309 7310 if (tnum_is_const(reg->var_off)) { 7311 min_off = max_off = reg->var_off.value + off; 7312 } else { 7313 /* Variable offset is prohibited for unprivileged mode for 7314 * simplicity since it requires corresponding support in 7315 * Spectre masking for stack ALU. 7316 * See also retrieve_ptr_limit(). 7317 */ 7318 if (!env->bypass_spec_v1) { 7319 char tn_buf[48]; 7320 7321 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7322 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 7323 regno, err_extra, tn_buf); 7324 return -EACCES; 7325 } 7326 /* Only initialized buffer on stack is allowed to be accessed 7327 * with variable offset. With uninitialized buffer it's hard to 7328 * guarantee that whole memory is marked as initialized on 7329 * helper return since specific bounds are unknown what may 7330 * cause uninitialized stack leaking. 7331 */ 7332 if (meta && meta->raw_mode) 7333 meta = NULL; 7334 7335 min_off = reg->smin_value + off; 7336 max_off = reg->smax_value + off; 7337 } 7338 7339 if (meta && meta->raw_mode) { 7340 /* Ensure we won't be overwriting dynptrs when simulating byte 7341 * by byte access in check_helper_call using meta.access_size. 7342 * This would be a problem if we have a helper in the future 7343 * which takes: 7344 * 7345 * helper(uninit_mem, len, dynptr) 7346 * 7347 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 7348 * may end up writing to dynptr itself when touching memory from 7349 * arg 1. This can be relaxed on a case by case basis for known 7350 * safe cases, but reject due to the possibilitiy of aliasing by 7351 * default. 7352 */ 7353 for (i = min_off; i < max_off + access_size; i++) { 7354 int stack_off = -i - 1; 7355 7356 spi = __get_spi(i); 7357 /* raw_mode may write past allocated_stack */ 7358 if (state->allocated_stack <= stack_off) 7359 continue; 7360 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 7361 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 7362 return -EACCES; 7363 } 7364 } 7365 meta->access_size = access_size; 7366 meta->regno = regno; 7367 return 0; 7368 } 7369 7370 for (i = min_off; i < max_off + access_size; i++) { 7371 u8 *stype; 7372 7373 slot = -i - 1; 7374 spi = slot / BPF_REG_SIZE; 7375 if (state->allocated_stack <= slot) { 7376 verbose(env, "verifier bug: allocated_stack too small"); 7377 return -EFAULT; 7378 } 7379 7380 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 7381 if (*stype == STACK_MISC) 7382 goto mark; 7383 if ((*stype == STACK_ZERO) || 7384 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 7385 if (clobber) { 7386 /* helper can write anything into the stack */ 7387 *stype = STACK_MISC; 7388 } 7389 goto mark; 7390 } 7391 7392 if (is_spilled_reg(&state->stack[spi]) && 7393 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 7394 env->allow_ptr_leaks)) { 7395 if (clobber) { 7396 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 7397 for (j = 0; j < BPF_REG_SIZE; j++) 7398 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 7399 } 7400 goto mark; 7401 } 7402 7403 if (tnum_is_const(reg->var_off)) { 7404 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 7405 err_extra, regno, min_off, i - min_off, access_size); 7406 } else { 7407 char tn_buf[48]; 7408 7409 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7410 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 7411 err_extra, regno, tn_buf, i - min_off, access_size); 7412 } 7413 return -EACCES; 7414 mark: 7415 /* reading any byte out of 8-byte 'spill_slot' will cause 7416 * the whole slot to be marked as 'read' 7417 */ 7418 mark_reg_read(env, &state->stack[spi].spilled_ptr, 7419 state->stack[spi].spilled_ptr.parent, 7420 REG_LIVE_READ64); 7421 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 7422 * be sure that whether stack slot is written to or not. Hence, 7423 * we must still conservatively propagate reads upwards even if 7424 * helper may write to the entire memory range. 7425 */ 7426 } 7427 return 0; 7428 } 7429 7430 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 7431 int access_size, enum bpf_access_type access_type, 7432 bool zero_size_allowed, 7433 struct bpf_call_arg_meta *meta) 7434 { 7435 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7436 u32 *max_access; 7437 7438 switch (base_type(reg->type)) { 7439 case PTR_TO_PACKET: 7440 case PTR_TO_PACKET_META: 7441 return check_packet_access(env, regno, reg->off, access_size, 7442 zero_size_allowed); 7443 case PTR_TO_MAP_KEY: 7444 if (access_type == BPF_WRITE) { 7445 verbose(env, "R%d cannot write into %s\n", regno, 7446 reg_type_str(env, reg->type)); 7447 return -EACCES; 7448 } 7449 return check_mem_region_access(env, regno, reg->off, access_size, 7450 reg->map_ptr->key_size, false); 7451 case PTR_TO_MAP_VALUE: 7452 if (check_map_access_type(env, regno, reg->off, access_size, access_type)) 7453 return -EACCES; 7454 return check_map_access(env, regno, reg->off, access_size, 7455 zero_size_allowed, ACCESS_HELPER); 7456 case PTR_TO_MEM: 7457 if (type_is_rdonly_mem(reg->type)) { 7458 if (access_type == BPF_WRITE) { 7459 verbose(env, "R%d cannot write into %s\n", regno, 7460 reg_type_str(env, reg->type)); 7461 return -EACCES; 7462 } 7463 } 7464 return check_mem_region_access(env, regno, reg->off, 7465 access_size, reg->mem_size, 7466 zero_size_allowed); 7467 case PTR_TO_BUF: 7468 if (type_is_rdonly_mem(reg->type)) { 7469 if (access_type == BPF_WRITE) { 7470 verbose(env, "R%d cannot write into %s\n", regno, 7471 reg_type_str(env, reg->type)); 7472 return -EACCES; 7473 } 7474 7475 max_access = &env->prog->aux->max_rdonly_access; 7476 } else { 7477 max_access = &env->prog->aux->max_rdwr_access; 7478 } 7479 return check_buffer_access(env, reg, regno, reg->off, 7480 access_size, zero_size_allowed, 7481 max_access); 7482 case PTR_TO_STACK: 7483 return check_stack_range_initialized( 7484 env, 7485 regno, reg->off, access_size, 7486 zero_size_allowed, ACCESS_HELPER, meta); 7487 case PTR_TO_BTF_ID: 7488 return check_ptr_to_btf_access(env, regs, regno, reg->off, 7489 access_size, BPF_READ, -1); 7490 case PTR_TO_CTX: 7491 /* in case the function doesn't know how to access the context, 7492 * (because we are in a program of type SYSCALL for example), we 7493 * can not statically check its size. 7494 * Dynamically check it now. 7495 */ 7496 if (!env->ops->convert_ctx_access) { 7497 int offset = access_size - 1; 7498 7499 /* Allow zero-byte read from PTR_TO_CTX */ 7500 if (access_size == 0) 7501 return zero_size_allowed ? 0 : -EACCES; 7502 7503 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 7504 access_type, -1, false, false); 7505 } 7506 7507 fallthrough; 7508 default: /* scalar_value or invalid ptr */ 7509 /* Allow zero-byte read from NULL, regardless of pointer type */ 7510 if (zero_size_allowed && access_size == 0 && 7511 register_is_null(reg)) 7512 return 0; 7513 7514 verbose(env, "R%d type=%s ", regno, 7515 reg_type_str(env, reg->type)); 7516 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7517 return -EACCES; 7518 } 7519 } 7520 7521 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 7522 * size. 7523 * 7524 * @regno is the register containing the access size. regno-1 is the register 7525 * containing the pointer. 7526 */ 7527 static int check_mem_size_reg(struct bpf_verifier_env *env, 7528 struct bpf_reg_state *reg, u32 regno, 7529 enum bpf_access_type access_type, 7530 bool zero_size_allowed, 7531 struct bpf_call_arg_meta *meta) 7532 { 7533 int err; 7534 7535 /* This is used to refine r0 return value bounds for helpers 7536 * that enforce this value as an upper bound on return values. 7537 * See do_refine_retval_range() for helpers that can refine 7538 * the return value. C type of helper is u32 so we pull register 7539 * bound from umax_value however, if negative verifier errors 7540 * out. Only upper bounds can be learned because retval is an 7541 * int type and negative retvals are allowed. 7542 */ 7543 meta->msize_max_value = reg->umax_value; 7544 7545 /* The register is SCALAR_VALUE; the access check happens using 7546 * its boundaries. For unprivileged variable accesses, disable 7547 * raw mode so that the program is required to initialize all 7548 * the memory that the helper could just partially fill up. 7549 */ 7550 if (!tnum_is_const(reg->var_off)) 7551 meta = NULL; 7552 7553 if (reg->smin_value < 0) { 7554 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7555 regno); 7556 return -EACCES; 7557 } 7558 7559 if (reg->umin_value == 0 && !zero_size_allowed) { 7560 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n", 7561 regno, reg->umin_value, reg->umax_value); 7562 return -EACCES; 7563 } 7564 7565 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7566 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7567 regno); 7568 return -EACCES; 7569 } 7570 err = check_helper_mem_access(env, regno - 1, reg->umax_value, 7571 access_type, zero_size_allowed, meta); 7572 if (!err) 7573 err = mark_chain_precision(env, regno); 7574 return err; 7575 } 7576 7577 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7578 u32 regno, u32 mem_size) 7579 { 7580 bool may_be_null = type_may_be_null(reg->type); 7581 struct bpf_reg_state saved_reg; 7582 int err; 7583 7584 if (register_is_null(reg)) 7585 return 0; 7586 7587 /* Assuming that the register contains a value check if the memory 7588 * access is safe. Temporarily save and restore the register's state as 7589 * the conversion shouldn't be visible to a caller. 7590 */ 7591 if (may_be_null) { 7592 saved_reg = *reg; 7593 mark_ptr_not_null_reg(reg); 7594 } 7595 7596 err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL); 7597 err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL); 7598 7599 if (may_be_null) 7600 *reg = saved_reg; 7601 7602 return err; 7603 } 7604 7605 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7606 u32 regno) 7607 { 7608 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7609 bool may_be_null = type_may_be_null(mem_reg->type); 7610 struct bpf_reg_state saved_reg; 7611 struct bpf_call_arg_meta meta; 7612 int err; 7613 7614 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7615 7616 memset(&meta, 0, sizeof(meta)); 7617 7618 if (may_be_null) { 7619 saved_reg = *mem_reg; 7620 mark_ptr_not_null_reg(mem_reg); 7621 } 7622 7623 err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta); 7624 err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta); 7625 7626 if (may_be_null) 7627 *mem_reg = saved_reg; 7628 7629 return err; 7630 } 7631 7632 /* Implementation details: 7633 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7634 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7635 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7636 * Two separate bpf_obj_new will also have different reg->id. 7637 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7638 * clears reg->id after value_or_null->value transition, since the verifier only 7639 * cares about the range of access to valid map value pointer and doesn't care 7640 * about actual address of the map element. 7641 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7642 * reg->id > 0 after value_or_null->value transition. By doing so 7643 * two bpf_map_lookups will be considered two different pointers that 7644 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7645 * returned from bpf_obj_new. 7646 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7647 * dead-locks. 7648 * Since only one bpf_spin_lock is allowed the checks are simpler than 7649 * reg_is_refcounted() logic. The verifier needs to remember only 7650 * one spin_lock instead of array of acquired_refs. 7651 * cur_state->active_lock remembers which map value element or allocated 7652 * object got locked and clears it after bpf_spin_unlock. 7653 */ 7654 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 7655 bool is_lock) 7656 { 7657 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7658 struct bpf_verifier_state *cur = env->cur_state; 7659 bool is_const = tnum_is_const(reg->var_off); 7660 u64 val = reg->var_off.value; 7661 struct bpf_map *map = NULL; 7662 struct btf *btf = NULL; 7663 struct btf_record *rec; 7664 7665 if (!is_const) { 7666 verbose(env, 7667 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 7668 regno); 7669 return -EINVAL; 7670 } 7671 if (reg->type == PTR_TO_MAP_VALUE) { 7672 map = reg->map_ptr; 7673 if (!map->btf) { 7674 verbose(env, 7675 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 7676 map->name); 7677 return -EINVAL; 7678 } 7679 } else { 7680 btf = reg->btf; 7681 } 7682 7683 rec = reg_btf_record(reg); 7684 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 7685 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 7686 map ? map->name : "kptr"); 7687 return -EINVAL; 7688 } 7689 if (rec->spin_lock_off != val + reg->off) { 7690 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 7691 val + reg->off, rec->spin_lock_off); 7692 return -EINVAL; 7693 } 7694 if (is_lock) { 7695 if (cur->active_lock.ptr) { 7696 verbose(env, 7697 "Locking two bpf_spin_locks are not allowed\n"); 7698 return -EINVAL; 7699 } 7700 if (map) 7701 cur->active_lock.ptr = map; 7702 else 7703 cur->active_lock.ptr = btf; 7704 cur->active_lock.id = reg->id; 7705 } else { 7706 void *ptr; 7707 7708 if (map) 7709 ptr = map; 7710 else 7711 ptr = btf; 7712 7713 if (!cur->active_lock.ptr) { 7714 verbose(env, "bpf_spin_unlock without taking a lock\n"); 7715 return -EINVAL; 7716 } 7717 if (cur->active_lock.ptr != ptr || 7718 cur->active_lock.id != reg->id) { 7719 verbose(env, "bpf_spin_unlock of different lock\n"); 7720 return -EINVAL; 7721 } 7722 7723 invalidate_non_owning_refs(env); 7724 7725 cur->active_lock.ptr = NULL; 7726 cur->active_lock.id = 0; 7727 } 7728 return 0; 7729 } 7730 7731 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7732 struct bpf_call_arg_meta *meta) 7733 { 7734 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7735 bool is_const = tnum_is_const(reg->var_off); 7736 struct bpf_map *map = reg->map_ptr; 7737 u64 val = reg->var_off.value; 7738 7739 if (!is_const) { 7740 verbose(env, 7741 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 7742 regno); 7743 return -EINVAL; 7744 } 7745 if (!map->btf) { 7746 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 7747 map->name); 7748 return -EINVAL; 7749 } 7750 if (!btf_record_has_field(map->record, BPF_TIMER)) { 7751 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 7752 return -EINVAL; 7753 } 7754 if (map->record->timer_off != val + reg->off) { 7755 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 7756 val + reg->off, map->record->timer_off); 7757 return -EINVAL; 7758 } 7759 if (meta->map_ptr) { 7760 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 7761 return -EFAULT; 7762 } 7763 meta->map_uid = reg->map_uid; 7764 meta->map_ptr = map; 7765 return 0; 7766 } 7767 7768 static int process_wq_func(struct bpf_verifier_env *env, int regno, 7769 struct bpf_kfunc_call_arg_meta *meta) 7770 { 7771 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7772 struct bpf_map *map = reg->map_ptr; 7773 u64 val = reg->var_off.value; 7774 7775 if (map->record->wq_off != val + reg->off) { 7776 verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n", 7777 val + reg->off, map->record->wq_off); 7778 return -EINVAL; 7779 } 7780 meta->map.uid = reg->map_uid; 7781 meta->map.ptr = map; 7782 return 0; 7783 } 7784 7785 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7786 struct bpf_call_arg_meta *meta) 7787 { 7788 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7789 struct btf_field *kptr_field; 7790 struct bpf_map *map_ptr; 7791 struct btf_record *rec; 7792 u32 kptr_off; 7793 7794 if (type_is_ptr_alloc_obj(reg->type)) { 7795 rec = reg_btf_record(reg); 7796 } else { /* PTR_TO_MAP_VALUE */ 7797 map_ptr = reg->map_ptr; 7798 if (!map_ptr->btf) { 7799 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7800 map_ptr->name); 7801 return -EINVAL; 7802 } 7803 rec = map_ptr->record; 7804 meta->map_ptr = map_ptr; 7805 } 7806 7807 if (!tnum_is_const(reg->var_off)) { 7808 verbose(env, 7809 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7810 regno); 7811 return -EINVAL; 7812 } 7813 7814 if (!btf_record_has_field(rec, BPF_KPTR)) { 7815 verbose(env, "R%d has no valid kptr\n", regno); 7816 return -EINVAL; 7817 } 7818 7819 kptr_off = reg->off + reg->var_off.value; 7820 kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR); 7821 if (!kptr_field) { 7822 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7823 return -EACCES; 7824 } 7825 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7826 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7827 return -EACCES; 7828 } 7829 meta->kptr_field = kptr_field; 7830 return 0; 7831 } 7832 7833 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7834 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7835 * 7836 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7837 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7838 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7839 * 7840 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7841 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7842 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7843 * mutate the view of the dynptr and also possibly destroy it. In the latter 7844 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7845 * memory that dynptr points to. 7846 * 7847 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7848 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7849 * readonly dynptr view yet, hence only the first case is tracked and checked. 7850 * 7851 * This is consistent with how C applies the const modifier to a struct object, 7852 * where the pointer itself inside bpf_dynptr becomes const but not what it 7853 * points to. 7854 * 7855 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7856 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7857 */ 7858 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7859 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7860 { 7861 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7862 int err; 7863 7864 if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) { 7865 verbose(env, 7866 "arg#%d expected pointer to stack or const struct bpf_dynptr\n", 7867 regno); 7868 return -EINVAL; 7869 } 7870 7871 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7872 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7873 */ 7874 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7875 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 7876 return -EFAULT; 7877 } 7878 7879 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7880 * constructing a mutable bpf_dynptr object. 7881 * 7882 * Currently, this is only possible with PTR_TO_STACK 7883 * pointing to a region of at least 16 bytes which doesn't 7884 * contain an existing bpf_dynptr. 7885 * 7886 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7887 * mutated or destroyed. However, the memory it points to 7888 * may be mutated. 7889 * 7890 * None - Points to a initialized dynptr that can be mutated and 7891 * destroyed, including mutation of the memory it points 7892 * to. 7893 */ 7894 if (arg_type & MEM_UNINIT) { 7895 int i; 7896 7897 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7898 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7899 return -EINVAL; 7900 } 7901 7902 /* we write BPF_DW bits (8 bytes) at a time */ 7903 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7904 err = check_mem_access(env, insn_idx, regno, 7905 i, BPF_DW, BPF_WRITE, -1, false, false); 7906 if (err) 7907 return err; 7908 } 7909 7910 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7911 } else /* MEM_RDONLY and None case from above */ { 7912 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7913 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7914 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7915 return -EINVAL; 7916 } 7917 7918 if (!is_dynptr_reg_valid_init(env, reg)) { 7919 verbose(env, 7920 "Expected an initialized dynptr as arg #%d\n", 7921 regno); 7922 return -EINVAL; 7923 } 7924 7925 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7926 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7927 verbose(env, 7928 "Expected a dynptr of type %s as arg #%d\n", 7929 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 7930 return -EINVAL; 7931 } 7932 7933 err = mark_dynptr_read(env, reg); 7934 } 7935 return err; 7936 } 7937 7938 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7939 { 7940 struct bpf_func_state *state = func(env, reg); 7941 7942 return state->stack[spi].spilled_ptr.ref_obj_id; 7943 } 7944 7945 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7946 { 7947 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7948 } 7949 7950 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7951 { 7952 return meta->kfunc_flags & KF_ITER_NEW; 7953 } 7954 7955 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7956 { 7957 return meta->kfunc_flags & KF_ITER_NEXT; 7958 } 7959 7960 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7961 { 7962 return meta->kfunc_flags & KF_ITER_DESTROY; 7963 } 7964 7965 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx, 7966 const struct btf_param *arg) 7967 { 7968 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7969 * kfunc is iter state pointer 7970 */ 7971 if (is_iter_kfunc(meta)) 7972 return arg_idx == 0; 7973 7974 /* iter passed as an argument to a generic kfunc */ 7975 return btf_param_match_suffix(meta->btf, arg, "__iter"); 7976 } 7977 7978 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7979 struct bpf_kfunc_call_arg_meta *meta) 7980 { 7981 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7982 const struct btf_type *t; 7983 int spi, err, i, nr_slots, btf_id; 7984 7985 /* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs() 7986 * ensures struct convention, so we wouldn't need to do any BTF 7987 * validation here. But given iter state can be passed as a parameter 7988 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more 7989 * conservative here. 7990 */ 7991 btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1); 7992 if (btf_id < 0) { 7993 verbose(env, "expected valid iter pointer as arg #%d\n", regno); 7994 return -EINVAL; 7995 } 7996 t = btf_type_by_id(meta->btf, btf_id); 7997 nr_slots = t->size / BPF_REG_SIZE; 7998 7999 if (is_iter_new_kfunc(meta)) { 8000 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 8001 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 8002 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 8003 iter_type_str(meta->btf, btf_id), regno); 8004 return -EINVAL; 8005 } 8006 8007 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 8008 err = check_mem_access(env, insn_idx, regno, 8009 i, BPF_DW, BPF_WRITE, -1, false, false); 8010 if (err) 8011 return err; 8012 } 8013 8014 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 8015 if (err) 8016 return err; 8017 } else { 8018 /* iter_next() or iter_destroy(), as well as any kfunc 8019 * accepting iter argument, expect initialized iter state 8020 */ 8021 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 8022 switch (err) { 8023 case 0: 8024 break; 8025 case -EINVAL: 8026 verbose(env, "expected an initialized iter_%s as arg #%d\n", 8027 iter_type_str(meta->btf, btf_id), regno); 8028 return err; 8029 case -EPROTO: 8030 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 8031 return err; 8032 default: 8033 return err; 8034 } 8035 8036 spi = iter_get_spi(env, reg, nr_slots); 8037 if (spi < 0) 8038 return spi; 8039 8040 err = mark_iter_read(env, reg, spi, nr_slots); 8041 if (err) 8042 return err; 8043 8044 /* remember meta->iter info for process_iter_next_call() */ 8045 meta->iter.spi = spi; 8046 meta->iter.frameno = reg->frameno; 8047 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 8048 8049 if (is_iter_destroy_kfunc(meta)) { 8050 err = unmark_stack_slots_iter(env, reg, nr_slots); 8051 if (err) 8052 return err; 8053 } 8054 } 8055 8056 return 0; 8057 } 8058 8059 /* Look for a previous loop entry at insn_idx: nearest parent state 8060 * stopped at insn_idx with callsites matching those in cur->frame. 8061 */ 8062 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 8063 struct bpf_verifier_state *cur, 8064 int insn_idx) 8065 { 8066 struct bpf_verifier_state_list *sl; 8067 struct bpf_verifier_state *st; 8068 8069 /* Explored states are pushed in stack order, most recent states come first */ 8070 sl = *explored_state(env, insn_idx); 8071 for (; sl; sl = sl->next) { 8072 /* If st->branches != 0 state is a part of current DFS verification path, 8073 * hence cur & st for a loop. 8074 */ 8075 st = &sl->state; 8076 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 8077 st->dfs_depth < cur->dfs_depth) 8078 return st; 8079 } 8080 8081 return NULL; 8082 } 8083 8084 static void reset_idmap_scratch(struct bpf_verifier_env *env); 8085 static bool regs_exact(const struct bpf_reg_state *rold, 8086 const struct bpf_reg_state *rcur, 8087 struct bpf_idmap *idmap); 8088 8089 static void maybe_widen_reg(struct bpf_verifier_env *env, 8090 struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 8091 struct bpf_idmap *idmap) 8092 { 8093 if (rold->type != SCALAR_VALUE) 8094 return; 8095 if (rold->type != rcur->type) 8096 return; 8097 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap)) 8098 return; 8099 __mark_reg_unknown(env, rcur); 8100 } 8101 8102 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 8103 struct bpf_verifier_state *old, 8104 struct bpf_verifier_state *cur) 8105 { 8106 struct bpf_func_state *fold, *fcur; 8107 int i, fr; 8108 8109 reset_idmap_scratch(env); 8110 for (fr = old->curframe; fr >= 0; fr--) { 8111 fold = old->frame[fr]; 8112 fcur = cur->frame[fr]; 8113 8114 for (i = 0; i < MAX_BPF_REG; i++) 8115 maybe_widen_reg(env, 8116 &fold->regs[i], 8117 &fcur->regs[i], 8118 &env->idmap_scratch); 8119 8120 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) { 8121 if (!is_spilled_reg(&fold->stack[i]) || 8122 !is_spilled_reg(&fcur->stack[i])) 8123 continue; 8124 8125 maybe_widen_reg(env, 8126 &fold->stack[i].spilled_ptr, 8127 &fcur->stack[i].spilled_ptr, 8128 &env->idmap_scratch); 8129 } 8130 } 8131 return 0; 8132 } 8133 8134 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st, 8135 struct bpf_kfunc_call_arg_meta *meta) 8136 { 8137 int iter_frameno = meta->iter.frameno; 8138 int iter_spi = meta->iter.spi; 8139 8140 return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 8141 } 8142 8143 /* process_iter_next_call() is called when verifier gets to iterator's next 8144 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 8145 * to it as just "iter_next()" in comments below. 8146 * 8147 * BPF verifier relies on a crucial contract for any iter_next() 8148 * implementation: it should *eventually* return NULL, and once that happens 8149 * it should keep returning NULL. That is, once iterator exhausts elements to 8150 * iterate, it should never reset or spuriously return new elements. 8151 * 8152 * With the assumption of such contract, process_iter_next_call() simulates 8153 * a fork in the verifier state to validate loop logic correctness and safety 8154 * without having to simulate infinite amount of iterations. 8155 * 8156 * In current state, we first assume that iter_next() returned NULL and 8157 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 8158 * conditions we should not form an infinite loop and should eventually reach 8159 * exit. 8160 * 8161 * Besides that, we also fork current state and enqueue it for later 8162 * verification. In a forked state we keep iterator state as ACTIVE 8163 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 8164 * also bump iteration depth to prevent erroneous infinite loop detection 8165 * later on (see iter_active_depths_differ() comment for details). In this 8166 * state we assume that we'll eventually loop back to another iter_next() 8167 * calls (it could be in exactly same location or in some other instruction, 8168 * it doesn't matter, we don't make any unnecessary assumptions about this, 8169 * everything revolves around iterator state in a stack slot, not which 8170 * instruction is calling iter_next()). When that happens, we either will come 8171 * to iter_next() with equivalent state and can conclude that next iteration 8172 * will proceed in exactly the same way as we just verified, so it's safe to 8173 * assume that loop converges. If not, we'll go on another iteration 8174 * simulation with a different input state, until all possible starting states 8175 * are validated or we reach maximum number of instructions limit. 8176 * 8177 * This way, we will either exhaustively discover all possible input states 8178 * that iterator loop can start with and eventually will converge, or we'll 8179 * effectively regress into bounded loop simulation logic and either reach 8180 * maximum number of instructions if loop is not provably convergent, or there 8181 * is some statically known limit on number of iterations (e.g., if there is 8182 * an explicit `if n > 100 then break;` statement somewhere in the loop). 8183 * 8184 * Iteration convergence logic in is_state_visited() relies on exact 8185 * states comparison, which ignores read and precision marks. 8186 * This is necessary because read and precision marks are not finalized 8187 * while in the loop. Exact comparison might preclude convergence for 8188 * simple programs like below: 8189 * 8190 * i = 0; 8191 * while(iter_next(&it)) 8192 * i++; 8193 * 8194 * At each iteration step i++ would produce a new distinct state and 8195 * eventually instruction processing limit would be reached. 8196 * 8197 * To avoid such behavior speculatively forget (widen) range for 8198 * imprecise scalar registers, if those registers were not precise at the 8199 * end of the previous iteration and do not match exactly. 8200 * 8201 * This is a conservative heuristic that allows to verify wide range of programs, 8202 * however it precludes verification of programs that conjure an 8203 * imprecise value on the first loop iteration and use it as precise on a second. 8204 * For example, the following safe program would fail to verify: 8205 * 8206 * struct bpf_num_iter it; 8207 * int arr[10]; 8208 * int i = 0, a = 0; 8209 * bpf_iter_num_new(&it, 0, 10); 8210 * while (bpf_iter_num_next(&it)) { 8211 * if (a == 0) { 8212 * a = 1; 8213 * i = 7; // Because i changed verifier would forget 8214 * // it's range on second loop entry. 8215 * } else { 8216 * arr[i] = 42; // This would fail to verify. 8217 * } 8218 * } 8219 * bpf_iter_num_destroy(&it); 8220 */ 8221 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 8222 struct bpf_kfunc_call_arg_meta *meta) 8223 { 8224 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 8225 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 8226 struct bpf_reg_state *cur_iter, *queued_iter; 8227 8228 BTF_TYPE_EMIT(struct bpf_iter); 8229 8230 cur_iter = get_iter_from_state(cur_st, meta); 8231 8232 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 8233 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 8234 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 8235 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 8236 return -EFAULT; 8237 } 8238 8239 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 8240 /* Because iter_next() call is a checkpoint is_state_visitied() 8241 * should guarantee parent state with same call sites and insn_idx. 8242 */ 8243 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 8244 !same_callsites(cur_st->parent, cur_st)) { 8245 verbose(env, "bug: bad parent state for iter next call"); 8246 return -EFAULT; 8247 } 8248 /* Note cur_st->parent in the call below, it is necessary to skip 8249 * checkpoint created for cur_st by is_state_visited() 8250 * right at this instruction. 8251 */ 8252 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 8253 /* branch out active iter state */ 8254 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 8255 if (!queued_st) 8256 return -ENOMEM; 8257 8258 queued_iter = get_iter_from_state(queued_st, meta); 8259 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 8260 queued_iter->iter.depth++; 8261 if (prev_st) 8262 widen_imprecise_scalars(env, prev_st, queued_st); 8263 8264 queued_fr = queued_st->frame[queued_st->curframe]; 8265 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 8266 } 8267 8268 /* switch to DRAINED state, but keep the depth unchanged */ 8269 /* mark current iter state as drained and assume returned NULL */ 8270 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 8271 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 8272 8273 return 0; 8274 } 8275 8276 static bool arg_type_is_mem_size(enum bpf_arg_type type) 8277 { 8278 return type == ARG_CONST_SIZE || 8279 type == ARG_CONST_SIZE_OR_ZERO; 8280 } 8281 8282 static bool arg_type_is_raw_mem(enum bpf_arg_type type) 8283 { 8284 return base_type(type) == ARG_PTR_TO_MEM && 8285 type & MEM_UNINIT; 8286 } 8287 8288 static bool arg_type_is_release(enum bpf_arg_type type) 8289 { 8290 return type & OBJ_RELEASE; 8291 } 8292 8293 static bool arg_type_is_dynptr(enum bpf_arg_type type) 8294 { 8295 return base_type(type) == ARG_PTR_TO_DYNPTR; 8296 } 8297 8298 static int resolve_map_arg_type(struct bpf_verifier_env *env, 8299 const struct bpf_call_arg_meta *meta, 8300 enum bpf_arg_type *arg_type) 8301 { 8302 if (!meta->map_ptr) { 8303 /* kernel subsystem misconfigured verifier */ 8304 verbose(env, "invalid map_ptr to access map->type\n"); 8305 return -EACCES; 8306 } 8307 8308 switch (meta->map_ptr->map_type) { 8309 case BPF_MAP_TYPE_SOCKMAP: 8310 case BPF_MAP_TYPE_SOCKHASH: 8311 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 8312 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 8313 } else { 8314 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 8315 return -EINVAL; 8316 } 8317 break; 8318 case BPF_MAP_TYPE_BLOOM_FILTER: 8319 if (meta->func_id == BPF_FUNC_map_peek_elem) 8320 *arg_type = ARG_PTR_TO_MAP_VALUE; 8321 break; 8322 default: 8323 break; 8324 } 8325 return 0; 8326 } 8327 8328 struct bpf_reg_types { 8329 const enum bpf_reg_type types[10]; 8330 u32 *btf_id; 8331 }; 8332 8333 static const struct bpf_reg_types sock_types = { 8334 .types = { 8335 PTR_TO_SOCK_COMMON, 8336 PTR_TO_SOCKET, 8337 PTR_TO_TCP_SOCK, 8338 PTR_TO_XDP_SOCK, 8339 }, 8340 }; 8341 8342 #ifdef CONFIG_NET 8343 static const struct bpf_reg_types btf_id_sock_common_types = { 8344 .types = { 8345 PTR_TO_SOCK_COMMON, 8346 PTR_TO_SOCKET, 8347 PTR_TO_TCP_SOCK, 8348 PTR_TO_XDP_SOCK, 8349 PTR_TO_BTF_ID, 8350 PTR_TO_BTF_ID | PTR_TRUSTED, 8351 }, 8352 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 8353 }; 8354 #endif 8355 8356 static const struct bpf_reg_types mem_types = { 8357 .types = { 8358 PTR_TO_STACK, 8359 PTR_TO_PACKET, 8360 PTR_TO_PACKET_META, 8361 PTR_TO_MAP_KEY, 8362 PTR_TO_MAP_VALUE, 8363 PTR_TO_MEM, 8364 PTR_TO_MEM | MEM_RINGBUF, 8365 PTR_TO_BUF, 8366 PTR_TO_BTF_ID | PTR_TRUSTED, 8367 }, 8368 }; 8369 8370 static const struct bpf_reg_types spin_lock_types = { 8371 .types = { 8372 PTR_TO_MAP_VALUE, 8373 PTR_TO_BTF_ID | MEM_ALLOC, 8374 } 8375 }; 8376 8377 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 8378 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 8379 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 8380 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 8381 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 8382 static const struct bpf_reg_types btf_ptr_types = { 8383 .types = { 8384 PTR_TO_BTF_ID, 8385 PTR_TO_BTF_ID | PTR_TRUSTED, 8386 PTR_TO_BTF_ID | MEM_RCU, 8387 }, 8388 }; 8389 static const struct bpf_reg_types percpu_btf_ptr_types = { 8390 .types = { 8391 PTR_TO_BTF_ID | MEM_PERCPU, 8392 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 8393 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 8394 } 8395 }; 8396 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 8397 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 8398 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8399 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 8400 static const struct bpf_reg_types kptr_xchg_dest_types = { 8401 .types = { 8402 PTR_TO_MAP_VALUE, 8403 PTR_TO_BTF_ID | MEM_ALLOC 8404 } 8405 }; 8406 static const struct bpf_reg_types dynptr_types = { 8407 .types = { 8408 PTR_TO_STACK, 8409 CONST_PTR_TO_DYNPTR, 8410 } 8411 }; 8412 8413 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 8414 [ARG_PTR_TO_MAP_KEY] = &mem_types, 8415 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 8416 [ARG_CONST_SIZE] = &scalar_types, 8417 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 8418 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 8419 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 8420 [ARG_PTR_TO_CTX] = &context_types, 8421 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 8422 #ifdef CONFIG_NET 8423 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 8424 #endif 8425 [ARG_PTR_TO_SOCKET] = &fullsock_types, 8426 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 8427 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 8428 [ARG_PTR_TO_MEM] = &mem_types, 8429 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 8430 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 8431 [ARG_PTR_TO_FUNC] = &func_ptr_types, 8432 [ARG_PTR_TO_STACK] = &stack_ptr_types, 8433 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 8434 [ARG_PTR_TO_TIMER] = &timer_types, 8435 [ARG_KPTR_XCHG_DEST] = &kptr_xchg_dest_types, 8436 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 8437 }; 8438 8439 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 8440 enum bpf_arg_type arg_type, 8441 const u32 *arg_btf_id, 8442 struct bpf_call_arg_meta *meta) 8443 { 8444 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8445 enum bpf_reg_type expected, type = reg->type; 8446 const struct bpf_reg_types *compatible; 8447 int i, j; 8448 8449 compatible = compatible_reg_types[base_type(arg_type)]; 8450 if (!compatible) { 8451 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 8452 return -EFAULT; 8453 } 8454 8455 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 8456 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 8457 * 8458 * Same for MAYBE_NULL: 8459 * 8460 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 8461 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 8462 * 8463 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 8464 * 8465 * Therefore we fold these flags depending on the arg_type before comparison. 8466 */ 8467 if (arg_type & MEM_RDONLY) 8468 type &= ~MEM_RDONLY; 8469 if (arg_type & PTR_MAYBE_NULL) 8470 type &= ~PTR_MAYBE_NULL; 8471 if (base_type(arg_type) == ARG_PTR_TO_MEM) 8472 type &= ~DYNPTR_TYPE_FLAG_MASK; 8473 8474 /* Local kptr types are allowed as the source argument of bpf_kptr_xchg */ 8475 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) { 8476 type &= ~MEM_ALLOC; 8477 type &= ~MEM_PERCPU; 8478 } 8479 8480 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 8481 expected = compatible->types[i]; 8482 if (expected == NOT_INIT) 8483 break; 8484 8485 if (type == expected) 8486 goto found; 8487 } 8488 8489 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 8490 for (j = 0; j + 1 < i; j++) 8491 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 8492 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 8493 return -EACCES; 8494 8495 found: 8496 if (base_type(reg->type) != PTR_TO_BTF_ID) 8497 return 0; 8498 8499 if (compatible == &mem_types) { 8500 if (!(arg_type & MEM_RDONLY)) { 8501 verbose(env, 8502 "%s() may write into memory pointed by R%d type=%s\n", 8503 func_id_name(meta->func_id), 8504 regno, reg_type_str(env, reg->type)); 8505 return -EACCES; 8506 } 8507 return 0; 8508 } 8509 8510 switch ((int)reg->type) { 8511 case PTR_TO_BTF_ID: 8512 case PTR_TO_BTF_ID | PTR_TRUSTED: 8513 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL: 8514 case PTR_TO_BTF_ID | MEM_RCU: 8515 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 8516 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 8517 { 8518 /* For bpf_sk_release, it needs to match against first member 8519 * 'struct sock_common', hence make an exception for it. This 8520 * allows bpf_sk_release to work for multiple socket types. 8521 */ 8522 bool strict_type_match = arg_type_is_release(arg_type) && 8523 meta->func_id != BPF_FUNC_sk_release; 8524 8525 if (type_may_be_null(reg->type) && 8526 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 8527 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 8528 return -EACCES; 8529 } 8530 8531 if (!arg_btf_id) { 8532 if (!compatible->btf_id) { 8533 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 8534 return -EFAULT; 8535 } 8536 arg_btf_id = compatible->btf_id; 8537 } 8538 8539 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8540 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8541 return -EACCES; 8542 } else { 8543 if (arg_btf_id == BPF_PTR_POISON) { 8544 verbose(env, "verifier internal error:"); 8545 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 8546 regno); 8547 return -EACCES; 8548 } 8549 8550 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 8551 btf_vmlinux, *arg_btf_id, 8552 strict_type_match)) { 8553 verbose(env, "R%d is of type %s but %s is expected\n", 8554 regno, btf_type_name(reg->btf, reg->btf_id), 8555 btf_type_name(btf_vmlinux, *arg_btf_id)); 8556 return -EACCES; 8557 } 8558 } 8559 break; 8560 } 8561 case PTR_TO_BTF_ID | MEM_ALLOC: 8562 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 8563 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8564 meta->func_id != BPF_FUNC_kptr_xchg) { 8565 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 8566 return -EFAULT; 8567 } 8568 /* Check if local kptr in src arg matches kptr in dst arg */ 8569 if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) { 8570 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8571 return -EACCES; 8572 } 8573 break; 8574 case PTR_TO_BTF_ID | MEM_PERCPU: 8575 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 8576 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8577 /* Handled by helper specific checks */ 8578 break; 8579 default: 8580 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 8581 return -EFAULT; 8582 } 8583 return 0; 8584 } 8585 8586 static struct btf_field * 8587 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8588 { 8589 struct btf_field *field; 8590 struct btf_record *rec; 8591 8592 rec = reg_btf_record(reg); 8593 if (!rec) 8594 return NULL; 8595 8596 field = btf_record_find(rec, off, fields); 8597 if (!field) 8598 return NULL; 8599 8600 return field; 8601 } 8602 8603 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 8604 const struct bpf_reg_state *reg, int regno, 8605 enum bpf_arg_type arg_type) 8606 { 8607 u32 type = reg->type; 8608 8609 /* When referenced register is passed to release function, its fixed 8610 * offset must be 0. 8611 * 8612 * We will check arg_type_is_release reg has ref_obj_id when storing 8613 * meta->release_regno. 8614 */ 8615 if (arg_type_is_release(arg_type)) { 8616 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8617 * may not directly point to the object being released, but to 8618 * dynptr pointing to such object, which might be at some offset 8619 * on the stack. In that case, we simply to fallback to the 8620 * default handling. 8621 */ 8622 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8623 return 0; 8624 8625 /* Doing check_ptr_off_reg check for the offset will catch this 8626 * because fixed_off_ok is false, but checking here allows us 8627 * to give the user a better error message. 8628 */ 8629 if (reg->off) { 8630 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 8631 regno); 8632 return -EINVAL; 8633 } 8634 return __check_ptr_off_reg(env, reg, regno, false); 8635 } 8636 8637 switch (type) { 8638 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8639 case PTR_TO_STACK: 8640 case PTR_TO_PACKET: 8641 case PTR_TO_PACKET_META: 8642 case PTR_TO_MAP_KEY: 8643 case PTR_TO_MAP_VALUE: 8644 case PTR_TO_MEM: 8645 case PTR_TO_MEM | MEM_RDONLY: 8646 case PTR_TO_MEM | MEM_RINGBUF: 8647 case PTR_TO_BUF: 8648 case PTR_TO_BUF | MEM_RDONLY: 8649 case PTR_TO_ARENA: 8650 case SCALAR_VALUE: 8651 return 0; 8652 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8653 * fixed offset. 8654 */ 8655 case PTR_TO_BTF_ID: 8656 case PTR_TO_BTF_ID | MEM_ALLOC: 8657 case PTR_TO_BTF_ID | PTR_TRUSTED: 8658 case PTR_TO_BTF_ID | MEM_RCU: 8659 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8660 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8661 /* When referenced PTR_TO_BTF_ID is passed to release function, 8662 * its fixed offset must be 0. In the other cases, fixed offset 8663 * can be non-zero. This was already checked above. So pass 8664 * fixed_off_ok as true to allow fixed offset for all other 8665 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8666 * still need to do checks instead of returning. 8667 */ 8668 return __check_ptr_off_reg(env, reg, regno, true); 8669 default: 8670 return __check_ptr_off_reg(env, reg, regno, false); 8671 } 8672 } 8673 8674 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8675 const struct bpf_func_proto *fn, 8676 struct bpf_reg_state *regs) 8677 { 8678 struct bpf_reg_state *state = NULL; 8679 int i; 8680 8681 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8682 if (arg_type_is_dynptr(fn->arg_type[i])) { 8683 if (state) { 8684 verbose(env, "verifier internal error: multiple dynptr args\n"); 8685 return NULL; 8686 } 8687 state = ®s[BPF_REG_1 + i]; 8688 } 8689 8690 if (!state) 8691 verbose(env, "verifier internal error: no dynptr arg found\n"); 8692 8693 return state; 8694 } 8695 8696 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8697 { 8698 struct bpf_func_state *state = func(env, reg); 8699 int spi; 8700 8701 if (reg->type == CONST_PTR_TO_DYNPTR) 8702 return reg->id; 8703 spi = dynptr_get_spi(env, reg); 8704 if (spi < 0) 8705 return spi; 8706 return state->stack[spi].spilled_ptr.id; 8707 } 8708 8709 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8710 { 8711 struct bpf_func_state *state = func(env, reg); 8712 int spi; 8713 8714 if (reg->type == CONST_PTR_TO_DYNPTR) 8715 return reg->ref_obj_id; 8716 spi = dynptr_get_spi(env, reg); 8717 if (spi < 0) 8718 return spi; 8719 return state->stack[spi].spilled_ptr.ref_obj_id; 8720 } 8721 8722 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8723 struct bpf_reg_state *reg) 8724 { 8725 struct bpf_func_state *state = func(env, reg); 8726 int spi; 8727 8728 if (reg->type == CONST_PTR_TO_DYNPTR) 8729 return reg->dynptr.type; 8730 8731 spi = __get_spi(reg->off); 8732 if (spi < 0) { 8733 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8734 return BPF_DYNPTR_TYPE_INVALID; 8735 } 8736 8737 return state->stack[spi].spilled_ptr.dynptr.type; 8738 } 8739 8740 static int check_reg_const_str(struct bpf_verifier_env *env, 8741 struct bpf_reg_state *reg, u32 regno) 8742 { 8743 struct bpf_map *map = reg->map_ptr; 8744 int err; 8745 int map_off; 8746 u64 map_addr; 8747 char *str_ptr; 8748 8749 if (reg->type != PTR_TO_MAP_VALUE) 8750 return -EINVAL; 8751 8752 if (!bpf_map_is_rdonly(map)) { 8753 verbose(env, "R%d does not point to a readonly map'\n", regno); 8754 return -EACCES; 8755 } 8756 8757 if (!tnum_is_const(reg->var_off)) { 8758 verbose(env, "R%d is not a constant address'\n", regno); 8759 return -EACCES; 8760 } 8761 8762 if (!map->ops->map_direct_value_addr) { 8763 verbose(env, "no direct value access support for this map type\n"); 8764 return -EACCES; 8765 } 8766 8767 err = check_map_access(env, regno, reg->off, 8768 map->value_size - reg->off, false, 8769 ACCESS_HELPER); 8770 if (err) 8771 return err; 8772 8773 map_off = reg->off + reg->var_off.value; 8774 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8775 if (err) { 8776 verbose(env, "direct value access on string failed\n"); 8777 return err; 8778 } 8779 8780 str_ptr = (char *)(long)(map_addr); 8781 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8782 verbose(env, "string is not zero-terminated\n"); 8783 return -EINVAL; 8784 } 8785 return 0; 8786 } 8787 8788 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8789 struct bpf_call_arg_meta *meta, 8790 const struct bpf_func_proto *fn, 8791 int insn_idx) 8792 { 8793 u32 regno = BPF_REG_1 + arg; 8794 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8795 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8796 enum bpf_reg_type type = reg->type; 8797 u32 *arg_btf_id = NULL; 8798 int err = 0; 8799 8800 if (arg_type == ARG_DONTCARE) 8801 return 0; 8802 8803 err = check_reg_arg(env, regno, SRC_OP); 8804 if (err) 8805 return err; 8806 8807 if (arg_type == ARG_ANYTHING) { 8808 if (is_pointer_value(env, regno)) { 8809 verbose(env, "R%d leaks addr into helper function\n", 8810 regno); 8811 return -EACCES; 8812 } 8813 return 0; 8814 } 8815 8816 if (type_is_pkt_pointer(type) && 8817 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8818 verbose(env, "helper access to the packet is not allowed\n"); 8819 return -EACCES; 8820 } 8821 8822 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8823 err = resolve_map_arg_type(env, meta, &arg_type); 8824 if (err) 8825 return err; 8826 } 8827 8828 if (register_is_null(reg) && type_may_be_null(arg_type)) 8829 /* A NULL register has a SCALAR_VALUE type, so skip 8830 * type checking. 8831 */ 8832 goto skip_type_check; 8833 8834 /* arg_btf_id and arg_size are in a union. */ 8835 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8836 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8837 arg_btf_id = fn->arg_btf_id[arg]; 8838 8839 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 8840 if (err) 8841 return err; 8842 8843 err = check_func_arg_reg_off(env, reg, regno, arg_type); 8844 if (err) 8845 return err; 8846 8847 skip_type_check: 8848 if (arg_type_is_release(arg_type)) { 8849 if (arg_type_is_dynptr(arg_type)) { 8850 struct bpf_func_state *state = func(env, reg); 8851 int spi; 8852 8853 /* Only dynptr created on stack can be released, thus 8854 * the get_spi and stack state checks for spilled_ptr 8855 * should only be done before process_dynptr_func for 8856 * PTR_TO_STACK. 8857 */ 8858 if (reg->type == PTR_TO_STACK) { 8859 spi = dynptr_get_spi(env, reg); 8860 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8861 verbose(env, "arg %d is an unacquired reference\n", regno); 8862 return -EINVAL; 8863 } 8864 } else { 8865 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8866 return -EINVAL; 8867 } 8868 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 8869 verbose(env, "R%d must be referenced when passed to release function\n", 8870 regno); 8871 return -EINVAL; 8872 } 8873 if (meta->release_regno) { 8874 verbose(env, "verifier internal error: more than one release argument\n"); 8875 return -EFAULT; 8876 } 8877 meta->release_regno = regno; 8878 } 8879 8880 if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) { 8881 if (meta->ref_obj_id) { 8882 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 8883 regno, reg->ref_obj_id, 8884 meta->ref_obj_id); 8885 return -EFAULT; 8886 } 8887 meta->ref_obj_id = reg->ref_obj_id; 8888 } 8889 8890 switch (base_type(arg_type)) { 8891 case ARG_CONST_MAP_PTR: 8892 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8893 if (meta->map_ptr) { 8894 /* Use map_uid (which is unique id of inner map) to reject: 8895 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8896 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8897 * if (inner_map1 && inner_map2) { 8898 * timer = bpf_map_lookup_elem(inner_map1); 8899 * if (timer) 8900 * // mismatch would have been allowed 8901 * bpf_timer_init(timer, inner_map2); 8902 * } 8903 * 8904 * Comparing map_ptr is enough to distinguish normal and outer maps. 8905 */ 8906 if (meta->map_ptr != reg->map_ptr || 8907 meta->map_uid != reg->map_uid) { 8908 verbose(env, 8909 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8910 meta->map_uid, reg->map_uid); 8911 return -EINVAL; 8912 } 8913 } 8914 meta->map_ptr = reg->map_ptr; 8915 meta->map_uid = reg->map_uid; 8916 break; 8917 case ARG_PTR_TO_MAP_KEY: 8918 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8919 * check that [key, key + map->key_size) are within 8920 * stack limits and initialized 8921 */ 8922 if (!meta->map_ptr) { 8923 /* in function declaration map_ptr must come before 8924 * map_key, so that it's verified and known before 8925 * we have to check map_key here. Otherwise it means 8926 * that kernel subsystem misconfigured verifier 8927 */ 8928 verbose(env, "invalid map_ptr to access map->key\n"); 8929 return -EACCES; 8930 } 8931 err = check_helper_mem_access(env, regno, meta->map_ptr->key_size, 8932 BPF_READ, false, NULL); 8933 break; 8934 case ARG_PTR_TO_MAP_VALUE: 8935 if (type_may_be_null(arg_type) && register_is_null(reg)) 8936 return 0; 8937 8938 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8939 * check [value, value + map->value_size) validity 8940 */ 8941 if (!meta->map_ptr) { 8942 /* kernel subsystem misconfigured verifier */ 8943 verbose(env, "invalid map_ptr to access map->value\n"); 8944 return -EACCES; 8945 } 8946 meta->raw_mode = arg_type & MEM_UNINIT; 8947 err = check_helper_mem_access(env, regno, meta->map_ptr->value_size, 8948 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 8949 false, meta); 8950 break; 8951 case ARG_PTR_TO_PERCPU_BTF_ID: 8952 if (!reg->btf_id) { 8953 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8954 return -EACCES; 8955 } 8956 meta->ret_btf = reg->btf; 8957 meta->ret_btf_id = reg->btf_id; 8958 break; 8959 case ARG_PTR_TO_SPIN_LOCK: 8960 if (in_rbtree_lock_required_cb(env)) { 8961 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8962 return -EACCES; 8963 } 8964 if (meta->func_id == BPF_FUNC_spin_lock) { 8965 err = process_spin_lock(env, regno, true); 8966 if (err) 8967 return err; 8968 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8969 err = process_spin_lock(env, regno, false); 8970 if (err) 8971 return err; 8972 } else { 8973 verbose(env, "verifier internal error\n"); 8974 return -EFAULT; 8975 } 8976 break; 8977 case ARG_PTR_TO_TIMER: 8978 err = process_timer_func(env, regno, meta); 8979 if (err) 8980 return err; 8981 break; 8982 case ARG_PTR_TO_FUNC: 8983 meta->subprogno = reg->subprogno; 8984 break; 8985 case ARG_PTR_TO_MEM: 8986 /* The access to this pointer is only checked when we hit the 8987 * next is_mem_size argument below. 8988 */ 8989 meta->raw_mode = arg_type & MEM_UNINIT; 8990 if (arg_type & MEM_FIXED_SIZE) { 8991 err = check_helper_mem_access(env, regno, fn->arg_size[arg], 8992 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 8993 false, meta); 8994 if (err) 8995 return err; 8996 if (arg_type & MEM_ALIGNED) 8997 err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true); 8998 } 8999 break; 9000 case ARG_CONST_SIZE: 9001 err = check_mem_size_reg(env, reg, regno, 9002 fn->arg_type[arg - 1] & MEM_WRITE ? 9003 BPF_WRITE : BPF_READ, 9004 false, meta); 9005 break; 9006 case ARG_CONST_SIZE_OR_ZERO: 9007 err = check_mem_size_reg(env, reg, regno, 9008 fn->arg_type[arg - 1] & MEM_WRITE ? 9009 BPF_WRITE : BPF_READ, 9010 true, meta); 9011 break; 9012 case ARG_PTR_TO_DYNPTR: 9013 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 9014 if (err) 9015 return err; 9016 break; 9017 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 9018 if (!tnum_is_const(reg->var_off)) { 9019 verbose(env, "R%d is not a known constant'\n", 9020 regno); 9021 return -EACCES; 9022 } 9023 meta->mem_size = reg->var_off.value; 9024 err = mark_chain_precision(env, regno); 9025 if (err) 9026 return err; 9027 break; 9028 case ARG_PTR_TO_CONST_STR: 9029 { 9030 err = check_reg_const_str(env, reg, regno); 9031 if (err) 9032 return err; 9033 break; 9034 } 9035 case ARG_KPTR_XCHG_DEST: 9036 err = process_kptr_func(env, regno, meta); 9037 if (err) 9038 return err; 9039 break; 9040 } 9041 9042 return err; 9043 } 9044 9045 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 9046 { 9047 enum bpf_attach_type eatype = env->prog->expected_attach_type; 9048 enum bpf_prog_type type = resolve_prog_type(env->prog); 9049 9050 if (func_id != BPF_FUNC_map_update_elem && 9051 func_id != BPF_FUNC_map_delete_elem) 9052 return false; 9053 9054 /* It's not possible to get access to a locked struct sock in these 9055 * contexts, so updating is safe. 9056 */ 9057 switch (type) { 9058 case BPF_PROG_TYPE_TRACING: 9059 if (eatype == BPF_TRACE_ITER) 9060 return true; 9061 break; 9062 case BPF_PROG_TYPE_SOCK_OPS: 9063 /* map_update allowed only via dedicated helpers with event type checks */ 9064 if (func_id == BPF_FUNC_map_delete_elem) 9065 return true; 9066 break; 9067 case BPF_PROG_TYPE_SOCKET_FILTER: 9068 case BPF_PROG_TYPE_SCHED_CLS: 9069 case BPF_PROG_TYPE_SCHED_ACT: 9070 case BPF_PROG_TYPE_XDP: 9071 case BPF_PROG_TYPE_SK_REUSEPORT: 9072 case BPF_PROG_TYPE_FLOW_DISSECTOR: 9073 case BPF_PROG_TYPE_SK_LOOKUP: 9074 return true; 9075 default: 9076 break; 9077 } 9078 9079 verbose(env, "cannot update sockmap in this context\n"); 9080 return false; 9081 } 9082 9083 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 9084 { 9085 return env->prog->jit_requested && 9086 bpf_jit_supports_subprog_tailcalls(); 9087 } 9088 9089 static int check_map_func_compatibility(struct bpf_verifier_env *env, 9090 struct bpf_map *map, int func_id) 9091 { 9092 if (!map) 9093 return 0; 9094 9095 /* We need a two way check, first is from map perspective ... */ 9096 switch (map->map_type) { 9097 case BPF_MAP_TYPE_PROG_ARRAY: 9098 if (func_id != BPF_FUNC_tail_call) 9099 goto error; 9100 break; 9101 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 9102 if (func_id != BPF_FUNC_perf_event_read && 9103 func_id != BPF_FUNC_perf_event_output && 9104 func_id != BPF_FUNC_skb_output && 9105 func_id != BPF_FUNC_perf_event_read_value && 9106 func_id != BPF_FUNC_xdp_output) 9107 goto error; 9108 break; 9109 case BPF_MAP_TYPE_RINGBUF: 9110 if (func_id != BPF_FUNC_ringbuf_output && 9111 func_id != BPF_FUNC_ringbuf_reserve && 9112 func_id != BPF_FUNC_ringbuf_query && 9113 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 9114 func_id != BPF_FUNC_ringbuf_submit_dynptr && 9115 func_id != BPF_FUNC_ringbuf_discard_dynptr) 9116 goto error; 9117 break; 9118 case BPF_MAP_TYPE_USER_RINGBUF: 9119 if (func_id != BPF_FUNC_user_ringbuf_drain) 9120 goto error; 9121 break; 9122 case BPF_MAP_TYPE_STACK_TRACE: 9123 if (func_id != BPF_FUNC_get_stackid) 9124 goto error; 9125 break; 9126 case BPF_MAP_TYPE_CGROUP_ARRAY: 9127 if (func_id != BPF_FUNC_skb_under_cgroup && 9128 func_id != BPF_FUNC_current_task_under_cgroup) 9129 goto error; 9130 break; 9131 case BPF_MAP_TYPE_CGROUP_STORAGE: 9132 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 9133 if (func_id != BPF_FUNC_get_local_storage) 9134 goto error; 9135 break; 9136 case BPF_MAP_TYPE_DEVMAP: 9137 case BPF_MAP_TYPE_DEVMAP_HASH: 9138 if (func_id != BPF_FUNC_redirect_map && 9139 func_id != BPF_FUNC_map_lookup_elem) 9140 goto error; 9141 break; 9142 /* Restrict bpf side of cpumap and xskmap, open when use-cases 9143 * appear. 9144 */ 9145 case BPF_MAP_TYPE_CPUMAP: 9146 if (func_id != BPF_FUNC_redirect_map) 9147 goto error; 9148 break; 9149 case BPF_MAP_TYPE_XSKMAP: 9150 if (func_id != BPF_FUNC_redirect_map && 9151 func_id != BPF_FUNC_map_lookup_elem) 9152 goto error; 9153 break; 9154 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 9155 case BPF_MAP_TYPE_HASH_OF_MAPS: 9156 if (func_id != BPF_FUNC_map_lookup_elem) 9157 goto error; 9158 break; 9159 case BPF_MAP_TYPE_SOCKMAP: 9160 if (func_id != BPF_FUNC_sk_redirect_map && 9161 func_id != BPF_FUNC_sock_map_update && 9162 func_id != BPF_FUNC_msg_redirect_map && 9163 func_id != BPF_FUNC_sk_select_reuseport && 9164 func_id != BPF_FUNC_map_lookup_elem && 9165 !may_update_sockmap(env, func_id)) 9166 goto error; 9167 break; 9168 case BPF_MAP_TYPE_SOCKHASH: 9169 if (func_id != BPF_FUNC_sk_redirect_hash && 9170 func_id != BPF_FUNC_sock_hash_update && 9171 func_id != BPF_FUNC_msg_redirect_hash && 9172 func_id != BPF_FUNC_sk_select_reuseport && 9173 func_id != BPF_FUNC_map_lookup_elem && 9174 !may_update_sockmap(env, func_id)) 9175 goto error; 9176 break; 9177 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 9178 if (func_id != BPF_FUNC_sk_select_reuseport) 9179 goto error; 9180 break; 9181 case BPF_MAP_TYPE_QUEUE: 9182 case BPF_MAP_TYPE_STACK: 9183 if (func_id != BPF_FUNC_map_peek_elem && 9184 func_id != BPF_FUNC_map_pop_elem && 9185 func_id != BPF_FUNC_map_push_elem) 9186 goto error; 9187 break; 9188 case BPF_MAP_TYPE_SK_STORAGE: 9189 if (func_id != BPF_FUNC_sk_storage_get && 9190 func_id != BPF_FUNC_sk_storage_delete && 9191 func_id != BPF_FUNC_kptr_xchg) 9192 goto error; 9193 break; 9194 case BPF_MAP_TYPE_INODE_STORAGE: 9195 if (func_id != BPF_FUNC_inode_storage_get && 9196 func_id != BPF_FUNC_inode_storage_delete && 9197 func_id != BPF_FUNC_kptr_xchg) 9198 goto error; 9199 break; 9200 case BPF_MAP_TYPE_TASK_STORAGE: 9201 if (func_id != BPF_FUNC_task_storage_get && 9202 func_id != BPF_FUNC_task_storage_delete && 9203 func_id != BPF_FUNC_kptr_xchg) 9204 goto error; 9205 break; 9206 case BPF_MAP_TYPE_CGRP_STORAGE: 9207 if (func_id != BPF_FUNC_cgrp_storage_get && 9208 func_id != BPF_FUNC_cgrp_storage_delete && 9209 func_id != BPF_FUNC_kptr_xchg) 9210 goto error; 9211 break; 9212 case BPF_MAP_TYPE_BLOOM_FILTER: 9213 if (func_id != BPF_FUNC_map_peek_elem && 9214 func_id != BPF_FUNC_map_push_elem) 9215 goto error; 9216 break; 9217 default: 9218 break; 9219 } 9220 9221 /* ... and second from the function itself. */ 9222 switch (func_id) { 9223 case BPF_FUNC_tail_call: 9224 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 9225 goto error; 9226 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 9227 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 9228 return -EINVAL; 9229 } 9230 break; 9231 case BPF_FUNC_perf_event_read: 9232 case BPF_FUNC_perf_event_output: 9233 case BPF_FUNC_perf_event_read_value: 9234 case BPF_FUNC_skb_output: 9235 case BPF_FUNC_xdp_output: 9236 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 9237 goto error; 9238 break; 9239 case BPF_FUNC_ringbuf_output: 9240 case BPF_FUNC_ringbuf_reserve: 9241 case BPF_FUNC_ringbuf_query: 9242 case BPF_FUNC_ringbuf_reserve_dynptr: 9243 case BPF_FUNC_ringbuf_submit_dynptr: 9244 case BPF_FUNC_ringbuf_discard_dynptr: 9245 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 9246 goto error; 9247 break; 9248 case BPF_FUNC_user_ringbuf_drain: 9249 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 9250 goto error; 9251 break; 9252 case BPF_FUNC_get_stackid: 9253 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 9254 goto error; 9255 break; 9256 case BPF_FUNC_current_task_under_cgroup: 9257 case BPF_FUNC_skb_under_cgroup: 9258 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 9259 goto error; 9260 break; 9261 case BPF_FUNC_redirect_map: 9262 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 9263 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 9264 map->map_type != BPF_MAP_TYPE_CPUMAP && 9265 map->map_type != BPF_MAP_TYPE_XSKMAP) 9266 goto error; 9267 break; 9268 case BPF_FUNC_sk_redirect_map: 9269 case BPF_FUNC_msg_redirect_map: 9270 case BPF_FUNC_sock_map_update: 9271 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 9272 goto error; 9273 break; 9274 case BPF_FUNC_sk_redirect_hash: 9275 case BPF_FUNC_msg_redirect_hash: 9276 case BPF_FUNC_sock_hash_update: 9277 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 9278 goto error; 9279 break; 9280 case BPF_FUNC_get_local_storage: 9281 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 9282 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 9283 goto error; 9284 break; 9285 case BPF_FUNC_sk_select_reuseport: 9286 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 9287 map->map_type != BPF_MAP_TYPE_SOCKMAP && 9288 map->map_type != BPF_MAP_TYPE_SOCKHASH) 9289 goto error; 9290 break; 9291 case BPF_FUNC_map_pop_elem: 9292 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9293 map->map_type != BPF_MAP_TYPE_STACK) 9294 goto error; 9295 break; 9296 case BPF_FUNC_map_peek_elem: 9297 case BPF_FUNC_map_push_elem: 9298 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9299 map->map_type != BPF_MAP_TYPE_STACK && 9300 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 9301 goto error; 9302 break; 9303 case BPF_FUNC_map_lookup_percpu_elem: 9304 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 9305 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 9306 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 9307 goto error; 9308 break; 9309 case BPF_FUNC_sk_storage_get: 9310 case BPF_FUNC_sk_storage_delete: 9311 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 9312 goto error; 9313 break; 9314 case BPF_FUNC_inode_storage_get: 9315 case BPF_FUNC_inode_storage_delete: 9316 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 9317 goto error; 9318 break; 9319 case BPF_FUNC_task_storage_get: 9320 case BPF_FUNC_task_storage_delete: 9321 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 9322 goto error; 9323 break; 9324 case BPF_FUNC_cgrp_storage_get: 9325 case BPF_FUNC_cgrp_storage_delete: 9326 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 9327 goto error; 9328 break; 9329 default: 9330 break; 9331 } 9332 9333 return 0; 9334 error: 9335 verbose(env, "cannot pass map_type %d into func %s#%d\n", 9336 map->map_type, func_id_name(func_id), func_id); 9337 return -EINVAL; 9338 } 9339 9340 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 9341 { 9342 int count = 0; 9343 9344 if (arg_type_is_raw_mem(fn->arg1_type)) 9345 count++; 9346 if (arg_type_is_raw_mem(fn->arg2_type)) 9347 count++; 9348 if (arg_type_is_raw_mem(fn->arg3_type)) 9349 count++; 9350 if (arg_type_is_raw_mem(fn->arg4_type)) 9351 count++; 9352 if (arg_type_is_raw_mem(fn->arg5_type)) 9353 count++; 9354 9355 /* We only support one arg being in raw mode at the moment, 9356 * which is sufficient for the helper functions we have 9357 * right now. 9358 */ 9359 return count <= 1; 9360 } 9361 9362 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 9363 { 9364 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 9365 bool has_size = fn->arg_size[arg] != 0; 9366 bool is_next_size = false; 9367 9368 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 9369 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 9370 9371 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 9372 return is_next_size; 9373 9374 return has_size == is_next_size || is_next_size == is_fixed; 9375 } 9376 9377 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 9378 { 9379 /* bpf_xxx(..., buf, len) call will access 'len' 9380 * bytes from memory 'buf'. Both arg types need 9381 * to be paired, so make sure there's no buggy 9382 * helper function specification. 9383 */ 9384 if (arg_type_is_mem_size(fn->arg1_type) || 9385 check_args_pair_invalid(fn, 0) || 9386 check_args_pair_invalid(fn, 1) || 9387 check_args_pair_invalid(fn, 2) || 9388 check_args_pair_invalid(fn, 3) || 9389 check_args_pair_invalid(fn, 4)) 9390 return false; 9391 9392 return true; 9393 } 9394 9395 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 9396 { 9397 int i; 9398 9399 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 9400 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 9401 return !!fn->arg_btf_id[i]; 9402 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 9403 return fn->arg_btf_id[i] == BPF_PTR_POISON; 9404 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 9405 /* arg_btf_id and arg_size are in a union. */ 9406 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 9407 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 9408 return false; 9409 } 9410 9411 return true; 9412 } 9413 9414 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 9415 { 9416 return check_raw_mode_ok(fn) && 9417 check_arg_pair_ok(fn) && 9418 check_btf_id_ok(fn) ? 0 : -EINVAL; 9419 } 9420 9421 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 9422 * are now invalid, so turn them into unknown SCALAR_VALUE. 9423 * 9424 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 9425 * since these slices point to packet data. 9426 */ 9427 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 9428 { 9429 struct bpf_func_state *state; 9430 struct bpf_reg_state *reg; 9431 9432 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9433 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 9434 mark_reg_invalid(env, reg); 9435 })); 9436 } 9437 9438 enum { 9439 AT_PKT_END = -1, 9440 BEYOND_PKT_END = -2, 9441 }; 9442 9443 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 9444 { 9445 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9446 struct bpf_reg_state *reg = &state->regs[regn]; 9447 9448 if (reg->type != PTR_TO_PACKET) 9449 /* PTR_TO_PACKET_META is not supported yet */ 9450 return; 9451 9452 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 9453 * How far beyond pkt_end it goes is unknown. 9454 * if (!range_open) it's the case of pkt >= pkt_end 9455 * if (range_open) it's the case of pkt > pkt_end 9456 * hence this pointer is at least 1 byte bigger than pkt_end 9457 */ 9458 if (range_open) 9459 reg->range = BEYOND_PKT_END; 9460 else 9461 reg->range = AT_PKT_END; 9462 } 9463 9464 /* The pointer with the specified id has released its reference to kernel 9465 * resources. Identify all copies of the same pointer and clear the reference. 9466 */ 9467 static int release_reference(struct bpf_verifier_env *env, 9468 int ref_obj_id) 9469 { 9470 struct bpf_func_state *state; 9471 struct bpf_reg_state *reg; 9472 int err; 9473 9474 err = release_reference_state(cur_func(env), ref_obj_id); 9475 if (err) 9476 return err; 9477 9478 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9479 if (reg->ref_obj_id == ref_obj_id) 9480 mark_reg_invalid(env, reg); 9481 })); 9482 9483 return 0; 9484 } 9485 9486 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9487 { 9488 struct bpf_func_state *unused; 9489 struct bpf_reg_state *reg; 9490 9491 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9492 if (type_is_non_owning_ref(reg->type)) 9493 mark_reg_invalid(env, reg); 9494 })); 9495 } 9496 9497 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9498 struct bpf_reg_state *regs) 9499 { 9500 int i; 9501 9502 /* after the call registers r0 - r5 were scratched */ 9503 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9504 mark_reg_not_init(env, regs, caller_saved[i]); 9505 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9506 } 9507 } 9508 9509 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9510 struct bpf_func_state *caller, 9511 struct bpf_func_state *callee, 9512 int insn_idx); 9513 9514 static int set_callee_state(struct bpf_verifier_env *env, 9515 struct bpf_func_state *caller, 9516 struct bpf_func_state *callee, int insn_idx); 9517 9518 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9519 set_callee_state_fn set_callee_state_cb, 9520 struct bpf_verifier_state *state) 9521 { 9522 struct bpf_func_state *caller, *callee; 9523 int err; 9524 9525 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9526 verbose(env, "the call stack of %d frames is too deep\n", 9527 state->curframe + 2); 9528 return -E2BIG; 9529 } 9530 9531 if (state->frame[state->curframe + 1]) { 9532 verbose(env, "verifier bug. Frame %d already allocated\n", 9533 state->curframe + 1); 9534 return -EFAULT; 9535 } 9536 9537 caller = state->frame[state->curframe]; 9538 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 9539 if (!callee) 9540 return -ENOMEM; 9541 state->frame[state->curframe + 1] = callee; 9542 9543 /* callee cannot access r0, r6 - r9 for reading and has to write 9544 * into its own stack before reading from it. 9545 * callee can read/write into caller's stack 9546 */ 9547 init_func_state(env, callee, 9548 /* remember the callsite, it will be used by bpf_exit */ 9549 callsite, 9550 state->curframe + 1 /* frameno within this callchain */, 9551 subprog /* subprog number within this prog */); 9552 /* Transfer references to the callee */ 9553 err = copy_reference_state(callee, caller); 9554 err = err ?: set_callee_state_cb(env, caller, callee, callsite); 9555 if (err) 9556 goto err_out; 9557 9558 /* only increment it after check_reg_arg() finished */ 9559 state->curframe++; 9560 9561 return 0; 9562 9563 err_out: 9564 free_func_state(callee); 9565 state->frame[state->curframe + 1] = NULL; 9566 return err; 9567 } 9568 9569 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, 9570 const struct btf *btf, 9571 struct bpf_reg_state *regs) 9572 { 9573 struct bpf_subprog_info *sub = subprog_info(env, subprog); 9574 struct bpf_verifier_log *log = &env->log; 9575 u32 i; 9576 int ret; 9577 9578 ret = btf_prepare_func_args(env, subprog); 9579 if (ret) 9580 return ret; 9581 9582 /* check that BTF function arguments match actual types that the 9583 * verifier sees. 9584 */ 9585 for (i = 0; i < sub->arg_cnt; i++) { 9586 u32 regno = i + 1; 9587 struct bpf_reg_state *reg = ®s[regno]; 9588 struct bpf_subprog_arg_info *arg = &sub->args[i]; 9589 9590 if (arg->arg_type == ARG_ANYTHING) { 9591 if (reg->type != SCALAR_VALUE) { 9592 bpf_log(log, "R%d is not a scalar\n", regno); 9593 return -EINVAL; 9594 } 9595 } else if (arg->arg_type == ARG_PTR_TO_CTX) { 9596 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9597 if (ret < 0) 9598 return ret; 9599 /* If function expects ctx type in BTF check that caller 9600 * is passing PTR_TO_CTX. 9601 */ 9602 if (reg->type != PTR_TO_CTX) { 9603 bpf_log(log, "arg#%d expects pointer to ctx\n", i); 9604 return -EINVAL; 9605 } 9606 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 9607 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9608 if (ret < 0) 9609 return ret; 9610 if (check_mem_reg(env, reg, regno, arg->mem_size)) 9611 return -EINVAL; 9612 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) { 9613 bpf_log(log, "arg#%d is expected to be non-NULL\n", i); 9614 return -EINVAL; 9615 } 9616 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 9617 /* 9618 * Can pass any value and the kernel won't crash, but 9619 * only PTR_TO_ARENA or SCALAR make sense. Everything 9620 * else is a bug in the bpf program. Point it out to 9621 * the user at the verification time instead of 9622 * run-time debug nightmare. 9623 */ 9624 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) { 9625 bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno); 9626 return -EINVAL; 9627 } 9628 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 9629 ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR); 9630 if (ret) 9631 return ret; 9632 9633 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0); 9634 if (ret) 9635 return ret; 9636 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 9637 struct bpf_call_arg_meta meta; 9638 int err; 9639 9640 if (register_is_null(reg) && type_may_be_null(arg->arg_type)) 9641 continue; 9642 9643 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */ 9644 err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta); 9645 err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type); 9646 if (err) 9647 return err; 9648 } else { 9649 bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n", 9650 i, arg->arg_type); 9651 return -EFAULT; 9652 } 9653 } 9654 9655 return 0; 9656 } 9657 9658 /* Compare BTF of a function call with given bpf_reg_state. 9659 * Returns: 9660 * EFAULT - there is a verifier bug. Abort verification. 9661 * EINVAL - there is a type mismatch or BTF is not available. 9662 * 0 - BTF matches with what bpf_reg_state expects. 9663 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized. 9664 */ 9665 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog, 9666 struct bpf_reg_state *regs) 9667 { 9668 struct bpf_prog *prog = env->prog; 9669 struct btf *btf = prog->aux->btf; 9670 u32 btf_id; 9671 int err; 9672 9673 if (!prog->aux->func_info) 9674 return -EINVAL; 9675 9676 btf_id = prog->aux->func_info[subprog].type_id; 9677 if (!btf_id) 9678 return -EFAULT; 9679 9680 if (prog->aux->func_info_aux[subprog].unreliable) 9681 return -EINVAL; 9682 9683 err = btf_check_func_arg_match(env, subprog, btf, regs); 9684 /* Compiler optimizations can remove arguments from static functions 9685 * or mismatched type can be passed into a global function. 9686 * In such cases mark the function as unreliable from BTF point of view. 9687 */ 9688 if (err) 9689 prog->aux->func_info_aux[subprog].unreliable = true; 9690 return err; 9691 } 9692 9693 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9694 int insn_idx, int subprog, 9695 set_callee_state_fn set_callee_state_cb) 9696 { 9697 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9698 struct bpf_func_state *caller, *callee; 9699 int err; 9700 9701 caller = state->frame[state->curframe]; 9702 err = btf_check_subprog_call(env, subprog, caller->regs); 9703 if (err == -EFAULT) 9704 return err; 9705 9706 /* set_callee_state is used for direct subprog calls, but we are 9707 * interested in validating only BPF helpers that can call subprogs as 9708 * callbacks 9709 */ 9710 env->subprog_info[subprog].is_cb = true; 9711 if (bpf_pseudo_kfunc_call(insn) && 9712 !is_callback_calling_kfunc(insn->imm)) { 9713 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 9714 func_id_name(insn->imm), insn->imm); 9715 return -EFAULT; 9716 } else if (!bpf_pseudo_kfunc_call(insn) && 9717 !is_callback_calling_function(insn->imm)) { /* helper */ 9718 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 9719 func_id_name(insn->imm), insn->imm); 9720 return -EFAULT; 9721 } 9722 9723 if (is_async_callback_calling_insn(insn)) { 9724 struct bpf_verifier_state *async_cb; 9725 9726 /* there is no real recursion here. timer and workqueue callbacks are async */ 9727 env->subprog_info[subprog].is_async_cb = true; 9728 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9729 insn_idx, subprog, 9730 is_bpf_wq_set_callback_impl_kfunc(insn->imm)); 9731 if (!async_cb) 9732 return -EFAULT; 9733 callee = async_cb->frame[0]; 9734 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9735 9736 /* Convert bpf_timer_set_callback() args into timer callback args */ 9737 err = set_callee_state_cb(env, caller, callee, insn_idx); 9738 if (err) 9739 return err; 9740 9741 return 0; 9742 } 9743 9744 /* for callback functions enqueue entry to callback and 9745 * proceed with next instruction within current frame. 9746 */ 9747 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9748 if (!callback_state) 9749 return -ENOMEM; 9750 9751 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9752 callback_state); 9753 if (err) 9754 return err; 9755 9756 callback_state->callback_unroll_depth++; 9757 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9758 caller->callback_depth = 0; 9759 return 0; 9760 } 9761 9762 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9763 int *insn_idx) 9764 { 9765 struct bpf_verifier_state *state = env->cur_state; 9766 struct bpf_func_state *caller; 9767 int err, subprog, target_insn; 9768 9769 target_insn = *insn_idx + insn->imm + 1; 9770 subprog = find_subprog(env, target_insn); 9771 if (subprog < 0) { 9772 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn); 9773 return -EFAULT; 9774 } 9775 9776 caller = state->frame[state->curframe]; 9777 err = btf_check_subprog_call(env, subprog, caller->regs); 9778 if (err == -EFAULT) 9779 return err; 9780 if (subprog_is_global(env, subprog)) { 9781 const char *sub_name = subprog_name(env, subprog); 9782 9783 /* Only global subprogs cannot be called with a lock held. */ 9784 if (env->cur_state->active_lock.ptr) { 9785 verbose(env, "global function calls are not allowed while holding a lock,\n" 9786 "use static function instead\n"); 9787 return -EINVAL; 9788 } 9789 9790 /* Only global subprogs cannot be called with preemption disabled. */ 9791 if (env->cur_state->active_preempt_lock) { 9792 verbose(env, "global function calls are not allowed with preemption disabled,\n" 9793 "use static function instead\n"); 9794 return -EINVAL; 9795 } 9796 9797 if (err) { 9798 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 9799 subprog, sub_name); 9800 return err; 9801 } 9802 9803 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 9804 subprog, sub_name); 9805 /* mark global subprog for verifying after main prog */ 9806 subprog_aux(env, subprog)->called = true; 9807 clear_caller_saved_regs(env, caller->regs); 9808 9809 /* All global functions return a 64-bit SCALAR_VALUE */ 9810 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9811 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9812 9813 /* continue with next insn after call */ 9814 return 0; 9815 } 9816 9817 /* for regular function entry setup new frame and continue 9818 * from that frame. 9819 */ 9820 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9821 if (err) 9822 return err; 9823 9824 clear_caller_saved_regs(env, caller->regs); 9825 9826 /* and go analyze first insn of the callee */ 9827 *insn_idx = env->subprog_info[subprog].start - 1; 9828 9829 if (env->log.level & BPF_LOG_LEVEL) { 9830 verbose(env, "caller:\n"); 9831 print_verifier_state(env, caller, true); 9832 verbose(env, "callee:\n"); 9833 print_verifier_state(env, state->frame[state->curframe], true); 9834 } 9835 9836 return 0; 9837 } 9838 9839 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9840 struct bpf_func_state *caller, 9841 struct bpf_func_state *callee) 9842 { 9843 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9844 * void *callback_ctx, u64 flags); 9845 * callback_fn(struct bpf_map *map, void *key, void *value, 9846 * void *callback_ctx); 9847 */ 9848 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9849 9850 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9851 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9852 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9853 9854 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9855 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9856 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9857 9858 /* pointer to stack or null */ 9859 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9860 9861 /* unused */ 9862 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9863 return 0; 9864 } 9865 9866 static int set_callee_state(struct bpf_verifier_env *env, 9867 struct bpf_func_state *caller, 9868 struct bpf_func_state *callee, int insn_idx) 9869 { 9870 int i; 9871 9872 /* copy r1 - r5 args that callee can access. The copy includes parent 9873 * pointers, which connects us up to the liveness chain 9874 */ 9875 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9876 callee->regs[i] = caller->regs[i]; 9877 return 0; 9878 } 9879 9880 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9881 struct bpf_func_state *caller, 9882 struct bpf_func_state *callee, 9883 int insn_idx) 9884 { 9885 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9886 struct bpf_map *map; 9887 int err; 9888 9889 /* valid map_ptr and poison value does not matter */ 9890 map = insn_aux->map_ptr_state.map_ptr; 9891 if (!map->ops->map_set_for_each_callback_args || 9892 !map->ops->map_for_each_callback) { 9893 verbose(env, "callback function not allowed for map\n"); 9894 return -ENOTSUPP; 9895 } 9896 9897 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9898 if (err) 9899 return err; 9900 9901 callee->in_callback_fn = true; 9902 callee->callback_ret_range = retval_range(0, 1); 9903 return 0; 9904 } 9905 9906 static int set_loop_callback_state(struct bpf_verifier_env *env, 9907 struct bpf_func_state *caller, 9908 struct bpf_func_state *callee, 9909 int insn_idx) 9910 { 9911 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9912 * u64 flags); 9913 * callback_fn(u32 index, void *callback_ctx); 9914 */ 9915 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9916 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9917 9918 /* unused */ 9919 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9920 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9921 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9922 9923 callee->in_callback_fn = true; 9924 callee->callback_ret_range = retval_range(0, 1); 9925 return 0; 9926 } 9927 9928 static int set_timer_callback_state(struct bpf_verifier_env *env, 9929 struct bpf_func_state *caller, 9930 struct bpf_func_state *callee, 9931 int insn_idx) 9932 { 9933 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9934 9935 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9936 * callback_fn(struct bpf_map *map, void *key, void *value); 9937 */ 9938 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9939 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9940 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9941 9942 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9943 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9944 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9945 9946 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9947 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9948 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9949 9950 /* unused */ 9951 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9952 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9953 callee->in_async_callback_fn = true; 9954 callee->callback_ret_range = retval_range(0, 1); 9955 return 0; 9956 } 9957 9958 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9959 struct bpf_func_state *caller, 9960 struct bpf_func_state *callee, 9961 int insn_idx) 9962 { 9963 /* bpf_find_vma(struct task_struct *task, u64 addr, 9964 * void *callback_fn, void *callback_ctx, u64 flags) 9965 * (callback_fn)(struct task_struct *task, 9966 * struct vm_area_struct *vma, void *callback_ctx); 9967 */ 9968 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9969 9970 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9971 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9972 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9973 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 9974 9975 /* pointer to stack or null */ 9976 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9977 9978 /* unused */ 9979 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9980 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9981 callee->in_callback_fn = true; 9982 callee->callback_ret_range = retval_range(0, 1); 9983 return 0; 9984 } 9985 9986 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9987 struct bpf_func_state *caller, 9988 struct bpf_func_state *callee, 9989 int insn_idx) 9990 { 9991 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9992 * callback_ctx, u64 flags); 9993 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9994 */ 9995 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9996 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9997 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9998 9999 /* unused */ 10000 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 10001 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10002 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10003 10004 callee->in_callback_fn = true; 10005 callee->callback_ret_range = retval_range(0, 1); 10006 return 0; 10007 } 10008 10009 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 10010 struct bpf_func_state *caller, 10011 struct bpf_func_state *callee, 10012 int insn_idx) 10013 { 10014 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 10015 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 10016 * 10017 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 10018 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 10019 * by this point, so look at 'root' 10020 */ 10021 struct btf_field *field; 10022 10023 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 10024 BPF_RB_ROOT); 10025 if (!field || !field->graph_root.value_btf_id) 10026 return -EFAULT; 10027 10028 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 10029 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 10030 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 10031 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 10032 10033 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 10034 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10035 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10036 callee->in_callback_fn = true; 10037 callee->callback_ret_range = retval_range(0, 1); 10038 return 0; 10039 } 10040 10041 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 10042 10043 /* Are we currently verifying the callback for a rbtree helper that must 10044 * be called with lock held? If so, no need to complain about unreleased 10045 * lock 10046 */ 10047 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 10048 { 10049 struct bpf_verifier_state *state = env->cur_state; 10050 struct bpf_insn *insn = env->prog->insnsi; 10051 struct bpf_func_state *callee; 10052 int kfunc_btf_id; 10053 10054 if (!state->curframe) 10055 return false; 10056 10057 callee = state->frame[state->curframe]; 10058 10059 if (!callee->in_callback_fn) 10060 return false; 10061 10062 kfunc_btf_id = insn[callee->callsite].imm; 10063 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 10064 } 10065 10066 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg, 10067 bool return_32bit) 10068 { 10069 if (return_32bit) 10070 return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval; 10071 else 10072 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval; 10073 } 10074 10075 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 10076 { 10077 struct bpf_verifier_state *state = env->cur_state, *prev_st; 10078 struct bpf_func_state *caller, *callee; 10079 struct bpf_reg_state *r0; 10080 bool in_callback_fn; 10081 int err; 10082 10083 callee = state->frame[state->curframe]; 10084 r0 = &callee->regs[BPF_REG_0]; 10085 if (r0->type == PTR_TO_STACK) { 10086 /* technically it's ok to return caller's stack pointer 10087 * (or caller's caller's pointer) back to the caller, 10088 * since these pointers are valid. Only current stack 10089 * pointer will be invalid as soon as function exits, 10090 * but let's be conservative 10091 */ 10092 verbose(env, "cannot return stack pointer to the caller\n"); 10093 return -EINVAL; 10094 } 10095 10096 caller = state->frame[state->curframe - 1]; 10097 if (callee->in_callback_fn) { 10098 if (r0->type != SCALAR_VALUE) { 10099 verbose(env, "R0 not a scalar value\n"); 10100 return -EACCES; 10101 } 10102 10103 /* we are going to rely on register's precise value */ 10104 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64); 10105 err = err ?: mark_chain_precision(env, BPF_REG_0); 10106 if (err) 10107 return err; 10108 10109 /* enforce R0 return value range, and bpf_callback_t returns 64bit */ 10110 if (!retval_range_within(callee->callback_ret_range, r0, false)) { 10111 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 10112 "At callback return", "R0"); 10113 return -EINVAL; 10114 } 10115 if (!calls_callback(env, callee->callsite)) { 10116 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n", 10117 *insn_idx, callee->callsite); 10118 return -EFAULT; 10119 } 10120 } else { 10121 /* return to the caller whatever r0 had in the callee */ 10122 caller->regs[BPF_REG_0] = *r0; 10123 } 10124 10125 /* callback_fn frame should have released its own additions to parent's 10126 * reference state at this point, or check_reference_leak would 10127 * complain, hence it must be the same as the caller. There is no need 10128 * to copy it back. 10129 */ 10130 if (!callee->in_callback_fn) { 10131 /* Transfer references to the caller */ 10132 err = copy_reference_state(caller, callee); 10133 if (err) 10134 return err; 10135 } 10136 10137 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 10138 * there function call logic would reschedule callback visit. If iteration 10139 * converges is_state_visited() would prune that visit eventually. 10140 */ 10141 in_callback_fn = callee->in_callback_fn; 10142 if (in_callback_fn) 10143 *insn_idx = callee->callsite; 10144 else 10145 *insn_idx = callee->callsite + 1; 10146 10147 if (env->log.level & BPF_LOG_LEVEL) { 10148 verbose(env, "returning from callee:\n"); 10149 print_verifier_state(env, callee, true); 10150 verbose(env, "to caller at %d:\n", *insn_idx); 10151 print_verifier_state(env, caller, true); 10152 } 10153 /* clear everything in the callee. In case of exceptional exits using 10154 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 10155 free_func_state(callee); 10156 state->frame[state->curframe--] = NULL; 10157 10158 /* for callbacks widen imprecise scalars to make programs like below verify: 10159 * 10160 * struct ctx { int i; } 10161 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 10162 * ... 10163 * struct ctx = { .i = 0; } 10164 * bpf_loop(100, cb, &ctx, 0); 10165 * 10166 * This is similar to what is done in process_iter_next_call() for open 10167 * coded iterators. 10168 */ 10169 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 10170 if (prev_st) { 10171 err = widen_imprecise_scalars(env, prev_st, state); 10172 if (err) 10173 return err; 10174 } 10175 return 0; 10176 } 10177 10178 static int do_refine_retval_range(struct bpf_verifier_env *env, 10179 struct bpf_reg_state *regs, int ret_type, 10180 int func_id, 10181 struct bpf_call_arg_meta *meta) 10182 { 10183 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 10184 10185 if (ret_type != RET_INTEGER) 10186 return 0; 10187 10188 switch (func_id) { 10189 case BPF_FUNC_get_stack: 10190 case BPF_FUNC_get_task_stack: 10191 case BPF_FUNC_probe_read_str: 10192 case BPF_FUNC_probe_read_kernel_str: 10193 case BPF_FUNC_probe_read_user_str: 10194 ret_reg->smax_value = meta->msize_max_value; 10195 ret_reg->s32_max_value = meta->msize_max_value; 10196 ret_reg->smin_value = -MAX_ERRNO; 10197 ret_reg->s32_min_value = -MAX_ERRNO; 10198 reg_bounds_sync(ret_reg); 10199 break; 10200 case BPF_FUNC_get_smp_processor_id: 10201 ret_reg->umax_value = nr_cpu_ids - 1; 10202 ret_reg->u32_max_value = nr_cpu_ids - 1; 10203 ret_reg->smax_value = nr_cpu_ids - 1; 10204 ret_reg->s32_max_value = nr_cpu_ids - 1; 10205 ret_reg->umin_value = 0; 10206 ret_reg->u32_min_value = 0; 10207 ret_reg->smin_value = 0; 10208 ret_reg->s32_min_value = 0; 10209 reg_bounds_sync(ret_reg); 10210 break; 10211 } 10212 10213 return reg_bounds_sanity_check(env, ret_reg, "retval"); 10214 } 10215 10216 static int 10217 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 10218 int func_id, int insn_idx) 10219 { 10220 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 10221 struct bpf_map *map = meta->map_ptr; 10222 10223 if (func_id != BPF_FUNC_tail_call && 10224 func_id != BPF_FUNC_map_lookup_elem && 10225 func_id != BPF_FUNC_map_update_elem && 10226 func_id != BPF_FUNC_map_delete_elem && 10227 func_id != BPF_FUNC_map_push_elem && 10228 func_id != BPF_FUNC_map_pop_elem && 10229 func_id != BPF_FUNC_map_peek_elem && 10230 func_id != BPF_FUNC_for_each_map_elem && 10231 func_id != BPF_FUNC_redirect_map && 10232 func_id != BPF_FUNC_map_lookup_percpu_elem) 10233 return 0; 10234 10235 if (map == NULL) { 10236 verbose(env, "kernel subsystem misconfigured verifier\n"); 10237 return -EINVAL; 10238 } 10239 10240 /* In case of read-only, some additional restrictions 10241 * need to be applied in order to prevent altering the 10242 * state of the map from program side. 10243 */ 10244 if ((map->map_flags & BPF_F_RDONLY_PROG) && 10245 (func_id == BPF_FUNC_map_delete_elem || 10246 func_id == BPF_FUNC_map_update_elem || 10247 func_id == BPF_FUNC_map_push_elem || 10248 func_id == BPF_FUNC_map_pop_elem)) { 10249 verbose(env, "write into map forbidden\n"); 10250 return -EACCES; 10251 } 10252 10253 if (!aux->map_ptr_state.map_ptr) 10254 bpf_map_ptr_store(aux, meta->map_ptr, 10255 !meta->map_ptr->bypass_spec_v1, false); 10256 else if (aux->map_ptr_state.map_ptr != meta->map_ptr) 10257 bpf_map_ptr_store(aux, meta->map_ptr, 10258 !meta->map_ptr->bypass_spec_v1, true); 10259 return 0; 10260 } 10261 10262 static int 10263 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 10264 int func_id, int insn_idx) 10265 { 10266 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 10267 struct bpf_reg_state *regs = cur_regs(env), *reg; 10268 struct bpf_map *map = meta->map_ptr; 10269 u64 val, max; 10270 int err; 10271 10272 if (func_id != BPF_FUNC_tail_call) 10273 return 0; 10274 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 10275 verbose(env, "kernel subsystem misconfigured verifier\n"); 10276 return -EINVAL; 10277 } 10278 10279 reg = ®s[BPF_REG_3]; 10280 val = reg->var_off.value; 10281 max = map->max_entries; 10282 10283 if (!(is_reg_const(reg, false) && val < max)) { 10284 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 10285 return 0; 10286 } 10287 10288 err = mark_chain_precision(env, BPF_REG_3); 10289 if (err) 10290 return err; 10291 if (bpf_map_key_unseen(aux)) 10292 bpf_map_key_store(aux, val); 10293 else if (!bpf_map_key_poisoned(aux) && 10294 bpf_map_key_immediate(aux) != val) 10295 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 10296 return 0; 10297 } 10298 10299 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 10300 { 10301 struct bpf_func_state *state = cur_func(env); 10302 bool refs_lingering = false; 10303 int i; 10304 10305 if (!exception_exit && state->frameno && !state->in_callback_fn) 10306 return 0; 10307 10308 for (i = 0; i < state->acquired_refs; i++) { 10309 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 10310 continue; 10311 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 10312 state->refs[i].id, state->refs[i].insn_idx); 10313 refs_lingering = true; 10314 } 10315 return refs_lingering ? -EINVAL : 0; 10316 } 10317 10318 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 10319 struct bpf_reg_state *regs) 10320 { 10321 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 10322 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 10323 struct bpf_map *fmt_map = fmt_reg->map_ptr; 10324 struct bpf_bprintf_data data = {}; 10325 int err, fmt_map_off, num_args; 10326 u64 fmt_addr; 10327 char *fmt; 10328 10329 /* data must be an array of u64 */ 10330 if (data_len_reg->var_off.value % 8) 10331 return -EINVAL; 10332 num_args = data_len_reg->var_off.value / 8; 10333 10334 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 10335 * and map_direct_value_addr is set. 10336 */ 10337 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 10338 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 10339 fmt_map_off); 10340 if (err) { 10341 verbose(env, "verifier bug\n"); 10342 return -EFAULT; 10343 } 10344 fmt = (char *)(long)fmt_addr + fmt_map_off; 10345 10346 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 10347 * can focus on validating the format specifiers. 10348 */ 10349 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 10350 if (err < 0) 10351 verbose(env, "Invalid format string\n"); 10352 10353 return err; 10354 } 10355 10356 static int check_get_func_ip(struct bpf_verifier_env *env) 10357 { 10358 enum bpf_prog_type type = resolve_prog_type(env->prog); 10359 int func_id = BPF_FUNC_get_func_ip; 10360 10361 if (type == BPF_PROG_TYPE_TRACING) { 10362 if (!bpf_prog_has_trampoline(env->prog)) { 10363 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 10364 func_id_name(func_id), func_id); 10365 return -ENOTSUPP; 10366 } 10367 return 0; 10368 } else if (type == BPF_PROG_TYPE_KPROBE) { 10369 return 0; 10370 } 10371 10372 verbose(env, "func %s#%d not supported for program type %d\n", 10373 func_id_name(func_id), func_id, type); 10374 return -ENOTSUPP; 10375 } 10376 10377 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 10378 { 10379 return &env->insn_aux_data[env->insn_idx]; 10380 } 10381 10382 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 10383 { 10384 struct bpf_reg_state *regs = cur_regs(env); 10385 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 10386 bool reg_is_null = register_is_null(reg); 10387 10388 if (reg_is_null) 10389 mark_chain_precision(env, BPF_REG_4); 10390 10391 return reg_is_null; 10392 } 10393 10394 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 10395 { 10396 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 10397 10398 if (!state->initialized) { 10399 state->initialized = 1; 10400 state->fit_for_inline = loop_flag_is_zero(env); 10401 state->callback_subprogno = subprogno; 10402 return; 10403 } 10404 10405 if (!state->fit_for_inline) 10406 return; 10407 10408 state->fit_for_inline = (loop_flag_is_zero(env) && 10409 state->callback_subprogno == subprogno); 10410 } 10411 10412 static int get_helper_proto(struct bpf_verifier_env *env, int func_id, 10413 const struct bpf_func_proto **ptr) 10414 { 10415 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) 10416 return -ERANGE; 10417 10418 if (!env->ops->get_func_proto) 10419 return -EINVAL; 10420 10421 *ptr = env->ops->get_func_proto(func_id, env->prog); 10422 return *ptr ? 0 : -EINVAL; 10423 } 10424 10425 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10426 int *insn_idx_p) 10427 { 10428 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 10429 bool returns_cpu_specific_alloc_ptr = false; 10430 const struct bpf_func_proto *fn = NULL; 10431 enum bpf_return_type ret_type; 10432 enum bpf_type_flag ret_flag; 10433 struct bpf_reg_state *regs; 10434 struct bpf_call_arg_meta meta; 10435 int insn_idx = *insn_idx_p; 10436 bool changes_data; 10437 int i, err, func_id; 10438 10439 /* find function prototype */ 10440 func_id = insn->imm; 10441 err = get_helper_proto(env, insn->imm, &fn); 10442 if (err == -ERANGE) { 10443 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id); 10444 return -EINVAL; 10445 } 10446 10447 if (err) { 10448 verbose(env, "program of this type cannot use helper %s#%d\n", 10449 func_id_name(func_id), func_id); 10450 return err; 10451 } 10452 10453 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 10454 if (!env->prog->gpl_compatible && fn->gpl_only) { 10455 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10456 return -EINVAL; 10457 } 10458 10459 if (fn->allowed && !fn->allowed(env->prog)) { 10460 verbose(env, "helper call is not allowed in probe\n"); 10461 return -EINVAL; 10462 } 10463 10464 if (!in_sleepable(env) && fn->might_sleep) { 10465 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 10466 return -EINVAL; 10467 } 10468 10469 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10470 changes_data = bpf_helper_changes_pkt_data(fn->func); 10471 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10472 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 10473 func_id_name(func_id), func_id); 10474 return -EINVAL; 10475 } 10476 10477 memset(&meta, 0, sizeof(meta)); 10478 meta.pkt_access = fn->pkt_access; 10479 10480 err = check_func_proto(fn, func_id); 10481 if (err) { 10482 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 10483 func_id_name(func_id), func_id); 10484 return err; 10485 } 10486 10487 if (env->cur_state->active_rcu_lock) { 10488 if (fn->might_sleep) { 10489 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 10490 func_id_name(func_id), func_id); 10491 return -EINVAL; 10492 } 10493 10494 if (in_sleepable(env) && is_storage_get_function(func_id)) 10495 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10496 } 10497 10498 if (env->cur_state->active_preempt_lock) { 10499 if (fn->might_sleep) { 10500 verbose(env, "sleepable helper %s#%d in non-preemptible region\n", 10501 func_id_name(func_id), func_id); 10502 return -EINVAL; 10503 } 10504 10505 if (in_sleepable(env) && is_storage_get_function(func_id)) 10506 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10507 } 10508 10509 meta.func_id = func_id; 10510 /* check args */ 10511 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10512 err = check_func_arg(env, i, &meta, fn, insn_idx); 10513 if (err) 10514 return err; 10515 } 10516 10517 err = record_func_map(env, &meta, func_id, insn_idx); 10518 if (err) 10519 return err; 10520 10521 err = record_func_key(env, &meta, func_id, insn_idx); 10522 if (err) 10523 return err; 10524 10525 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10526 * is inferred from register state. 10527 */ 10528 for (i = 0; i < meta.access_size; i++) { 10529 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 10530 BPF_WRITE, -1, false, false); 10531 if (err) 10532 return err; 10533 } 10534 10535 regs = cur_regs(env); 10536 10537 if (meta.release_regno) { 10538 err = -EINVAL; 10539 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 10540 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 10541 * is safe to do directly. 10542 */ 10543 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 10544 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 10545 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 10546 return -EFAULT; 10547 } 10548 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 10549 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 10550 u32 ref_obj_id = meta.ref_obj_id; 10551 bool in_rcu = in_rcu_cs(env); 10552 struct bpf_func_state *state; 10553 struct bpf_reg_state *reg; 10554 10555 err = release_reference_state(cur_func(env), ref_obj_id); 10556 if (!err) { 10557 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10558 if (reg->ref_obj_id == ref_obj_id) { 10559 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 10560 reg->ref_obj_id = 0; 10561 reg->type &= ~MEM_ALLOC; 10562 reg->type |= MEM_RCU; 10563 } else { 10564 mark_reg_invalid(env, reg); 10565 } 10566 } 10567 })); 10568 } 10569 } else if (meta.ref_obj_id) { 10570 err = release_reference(env, meta.ref_obj_id); 10571 } else if (register_is_null(®s[meta.release_regno])) { 10572 /* meta.ref_obj_id can only be 0 if register that is meant to be 10573 * released is NULL, which must be > R0. 10574 */ 10575 err = 0; 10576 } 10577 if (err) { 10578 verbose(env, "func %s#%d reference has not been acquired before\n", 10579 func_id_name(func_id), func_id); 10580 return err; 10581 } 10582 } 10583 10584 switch (func_id) { 10585 case BPF_FUNC_tail_call: 10586 err = check_reference_leak(env, false); 10587 if (err) { 10588 verbose(env, "tail_call would lead to reference leak\n"); 10589 return err; 10590 } 10591 break; 10592 case BPF_FUNC_get_local_storage: 10593 /* check that flags argument in get_local_storage(map, flags) is 0, 10594 * this is required because get_local_storage() can't return an error. 10595 */ 10596 if (!register_is_null(®s[BPF_REG_2])) { 10597 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10598 return -EINVAL; 10599 } 10600 break; 10601 case BPF_FUNC_for_each_map_elem: 10602 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10603 set_map_elem_callback_state); 10604 break; 10605 case BPF_FUNC_timer_set_callback: 10606 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10607 set_timer_callback_state); 10608 break; 10609 case BPF_FUNC_find_vma: 10610 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10611 set_find_vma_callback_state); 10612 break; 10613 case BPF_FUNC_snprintf: 10614 err = check_bpf_snprintf_call(env, regs); 10615 break; 10616 case BPF_FUNC_loop: 10617 update_loop_inline_state(env, meta.subprogno); 10618 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10619 * is finished, thus mark it precise. 10620 */ 10621 err = mark_chain_precision(env, BPF_REG_1); 10622 if (err) 10623 return err; 10624 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) { 10625 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10626 set_loop_callback_state); 10627 } else { 10628 cur_func(env)->callback_depth = 0; 10629 if (env->log.level & BPF_LOG_LEVEL2) 10630 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10631 env->cur_state->curframe); 10632 } 10633 break; 10634 case BPF_FUNC_dynptr_from_mem: 10635 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10636 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10637 reg_type_str(env, regs[BPF_REG_1].type)); 10638 return -EACCES; 10639 } 10640 break; 10641 case BPF_FUNC_set_retval: 10642 if (prog_type == BPF_PROG_TYPE_LSM && 10643 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10644 if (!env->prog->aux->attach_func_proto->type) { 10645 /* Make sure programs that attach to void 10646 * hooks don't try to modify return value. 10647 */ 10648 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10649 return -EINVAL; 10650 } 10651 } 10652 break; 10653 case BPF_FUNC_dynptr_data: 10654 { 10655 struct bpf_reg_state *reg; 10656 int id, ref_obj_id; 10657 10658 reg = get_dynptr_arg_reg(env, fn, regs); 10659 if (!reg) 10660 return -EFAULT; 10661 10662 10663 if (meta.dynptr_id) { 10664 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 10665 return -EFAULT; 10666 } 10667 if (meta.ref_obj_id) { 10668 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 10669 return -EFAULT; 10670 } 10671 10672 id = dynptr_id(env, reg); 10673 if (id < 0) { 10674 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 10675 return id; 10676 } 10677 10678 ref_obj_id = dynptr_ref_obj_id(env, reg); 10679 if (ref_obj_id < 0) { 10680 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 10681 return ref_obj_id; 10682 } 10683 10684 meta.dynptr_id = id; 10685 meta.ref_obj_id = ref_obj_id; 10686 10687 break; 10688 } 10689 case BPF_FUNC_dynptr_write: 10690 { 10691 enum bpf_dynptr_type dynptr_type; 10692 struct bpf_reg_state *reg; 10693 10694 reg = get_dynptr_arg_reg(env, fn, regs); 10695 if (!reg) 10696 return -EFAULT; 10697 10698 dynptr_type = dynptr_get_type(env, reg); 10699 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10700 return -EFAULT; 10701 10702 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 10703 /* this will trigger clear_all_pkt_pointers(), which will 10704 * invalidate all dynptr slices associated with the skb 10705 */ 10706 changes_data = true; 10707 10708 break; 10709 } 10710 case BPF_FUNC_per_cpu_ptr: 10711 case BPF_FUNC_this_cpu_ptr: 10712 { 10713 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 10714 const struct btf_type *type; 10715 10716 if (reg->type & MEM_RCU) { 10717 type = btf_type_by_id(reg->btf, reg->btf_id); 10718 if (!type || !btf_type_is_struct(type)) { 10719 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 10720 return -EFAULT; 10721 } 10722 returns_cpu_specific_alloc_ptr = true; 10723 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 10724 } 10725 break; 10726 } 10727 case BPF_FUNC_user_ringbuf_drain: 10728 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10729 set_user_ringbuf_callback_state); 10730 break; 10731 } 10732 10733 if (err) 10734 return err; 10735 10736 /* reset caller saved regs */ 10737 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10738 mark_reg_not_init(env, regs, caller_saved[i]); 10739 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10740 } 10741 10742 /* helper call returns 64-bit value. */ 10743 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10744 10745 /* update return register (already marked as written above) */ 10746 ret_type = fn->ret_type; 10747 ret_flag = type_flag(ret_type); 10748 10749 switch (base_type(ret_type)) { 10750 case RET_INTEGER: 10751 /* sets type to SCALAR_VALUE */ 10752 mark_reg_unknown(env, regs, BPF_REG_0); 10753 break; 10754 case RET_VOID: 10755 regs[BPF_REG_0].type = NOT_INIT; 10756 break; 10757 case RET_PTR_TO_MAP_VALUE: 10758 /* There is no offset yet applied, variable or fixed */ 10759 mark_reg_known_zero(env, regs, BPF_REG_0); 10760 /* remember map_ptr, so that check_map_access() 10761 * can check 'value_size' boundary of memory access 10762 * to map element returned from bpf_map_lookup_elem() 10763 */ 10764 if (meta.map_ptr == NULL) { 10765 verbose(env, 10766 "kernel subsystem misconfigured verifier\n"); 10767 return -EINVAL; 10768 } 10769 regs[BPF_REG_0].map_ptr = meta.map_ptr; 10770 regs[BPF_REG_0].map_uid = meta.map_uid; 10771 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10772 if (!type_may_be_null(ret_type) && 10773 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 10774 regs[BPF_REG_0].id = ++env->id_gen; 10775 } 10776 break; 10777 case RET_PTR_TO_SOCKET: 10778 mark_reg_known_zero(env, regs, BPF_REG_0); 10779 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10780 break; 10781 case RET_PTR_TO_SOCK_COMMON: 10782 mark_reg_known_zero(env, regs, BPF_REG_0); 10783 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10784 break; 10785 case RET_PTR_TO_TCP_SOCK: 10786 mark_reg_known_zero(env, regs, BPF_REG_0); 10787 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10788 break; 10789 case RET_PTR_TO_MEM: 10790 mark_reg_known_zero(env, regs, BPF_REG_0); 10791 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10792 regs[BPF_REG_0].mem_size = meta.mem_size; 10793 break; 10794 case RET_PTR_TO_MEM_OR_BTF_ID: 10795 { 10796 const struct btf_type *t; 10797 10798 mark_reg_known_zero(env, regs, BPF_REG_0); 10799 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10800 if (!btf_type_is_struct(t)) { 10801 u32 tsize; 10802 const struct btf_type *ret; 10803 const char *tname; 10804 10805 /* resolve the type size of ksym. */ 10806 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10807 if (IS_ERR(ret)) { 10808 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10809 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10810 tname, PTR_ERR(ret)); 10811 return -EINVAL; 10812 } 10813 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10814 regs[BPF_REG_0].mem_size = tsize; 10815 } else { 10816 if (returns_cpu_specific_alloc_ptr) { 10817 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10818 } else { 10819 /* MEM_RDONLY may be carried from ret_flag, but it 10820 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10821 * it will confuse the check of PTR_TO_BTF_ID in 10822 * check_mem_access(). 10823 */ 10824 ret_flag &= ~MEM_RDONLY; 10825 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10826 } 10827 10828 regs[BPF_REG_0].btf = meta.ret_btf; 10829 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10830 } 10831 break; 10832 } 10833 case RET_PTR_TO_BTF_ID: 10834 { 10835 struct btf *ret_btf; 10836 int ret_btf_id; 10837 10838 mark_reg_known_zero(env, regs, BPF_REG_0); 10839 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10840 if (func_id == BPF_FUNC_kptr_xchg) { 10841 ret_btf = meta.kptr_field->kptr.btf; 10842 ret_btf_id = meta.kptr_field->kptr.btf_id; 10843 if (!btf_is_kernel(ret_btf)) { 10844 regs[BPF_REG_0].type |= MEM_ALLOC; 10845 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10846 regs[BPF_REG_0].type |= MEM_PERCPU; 10847 } 10848 } else { 10849 if (fn->ret_btf_id == BPF_PTR_POISON) { 10850 verbose(env, "verifier internal error:"); 10851 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 10852 func_id_name(func_id)); 10853 return -EINVAL; 10854 } 10855 ret_btf = btf_vmlinux; 10856 ret_btf_id = *fn->ret_btf_id; 10857 } 10858 if (ret_btf_id == 0) { 10859 verbose(env, "invalid return type %u of func %s#%d\n", 10860 base_type(ret_type), func_id_name(func_id), 10861 func_id); 10862 return -EINVAL; 10863 } 10864 regs[BPF_REG_0].btf = ret_btf; 10865 regs[BPF_REG_0].btf_id = ret_btf_id; 10866 break; 10867 } 10868 default: 10869 verbose(env, "unknown return type %u of func %s#%d\n", 10870 base_type(ret_type), func_id_name(func_id), func_id); 10871 return -EINVAL; 10872 } 10873 10874 if (type_may_be_null(regs[BPF_REG_0].type)) 10875 regs[BPF_REG_0].id = ++env->id_gen; 10876 10877 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 10878 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 10879 func_id_name(func_id), func_id); 10880 return -EFAULT; 10881 } 10882 10883 if (is_dynptr_ref_function(func_id)) 10884 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 10885 10886 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 10887 /* For release_reference() */ 10888 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10889 } else if (is_acquire_function(func_id, meta.map_ptr)) { 10890 int id = acquire_reference_state(env, insn_idx); 10891 10892 if (id < 0) 10893 return id; 10894 /* For mark_ptr_or_null_reg() */ 10895 regs[BPF_REG_0].id = id; 10896 /* For release_reference() */ 10897 regs[BPF_REG_0].ref_obj_id = id; 10898 } 10899 10900 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 10901 if (err) 10902 return err; 10903 10904 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 10905 if (err) 10906 return err; 10907 10908 if ((func_id == BPF_FUNC_get_stack || 10909 func_id == BPF_FUNC_get_task_stack) && 10910 !env->prog->has_callchain_buf) { 10911 const char *err_str; 10912 10913 #ifdef CONFIG_PERF_EVENTS 10914 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10915 err_str = "cannot get callchain buffer for func %s#%d\n"; 10916 #else 10917 err = -ENOTSUPP; 10918 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10919 #endif 10920 if (err) { 10921 verbose(env, err_str, func_id_name(func_id), func_id); 10922 return err; 10923 } 10924 10925 env->prog->has_callchain_buf = true; 10926 } 10927 10928 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10929 env->prog->call_get_stack = true; 10930 10931 if (func_id == BPF_FUNC_get_func_ip) { 10932 if (check_get_func_ip(env)) 10933 return -ENOTSUPP; 10934 env->prog->call_get_func_ip = true; 10935 } 10936 10937 if (changes_data) 10938 clear_all_pkt_pointers(env); 10939 return 0; 10940 } 10941 10942 /* mark_btf_func_reg_size() is used when the reg size is determined by 10943 * the BTF func_proto's return value size and argument. 10944 */ 10945 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10946 size_t reg_size) 10947 { 10948 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 10949 10950 if (regno == BPF_REG_0) { 10951 /* Function return value */ 10952 reg->live |= REG_LIVE_WRITTEN; 10953 reg->subreg_def = reg_size == sizeof(u64) ? 10954 DEF_NOT_SUBREG : env->insn_idx + 1; 10955 } else { 10956 /* Function argument */ 10957 if (reg_size == sizeof(u64)) { 10958 mark_insn_zext(env, reg); 10959 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 10960 } else { 10961 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 10962 } 10963 } 10964 } 10965 10966 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10967 { 10968 return meta->kfunc_flags & KF_ACQUIRE; 10969 } 10970 10971 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10972 { 10973 return meta->kfunc_flags & KF_RELEASE; 10974 } 10975 10976 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 10977 { 10978 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 10979 } 10980 10981 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 10982 { 10983 return meta->kfunc_flags & KF_SLEEPABLE; 10984 } 10985 10986 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10987 { 10988 return meta->kfunc_flags & KF_DESTRUCTIVE; 10989 } 10990 10991 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10992 { 10993 return meta->kfunc_flags & KF_RCU; 10994 } 10995 10996 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 10997 { 10998 return meta->kfunc_flags & KF_RCU_PROTECTED; 10999 } 11000 11001 static bool is_kfunc_arg_mem_size(const struct btf *btf, 11002 const struct btf_param *arg, 11003 const struct bpf_reg_state *reg) 11004 { 11005 const struct btf_type *t; 11006 11007 t = btf_type_skip_modifiers(btf, arg->type, NULL); 11008 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 11009 return false; 11010 11011 return btf_param_match_suffix(btf, arg, "__sz"); 11012 } 11013 11014 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 11015 const struct btf_param *arg, 11016 const struct bpf_reg_state *reg) 11017 { 11018 const struct btf_type *t; 11019 11020 t = btf_type_skip_modifiers(btf, arg->type, NULL); 11021 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 11022 return false; 11023 11024 return btf_param_match_suffix(btf, arg, "__szk"); 11025 } 11026 11027 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 11028 { 11029 return btf_param_match_suffix(btf, arg, "__opt"); 11030 } 11031 11032 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 11033 { 11034 return btf_param_match_suffix(btf, arg, "__k"); 11035 } 11036 11037 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 11038 { 11039 return btf_param_match_suffix(btf, arg, "__ign"); 11040 } 11041 11042 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg) 11043 { 11044 return btf_param_match_suffix(btf, arg, "__map"); 11045 } 11046 11047 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 11048 { 11049 return btf_param_match_suffix(btf, arg, "__alloc"); 11050 } 11051 11052 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 11053 { 11054 return btf_param_match_suffix(btf, arg, "__uninit"); 11055 } 11056 11057 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 11058 { 11059 return btf_param_match_suffix(btf, arg, "__refcounted_kptr"); 11060 } 11061 11062 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 11063 { 11064 return btf_param_match_suffix(btf, arg, "__nullable"); 11065 } 11066 11067 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 11068 { 11069 return btf_param_match_suffix(btf, arg, "__str"); 11070 } 11071 11072 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 11073 const struct btf_param *arg, 11074 const char *name) 11075 { 11076 int len, target_len = strlen(name); 11077 const char *param_name; 11078 11079 param_name = btf_name_by_offset(btf, arg->name_off); 11080 if (str_is_empty(param_name)) 11081 return false; 11082 len = strlen(param_name); 11083 if (len != target_len) 11084 return false; 11085 if (strcmp(param_name, name)) 11086 return false; 11087 11088 return true; 11089 } 11090 11091 enum { 11092 KF_ARG_DYNPTR_ID, 11093 KF_ARG_LIST_HEAD_ID, 11094 KF_ARG_LIST_NODE_ID, 11095 KF_ARG_RB_ROOT_ID, 11096 KF_ARG_RB_NODE_ID, 11097 KF_ARG_WORKQUEUE_ID, 11098 }; 11099 11100 BTF_ID_LIST(kf_arg_btf_ids) 11101 BTF_ID(struct, bpf_dynptr) 11102 BTF_ID(struct, bpf_list_head) 11103 BTF_ID(struct, bpf_list_node) 11104 BTF_ID(struct, bpf_rb_root) 11105 BTF_ID(struct, bpf_rb_node) 11106 BTF_ID(struct, bpf_wq) 11107 11108 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 11109 const struct btf_param *arg, int type) 11110 { 11111 const struct btf_type *t; 11112 u32 res_id; 11113 11114 t = btf_type_skip_modifiers(btf, arg->type, NULL); 11115 if (!t) 11116 return false; 11117 if (!btf_type_is_ptr(t)) 11118 return false; 11119 t = btf_type_skip_modifiers(btf, t->type, &res_id); 11120 if (!t) 11121 return false; 11122 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 11123 } 11124 11125 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 11126 { 11127 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 11128 } 11129 11130 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 11131 { 11132 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 11133 } 11134 11135 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 11136 { 11137 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 11138 } 11139 11140 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 11141 { 11142 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 11143 } 11144 11145 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 11146 { 11147 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 11148 } 11149 11150 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg) 11151 { 11152 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID); 11153 } 11154 11155 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 11156 const struct btf_param *arg) 11157 { 11158 const struct btf_type *t; 11159 11160 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 11161 if (!t) 11162 return false; 11163 11164 return true; 11165 } 11166 11167 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 11168 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 11169 const struct btf *btf, 11170 const struct btf_type *t, int rec) 11171 { 11172 const struct btf_type *member_type; 11173 const struct btf_member *member; 11174 u32 i; 11175 11176 if (!btf_type_is_struct(t)) 11177 return false; 11178 11179 for_each_member(i, t, member) { 11180 const struct btf_array *array; 11181 11182 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 11183 if (btf_type_is_struct(member_type)) { 11184 if (rec >= 3) { 11185 verbose(env, "max struct nesting depth exceeded\n"); 11186 return false; 11187 } 11188 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 11189 return false; 11190 continue; 11191 } 11192 if (btf_type_is_array(member_type)) { 11193 array = btf_array(member_type); 11194 if (!array->nelems) 11195 return false; 11196 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 11197 if (!btf_type_is_scalar(member_type)) 11198 return false; 11199 continue; 11200 } 11201 if (!btf_type_is_scalar(member_type)) 11202 return false; 11203 } 11204 return true; 11205 } 11206 11207 enum kfunc_ptr_arg_type { 11208 KF_ARG_PTR_TO_CTX, 11209 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 11210 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 11211 KF_ARG_PTR_TO_DYNPTR, 11212 KF_ARG_PTR_TO_ITER, 11213 KF_ARG_PTR_TO_LIST_HEAD, 11214 KF_ARG_PTR_TO_LIST_NODE, 11215 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 11216 KF_ARG_PTR_TO_MEM, 11217 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 11218 KF_ARG_PTR_TO_CALLBACK, 11219 KF_ARG_PTR_TO_RB_ROOT, 11220 KF_ARG_PTR_TO_RB_NODE, 11221 KF_ARG_PTR_TO_NULL, 11222 KF_ARG_PTR_TO_CONST_STR, 11223 KF_ARG_PTR_TO_MAP, 11224 KF_ARG_PTR_TO_WORKQUEUE, 11225 }; 11226 11227 enum special_kfunc_type { 11228 KF_bpf_obj_new_impl, 11229 KF_bpf_obj_drop_impl, 11230 KF_bpf_refcount_acquire_impl, 11231 KF_bpf_list_push_front_impl, 11232 KF_bpf_list_push_back_impl, 11233 KF_bpf_list_pop_front, 11234 KF_bpf_list_pop_back, 11235 KF_bpf_cast_to_kern_ctx, 11236 KF_bpf_rdonly_cast, 11237 KF_bpf_rcu_read_lock, 11238 KF_bpf_rcu_read_unlock, 11239 KF_bpf_rbtree_remove, 11240 KF_bpf_rbtree_add_impl, 11241 KF_bpf_rbtree_first, 11242 KF_bpf_dynptr_from_skb, 11243 KF_bpf_dynptr_from_xdp, 11244 KF_bpf_dynptr_slice, 11245 KF_bpf_dynptr_slice_rdwr, 11246 KF_bpf_dynptr_clone, 11247 KF_bpf_percpu_obj_new_impl, 11248 KF_bpf_percpu_obj_drop_impl, 11249 KF_bpf_throw, 11250 KF_bpf_wq_set_callback_impl, 11251 KF_bpf_preempt_disable, 11252 KF_bpf_preempt_enable, 11253 KF_bpf_iter_css_task_new, 11254 KF_bpf_session_cookie, 11255 }; 11256 11257 BTF_SET_START(special_kfunc_set) 11258 BTF_ID(func, bpf_obj_new_impl) 11259 BTF_ID(func, bpf_obj_drop_impl) 11260 BTF_ID(func, bpf_refcount_acquire_impl) 11261 BTF_ID(func, bpf_list_push_front_impl) 11262 BTF_ID(func, bpf_list_push_back_impl) 11263 BTF_ID(func, bpf_list_pop_front) 11264 BTF_ID(func, bpf_list_pop_back) 11265 BTF_ID(func, bpf_cast_to_kern_ctx) 11266 BTF_ID(func, bpf_rdonly_cast) 11267 BTF_ID(func, bpf_rbtree_remove) 11268 BTF_ID(func, bpf_rbtree_add_impl) 11269 BTF_ID(func, bpf_rbtree_first) 11270 BTF_ID(func, bpf_dynptr_from_skb) 11271 BTF_ID(func, bpf_dynptr_from_xdp) 11272 BTF_ID(func, bpf_dynptr_slice) 11273 BTF_ID(func, bpf_dynptr_slice_rdwr) 11274 BTF_ID(func, bpf_dynptr_clone) 11275 BTF_ID(func, bpf_percpu_obj_new_impl) 11276 BTF_ID(func, bpf_percpu_obj_drop_impl) 11277 BTF_ID(func, bpf_throw) 11278 BTF_ID(func, bpf_wq_set_callback_impl) 11279 #ifdef CONFIG_CGROUPS 11280 BTF_ID(func, bpf_iter_css_task_new) 11281 #endif 11282 BTF_SET_END(special_kfunc_set) 11283 11284 BTF_ID_LIST(special_kfunc_list) 11285 BTF_ID(func, bpf_obj_new_impl) 11286 BTF_ID(func, bpf_obj_drop_impl) 11287 BTF_ID(func, bpf_refcount_acquire_impl) 11288 BTF_ID(func, bpf_list_push_front_impl) 11289 BTF_ID(func, bpf_list_push_back_impl) 11290 BTF_ID(func, bpf_list_pop_front) 11291 BTF_ID(func, bpf_list_pop_back) 11292 BTF_ID(func, bpf_cast_to_kern_ctx) 11293 BTF_ID(func, bpf_rdonly_cast) 11294 BTF_ID(func, bpf_rcu_read_lock) 11295 BTF_ID(func, bpf_rcu_read_unlock) 11296 BTF_ID(func, bpf_rbtree_remove) 11297 BTF_ID(func, bpf_rbtree_add_impl) 11298 BTF_ID(func, bpf_rbtree_first) 11299 BTF_ID(func, bpf_dynptr_from_skb) 11300 BTF_ID(func, bpf_dynptr_from_xdp) 11301 BTF_ID(func, bpf_dynptr_slice) 11302 BTF_ID(func, bpf_dynptr_slice_rdwr) 11303 BTF_ID(func, bpf_dynptr_clone) 11304 BTF_ID(func, bpf_percpu_obj_new_impl) 11305 BTF_ID(func, bpf_percpu_obj_drop_impl) 11306 BTF_ID(func, bpf_throw) 11307 BTF_ID(func, bpf_wq_set_callback_impl) 11308 BTF_ID(func, bpf_preempt_disable) 11309 BTF_ID(func, bpf_preempt_enable) 11310 #ifdef CONFIG_CGROUPS 11311 BTF_ID(func, bpf_iter_css_task_new) 11312 #else 11313 BTF_ID_UNUSED 11314 #endif 11315 #ifdef CONFIG_BPF_EVENTS 11316 BTF_ID(func, bpf_session_cookie) 11317 #else 11318 BTF_ID_UNUSED 11319 #endif 11320 11321 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 11322 { 11323 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 11324 meta->arg_owning_ref) { 11325 return false; 11326 } 11327 11328 return meta->kfunc_flags & KF_RET_NULL; 11329 } 11330 11331 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 11332 { 11333 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 11334 } 11335 11336 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 11337 { 11338 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 11339 } 11340 11341 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta) 11342 { 11343 return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable]; 11344 } 11345 11346 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta) 11347 { 11348 return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable]; 11349 } 11350 11351 static enum kfunc_ptr_arg_type 11352 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 11353 struct bpf_kfunc_call_arg_meta *meta, 11354 const struct btf_type *t, const struct btf_type *ref_t, 11355 const char *ref_tname, const struct btf_param *args, 11356 int argno, int nargs) 11357 { 11358 u32 regno = argno + 1; 11359 struct bpf_reg_state *regs = cur_regs(env); 11360 struct bpf_reg_state *reg = ®s[regno]; 11361 bool arg_mem_size = false; 11362 11363 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 11364 return KF_ARG_PTR_TO_CTX; 11365 11366 /* In this function, we verify the kfunc's BTF as per the argument type, 11367 * leaving the rest of the verification with respect to the register 11368 * type to our caller. When a set of conditions hold in the BTF type of 11369 * arguments, we resolve it to a known kfunc_ptr_arg_type. 11370 */ 11371 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 11372 return KF_ARG_PTR_TO_CTX; 11373 11374 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg)) 11375 return KF_ARG_PTR_TO_NULL; 11376 11377 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 11378 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 11379 11380 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 11381 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 11382 11383 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 11384 return KF_ARG_PTR_TO_DYNPTR; 11385 11386 if (is_kfunc_arg_iter(meta, argno, &args[argno])) 11387 return KF_ARG_PTR_TO_ITER; 11388 11389 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 11390 return KF_ARG_PTR_TO_LIST_HEAD; 11391 11392 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 11393 return KF_ARG_PTR_TO_LIST_NODE; 11394 11395 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 11396 return KF_ARG_PTR_TO_RB_ROOT; 11397 11398 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 11399 return KF_ARG_PTR_TO_RB_NODE; 11400 11401 if (is_kfunc_arg_const_str(meta->btf, &args[argno])) 11402 return KF_ARG_PTR_TO_CONST_STR; 11403 11404 if (is_kfunc_arg_map(meta->btf, &args[argno])) 11405 return KF_ARG_PTR_TO_MAP; 11406 11407 if (is_kfunc_arg_wq(meta->btf, &args[argno])) 11408 return KF_ARG_PTR_TO_WORKQUEUE; 11409 11410 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 11411 if (!btf_type_is_struct(ref_t)) { 11412 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 11413 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 11414 return -EINVAL; 11415 } 11416 return KF_ARG_PTR_TO_BTF_ID; 11417 } 11418 11419 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 11420 return KF_ARG_PTR_TO_CALLBACK; 11421 11422 if (argno + 1 < nargs && 11423 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 11424 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 11425 arg_mem_size = true; 11426 11427 /* This is the catch all argument type of register types supported by 11428 * check_helper_mem_access. However, we only allow when argument type is 11429 * pointer to scalar, or struct composed (recursively) of scalars. When 11430 * arg_mem_size is true, the pointer can be void *. 11431 */ 11432 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 11433 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 11434 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 11435 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 11436 return -EINVAL; 11437 } 11438 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 11439 } 11440 11441 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 11442 struct bpf_reg_state *reg, 11443 const struct btf_type *ref_t, 11444 const char *ref_tname, u32 ref_id, 11445 struct bpf_kfunc_call_arg_meta *meta, 11446 int argno) 11447 { 11448 const struct btf_type *reg_ref_t; 11449 bool strict_type_match = false; 11450 const struct btf *reg_btf; 11451 const char *reg_ref_tname; 11452 bool taking_projection; 11453 bool struct_same; 11454 u32 reg_ref_id; 11455 11456 if (base_type(reg->type) == PTR_TO_BTF_ID) { 11457 reg_btf = reg->btf; 11458 reg_ref_id = reg->btf_id; 11459 } else { 11460 reg_btf = btf_vmlinux; 11461 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 11462 } 11463 11464 /* Enforce strict type matching for calls to kfuncs that are acquiring 11465 * or releasing a reference, or are no-cast aliases. We do _not_ 11466 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 11467 * as we want to enable BPF programs to pass types that are bitwise 11468 * equivalent without forcing them to explicitly cast with something 11469 * like bpf_cast_to_kern_ctx(). 11470 * 11471 * For example, say we had a type like the following: 11472 * 11473 * struct bpf_cpumask { 11474 * cpumask_t cpumask; 11475 * refcount_t usage; 11476 * }; 11477 * 11478 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 11479 * to a struct cpumask, so it would be safe to pass a struct 11480 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 11481 * 11482 * The philosophy here is similar to how we allow scalars of different 11483 * types to be passed to kfuncs as long as the size is the same. The 11484 * only difference here is that we're simply allowing 11485 * btf_struct_ids_match() to walk the struct at the 0th offset, and 11486 * resolve types. 11487 */ 11488 if ((is_kfunc_release(meta) && reg->ref_obj_id) || 11489 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 11490 strict_type_match = true; 11491 11492 WARN_ON_ONCE(is_kfunc_release(meta) && 11493 (reg->off || !tnum_is_const(reg->var_off) || 11494 reg->var_off.value)); 11495 11496 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 11497 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 11498 struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match); 11499 /* If kfunc is accepting a projection type (ie. __sk_buff), it cannot 11500 * actually use it -- it must cast to the underlying type. So we allow 11501 * caller to pass in the underlying type. 11502 */ 11503 taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname); 11504 if (!taking_projection && !struct_same) { 11505 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 11506 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 11507 btf_type_str(reg_ref_t), reg_ref_tname); 11508 return -EINVAL; 11509 } 11510 return 0; 11511 } 11512 11513 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11514 { 11515 struct bpf_verifier_state *state = env->cur_state; 11516 struct btf_record *rec = reg_btf_record(reg); 11517 11518 if (!state->active_lock.ptr) { 11519 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 11520 return -EFAULT; 11521 } 11522 11523 if (type_flag(reg->type) & NON_OWN_REF) { 11524 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 11525 return -EFAULT; 11526 } 11527 11528 reg->type |= NON_OWN_REF; 11529 if (rec->refcount_off >= 0) 11530 reg->type |= MEM_RCU; 11531 11532 return 0; 11533 } 11534 11535 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 11536 { 11537 struct bpf_func_state *state, *unused; 11538 struct bpf_reg_state *reg; 11539 int i; 11540 11541 state = cur_func(env); 11542 11543 if (!ref_obj_id) { 11544 verbose(env, "verifier internal error: ref_obj_id is zero for " 11545 "owning -> non-owning conversion\n"); 11546 return -EFAULT; 11547 } 11548 11549 for (i = 0; i < state->acquired_refs; i++) { 11550 if (state->refs[i].id != ref_obj_id) 11551 continue; 11552 11553 /* Clear ref_obj_id here so release_reference doesn't clobber 11554 * the whole reg 11555 */ 11556 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11557 if (reg->ref_obj_id == ref_obj_id) { 11558 reg->ref_obj_id = 0; 11559 ref_set_non_owning(env, reg); 11560 } 11561 })); 11562 return 0; 11563 } 11564 11565 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 11566 return -EFAULT; 11567 } 11568 11569 /* Implementation details: 11570 * 11571 * Each register points to some region of memory, which we define as an 11572 * allocation. Each allocation may embed a bpf_spin_lock which protects any 11573 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 11574 * allocation. The lock and the data it protects are colocated in the same 11575 * memory region. 11576 * 11577 * Hence, everytime a register holds a pointer value pointing to such 11578 * allocation, the verifier preserves a unique reg->id for it. 11579 * 11580 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 11581 * bpf_spin_lock is called. 11582 * 11583 * To enable this, lock state in the verifier captures two values: 11584 * active_lock.ptr = Register's type specific pointer 11585 * active_lock.id = A unique ID for each register pointer value 11586 * 11587 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11588 * supported register types. 11589 * 11590 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11591 * allocated objects is the reg->btf pointer. 11592 * 11593 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11594 * can establish the provenance of the map value statically for each distinct 11595 * lookup into such maps. They always contain a single map value hence unique 11596 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11597 * 11598 * So, in case of global variables, they use array maps with max_entries = 1, 11599 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11600 * into the same map value as max_entries is 1, as described above). 11601 * 11602 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11603 * outer map pointer (in verifier context), but each lookup into an inner map 11604 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11605 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11606 * will get different reg->id assigned to each lookup, hence different 11607 * active_lock.id. 11608 * 11609 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11610 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11611 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11612 */ 11613 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11614 { 11615 void *ptr; 11616 u32 id; 11617 11618 switch ((int)reg->type) { 11619 case PTR_TO_MAP_VALUE: 11620 ptr = reg->map_ptr; 11621 break; 11622 case PTR_TO_BTF_ID | MEM_ALLOC: 11623 ptr = reg->btf; 11624 break; 11625 default: 11626 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 11627 return -EFAULT; 11628 } 11629 id = reg->id; 11630 11631 if (!env->cur_state->active_lock.ptr) 11632 return -EINVAL; 11633 if (env->cur_state->active_lock.ptr != ptr || 11634 env->cur_state->active_lock.id != id) { 11635 verbose(env, "held lock and object are not in the same allocation\n"); 11636 return -EINVAL; 11637 } 11638 return 0; 11639 } 11640 11641 static bool is_bpf_list_api_kfunc(u32 btf_id) 11642 { 11643 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11644 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11645 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11646 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 11647 } 11648 11649 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11650 { 11651 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 11652 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11653 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 11654 } 11655 11656 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11657 { 11658 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 11659 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11660 } 11661 11662 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11663 { 11664 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11665 } 11666 11667 static bool is_async_callback_calling_kfunc(u32 btf_id) 11668 { 11669 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl]; 11670 } 11671 11672 static bool is_bpf_throw_kfunc(struct bpf_insn *insn) 11673 { 11674 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 11675 insn->imm == special_kfunc_list[KF_bpf_throw]; 11676 } 11677 11678 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id) 11679 { 11680 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl]; 11681 } 11682 11683 static bool is_callback_calling_kfunc(u32 btf_id) 11684 { 11685 return is_sync_callback_calling_kfunc(btf_id) || 11686 is_async_callback_calling_kfunc(btf_id); 11687 } 11688 11689 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11690 { 11691 return is_bpf_rbtree_api_kfunc(btf_id); 11692 } 11693 11694 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11695 enum btf_field_type head_field_type, 11696 u32 kfunc_btf_id) 11697 { 11698 bool ret; 11699 11700 switch (head_field_type) { 11701 case BPF_LIST_HEAD: 11702 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11703 break; 11704 case BPF_RB_ROOT: 11705 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11706 break; 11707 default: 11708 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11709 btf_field_type_name(head_field_type)); 11710 return false; 11711 } 11712 11713 if (!ret) 11714 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11715 btf_field_type_name(head_field_type)); 11716 return ret; 11717 } 11718 11719 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11720 enum btf_field_type node_field_type, 11721 u32 kfunc_btf_id) 11722 { 11723 bool ret; 11724 11725 switch (node_field_type) { 11726 case BPF_LIST_NODE: 11727 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11728 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 11729 break; 11730 case BPF_RB_NODE: 11731 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11732 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 11733 break; 11734 default: 11735 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11736 btf_field_type_name(node_field_type)); 11737 return false; 11738 } 11739 11740 if (!ret) 11741 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11742 btf_field_type_name(node_field_type)); 11743 return ret; 11744 } 11745 11746 static int 11747 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11748 struct bpf_reg_state *reg, u32 regno, 11749 struct bpf_kfunc_call_arg_meta *meta, 11750 enum btf_field_type head_field_type, 11751 struct btf_field **head_field) 11752 { 11753 const char *head_type_name; 11754 struct btf_field *field; 11755 struct btf_record *rec; 11756 u32 head_off; 11757 11758 if (meta->btf != btf_vmlinux) { 11759 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11760 return -EFAULT; 11761 } 11762 11763 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11764 return -EFAULT; 11765 11766 head_type_name = btf_field_type_name(head_field_type); 11767 if (!tnum_is_const(reg->var_off)) { 11768 verbose(env, 11769 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11770 regno, head_type_name); 11771 return -EINVAL; 11772 } 11773 11774 rec = reg_btf_record(reg); 11775 head_off = reg->off + reg->var_off.value; 11776 field = btf_record_find(rec, head_off, head_field_type); 11777 if (!field) { 11778 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11779 return -EINVAL; 11780 } 11781 11782 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11783 if (check_reg_allocation_locked(env, reg)) { 11784 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11785 rec->spin_lock_off, head_type_name); 11786 return -EINVAL; 11787 } 11788 11789 if (*head_field) { 11790 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 11791 return -EFAULT; 11792 } 11793 *head_field = field; 11794 return 0; 11795 } 11796 11797 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11798 struct bpf_reg_state *reg, u32 regno, 11799 struct bpf_kfunc_call_arg_meta *meta) 11800 { 11801 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 11802 &meta->arg_list_head.field); 11803 } 11804 11805 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11806 struct bpf_reg_state *reg, u32 regno, 11807 struct bpf_kfunc_call_arg_meta *meta) 11808 { 11809 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 11810 &meta->arg_rbtree_root.field); 11811 } 11812 11813 static int 11814 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11815 struct bpf_reg_state *reg, u32 regno, 11816 struct bpf_kfunc_call_arg_meta *meta, 11817 enum btf_field_type head_field_type, 11818 enum btf_field_type node_field_type, 11819 struct btf_field **node_field) 11820 { 11821 const char *node_type_name; 11822 const struct btf_type *et, *t; 11823 struct btf_field *field; 11824 u32 node_off; 11825 11826 if (meta->btf != btf_vmlinux) { 11827 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11828 return -EFAULT; 11829 } 11830 11831 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11832 return -EFAULT; 11833 11834 node_type_name = btf_field_type_name(node_field_type); 11835 if (!tnum_is_const(reg->var_off)) { 11836 verbose(env, 11837 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11838 regno, node_type_name); 11839 return -EINVAL; 11840 } 11841 11842 node_off = reg->off + reg->var_off.value; 11843 field = reg_find_field_offset(reg, node_off, node_field_type); 11844 if (!field) { 11845 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11846 return -EINVAL; 11847 } 11848 11849 field = *node_field; 11850 11851 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11852 t = btf_type_by_id(reg->btf, reg->btf_id); 11853 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11854 field->graph_root.value_btf_id, true)) { 11855 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11856 "in struct %s, but arg is at offset=%d in struct %s\n", 11857 btf_field_type_name(head_field_type), 11858 btf_field_type_name(node_field_type), 11859 field->graph_root.node_offset, 11860 btf_name_by_offset(field->graph_root.btf, et->name_off), 11861 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11862 return -EINVAL; 11863 } 11864 meta->arg_btf = reg->btf; 11865 meta->arg_btf_id = reg->btf_id; 11866 11867 if (node_off != field->graph_root.node_offset) { 11868 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11869 node_off, btf_field_type_name(node_field_type), 11870 field->graph_root.node_offset, 11871 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11872 return -EINVAL; 11873 } 11874 11875 return 0; 11876 } 11877 11878 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11879 struct bpf_reg_state *reg, u32 regno, 11880 struct bpf_kfunc_call_arg_meta *meta) 11881 { 11882 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11883 BPF_LIST_HEAD, BPF_LIST_NODE, 11884 &meta->arg_list_head.field); 11885 } 11886 11887 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11888 struct bpf_reg_state *reg, u32 regno, 11889 struct bpf_kfunc_call_arg_meta *meta) 11890 { 11891 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11892 BPF_RB_ROOT, BPF_RB_NODE, 11893 &meta->arg_rbtree_root.field); 11894 } 11895 11896 /* 11897 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 11898 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 11899 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 11900 * them can only be attached to some specific hook points. 11901 */ 11902 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 11903 { 11904 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11905 11906 switch (prog_type) { 11907 case BPF_PROG_TYPE_LSM: 11908 return true; 11909 case BPF_PROG_TYPE_TRACING: 11910 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 11911 return true; 11912 fallthrough; 11913 default: 11914 return in_sleepable(env); 11915 } 11916 } 11917 11918 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11919 int insn_idx) 11920 { 11921 const char *func_name = meta->func_name, *ref_tname; 11922 const struct btf *btf = meta->btf; 11923 const struct btf_param *args; 11924 struct btf_record *rec; 11925 u32 i, nargs; 11926 int ret; 11927 11928 args = (const struct btf_param *)(meta->func_proto + 1); 11929 nargs = btf_type_vlen(meta->func_proto); 11930 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 11931 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11932 MAX_BPF_FUNC_REG_ARGS); 11933 return -EINVAL; 11934 } 11935 11936 /* Check that BTF function arguments match actual types that the 11937 * verifier sees. 11938 */ 11939 for (i = 0; i < nargs; i++) { 11940 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 11941 const struct btf_type *t, *ref_t, *resolve_ret; 11942 enum bpf_arg_type arg_type = ARG_DONTCARE; 11943 u32 regno = i + 1, ref_id, type_size; 11944 bool is_ret_buf_sz = false; 11945 int kf_arg_type; 11946 11947 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11948 11949 if (is_kfunc_arg_ignore(btf, &args[i])) 11950 continue; 11951 11952 if (btf_type_is_scalar(t)) { 11953 if (reg->type != SCALAR_VALUE) { 11954 verbose(env, "R%d is not a scalar\n", regno); 11955 return -EINVAL; 11956 } 11957 11958 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11959 if (meta->arg_constant.found) { 11960 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11961 return -EFAULT; 11962 } 11963 if (!tnum_is_const(reg->var_off)) { 11964 verbose(env, "R%d must be a known constant\n", regno); 11965 return -EINVAL; 11966 } 11967 ret = mark_chain_precision(env, regno); 11968 if (ret < 0) 11969 return ret; 11970 meta->arg_constant.found = true; 11971 meta->arg_constant.value = reg->var_off.value; 11972 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 11973 meta->r0_rdonly = true; 11974 is_ret_buf_sz = true; 11975 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 11976 is_ret_buf_sz = true; 11977 } 11978 11979 if (is_ret_buf_sz) { 11980 if (meta->r0_size) { 11981 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 11982 return -EINVAL; 11983 } 11984 11985 if (!tnum_is_const(reg->var_off)) { 11986 verbose(env, "R%d is not a const\n", regno); 11987 return -EINVAL; 11988 } 11989 11990 meta->r0_size = reg->var_off.value; 11991 ret = mark_chain_precision(env, regno); 11992 if (ret) 11993 return ret; 11994 } 11995 continue; 11996 } 11997 11998 if (!btf_type_is_ptr(t)) { 11999 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 12000 return -EINVAL; 12001 } 12002 12003 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 12004 (register_is_null(reg) || type_may_be_null(reg->type)) && 12005 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 12006 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 12007 return -EACCES; 12008 } 12009 12010 if (reg->ref_obj_id) { 12011 if (is_kfunc_release(meta) && meta->ref_obj_id) { 12012 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 12013 regno, reg->ref_obj_id, 12014 meta->ref_obj_id); 12015 return -EFAULT; 12016 } 12017 meta->ref_obj_id = reg->ref_obj_id; 12018 if (is_kfunc_release(meta)) 12019 meta->release_regno = regno; 12020 } 12021 12022 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 12023 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12024 12025 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 12026 if (kf_arg_type < 0) 12027 return kf_arg_type; 12028 12029 switch (kf_arg_type) { 12030 case KF_ARG_PTR_TO_NULL: 12031 continue; 12032 case KF_ARG_PTR_TO_MAP: 12033 if (!reg->map_ptr) { 12034 verbose(env, "pointer in R%d isn't map pointer\n", regno); 12035 return -EINVAL; 12036 } 12037 if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) { 12038 /* Use map_uid (which is unique id of inner map) to reject: 12039 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 12040 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 12041 * if (inner_map1 && inner_map2) { 12042 * wq = bpf_map_lookup_elem(inner_map1); 12043 * if (wq) 12044 * // mismatch would have been allowed 12045 * bpf_wq_init(wq, inner_map2); 12046 * } 12047 * 12048 * Comparing map_ptr is enough to distinguish normal and outer maps. 12049 */ 12050 if (meta->map.ptr != reg->map_ptr || 12051 meta->map.uid != reg->map_uid) { 12052 verbose(env, 12053 "workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 12054 meta->map.uid, reg->map_uid); 12055 return -EINVAL; 12056 } 12057 } 12058 meta->map.ptr = reg->map_ptr; 12059 meta->map.uid = reg->map_uid; 12060 fallthrough; 12061 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 12062 case KF_ARG_PTR_TO_BTF_ID: 12063 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 12064 break; 12065 12066 if (!is_trusted_reg(reg)) { 12067 if (!is_kfunc_rcu(meta)) { 12068 verbose(env, "R%d must be referenced or trusted\n", regno); 12069 return -EINVAL; 12070 } 12071 if (!is_rcu_reg(reg)) { 12072 verbose(env, "R%d must be a rcu pointer\n", regno); 12073 return -EINVAL; 12074 } 12075 } 12076 fallthrough; 12077 case KF_ARG_PTR_TO_CTX: 12078 case KF_ARG_PTR_TO_DYNPTR: 12079 case KF_ARG_PTR_TO_ITER: 12080 case KF_ARG_PTR_TO_LIST_HEAD: 12081 case KF_ARG_PTR_TO_LIST_NODE: 12082 case KF_ARG_PTR_TO_RB_ROOT: 12083 case KF_ARG_PTR_TO_RB_NODE: 12084 case KF_ARG_PTR_TO_MEM: 12085 case KF_ARG_PTR_TO_MEM_SIZE: 12086 case KF_ARG_PTR_TO_CALLBACK: 12087 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12088 case KF_ARG_PTR_TO_CONST_STR: 12089 case KF_ARG_PTR_TO_WORKQUEUE: 12090 break; 12091 default: 12092 WARN_ON_ONCE(1); 12093 return -EFAULT; 12094 } 12095 12096 if (is_kfunc_release(meta) && reg->ref_obj_id) 12097 arg_type |= OBJ_RELEASE; 12098 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 12099 if (ret < 0) 12100 return ret; 12101 12102 switch (kf_arg_type) { 12103 case KF_ARG_PTR_TO_CTX: 12104 if (reg->type != PTR_TO_CTX) { 12105 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", 12106 i, reg_type_str(env, reg->type)); 12107 return -EINVAL; 12108 } 12109 12110 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12111 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 12112 if (ret < 0) 12113 return -EINVAL; 12114 meta->ret_btf_id = ret; 12115 } 12116 break; 12117 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 12118 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 12119 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) { 12120 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i); 12121 return -EINVAL; 12122 } 12123 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 12124 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 12125 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i); 12126 return -EINVAL; 12127 } 12128 } else { 12129 verbose(env, "arg#%d expected pointer to allocated object\n", i); 12130 return -EINVAL; 12131 } 12132 if (!reg->ref_obj_id) { 12133 verbose(env, "allocated object must be referenced\n"); 12134 return -EINVAL; 12135 } 12136 if (meta->btf == btf_vmlinux) { 12137 meta->arg_btf = reg->btf; 12138 meta->arg_btf_id = reg->btf_id; 12139 } 12140 break; 12141 case KF_ARG_PTR_TO_DYNPTR: 12142 { 12143 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 12144 int clone_ref_obj_id = 0; 12145 12146 if (reg->type == CONST_PTR_TO_DYNPTR) 12147 dynptr_arg_type |= MEM_RDONLY; 12148 12149 if (is_kfunc_arg_uninit(btf, &args[i])) 12150 dynptr_arg_type |= MEM_UNINIT; 12151 12152 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 12153 dynptr_arg_type |= DYNPTR_TYPE_SKB; 12154 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 12155 dynptr_arg_type |= DYNPTR_TYPE_XDP; 12156 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 12157 (dynptr_arg_type & MEM_UNINIT)) { 12158 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 12159 12160 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 12161 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 12162 return -EFAULT; 12163 } 12164 12165 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 12166 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 12167 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 12168 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 12169 return -EFAULT; 12170 } 12171 } 12172 12173 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 12174 if (ret < 0) 12175 return ret; 12176 12177 if (!(dynptr_arg_type & MEM_UNINIT)) { 12178 int id = dynptr_id(env, reg); 12179 12180 if (id < 0) { 12181 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 12182 return id; 12183 } 12184 meta->initialized_dynptr.id = id; 12185 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 12186 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 12187 } 12188 12189 break; 12190 } 12191 case KF_ARG_PTR_TO_ITER: 12192 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 12193 if (!check_css_task_iter_allowlist(env)) { 12194 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 12195 return -EINVAL; 12196 } 12197 } 12198 ret = process_iter_arg(env, regno, insn_idx, meta); 12199 if (ret < 0) 12200 return ret; 12201 break; 12202 case KF_ARG_PTR_TO_LIST_HEAD: 12203 if (reg->type != PTR_TO_MAP_VALUE && 12204 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12205 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 12206 return -EINVAL; 12207 } 12208 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 12209 verbose(env, "allocated object must be referenced\n"); 12210 return -EINVAL; 12211 } 12212 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 12213 if (ret < 0) 12214 return ret; 12215 break; 12216 case KF_ARG_PTR_TO_RB_ROOT: 12217 if (reg->type != PTR_TO_MAP_VALUE && 12218 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12219 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 12220 return -EINVAL; 12221 } 12222 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 12223 verbose(env, "allocated object must be referenced\n"); 12224 return -EINVAL; 12225 } 12226 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 12227 if (ret < 0) 12228 return ret; 12229 break; 12230 case KF_ARG_PTR_TO_LIST_NODE: 12231 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12232 verbose(env, "arg#%d expected pointer to allocated object\n", i); 12233 return -EINVAL; 12234 } 12235 if (!reg->ref_obj_id) { 12236 verbose(env, "allocated object must be referenced\n"); 12237 return -EINVAL; 12238 } 12239 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 12240 if (ret < 0) 12241 return ret; 12242 break; 12243 case KF_ARG_PTR_TO_RB_NODE: 12244 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 12245 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 12246 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 12247 return -EINVAL; 12248 } 12249 if (in_rbtree_lock_required_cb(env)) { 12250 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 12251 return -EINVAL; 12252 } 12253 } else { 12254 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12255 verbose(env, "arg#%d expected pointer to allocated object\n", i); 12256 return -EINVAL; 12257 } 12258 if (!reg->ref_obj_id) { 12259 verbose(env, "allocated object must be referenced\n"); 12260 return -EINVAL; 12261 } 12262 } 12263 12264 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 12265 if (ret < 0) 12266 return ret; 12267 break; 12268 case KF_ARG_PTR_TO_MAP: 12269 /* If argument has '__map' suffix expect 'struct bpf_map *' */ 12270 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP]; 12271 ref_t = btf_type_by_id(btf_vmlinux, ref_id); 12272 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12273 fallthrough; 12274 case KF_ARG_PTR_TO_BTF_ID: 12275 /* Only base_type is checked, further checks are done here */ 12276 if ((base_type(reg->type) != PTR_TO_BTF_ID || 12277 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 12278 !reg2btf_ids[base_type(reg->type)]) { 12279 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 12280 verbose(env, "expected %s or socket\n", 12281 reg_type_str(env, base_type(reg->type) | 12282 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 12283 return -EINVAL; 12284 } 12285 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 12286 if (ret < 0) 12287 return ret; 12288 break; 12289 case KF_ARG_PTR_TO_MEM: 12290 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 12291 if (IS_ERR(resolve_ret)) { 12292 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 12293 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 12294 return -EINVAL; 12295 } 12296 ret = check_mem_reg(env, reg, regno, type_size); 12297 if (ret < 0) 12298 return ret; 12299 break; 12300 case KF_ARG_PTR_TO_MEM_SIZE: 12301 { 12302 struct bpf_reg_state *buff_reg = ®s[regno]; 12303 const struct btf_param *buff_arg = &args[i]; 12304 struct bpf_reg_state *size_reg = ®s[regno + 1]; 12305 const struct btf_param *size_arg = &args[i + 1]; 12306 12307 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 12308 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 12309 if (ret < 0) { 12310 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 12311 return ret; 12312 } 12313 } 12314 12315 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 12316 if (meta->arg_constant.found) { 12317 verbose(env, "verifier internal error: only one constant argument permitted\n"); 12318 return -EFAULT; 12319 } 12320 if (!tnum_is_const(size_reg->var_off)) { 12321 verbose(env, "R%d must be a known constant\n", regno + 1); 12322 return -EINVAL; 12323 } 12324 meta->arg_constant.found = true; 12325 meta->arg_constant.value = size_reg->var_off.value; 12326 } 12327 12328 /* Skip next '__sz' or '__szk' argument */ 12329 i++; 12330 break; 12331 } 12332 case KF_ARG_PTR_TO_CALLBACK: 12333 if (reg->type != PTR_TO_FUNC) { 12334 verbose(env, "arg%d expected pointer to func\n", i); 12335 return -EINVAL; 12336 } 12337 meta->subprogno = reg->subprogno; 12338 break; 12339 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12340 if (!type_is_ptr_alloc_obj(reg->type)) { 12341 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 12342 return -EINVAL; 12343 } 12344 if (!type_is_non_owning_ref(reg->type)) 12345 meta->arg_owning_ref = true; 12346 12347 rec = reg_btf_record(reg); 12348 if (!rec) { 12349 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 12350 return -EFAULT; 12351 } 12352 12353 if (rec->refcount_off < 0) { 12354 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 12355 return -EINVAL; 12356 } 12357 12358 meta->arg_btf = reg->btf; 12359 meta->arg_btf_id = reg->btf_id; 12360 break; 12361 case KF_ARG_PTR_TO_CONST_STR: 12362 if (reg->type != PTR_TO_MAP_VALUE) { 12363 verbose(env, "arg#%d doesn't point to a const string\n", i); 12364 return -EINVAL; 12365 } 12366 ret = check_reg_const_str(env, reg, regno); 12367 if (ret) 12368 return ret; 12369 break; 12370 case KF_ARG_PTR_TO_WORKQUEUE: 12371 if (reg->type != PTR_TO_MAP_VALUE) { 12372 verbose(env, "arg#%d doesn't point to a map value\n", i); 12373 return -EINVAL; 12374 } 12375 ret = process_wq_func(env, regno, meta); 12376 if (ret < 0) 12377 return ret; 12378 break; 12379 } 12380 } 12381 12382 if (is_kfunc_release(meta) && !meta->release_regno) { 12383 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 12384 func_name); 12385 return -EINVAL; 12386 } 12387 12388 return 0; 12389 } 12390 12391 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 12392 struct bpf_insn *insn, 12393 struct bpf_kfunc_call_arg_meta *meta, 12394 const char **kfunc_name) 12395 { 12396 const struct btf_type *func, *func_proto; 12397 u32 func_id, *kfunc_flags; 12398 const char *func_name; 12399 struct btf *desc_btf; 12400 12401 if (kfunc_name) 12402 *kfunc_name = NULL; 12403 12404 if (!insn->imm) 12405 return -EINVAL; 12406 12407 desc_btf = find_kfunc_desc_btf(env, insn->off); 12408 if (IS_ERR(desc_btf)) 12409 return PTR_ERR(desc_btf); 12410 12411 func_id = insn->imm; 12412 func = btf_type_by_id(desc_btf, func_id); 12413 func_name = btf_name_by_offset(desc_btf, func->name_off); 12414 if (kfunc_name) 12415 *kfunc_name = func_name; 12416 func_proto = btf_type_by_id(desc_btf, func->type); 12417 12418 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 12419 if (!kfunc_flags) { 12420 return -EACCES; 12421 } 12422 12423 memset(meta, 0, sizeof(*meta)); 12424 meta->btf = desc_btf; 12425 meta->func_id = func_id; 12426 meta->kfunc_flags = *kfunc_flags; 12427 meta->func_proto = func_proto; 12428 meta->func_name = func_name; 12429 12430 return 0; 12431 } 12432 12433 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 12434 12435 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 12436 int *insn_idx_p) 12437 { 12438 bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable; 12439 u32 i, nargs, ptr_type_id, release_ref_obj_id; 12440 struct bpf_reg_state *regs = cur_regs(env); 12441 const char *func_name, *ptr_type_name; 12442 const struct btf_type *t, *ptr_type; 12443 struct bpf_kfunc_call_arg_meta meta; 12444 struct bpf_insn_aux_data *insn_aux; 12445 int err, insn_idx = *insn_idx_p; 12446 const struct btf_param *args; 12447 const struct btf_type *ret_t; 12448 struct btf *desc_btf; 12449 12450 /* skip for now, but return error when we find this in fixup_kfunc_call */ 12451 if (!insn->imm) 12452 return 0; 12453 12454 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 12455 if (err == -EACCES && func_name) 12456 verbose(env, "calling kernel function %s is not allowed\n", func_name); 12457 if (err) 12458 return err; 12459 desc_btf = meta.btf; 12460 insn_aux = &env->insn_aux_data[insn_idx]; 12461 12462 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 12463 12464 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 12465 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 12466 return -EACCES; 12467 } 12468 12469 sleepable = is_kfunc_sleepable(&meta); 12470 if (sleepable && !in_sleepable(env)) { 12471 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 12472 return -EACCES; 12473 } 12474 12475 /* Check the arguments */ 12476 err = check_kfunc_args(env, &meta, insn_idx); 12477 if (err < 0) 12478 return err; 12479 12480 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12481 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12482 set_rbtree_add_callback_state); 12483 if (err) { 12484 verbose(env, "kfunc %s#%d failed callback verification\n", 12485 func_name, meta.func_id); 12486 return err; 12487 } 12488 } 12489 12490 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) { 12491 meta.r0_size = sizeof(u64); 12492 meta.r0_rdonly = false; 12493 } 12494 12495 if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) { 12496 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12497 set_timer_callback_state); 12498 if (err) { 12499 verbose(env, "kfunc %s#%d failed callback verification\n", 12500 func_name, meta.func_id); 12501 return err; 12502 } 12503 } 12504 12505 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 12506 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 12507 12508 preempt_disable = is_kfunc_bpf_preempt_disable(&meta); 12509 preempt_enable = is_kfunc_bpf_preempt_enable(&meta); 12510 12511 if (env->cur_state->active_rcu_lock) { 12512 struct bpf_func_state *state; 12513 struct bpf_reg_state *reg; 12514 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 12515 12516 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 12517 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 12518 return -EACCES; 12519 } 12520 12521 if (rcu_lock) { 12522 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 12523 return -EINVAL; 12524 } else if (rcu_unlock) { 12525 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({ 12526 if (reg->type & MEM_RCU) { 12527 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 12528 reg->type |= PTR_UNTRUSTED; 12529 } 12530 })); 12531 env->cur_state->active_rcu_lock = false; 12532 } else if (sleepable) { 12533 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 12534 return -EACCES; 12535 } 12536 } else if (rcu_lock) { 12537 env->cur_state->active_rcu_lock = true; 12538 } else if (rcu_unlock) { 12539 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 12540 return -EINVAL; 12541 } 12542 12543 if (env->cur_state->active_preempt_lock) { 12544 if (preempt_disable) { 12545 env->cur_state->active_preempt_lock++; 12546 } else if (preempt_enable) { 12547 env->cur_state->active_preempt_lock--; 12548 } else if (sleepable) { 12549 verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name); 12550 return -EACCES; 12551 } 12552 } else if (preempt_disable) { 12553 env->cur_state->active_preempt_lock++; 12554 } else if (preempt_enable) { 12555 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name); 12556 return -EINVAL; 12557 } 12558 12559 /* In case of release function, we get register number of refcounted 12560 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 12561 */ 12562 if (meta.release_regno) { 12563 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 12564 if (err) { 12565 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12566 func_name, meta.func_id); 12567 return err; 12568 } 12569 } 12570 12571 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 12572 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 12573 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12574 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 12575 insn_aux->insert_off = regs[BPF_REG_2].off; 12576 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 12577 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 12578 if (err) { 12579 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 12580 func_name, meta.func_id); 12581 return err; 12582 } 12583 12584 err = release_reference(env, release_ref_obj_id); 12585 if (err) { 12586 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12587 func_name, meta.func_id); 12588 return err; 12589 } 12590 } 12591 12592 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 12593 if (!bpf_jit_supports_exceptions()) { 12594 verbose(env, "JIT does not support calling kfunc %s#%d\n", 12595 func_name, meta.func_id); 12596 return -ENOTSUPP; 12597 } 12598 env->seen_exception = true; 12599 12600 /* In the case of the default callback, the cookie value passed 12601 * to bpf_throw becomes the return value of the program. 12602 */ 12603 if (!env->exception_callback_subprog) { 12604 err = check_return_code(env, BPF_REG_1, "R1"); 12605 if (err < 0) 12606 return err; 12607 } 12608 } 12609 12610 for (i = 0; i < CALLER_SAVED_REGS; i++) 12611 mark_reg_not_init(env, regs, caller_saved[i]); 12612 12613 /* Check return type */ 12614 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 12615 12616 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 12617 /* Only exception is bpf_obj_new_impl */ 12618 if (meta.btf != btf_vmlinux || 12619 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 12620 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] && 12621 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 12622 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 12623 return -EINVAL; 12624 } 12625 } 12626 12627 if (btf_type_is_scalar(t)) { 12628 mark_reg_unknown(env, regs, BPF_REG_0); 12629 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 12630 } else if (btf_type_is_ptr(t)) { 12631 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 12632 12633 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12634 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 12635 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12636 struct btf_struct_meta *struct_meta; 12637 struct btf *ret_btf; 12638 u32 ret_btf_id; 12639 12640 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set) 12641 return -ENOMEM; 12642 12643 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 12644 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 12645 return -EINVAL; 12646 } 12647 12648 ret_btf = env->prog->aux->btf; 12649 ret_btf_id = meta.arg_constant.value; 12650 12651 /* This may be NULL due to user not supplying a BTF */ 12652 if (!ret_btf) { 12653 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 12654 return -EINVAL; 12655 } 12656 12657 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 12658 if (!ret_t || !__btf_type_is_struct(ret_t)) { 12659 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 12660 return -EINVAL; 12661 } 12662 12663 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12664 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 12665 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 12666 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 12667 return -EINVAL; 12668 } 12669 12670 if (!bpf_global_percpu_ma_set) { 12671 mutex_lock(&bpf_percpu_ma_lock); 12672 if (!bpf_global_percpu_ma_set) { 12673 /* Charge memory allocated with bpf_global_percpu_ma to 12674 * root memcg. The obj_cgroup for root memcg is NULL. 12675 */ 12676 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 12677 if (!err) 12678 bpf_global_percpu_ma_set = true; 12679 } 12680 mutex_unlock(&bpf_percpu_ma_lock); 12681 if (err) 12682 return err; 12683 } 12684 12685 mutex_lock(&bpf_percpu_ma_lock); 12686 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 12687 mutex_unlock(&bpf_percpu_ma_lock); 12688 if (err) 12689 return err; 12690 } 12691 12692 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 12693 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12694 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 12695 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 12696 return -EINVAL; 12697 } 12698 12699 if (struct_meta) { 12700 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 12701 return -EINVAL; 12702 } 12703 } 12704 12705 mark_reg_known_zero(env, regs, BPF_REG_0); 12706 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12707 regs[BPF_REG_0].btf = ret_btf; 12708 regs[BPF_REG_0].btf_id = ret_btf_id; 12709 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) 12710 regs[BPF_REG_0].type |= MEM_PERCPU; 12711 12712 insn_aux->obj_new_size = ret_t->size; 12713 insn_aux->kptr_struct_meta = struct_meta; 12714 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 12715 mark_reg_known_zero(env, regs, BPF_REG_0); 12716 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12717 regs[BPF_REG_0].btf = meta.arg_btf; 12718 regs[BPF_REG_0].btf_id = meta.arg_btf_id; 12719 12720 insn_aux->kptr_struct_meta = 12721 btf_find_struct_meta(meta.arg_btf, 12722 meta.arg_btf_id); 12723 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 12724 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 12725 struct btf_field *field = meta.arg_list_head.field; 12726 12727 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12728 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12729 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12730 struct btf_field *field = meta.arg_rbtree_root.field; 12731 12732 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12733 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12734 mark_reg_known_zero(env, regs, BPF_REG_0); 12735 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 12736 regs[BPF_REG_0].btf = desc_btf; 12737 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 12738 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 12739 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 12740 if (!ret_t || !btf_type_is_struct(ret_t)) { 12741 verbose(env, 12742 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 12743 return -EINVAL; 12744 } 12745 12746 mark_reg_known_zero(env, regs, BPF_REG_0); 12747 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 12748 regs[BPF_REG_0].btf = desc_btf; 12749 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 12750 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 12751 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 12752 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 12753 12754 mark_reg_known_zero(env, regs, BPF_REG_0); 12755 12756 if (!meta.arg_constant.found) { 12757 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 12758 return -EFAULT; 12759 } 12760 12761 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 12762 12763 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 12764 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 12765 12766 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 12767 regs[BPF_REG_0].type |= MEM_RDONLY; 12768 } else { 12769 /* this will set env->seen_direct_write to true */ 12770 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 12771 verbose(env, "the prog does not allow writes to packet data\n"); 12772 return -EINVAL; 12773 } 12774 } 12775 12776 if (!meta.initialized_dynptr.id) { 12777 verbose(env, "verifier internal error: no dynptr id\n"); 12778 return -EFAULT; 12779 } 12780 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 12781 12782 /* we don't need to set BPF_REG_0's ref obj id 12783 * because packet slices are not refcounted (see 12784 * dynptr_type_refcounted) 12785 */ 12786 } else { 12787 verbose(env, "kernel function %s unhandled dynamic return type\n", 12788 meta.func_name); 12789 return -EFAULT; 12790 } 12791 } else if (btf_type_is_void(ptr_type)) { 12792 /* kfunc returning 'void *' is equivalent to returning scalar */ 12793 mark_reg_unknown(env, regs, BPF_REG_0); 12794 } else if (!__btf_type_is_struct(ptr_type)) { 12795 if (!meta.r0_size) { 12796 __u32 sz; 12797 12798 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 12799 meta.r0_size = sz; 12800 meta.r0_rdonly = true; 12801 } 12802 } 12803 if (!meta.r0_size) { 12804 ptr_type_name = btf_name_by_offset(desc_btf, 12805 ptr_type->name_off); 12806 verbose(env, 12807 "kernel function %s returns pointer type %s %s is not supported\n", 12808 func_name, 12809 btf_type_str(ptr_type), 12810 ptr_type_name); 12811 return -EINVAL; 12812 } 12813 12814 mark_reg_known_zero(env, regs, BPF_REG_0); 12815 regs[BPF_REG_0].type = PTR_TO_MEM; 12816 regs[BPF_REG_0].mem_size = meta.r0_size; 12817 12818 if (meta.r0_rdonly) 12819 regs[BPF_REG_0].type |= MEM_RDONLY; 12820 12821 /* Ensures we don't access the memory after a release_reference() */ 12822 if (meta.ref_obj_id) 12823 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 12824 } else { 12825 mark_reg_known_zero(env, regs, BPF_REG_0); 12826 regs[BPF_REG_0].btf = desc_btf; 12827 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 12828 regs[BPF_REG_0].btf_id = ptr_type_id; 12829 12830 if (is_iter_next_kfunc(&meta)) { 12831 struct bpf_reg_state *cur_iter; 12832 12833 cur_iter = get_iter_from_state(env->cur_state, &meta); 12834 12835 if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */ 12836 regs[BPF_REG_0].type |= MEM_RCU; 12837 else 12838 regs[BPF_REG_0].type |= PTR_TRUSTED; 12839 } 12840 } 12841 12842 if (is_kfunc_ret_null(&meta)) { 12843 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 12844 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 12845 regs[BPF_REG_0].id = ++env->id_gen; 12846 } 12847 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 12848 if (is_kfunc_acquire(&meta)) { 12849 int id = acquire_reference_state(env, insn_idx); 12850 12851 if (id < 0) 12852 return id; 12853 if (is_kfunc_ret_null(&meta)) 12854 regs[BPF_REG_0].id = id; 12855 regs[BPF_REG_0].ref_obj_id = id; 12856 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12857 ref_set_non_owning(env, ®s[BPF_REG_0]); 12858 } 12859 12860 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 12861 regs[BPF_REG_0].id = ++env->id_gen; 12862 } else if (btf_type_is_void(t)) { 12863 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12864 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 12865 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 12866 insn_aux->kptr_struct_meta = 12867 btf_find_struct_meta(meta.arg_btf, 12868 meta.arg_btf_id); 12869 } 12870 } 12871 } 12872 12873 nargs = btf_type_vlen(meta.func_proto); 12874 args = (const struct btf_param *)(meta.func_proto + 1); 12875 for (i = 0; i < nargs; i++) { 12876 u32 regno = i + 1; 12877 12878 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 12879 if (btf_type_is_ptr(t)) 12880 mark_btf_func_reg_size(env, regno, sizeof(void *)); 12881 else 12882 /* scalar. ensured by btf_check_kfunc_arg_match() */ 12883 mark_btf_func_reg_size(env, regno, t->size); 12884 } 12885 12886 if (is_iter_next_kfunc(&meta)) { 12887 err = process_iter_next_call(env, insn_idx, &meta); 12888 if (err) 12889 return err; 12890 } 12891 12892 return 0; 12893 } 12894 12895 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 12896 const struct bpf_reg_state *reg, 12897 enum bpf_reg_type type) 12898 { 12899 bool known = tnum_is_const(reg->var_off); 12900 s64 val = reg->var_off.value; 12901 s64 smin = reg->smin_value; 12902 12903 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 12904 verbose(env, "math between %s pointer and %lld is not allowed\n", 12905 reg_type_str(env, type), val); 12906 return false; 12907 } 12908 12909 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 12910 verbose(env, "%s pointer offset %d is not allowed\n", 12911 reg_type_str(env, type), reg->off); 12912 return false; 12913 } 12914 12915 if (smin == S64_MIN) { 12916 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 12917 reg_type_str(env, type)); 12918 return false; 12919 } 12920 12921 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 12922 verbose(env, "value %lld makes %s pointer be out of bounds\n", 12923 smin, reg_type_str(env, type)); 12924 return false; 12925 } 12926 12927 return true; 12928 } 12929 12930 enum { 12931 REASON_BOUNDS = -1, 12932 REASON_TYPE = -2, 12933 REASON_PATHS = -3, 12934 REASON_LIMIT = -4, 12935 REASON_STACK = -5, 12936 }; 12937 12938 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 12939 u32 *alu_limit, bool mask_to_left) 12940 { 12941 u32 max = 0, ptr_limit = 0; 12942 12943 switch (ptr_reg->type) { 12944 case PTR_TO_STACK: 12945 /* Offset 0 is out-of-bounds, but acceptable start for the 12946 * left direction, see BPF_REG_FP. Also, unknown scalar 12947 * offset where we would need to deal with min/max bounds is 12948 * currently prohibited for unprivileged. 12949 */ 12950 max = MAX_BPF_STACK + mask_to_left; 12951 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 12952 break; 12953 case PTR_TO_MAP_VALUE: 12954 max = ptr_reg->map_ptr->value_size; 12955 ptr_limit = (mask_to_left ? 12956 ptr_reg->smin_value : 12957 ptr_reg->umax_value) + ptr_reg->off; 12958 break; 12959 default: 12960 return REASON_TYPE; 12961 } 12962 12963 if (ptr_limit >= max) 12964 return REASON_LIMIT; 12965 *alu_limit = ptr_limit; 12966 return 0; 12967 } 12968 12969 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 12970 const struct bpf_insn *insn) 12971 { 12972 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 12973 } 12974 12975 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 12976 u32 alu_state, u32 alu_limit) 12977 { 12978 /* If we arrived here from different branches with different 12979 * state or limits to sanitize, then this won't work. 12980 */ 12981 if (aux->alu_state && 12982 (aux->alu_state != alu_state || 12983 aux->alu_limit != alu_limit)) 12984 return REASON_PATHS; 12985 12986 /* Corresponding fixup done in do_misc_fixups(). */ 12987 aux->alu_state = alu_state; 12988 aux->alu_limit = alu_limit; 12989 return 0; 12990 } 12991 12992 static int sanitize_val_alu(struct bpf_verifier_env *env, 12993 struct bpf_insn *insn) 12994 { 12995 struct bpf_insn_aux_data *aux = cur_aux(env); 12996 12997 if (can_skip_alu_sanitation(env, insn)) 12998 return 0; 12999 13000 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 13001 } 13002 13003 static bool sanitize_needed(u8 opcode) 13004 { 13005 return opcode == BPF_ADD || opcode == BPF_SUB; 13006 } 13007 13008 struct bpf_sanitize_info { 13009 struct bpf_insn_aux_data aux; 13010 bool mask_to_left; 13011 }; 13012 13013 static struct bpf_verifier_state * 13014 sanitize_speculative_path(struct bpf_verifier_env *env, 13015 const struct bpf_insn *insn, 13016 u32 next_idx, u32 curr_idx) 13017 { 13018 struct bpf_verifier_state *branch; 13019 struct bpf_reg_state *regs; 13020 13021 branch = push_stack(env, next_idx, curr_idx, true); 13022 if (branch && insn) { 13023 regs = branch->frame[branch->curframe]->regs; 13024 if (BPF_SRC(insn->code) == BPF_K) { 13025 mark_reg_unknown(env, regs, insn->dst_reg); 13026 } else if (BPF_SRC(insn->code) == BPF_X) { 13027 mark_reg_unknown(env, regs, insn->dst_reg); 13028 mark_reg_unknown(env, regs, insn->src_reg); 13029 } 13030 } 13031 return branch; 13032 } 13033 13034 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 13035 struct bpf_insn *insn, 13036 const struct bpf_reg_state *ptr_reg, 13037 const struct bpf_reg_state *off_reg, 13038 struct bpf_reg_state *dst_reg, 13039 struct bpf_sanitize_info *info, 13040 const bool commit_window) 13041 { 13042 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 13043 struct bpf_verifier_state *vstate = env->cur_state; 13044 bool off_is_imm = tnum_is_const(off_reg->var_off); 13045 bool off_is_neg = off_reg->smin_value < 0; 13046 bool ptr_is_dst_reg = ptr_reg == dst_reg; 13047 u8 opcode = BPF_OP(insn->code); 13048 u32 alu_state, alu_limit; 13049 struct bpf_reg_state tmp; 13050 bool ret; 13051 int err; 13052 13053 if (can_skip_alu_sanitation(env, insn)) 13054 return 0; 13055 13056 /* We already marked aux for masking from non-speculative 13057 * paths, thus we got here in the first place. We only care 13058 * to explore bad access from here. 13059 */ 13060 if (vstate->speculative) 13061 goto do_sim; 13062 13063 if (!commit_window) { 13064 if (!tnum_is_const(off_reg->var_off) && 13065 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 13066 return REASON_BOUNDS; 13067 13068 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 13069 (opcode == BPF_SUB && !off_is_neg); 13070 } 13071 13072 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 13073 if (err < 0) 13074 return err; 13075 13076 if (commit_window) { 13077 /* In commit phase we narrow the masking window based on 13078 * the observed pointer move after the simulated operation. 13079 */ 13080 alu_state = info->aux.alu_state; 13081 alu_limit = abs(info->aux.alu_limit - alu_limit); 13082 } else { 13083 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 13084 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 13085 alu_state |= ptr_is_dst_reg ? 13086 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 13087 13088 /* Limit pruning on unknown scalars to enable deep search for 13089 * potential masking differences from other program paths. 13090 */ 13091 if (!off_is_imm) 13092 env->explore_alu_limits = true; 13093 } 13094 13095 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 13096 if (err < 0) 13097 return err; 13098 do_sim: 13099 /* If we're in commit phase, we're done here given we already 13100 * pushed the truncated dst_reg into the speculative verification 13101 * stack. 13102 * 13103 * Also, when register is a known constant, we rewrite register-based 13104 * operation to immediate-based, and thus do not need masking (and as 13105 * a consequence, do not need to simulate the zero-truncation either). 13106 */ 13107 if (commit_window || off_is_imm) 13108 return 0; 13109 13110 /* Simulate and find potential out-of-bounds access under 13111 * speculative execution from truncation as a result of 13112 * masking when off was not within expected range. If off 13113 * sits in dst, then we temporarily need to move ptr there 13114 * to simulate dst (== 0) +/-= ptr. Needed, for example, 13115 * for cases where we use K-based arithmetic in one direction 13116 * and truncated reg-based in the other in order to explore 13117 * bad access. 13118 */ 13119 if (!ptr_is_dst_reg) { 13120 tmp = *dst_reg; 13121 copy_register_state(dst_reg, ptr_reg); 13122 } 13123 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 13124 env->insn_idx); 13125 if (!ptr_is_dst_reg && ret) 13126 *dst_reg = tmp; 13127 return !ret ? REASON_STACK : 0; 13128 } 13129 13130 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 13131 { 13132 struct bpf_verifier_state *vstate = env->cur_state; 13133 13134 /* If we simulate paths under speculation, we don't update the 13135 * insn as 'seen' such that when we verify unreachable paths in 13136 * the non-speculative domain, sanitize_dead_code() can still 13137 * rewrite/sanitize them. 13138 */ 13139 if (!vstate->speculative) 13140 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 13141 } 13142 13143 static int sanitize_err(struct bpf_verifier_env *env, 13144 const struct bpf_insn *insn, int reason, 13145 const struct bpf_reg_state *off_reg, 13146 const struct bpf_reg_state *dst_reg) 13147 { 13148 static const char *err = "pointer arithmetic with it prohibited for !root"; 13149 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 13150 u32 dst = insn->dst_reg, src = insn->src_reg; 13151 13152 switch (reason) { 13153 case REASON_BOUNDS: 13154 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 13155 off_reg == dst_reg ? dst : src, err); 13156 break; 13157 case REASON_TYPE: 13158 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 13159 off_reg == dst_reg ? src : dst, err); 13160 break; 13161 case REASON_PATHS: 13162 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 13163 dst, op, err); 13164 break; 13165 case REASON_LIMIT: 13166 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 13167 dst, op, err); 13168 break; 13169 case REASON_STACK: 13170 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 13171 dst, err); 13172 break; 13173 default: 13174 verbose(env, "verifier internal error: unknown reason (%d)\n", 13175 reason); 13176 break; 13177 } 13178 13179 return -EACCES; 13180 } 13181 13182 /* check that stack access falls within stack limits and that 'reg' doesn't 13183 * have a variable offset. 13184 * 13185 * Variable offset is prohibited for unprivileged mode for simplicity since it 13186 * requires corresponding support in Spectre masking for stack ALU. See also 13187 * retrieve_ptr_limit(). 13188 * 13189 * 13190 * 'off' includes 'reg->off'. 13191 */ 13192 static int check_stack_access_for_ptr_arithmetic( 13193 struct bpf_verifier_env *env, 13194 int regno, 13195 const struct bpf_reg_state *reg, 13196 int off) 13197 { 13198 if (!tnum_is_const(reg->var_off)) { 13199 char tn_buf[48]; 13200 13201 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 13202 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 13203 regno, tn_buf, off); 13204 return -EACCES; 13205 } 13206 13207 if (off >= 0 || off < -MAX_BPF_STACK) { 13208 verbose(env, "R%d stack pointer arithmetic goes out of range, " 13209 "prohibited for !root; off=%d\n", regno, off); 13210 return -EACCES; 13211 } 13212 13213 return 0; 13214 } 13215 13216 static int sanitize_check_bounds(struct bpf_verifier_env *env, 13217 const struct bpf_insn *insn, 13218 const struct bpf_reg_state *dst_reg) 13219 { 13220 u32 dst = insn->dst_reg; 13221 13222 /* For unprivileged we require that resulting offset must be in bounds 13223 * in order to be able to sanitize access later on. 13224 */ 13225 if (env->bypass_spec_v1) 13226 return 0; 13227 13228 switch (dst_reg->type) { 13229 case PTR_TO_STACK: 13230 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 13231 dst_reg->off + dst_reg->var_off.value)) 13232 return -EACCES; 13233 break; 13234 case PTR_TO_MAP_VALUE: 13235 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 13236 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 13237 "prohibited for !root\n", dst); 13238 return -EACCES; 13239 } 13240 break; 13241 default: 13242 break; 13243 } 13244 13245 return 0; 13246 } 13247 13248 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 13249 * Caller should also handle BPF_MOV case separately. 13250 * If we return -EACCES, caller may want to try again treating pointer as a 13251 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 13252 */ 13253 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 13254 struct bpf_insn *insn, 13255 const struct bpf_reg_state *ptr_reg, 13256 const struct bpf_reg_state *off_reg) 13257 { 13258 struct bpf_verifier_state *vstate = env->cur_state; 13259 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13260 struct bpf_reg_state *regs = state->regs, *dst_reg; 13261 bool known = tnum_is_const(off_reg->var_off); 13262 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 13263 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 13264 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 13265 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 13266 struct bpf_sanitize_info info = {}; 13267 u8 opcode = BPF_OP(insn->code); 13268 u32 dst = insn->dst_reg; 13269 int ret; 13270 13271 dst_reg = ®s[dst]; 13272 13273 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 13274 smin_val > smax_val || umin_val > umax_val) { 13275 /* Taint dst register if offset had invalid bounds derived from 13276 * e.g. dead branches. 13277 */ 13278 __mark_reg_unknown(env, dst_reg); 13279 return 0; 13280 } 13281 13282 if (BPF_CLASS(insn->code) != BPF_ALU64) { 13283 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 13284 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13285 __mark_reg_unknown(env, dst_reg); 13286 return 0; 13287 } 13288 13289 verbose(env, 13290 "R%d 32-bit pointer arithmetic prohibited\n", 13291 dst); 13292 return -EACCES; 13293 } 13294 13295 if (ptr_reg->type & PTR_MAYBE_NULL) { 13296 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 13297 dst, reg_type_str(env, ptr_reg->type)); 13298 return -EACCES; 13299 } 13300 13301 switch (base_type(ptr_reg->type)) { 13302 case PTR_TO_CTX: 13303 case PTR_TO_MAP_VALUE: 13304 case PTR_TO_MAP_KEY: 13305 case PTR_TO_STACK: 13306 case PTR_TO_PACKET_META: 13307 case PTR_TO_PACKET: 13308 case PTR_TO_TP_BUFFER: 13309 case PTR_TO_BTF_ID: 13310 case PTR_TO_MEM: 13311 case PTR_TO_BUF: 13312 case PTR_TO_FUNC: 13313 case CONST_PTR_TO_DYNPTR: 13314 break; 13315 case PTR_TO_FLOW_KEYS: 13316 if (known) 13317 break; 13318 fallthrough; 13319 case CONST_PTR_TO_MAP: 13320 /* smin_val represents the known value */ 13321 if (known && smin_val == 0 && opcode == BPF_ADD) 13322 break; 13323 fallthrough; 13324 default: 13325 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 13326 dst, reg_type_str(env, ptr_reg->type)); 13327 return -EACCES; 13328 } 13329 13330 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 13331 * The id may be overwritten later if we create a new variable offset. 13332 */ 13333 dst_reg->type = ptr_reg->type; 13334 dst_reg->id = ptr_reg->id; 13335 13336 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 13337 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 13338 return -EINVAL; 13339 13340 /* pointer types do not carry 32-bit bounds at the moment. */ 13341 __mark_reg32_unbounded(dst_reg); 13342 13343 if (sanitize_needed(opcode)) { 13344 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 13345 &info, false); 13346 if (ret < 0) 13347 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13348 } 13349 13350 switch (opcode) { 13351 case BPF_ADD: 13352 /* We can take a fixed offset as long as it doesn't overflow 13353 * the s32 'off' field 13354 */ 13355 if (known && (ptr_reg->off + smin_val == 13356 (s64)(s32)(ptr_reg->off + smin_val))) { 13357 /* pointer += K. Accumulate it into fixed offset */ 13358 dst_reg->smin_value = smin_ptr; 13359 dst_reg->smax_value = smax_ptr; 13360 dst_reg->umin_value = umin_ptr; 13361 dst_reg->umax_value = umax_ptr; 13362 dst_reg->var_off = ptr_reg->var_off; 13363 dst_reg->off = ptr_reg->off + smin_val; 13364 dst_reg->raw = ptr_reg->raw; 13365 break; 13366 } 13367 /* A new variable offset is created. Note that off_reg->off 13368 * == 0, since it's a scalar. 13369 * dst_reg gets the pointer type and since some positive 13370 * integer value was added to the pointer, give it a new 'id' 13371 * if it's a PTR_TO_PACKET. 13372 * this creates a new 'base' pointer, off_reg (variable) gets 13373 * added into the variable offset, and we copy the fixed offset 13374 * from ptr_reg. 13375 */ 13376 if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) || 13377 check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) { 13378 dst_reg->smin_value = S64_MIN; 13379 dst_reg->smax_value = S64_MAX; 13380 } 13381 if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) || 13382 check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) { 13383 dst_reg->umin_value = 0; 13384 dst_reg->umax_value = U64_MAX; 13385 } 13386 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 13387 dst_reg->off = ptr_reg->off; 13388 dst_reg->raw = ptr_reg->raw; 13389 if (reg_is_pkt_pointer(ptr_reg)) { 13390 dst_reg->id = ++env->id_gen; 13391 /* something was added to pkt_ptr, set range to zero */ 13392 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13393 } 13394 break; 13395 case BPF_SUB: 13396 if (dst_reg == off_reg) { 13397 /* scalar -= pointer. Creates an unknown scalar */ 13398 verbose(env, "R%d tried to subtract pointer from scalar\n", 13399 dst); 13400 return -EACCES; 13401 } 13402 /* We don't allow subtraction from FP, because (according to 13403 * test_verifier.c test "invalid fp arithmetic", JITs might not 13404 * be able to deal with it. 13405 */ 13406 if (ptr_reg->type == PTR_TO_STACK) { 13407 verbose(env, "R%d subtraction from stack pointer prohibited\n", 13408 dst); 13409 return -EACCES; 13410 } 13411 if (known && (ptr_reg->off - smin_val == 13412 (s64)(s32)(ptr_reg->off - smin_val))) { 13413 /* pointer -= K. Subtract it from fixed offset */ 13414 dst_reg->smin_value = smin_ptr; 13415 dst_reg->smax_value = smax_ptr; 13416 dst_reg->umin_value = umin_ptr; 13417 dst_reg->umax_value = umax_ptr; 13418 dst_reg->var_off = ptr_reg->var_off; 13419 dst_reg->id = ptr_reg->id; 13420 dst_reg->off = ptr_reg->off - smin_val; 13421 dst_reg->raw = ptr_reg->raw; 13422 break; 13423 } 13424 /* A new variable offset is created. If the subtrahend is known 13425 * nonnegative, then any reg->range we had before is still good. 13426 */ 13427 if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) || 13428 check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) { 13429 /* Overflow possible, we know nothing */ 13430 dst_reg->smin_value = S64_MIN; 13431 dst_reg->smax_value = S64_MAX; 13432 } 13433 if (umin_ptr < umax_val) { 13434 /* Overflow possible, we know nothing */ 13435 dst_reg->umin_value = 0; 13436 dst_reg->umax_value = U64_MAX; 13437 } else { 13438 /* Cannot overflow (as long as bounds are consistent) */ 13439 dst_reg->umin_value = umin_ptr - umax_val; 13440 dst_reg->umax_value = umax_ptr - umin_val; 13441 } 13442 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 13443 dst_reg->off = ptr_reg->off; 13444 dst_reg->raw = ptr_reg->raw; 13445 if (reg_is_pkt_pointer(ptr_reg)) { 13446 dst_reg->id = ++env->id_gen; 13447 /* something was added to pkt_ptr, set range to zero */ 13448 if (smin_val < 0) 13449 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13450 } 13451 break; 13452 case BPF_AND: 13453 case BPF_OR: 13454 case BPF_XOR: 13455 /* bitwise ops on pointers are troublesome, prohibit. */ 13456 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 13457 dst, bpf_alu_string[opcode >> 4]); 13458 return -EACCES; 13459 default: 13460 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 13461 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 13462 dst, bpf_alu_string[opcode >> 4]); 13463 return -EACCES; 13464 } 13465 13466 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 13467 return -EINVAL; 13468 reg_bounds_sync(dst_reg); 13469 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 13470 return -EACCES; 13471 if (sanitize_needed(opcode)) { 13472 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 13473 &info, true); 13474 if (ret < 0) 13475 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13476 } 13477 13478 return 0; 13479 } 13480 13481 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 13482 struct bpf_reg_state *src_reg) 13483 { 13484 s32 *dst_smin = &dst_reg->s32_min_value; 13485 s32 *dst_smax = &dst_reg->s32_max_value; 13486 u32 *dst_umin = &dst_reg->u32_min_value; 13487 u32 *dst_umax = &dst_reg->u32_max_value; 13488 13489 if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) || 13490 check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) { 13491 *dst_smin = S32_MIN; 13492 *dst_smax = S32_MAX; 13493 } 13494 if (check_add_overflow(*dst_umin, src_reg->u32_min_value, dst_umin) || 13495 check_add_overflow(*dst_umax, src_reg->u32_max_value, dst_umax)) { 13496 *dst_umin = 0; 13497 *dst_umax = U32_MAX; 13498 } 13499 } 13500 13501 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 13502 struct bpf_reg_state *src_reg) 13503 { 13504 s64 *dst_smin = &dst_reg->smin_value; 13505 s64 *dst_smax = &dst_reg->smax_value; 13506 u64 *dst_umin = &dst_reg->umin_value; 13507 u64 *dst_umax = &dst_reg->umax_value; 13508 13509 if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) || 13510 check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) { 13511 *dst_smin = S64_MIN; 13512 *dst_smax = S64_MAX; 13513 } 13514 if (check_add_overflow(*dst_umin, src_reg->umin_value, dst_umin) || 13515 check_add_overflow(*dst_umax, src_reg->umax_value, dst_umax)) { 13516 *dst_umin = 0; 13517 *dst_umax = U64_MAX; 13518 } 13519 } 13520 13521 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 13522 struct bpf_reg_state *src_reg) 13523 { 13524 s32 *dst_smin = &dst_reg->s32_min_value; 13525 s32 *dst_smax = &dst_reg->s32_max_value; 13526 u32 umin_val = src_reg->u32_min_value; 13527 u32 umax_val = src_reg->u32_max_value; 13528 13529 if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) || 13530 check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) { 13531 /* Overflow possible, we know nothing */ 13532 *dst_smin = S32_MIN; 13533 *dst_smax = S32_MAX; 13534 } 13535 if (dst_reg->u32_min_value < umax_val) { 13536 /* Overflow possible, we know nothing */ 13537 dst_reg->u32_min_value = 0; 13538 dst_reg->u32_max_value = U32_MAX; 13539 } else { 13540 /* Cannot overflow (as long as bounds are consistent) */ 13541 dst_reg->u32_min_value -= umax_val; 13542 dst_reg->u32_max_value -= umin_val; 13543 } 13544 } 13545 13546 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 13547 struct bpf_reg_state *src_reg) 13548 { 13549 s64 *dst_smin = &dst_reg->smin_value; 13550 s64 *dst_smax = &dst_reg->smax_value; 13551 u64 umin_val = src_reg->umin_value; 13552 u64 umax_val = src_reg->umax_value; 13553 13554 if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) || 13555 check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) { 13556 /* Overflow possible, we know nothing */ 13557 *dst_smin = S64_MIN; 13558 *dst_smax = S64_MAX; 13559 } 13560 if (dst_reg->umin_value < umax_val) { 13561 /* Overflow possible, we know nothing */ 13562 dst_reg->umin_value = 0; 13563 dst_reg->umax_value = U64_MAX; 13564 } else { 13565 /* Cannot overflow (as long as bounds are consistent) */ 13566 dst_reg->umin_value -= umax_val; 13567 dst_reg->umax_value -= umin_val; 13568 } 13569 } 13570 13571 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 13572 struct bpf_reg_state *src_reg) 13573 { 13574 s32 smin_val = src_reg->s32_min_value; 13575 u32 umin_val = src_reg->u32_min_value; 13576 u32 umax_val = src_reg->u32_max_value; 13577 13578 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 13579 /* Ain't nobody got time to multiply that sign */ 13580 __mark_reg32_unbounded(dst_reg); 13581 return; 13582 } 13583 /* Both values are positive, so we can work with unsigned and 13584 * copy the result to signed (unless it exceeds S32_MAX). 13585 */ 13586 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 13587 /* Potential overflow, we know nothing */ 13588 __mark_reg32_unbounded(dst_reg); 13589 return; 13590 } 13591 dst_reg->u32_min_value *= umin_val; 13592 dst_reg->u32_max_value *= umax_val; 13593 if (dst_reg->u32_max_value > S32_MAX) { 13594 /* Overflow possible, we know nothing */ 13595 dst_reg->s32_min_value = S32_MIN; 13596 dst_reg->s32_max_value = S32_MAX; 13597 } else { 13598 dst_reg->s32_min_value = dst_reg->u32_min_value; 13599 dst_reg->s32_max_value = dst_reg->u32_max_value; 13600 } 13601 } 13602 13603 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 13604 struct bpf_reg_state *src_reg) 13605 { 13606 s64 smin_val = src_reg->smin_value; 13607 u64 umin_val = src_reg->umin_value; 13608 u64 umax_val = src_reg->umax_value; 13609 13610 if (smin_val < 0 || dst_reg->smin_value < 0) { 13611 /* Ain't nobody got time to multiply that sign */ 13612 __mark_reg64_unbounded(dst_reg); 13613 return; 13614 } 13615 /* Both values are positive, so we can work with unsigned and 13616 * copy the result to signed (unless it exceeds S64_MAX). 13617 */ 13618 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 13619 /* Potential overflow, we know nothing */ 13620 __mark_reg64_unbounded(dst_reg); 13621 return; 13622 } 13623 dst_reg->umin_value *= umin_val; 13624 dst_reg->umax_value *= umax_val; 13625 if (dst_reg->umax_value > S64_MAX) { 13626 /* Overflow possible, we know nothing */ 13627 dst_reg->smin_value = S64_MIN; 13628 dst_reg->smax_value = S64_MAX; 13629 } else { 13630 dst_reg->smin_value = dst_reg->umin_value; 13631 dst_reg->smax_value = dst_reg->umax_value; 13632 } 13633 } 13634 13635 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 13636 struct bpf_reg_state *src_reg) 13637 { 13638 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13639 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13640 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13641 u32 umax_val = src_reg->u32_max_value; 13642 13643 if (src_known && dst_known) { 13644 __mark_reg32_known(dst_reg, var32_off.value); 13645 return; 13646 } 13647 13648 /* We get our minimum from the var_off, since that's inherently 13649 * bitwise. Our maximum is the minimum of the operands' maxima. 13650 */ 13651 dst_reg->u32_min_value = var32_off.value; 13652 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 13653 13654 /* Safe to set s32 bounds by casting u32 result into s32 when u32 13655 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 13656 */ 13657 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 13658 dst_reg->s32_min_value = dst_reg->u32_min_value; 13659 dst_reg->s32_max_value = dst_reg->u32_max_value; 13660 } else { 13661 dst_reg->s32_min_value = S32_MIN; 13662 dst_reg->s32_max_value = S32_MAX; 13663 } 13664 } 13665 13666 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 13667 struct bpf_reg_state *src_reg) 13668 { 13669 bool src_known = tnum_is_const(src_reg->var_off); 13670 bool dst_known = tnum_is_const(dst_reg->var_off); 13671 u64 umax_val = src_reg->umax_value; 13672 13673 if (src_known && dst_known) { 13674 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13675 return; 13676 } 13677 13678 /* We get our minimum from the var_off, since that's inherently 13679 * bitwise. Our maximum is the minimum of the operands' maxima. 13680 */ 13681 dst_reg->umin_value = dst_reg->var_off.value; 13682 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 13683 13684 /* Safe to set s64 bounds by casting u64 result into s64 when u64 13685 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 13686 */ 13687 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 13688 dst_reg->smin_value = dst_reg->umin_value; 13689 dst_reg->smax_value = dst_reg->umax_value; 13690 } else { 13691 dst_reg->smin_value = S64_MIN; 13692 dst_reg->smax_value = S64_MAX; 13693 } 13694 /* We may learn something more from the var_off */ 13695 __update_reg_bounds(dst_reg); 13696 } 13697 13698 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 13699 struct bpf_reg_state *src_reg) 13700 { 13701 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13702 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13703 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13704 u32 umin_val = src_reg->u32_min_value; 13705 13706 if (src_known && dst_known) { 13707 __mark_reg32_known(dst_reg, var32_off.value); 13708 return; 13709 } 13710 13711 /* We get our maximum from the var_off, and our minimum is the 13712 * maximum of the operands' minima 13713 */ 13714 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 13715 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13716 13717 /* Safe to set s32 bounds by casting u32 result into s32 when u32 13718 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 13719 */ 13720 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 13721 dst_reg->s32_min_value = dst_reg->u32_min_value; 13722 dst_reg->s32_max_value = dst_reg->u32_max_value; 13723 } else { 13724 dst_reg->s32_min_value = S32_MIN; 13725 dst_reg->s32_max_value = S32_MAX; 13726 } 13727 } 13728 13729 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 13730 struct bpf_reg_state *src_reg) 13731 { 13732 bool src_known = tnum_is_const(src_reg->var_off); 13733 bool dst_known = tnum_is_const(dst_reg->var_off); 13734 u64 umin_val = src_reg->umin_value; 13735 13736 if (src_known && dst_known) { 13737 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13738 return; 13739 } 13740 13741 /* We get our maximum from the var_off, and our minimum is the 13742 * maximum of the operands' minima 13743 */ 13744 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 13745 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13746 13747 /* Safe to set s64 bounds by casting u64 result into s64 when u64 13748 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 13749 */ 13750 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 13751 dst_reg->smin_value = dst_reg->umin_value; 13752 dst_reg->smax_value = dst_reg->umax_value; 13753 } else { 13754 dst_reg->smin_value = S64_MIN; 13755 dst_reg->smax_value = S64_MAX; 13756 } 13757 /* We may learn something more from the var_off */ 13758 __update_reg_bounds(dst_reg); 13759 } 13760 13761 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 13762 struct bpf_reg_state *src_reg) 13763 { 13764 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13765 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13766 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13767 13768 if (src_known && dst_known) { 13769 __mark_reg32_known(dst_reg, var32_off.value); 13770 return; 13771 } 13772 13773 /* We get both minimum and maximum from the var32_off. */ 13774 dst_reg->u32_min_value = var32_off.value; 13775 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13776 13777 /* Safe to set s32 bounds by casting u32 result into s32 when u32 13778 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 13779 */ 13780 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 13781 dst_reg->s32_min_value = dst_reg->u32_min_value; 13782 dst_reg->s32_max_value = dst_reg->u32_max_value; 13783 } else { 13784 dst_reg->s32_min_value = S32_MIN; 13785 dst_reg->s32_max_value = S32_MAX; 13786 } 13787 } 13788 13789 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 13790 struct bpf_reg_state *src_reg) 13791 { 13792 bool src_known = tnum_is_const(src_reg->var_off); 13793 bool dst_known = tnum_is_const(dst_reg->var_off); 13794 13795 if (src_known && dst_known) { 13796 /* dst_reg->var_off.value has been updated earlier */ 13797 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13798 return; 13799 } 13800 13801 /* We get both minimum and maximum from the var_off. */ 13802 dst_reg->umin_value = dst_reg->var_off.value; 13803 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13804 13805 /* Safe to set s64 bounds by casting u64 result into s64 when u64 13806 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 13807 */ 13808 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 13809 dst_reg->smin_value = dst_reg->umin_value; 13810 dst_reg->smax_value = dst_reg->umax_value; 13811 } else { 13812 dst_reg->smin_value = S64_MIN; 13813 dst_reg->smax_value = S64_MAX; 13814 } 13815 13816 __update_reg_bounds(dst_reg); 13817 } 13818 13819 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13820 u64 umin_val, u64 umax_val) 13821 { 13822 /* We lose all sign bit information (except what we can pick 13823 * up from var_off) 13824 */ 13825 dst_reg->s32_min_value = S32_MIN; 13826 dst_reg->s32_max_value = S32_MAX; 13827 /* If we might shift our top bit out, then we know nothing */ 13828 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 13829 dst_reg->u32_min_value = 0; 13830 dst_reg->u32_max_value = U32_MAX; 13831 } else { 13832 dst_reg->u32_min_value <<= umin_val; 13833 dst_reg->u32_max_value <<= umax_val; 13834 } 13835 } 13836 13837 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13838 struct bpf_reg_state *src_reg) 13839 { 13840 u32 umax_val = src_reg->u32_max_value; 13841 u32 umin_val = src_reg->u32_min_value; 13842 /* u32 alu operation will zext upper bits */ 13843 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13844 13845 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13846 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 13847 /* Not required but being careful mark reg64 bounds as unknown so 13848 * that we are forced to pick them up from tnum and zext later and 13849 * if some path skips this step we are still safe. 13850 */ 13851 __mark_reg64_unbounded(dst_reg); 13852 __update_reg32_bounds(dst_reg); 13853 } 13854 13855 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 13856 u64 umin_val, u64 umax_val) 13857 { 13858 /* Special case <<32 because it is a common compiler pattern to sign 13859 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 13860 * positive we know this shift will also be positive so we can track 13861 * bounds correctly. Otherwise we lose all sign bit information except 13862 * what we can pick up from var_off. Perhaps we can generalize this 13863 * later to shifts of any length. 13864 */ 13865 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 13866 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 13867 else 13868 dst_reg->smax_value = S64_MAX; 13869 13870 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 13871 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 13872 else 13873 dst_reg->smin_value = S64_MIN; 13874 13875 /* If we might shift our top bit out, then we know nothing */ 13876 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 13877 dst_reg->umin_value = 0; 13878 dst_reg->umax_value = U64_MAX; 13879 } else { 13880 dst_reg->umin_value <<= umin_val; 13881 dst_reg->umax_value <<= umax_val; 13882 } 13883 } 13884 13885 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 13886 struct bpf_reg_state *src_reg) 13887 { 13888 u64 umax_val = src_reg->umax_value; 13889 u64 umin_val = src_reg->umin_value; 13890 13891 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 13892 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 13893 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13894 13895 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 13896 /* We may learn something more from the var_off */ 13897 __update_reg_bounds(dst_reg); 13898 } 13899 13900 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 13901 struct bpf_reg_state *src_reg) 13902 { 13903 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13904 u32 umax_val = src_reg->u32_max_value; 13905 u32 umin_val = src_reg->u32_min_value; 13906 13907 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13908 * be negative, then either: 13909 * 1) src_reg might be zero, so the sign bit of the result is 13910 * unknown, so we lose our signed bounds 13911 * 2) it's known negative, thus the unsigned bounds capture the 13912 * signed bounds 13913 * 3) the signed bounds cross zero, so they tell us nothing 13914 * about the result 13915 * If the value in dst_reg is known nonnegative, then again the 13916 * unsigned bounds capture the signed bounds. 13917 * Thus, in all cases it suffices to blow away our signed bounds 13918 * and rely on inferring new ones from the unsigned bounds and 13919 * var_off of the result. 13920 */ 13921 dst_reg->s32_min_value = S32_MIN; 13922 dst_reg->s32_max_value = S32_MAX; 13923 13924 dst_reg->var_off = tnum_rshift(subreg, umin_val); 13925 dst_reg->u32_min_value >>= umax_val; 13926 dst_reg->u32_max_value >>= umin_val; 13927 13928 __mark_reg64_unbounded(dst_reg); 13929 __update_reg32_bounds(dst_reg); 13930 } 13931 13932 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 13933 struct bpf_reg_state *src_reg) 13934 { 13935 u64 umax_val = src_reg->umax_value; 13936 u64 umin_val = src_reg->umin_value; 13937 13938 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13939 * be negative, then either: 13940 * 1) src_reg might be zero, so the sign bit of the result is 13941 * unknown, so we lose our signed bounds 13942 * 2) it's known negative, thus the unsigned bounds capture the 13943 * signed bounds 13944 * 3) the signed bounds cross zero, so they tell us nothing 13945 * about the result 13946 * If the value in dst_reg is known nonnegative, then again the 13947 * unsigned bounds capture the signed bounds. 13948 * Thus, in all cases it suffices to blow away our signed bounds 13949 * and rely on inferring new ones from the unsigned bounds and 13950 * var_off of the result. 13951 */ 13952 dst_reg->smin_value = S64_MIN; 13953 dst_reg->smax_value = S64_MAX; 13954 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 13955 dst_reg->umin_value >>= umax_val; 13956 dst_reg->umax_value >>= umin_val; 13957 13958 /* Its not easy to operate on alu32 bounds here because it depends 13959 * on bits being shifted in. Take easy way out and mark unbounded 13960 * so we can recalculate later from tnum. 13961 */ 13962 __mark_reg32_unbounded(dst_reg); 13963 __update_reg_bounds(dst_reg); 13964 } 13965 13966 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 13967 struct bpf_reg_state *src_reg) 13968 { 13969 u64 umin_val = src_reg->u32_min_value; 13970 13971 /* Upon reaching here, src_known is true and 13972 * umax_val is equal to umin_val. 13973 */ 13974 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 13975 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 13976 13977 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 13978 13979 /* blow away the dst_reg umin_value/umax_value and rely on 13980 * dst_reg var_off to refine the result. 13981 */ 13982 dst_reg->u32_min_value = 0; 13983 dst_reg->u32_max_value = U32_MAX; 13984 13985 __mark_reg64_unbounded(dst_reg); 13986 __update_reg32_bounds(dst_reg); 13987 } 13988 13989 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 13990 struct bpf_reg_state *src_reg) 13991 { 13992 u64 umin_val = src_reg->umin_value; 13993 13994 /* Upon reaching here, src_known is true and umax_val is equal 13995 * to umin_val. 13996 */ 13997 dst_reg->smin_value >>= umin_val; 13998 dst_reg->smax_value >>= umin_val; 13999 14000 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 14001 14002 /* blow away the dst_reg umin_value/umax_value and rely on 14003 * dst_reg var_off to refine the result. 14004 */ 14005 dst_reg->umin_value = 0; 14006 dst_reg->umax_value = U64_MAX; 14007 14008 /* Its not easy to operate on alu32 bounds here because it depends 14009 * on bits being shifted in from upper 32-bits. Take easy way out 14010 * and mark unbounded so we can recalculate later from tnum. 14011 */ 14012 __mark_reg32_unbounded(dst_reg); 14013 __update_reg_bounds(dst_reg); 14014 } 14015 14016 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn, 14017 const struct bpf_reg_state *src_reg) 14018 { 14019 bool src_is_const = false; 14020 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 14021 14022 if (insn_bitness == 32) { 14023 if (tnum_subreg_is_const(src_reg->var_off) 14024 && src_reg->s32_min_value == src_reg->s32_max_value 14025 && src_reg->u32_min_value == src_reg->u32_max_value) 14026 src_is_const = true; 14027 } else { 14028 if (tnum_is_const(src_reg->var_off) 14029 && src_reg->smin_value == src_reg->smax_value 14030 && src_reg->umin_value == src_reg->umax_value) 14031 src_is_const = true; 14032 } 14033 14034 switch (BPF_OP(insn->code)) { 14035 case BPF_ADD: 14036 case BPF_SUB: 14037 case BPF_AND: 14038 case BPF_XOR: 14039 case BPF_OR: 14040 case BPF_MUL: 14041 return true; 14042 14043 /* Shift operators range is only computable if shift dimension operand 14044 * is a constant. Shifts greater than 31 or 63 are undefined. This 14045 * includes shifts by a negative number. 14046 */ 14047 case BPF_LSH: 14048 case BPF_RSH: 14049 case BPF_ARSH: 14050 return (src_is_const && src_reg->umax_value < insn_bitness); 14051 default: 14052 return false; 14053 } 14054 } 14055 14056 /* WARNING: This function does calculations on 64-bit values, but the actual 14057 * execution may occur on 32-bit values. Therefore, things like bitshifts 14058 * need extra checks in the 32-bit case. 14059 */ 14060 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 14061 struct bpf_insn *insn, 14062 struct bpf_reg_state *dst_reg, 14063 struct bpf_reg_state src_reg) 14064 { 14065 u8 opcode = BPF_OP(insn->code); 14066 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14067 int ret; 14068 14069 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) { 14070 __mark_reg_unknown(env, dst_reg); 14071 return 0; 14072 } 14073 14074 if (sanitize_needed(opcode)) { 14075 ret = sanitize_val_alu(env, insn); 14076 if (ret < 0) 14077 return sanitize_err(env, insn, ret, NULL, NULL); 14078 } 14079 14080 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 14081 * There are two classes of instructions: The first class we track both 14082 * alu32 and alu64 sign/unsigned bounds independently this provides the 14083 * greatest amount of precision when alu operations are mixed with jmp32 14084 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 14085 * and BPF_OR. This is possible because these ops have fairly easy to 14086 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 14087 * See alu32 verifier tests for examples. The second class of 14088 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 14089 * with regards to tracking sign/unsigned bounds because the bits may 14090 * cross subreg boundaries in the alu64 case. When this happens we mark 14091 * the reg unbounded in the subreg bound space and use the resulting 14092 * tnum to calculate an approximation of the sign/unsigned bounds. 14093 */ 14094 switch (opcode) { 14095 case BPF_ADD: 14096 scalar32_min_max_add(dst_reg, &src_reg); 14097 scalar_min_max_add(dst_reg, &src_reg); 14098 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 14099 break; 14100 case BPF_SUB: 14101 scalar32_min_max_sub(dst_reg, &src_reg); 14102 scalar_min_max_sub(dst_reg, &src_reg); 14103 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 14104 break; 14105 case BPF_MUL: 14106 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 14107 scalar32_min_max_mul(dst_reg, &src_reg); 14108 scalar_min_max_mul(dst_reg, &src_reg); 14109 break; 14110 case BPF_AND: 14111 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 14112 scalar32_min_max_and(dst_reg, &src_reg); 14113 scalar_min_max_and(dst_reg, &src_reg); 14114 break; 14115 case BPF_OR: 14116 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 14117 scalar32_min_max_or(dst_reg, &src_reg); 14118 scalar_min_max_or(dst_reg, &src_reg); 14119 break; 14120 case BPF_XOR: 14121 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 14122 scalar32_min_max_xor(dst_reg, &src_reg); 14123 scalar_min_max_xor(dst_reg, &src_reg); 14124 break; 14125 case BPF_LSH: 14126 if (alu32) 14127 scalar32_min_max_lsh(dst_reg, &src_reg); 14128 else 14129 scalar_min_max_lsh(dst_reg, &src_reg); 14130 break; 14131 case BPF_RSH: 14132 if (alu32) 14133 scalar32_min_max_rsh(dst_reg, &src_reg); 14134 else 14135 scalar_min_max_rsh(dst_reg, &src_reg); 14136 break; 14137 case BPF_ARSH: 14138 if (alu32) 14139 scalar32_min_max_arsh(dst_reg, &src_reg); 14140 else 14141 scalar_min_max_arsh(dst_reg, &src_reg); 14142 break; 14143 default: 14144 break; 14145 } 14146 14147 /* ALU32 ops are zero extended into 64bit register */ 14148 if (alu32) 14149 zext_32_to_64(dst_reg); 14150 reg_bounds_sync(dst_reg); 14151 return 0; 14152 } 14153 14154 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 14155 * and var_off. 14156 */ 14157 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 14158 struct bpf_insn *insn) 14159 { 14160 struct bpf_verifier_state *vstate = env->cur_state; 14161 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14162 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 14163 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 14164 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14165 u8 opcode = BPF_OP(insn->code); 14166 int err; 14167 14168 dst_reg = ®s[insn->dst_reg]; 14169 src_reg = NULL; 14170 14171 if (dst_reg->type == PTR_TO_ARENA) { 14172 struct bpf_insn_aux_data *aux = cur_aux(env); 14173 14174 if (BPF_CLASS(insn->code) == BPF_ALU64) 14175 /* 14176 * 32-bit operations zero upper bits automatically. 14177 * 64-bit operations need to be converted to 32. 14178 */ 14179 aux->needs_zext = true; 14180 14181 /* Any arithmetic operations are allowed on arena pointers */ 14182 return 0; 14183 } 14184 14185 if (dst_reg->type != SCALAR_VALUE) 14186 ptr_reg = dst_reg; 14187 14188 if (BPF_SRC(insn->code) == BPF_X) { 14189 src_reg = ®s[insn->src_reg]; 14190 if (src_reg->type != SCALAR_VALUE) { 14191 if (dst_reg->type != SCALAR_VALUE) { 14192 /* Combining two pointers by any ALU op yields 14193 * an arbitrary scalar. Disallow all math except 14194 * pointer subtraction 14195 */ 14196 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 14197 mark_reg_unknown(env, regs, insn->dst_reg); 14198 return 0; 14199 } 14200 verbose(env, "R%d pointer %s pointer prohibited\n", 14201 insn->dst_reg, 14202 bpf_alu_string[opcode >> 4]); 14203 return -EACCES; 14204 } else { 14205 /* scalar += pointer 14206 * This is legal, but we have to reverse our 14207 * src/dest handling in computing the range 14208 */ 14209 err = mark_chain_precision(env, insn->dst_reg); 14210 if (err) 14211 return err; 14212 return adjust_ptr_min_max_vals(env, insn, 14213 src_reg, dst_reg); 14214 } 14215 } else if (ptr_reg) { 14216 /* pointer += scalar */ 14217 err = mark_chain_precision(env, insn->src_reg); 14218 if (err) 14219 return err; 14220 return adjust_ptr_min_max_vals(env, insn, 14221 dst_reg, src_reg); 14222 } else if (dst_reg->precise) { 14223 /* if dst_reg is precise, src_reg should be precise as well */ 14224 err = mark_chain_precision(env, insn->src_reg); 14225 if (err) 14226 return err; 14227 } 14228 } else { 14229 /* Pretend the src is a reg with a known value, since we only 14230 * need to be able to read from this state. 14231 */ 14232 off_reg.type = SCALAR_VALUE; 14233 __mark_reg_known(&off_reg, insn->imm); 14234 src_reg = &off_reg; 14235 if (ptr_reg) /* pointer += K */ 14236 return adjust_ptr_min_max_vals(env, insn, 14237 ptr_reg, src_reg); 14238 } 14239 14240 /* Got here implies adding two SCALAR_VALUEs */ 14241 if (WARN_ON_ONCE(ptr_reg)) { 14242 print_verifier_state(env, state, true); 14243 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 14244 return -EINVAL; 14245 } 14246 if (WARN_ON(!src_reg)) { 14247 print_verifier_state(env, state, true); 14248 verbose(env, "verifier internal error: no src_reg\n"); 14249 return -EINVAL; 14250 } 14251 err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 14252 if (err) 14253 return err; 14254 /* 14255 * Compilers can generate the code 14256 * r1 = r2 14257 * r1 += 0x1 14258 * if r2 < 1000 goto ... 14259 * use r1 in memory access 14260 * So for 64-bit alu remember constant delta between r2 and r1 and 14261 * update r1 after 'if' condition. 14262 */ 14263 if (env->bpf_capable && 14264 BPF_OP(insn->code) == BPF_ADD && !alu32 && 14265 dst_reg->id && is_reg_const(src_reg, false)) { 14266 u64 val = reg_const_value(src_reg, false); 14267 14268 if ((dst_reg->id & BPF_ADD_CONST) || 14269 /* prevent overflow in sync_linked_regs() later */ 14270 val > (u32)S32_MAX) { 14271 /* 14272 * If the register already went through rX += val 14273 * we cannot accumulate another val into rx->off. 14274 */ 14275 dst_reg->off = 0; 14276 dst_reg->id = 0; 14277 } else { 14278 dst_reg->id |= BPF_ADD_CONST; 14279 dst_reg->off = val; 14280 } 14281 } else { 14282 /* 14283 * Make sure ID is cleared otherwise dst_reg min/max could be 14284 * incorrectly propagated into other registers by sync_linked_regs() 14285 */ 14286 dst_reg->id = 0; 14287 } 14288 return 0; 14289 } 14290 14291 /* check validity of 32-bit and 64-bit arithmetic operations */ 14292 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 14293 { 14294 struct bpf_reg_state *regs = cur_regs(env); 14295 u8 opcode = BPF_OP(insn->code); 14296 int err; 14297 14298 if (opcode == BPF_END || opcode == BPF_NEG) { 14299 if (opcode == BPF_NEG) { 14300 if (BPF_SRC(insn->code) != BPF_K || 14301 insn->src_reg != BPF_REG_0 || 14302 insn->off != 0 || insn->imm != 0) { 14303 verbose(env, "BPF_NEG uses reserved fields\n"); 14304 return -EINVAL; 14305 } 14306 } else { 14307 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 14308 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 14309 (BPF_CLASS(insn->code) == BPF_ALU64 && 14310 BPF_SRC(insn->code) != BPF_TO_LE)) { 14311 verbose(env, "BPF_END uses reserved fields\n"); 14312 return -EINVAL; 14313 } 14314 } 14315 14316 /* check src operand */ 14317 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14318 if (err) 14319 return err; 14320 14321 if (is_pointer_value(env, insn->dst_reg)) { 14322 verbose(env, "R%d pointer arithmetic prohibited\n", 14323 insn->dst_reg); 14324 return -EACCES; 14325 } 14326 14327 /* check dest operand */ 14328 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14329 if (err) 14330 return err; 14331 14332 } else if (opcode == BPF_MOV) { 14333 14334 if (BPF_SRC(insn->code) == BPF_X) { 14335 if (BPF_CLASS(insn->code) == BPF_ALU) { 14336 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) || 14337 insn->imm) { 14338 verbose(env, "BPF_MOV uses reserved fields\n"); 14339 return -EINVAL; 14340 } 14341 } else if (insn->off == BPF_ADDR_SPACE_CAST) { 14342 if (insn->imm != 1 && insn->imm != 1u << 16) { 14343 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n"); 14344 return -EINVAL; 14345 } 14346 if (!env->prog->aux->arena) { 14347 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n"); 14348 return -EINVAL; 14349 } 14350 } else { 14351 if ((insn->off != 0 && insn->off != 8 && insn->off != 16 && 14352 insn->off != 32) || insn->imm) { 14353 verbose(env, "BPF_MOV uses reserved fields\n"); 14354 return -EINVAL; 14355 } 14356 } 14357 14358 /* check src operand */ 14359 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14360 if (err) 14361 return err; 14362 } else { 14363 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 14364 verbose(env, "BPF_MOV uses reserved fields\n"); 14365 return -EINVAL; 14366 } 14367 } 14368 14369 /* check dest operand, mark as required later */ 14370 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14371 if (err) 14372 return err; 14373 14374 if (BPF_SRC(insn->code) == BPF_X) { 14375 struct bpf_reg_state *src_reg = regs + insn->src_reg; 14376 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 14377 14378 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14379 if (insn->imm) { 14380 /* off == BPF_ADDR_SPACE_CAST */ 14381 mark_reg_unknown(env, regs, insn->dst_reg); 14382 if (insn->imm == 1) { /* cast from as(1) to as(0) */ 14383 dst_reg->type = PTR_TO_ARENA; 14384 /* PTR_TO_ARENA is 32-bit */ 14385 dst_reg->subreg_def = env->insn_idx + 1; 14386 } 14387 } else if (insn->off == 0) { 14388 /* case: R1 = R2 14389 * copy register state to dest reg 14390 */ 14391 assign_scalar_id_before_mov(env, src_reg); 14392 copy_register_state(dst_reg, src_reg); 14393 dst_reg->live |= REG_LIVE_WRITTEN; 14394 dst_reg->subreg_def = DEF_NOT_SUBREG; 14395 } else { 14396 /* case: R1 = (s8, s16 s32)R2 */ 14397 if (is_pointer_value(env, insn->src_reg)) { 14398 verbose(env, 14399 "R%d sign-extension part of pointer\n", 14400 insn->src_reg); 14401 return -EACCES; 14402 } else if (src_reg->type == SCALAR_VALUE) { 14403 bool no_sext; 14404 14405 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 14406 if (no_sext) 14407 assign_scalar_id_before_mov(env, src_reg); 14408 copy_register_state(dst_reg, src_reg); 14409 if (!no_sext) 14410 dst_reg->id = 0; 14411 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 14412 dst_reg->live |= REG_LIVE_WRITTEN; 14413 dst_reg->subreg_def = DEF_NOT_SUBREG; 14414 } else { 14415 mark_reg_unknown(env, regs, insn->dst_reg); 14416 } 14417 } 14418 } else { 14419 /* R1 = (u32) R2 */ 14420 if (is_pointer_value(env, insn->src_reg)) { 14421 verbose(env, 14422 "R%d partial copy of pointer\n", 14423 insn->src_reg); 14424 return -EACCES; 14425 } else if (src_reg->type == SCALAR_VALUE) { 14426 if (insn->off == 0) { 14427 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 14428 14429 if (is_src_reg_u32) 14430 assign_scalar_id_before_mov(env, src_reg); 14431 copy_register_state(dst_reg, src_reg); 14432 /* Make sure ID is cleared if src_reg is not in u32 14433 * range otherwise dst_reg min/max could be incorrectly 14434 * propagated into src_reg by sync_linked_regs() 14435 */ 14436 if (!is_src_reg_u32) 14437 dst_reg->id = 0; 14438 dst_reg->live |= REG_LIVE_WRITTEN; 14439 dst_reg->subreg_def = env->insn_idx + 1; 14440 } else { 14441 /* case: W1 = (s8, s16)W2 */ 14442 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 14443 14444 if (no_sext) 14445 assign_scalar_id_before_mov(env, src_reg); 14446 copy_register_state(dst_reg, src_reg); 14447 if (!no_sext) 14448 dst_reg->id = 0; 14449 dst_reg->live |= REG_LIVE_WRITTEN; 14450 dst_reg->subreg_def = env->insn_idx + 1; 14451 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 14452 } 14453 } else { 14454 mark_reg_unknown(env, regs, 14455 insn->dst_reg); 14456 } 14457 zext_32_to_64(dst_reg); 14458 reg_bounds_sync(dst_reg); 14459 } 14460 } else { 14461 /* case: R = imm 14462 * remember the value we stored into this reg 14463 */ 14464 /* clear any state __mark_reg_known doesn't set */ 14465 mark_reg_unknown(env, regs, insn->dst_reg); 14466 regs[insn->dst_reg].type = SCALAR_VALUE; 14467 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14468 __mark_reg_known(regs + insn->dst_reg, 14469 insn->imm); 14470 } else { 14471 __mark_reg_known(regs + insn->dst_reg, 14472 (u32)insn->imm); 14473 } 14474 } 14475 14476 } else if (opcode > BPF_END) { 14477 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 14478 return -EINVAL; 14479 14480 } else { /* all other ALU ops: and, sub, xor, add, ... */ 14481 14482 if (BPF_SRC(insn->code) == BPF_X) { 14483 if (insn->imm != 0 || insn->off > 1 || 14484 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14485 verbose(env, "BPF_ALU uses reserved fields\n"); 14486 return -EINVAL; 14487 } 14488 /* check src1 operand */ 14489 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14490 if (err) 14491 return err; 14492 } else { 14493 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 14494 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14495 verbose(env, "BPF_ALU uses reserved fields\n"); 14496 return -EINVAL; 14497 } 14498 } 14499 14500 /* check src2 operand */ 14501 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14502 if (err) 14503 return err; 14504 14505 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 14506 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 14507 verbose(env, "div by zero\n"); 14508 return -EINVAL; 14509 } 14510 14511 if ((opcode == BPF_LSH || opcode == BPF_RSH || 14512 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 14513 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 14514 14515 if (insn->imm < 0 || insn->imm >= size) { 14516 verbose(env, "invalid shift %d\n", insn->imm); 14517 return -EINVAL; 14518 } 14519 } 14520 14521 /* check dest operand */ 14522 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14523 err = err ?: adjust_reg_min_max_vals(env, insn); 14524 if (err) 14525 return err; 14526 } 14527 14528 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 14529 } 14530 14531 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 14532 struct bpf_reg_state *dst_reg, 14533 enum bpf_reg_type type, 14534 bool range_right_open) 14535 { 14536 struct bpf_func_state *state; 14537 struct bpf_reg_state *reg; 14538 int new_range; 14539 14540 if (dst_reg->off < 0 || 14541 (dst_reg->off == 0 && range_right_open)) 14542 /* This doesn't give us any range */ 14543 return; 14544 14545 if (dst_reg->umax_value > MAX_PACKET_OFF || 14546 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 14547 /* Risk of overflow. For instance, ptr + (1<<63) may be less 14548 * than pkt_end, but that's because it's also less than pkt. 14549 */ 14550 return; 14551 14552 new_range = dst_reg->off; 14553 if (range_right_open) 14554 new_range++; 14555 14556 /* Examples for register markings: 14557 * 14558 * pkt_data in dst register: 14559 * 14560 * r2 = r3; 14561 * r2 += 8; 14562 * if (r2 > pkt_end) goto <handle exception> 14563 * <access okay> 14564 * 14565 * r2 = r3; 14566 * r2 += 8; 14567 * if (r2 < pkt_end) goto <access okay> 14568 * <handle exception> 14569 * 14570 * Where: 14571 * r2 == dst_reg, pkt_end == src_reg 14572 * r2=pkt(id=n,off=8,r=0) 14573 * r3=pkt(id=n,off=0,r=0) 14574 * 14575 * pkt_data in src register: 14576 * 14577 * r2 = r3; 14578 * r2 += 8; 14579 * if (pkt_end >= r2) goto <access okay> 14580 * <handle exception> 14581 * 14582 * r2 = r3; 14583 * r2 += 8; 14584 * if (pkt_end <= r2) goto <handle exception> 14585 * <access okay> 14586 * 14587 * Where: 14588 * pkt_end == dst_reg, r2 == src_reg 14589 * r2=pkt(id=n,off=8,r=0) 14590 * r3=pkt(id=n,off=0,r=0) 14591 * 14592 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 14593 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 14594 * and [r3, r3 + 8-1) respectively is safe to access depending on 14595 * the check. 14596 */ 14597 14598 /* If our ids match, then we must have the same max_value. And we 14599 * don't care about the other reg's fixed offset, since if it's too big 14600 * the range won't allow anything. 14601 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 14602 */ 14603 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14604 if (reg->type == type && reg->id == dst_reg->id) 14605 /* keep the maximum range already checked */ 14606 reg->range = max(reg->range, new_range); 14607 })); 14608 } 14609 14610 /* 14611 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 14612 */ 14613 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14614 u8 opcode, bool is_jmp32) 14615 { 14616 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 14617 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 14618 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value; 14619 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value; 14620 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value; 14621 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value; 14622 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value; 14623 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value; 14624 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value; 14625 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value; 14626 14627 switch (opcode) { 14628 case BPF_JEQ: 14629 /* constants, umin/umax and smin/smax checks would be 14630 * redundant in this case because they all should match 14631 */ 14632 if (tnum_is_const(t1) && tnum_is_const(t2)) 14633 return t1.value == t2.value; 14634 /* non-overlapping ranges */ 14635 if (umin1 > umax2 || umax1 < umin2) 14636 return 0; 14637 if (smin1 > smax2 || smax1 < smin2) 14638 return 0; 14639 if (!is_jmp32) { 14640 /* if 64-bit ranges are inconclusive, see if we can 14641 * utilize 32-bit subrange knowledge to eliminate 14642 * branches that can't be taken a priori 14643 */ 14644 if (reg1->u32_min_value > reg2->u32_max_value || 14645 reg1->u32_max_value < reg2->u32_min_value) 14646 return 0; 14647 if (reg1->s32_min_value > reg2->s32_max_value || 14648 reg1->s32_max_value < reg2->s32_min_value) 14649 return 0; 14650 } 14651 break; 14652 case BPF_JNE: 14653 /* constants, umin/umax and smin/smax checks would be 14654 * redundant in this case because they all should match 14655 */ 14656 if (tnum_is_const(t1) && tnum_is_const(t2)) 14657 return t1.value != t2.value; 14658 /* non-overlapping ranges */ 14659 if (umin1 > umax2 || umax1 < umin2) 14660 return 1; 14661 if (smin1 > smax2 || smax1 < smin2) 14662 return 1; 14663 if (!is_jmp32) { 14664 /* if 64-bit ranges are inconclusive, see if we can 14665 * utilize 32-bit subrange knowledge to eliminate 14666 * branches that can't be taken a priori 14667 */ 14668 if (reg1->u32_min_value > reg2->u32_max_value || 14669 reg1->u32_max_value < reg2->u32_min_value) 14670 return 1; 14671 if (reg1->s32_min_value > reg2->s32_max_value || 14672 reg1->s32_max_value < reg2->s32_min_value) 14673 return 1; 14674 } 14675 break; 14676 case BPF_JSET: 14677 if (!is_reg_const(reg2, is_jmp32)) { 14678 swap(reg1, reg2); 14679 swap(t1, t2); 14680 } 14681 if (!is_reg_const(reg2, is_jmp32)) 14682 return -1; 14683 if ((~t1.mask & t1.value) & t2.value) 14684 return 1; 14685 if (!((t1.mask | t1.value) & t2.value)) 14686 return 0; 14687 break; 14688 case BPF_JGT: 14689 if (umin1 > umax2) 14690 return 1; 14691 else if (umax1 <= umin2) 14692 return 0; 14693 break; 14694 case BPF_JSGT: 14695 if (smin1 > smax2) 14696 return 1; 14697 else if (smax1 <= smin2) 14698 return 0; 14699 break; 14700 case BPF_JLT: 14701 if (umax1 < umin2) 14702 return 1; 14703 else if (umin1 >= umax2) 14704 return 0; 14705 break; 14706 case BPF_JSLT: 14707 if (smax1 < smin2) 14708 return 1; 14709 else if (smin1 >= smax2) 14710 return 0; 14711 break; 14712 case BPF_JGE: 14713 if (umin1 >= umax2) 14714 return 1; 14715 else if (umax1 < umin2) 14716 return 0; 14717 break; 14718 case BPF_JSGE: 14719 if (smin1 >= smax2) 14720 return 1; 14721 else if (smax1 < smin2) 14722 return 0; 14723 break; 14724 case BPF_JLE: 14725 if (umax1 <= umin2) 14726 return 1; 14727 else if (umin1 > umax2) 14728 return 0; 14729 break; 14730 case BPF_JSLE: 14731 if (smax1 <= smin2) 14732 return 1; 14733 else if (smin1 > smax2) 14734 return 0; 14735 break; 14736 } 14737 14738 return -1; 14739 } 14740 14741 static int flip_opcode(u32 opcode) 14742 { 14743 /* How can we transform "a <op> b" into "b <op> a"? */ 14744 static const u8 opcode_flip[16] = { 14745 /* these stay the same */ 14746 [BPF_JEQ >> 4] = BPF_JEQ, 14747 [BPF_JNE >> 4] = BPF_JNE, 14748 [BPF_JSET >> 4] = BPF_JSET, 14749 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 14750 [BPF_JGE >> 4] = BPF_JLE, 14751 [BPF_JGT >> 4] = BPF_JLT, 14752 [BPF_JLE >> 4] = BPF_JGE, 14753 [BPF_JLT >> 4] = BPF_JGT, 14754 [BPF_JSGE >> 4] = BPF_JSLE, 14755 [BPF_JSGT >> 4] = BPF_JSLT, 14756 [BPF_JSLE >> 4] = BPF_JSGE, 14757 [BPF_JSLT >> 4] = BPF_JSGT 14758 }; 14759 return opcode_flip[opcode >> 4]; 14760 } 14761 14762 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 14763 struct bpf_reg_state *src_reg, 14764 u8 opcode) 14765 { 14766 struct bpf_reg_state *pkt; 14767 14768 if (src_reg->type == PTR_TO_PACKET_END) { 14769 pkt = dst_reg; 14770 } else if (dst_reg->type == PTR_TO_PACKET_END) { 14771 pkt = src_reg; 14772 opcode = flip_opcode(opcode); 14773 } else { 14774 return -1; 14775 } 14776 14777 if (pkt->range >= 0) 14778 return -1; 14779 14780 switch (opcode) { 14781 case BPF_JLE: 14782 /* pkt <= pkt_end */ 14783 fallthrough; 14784 case BPF_JGT: 14785 /* pkt > pkt_end */ 14786 if (pkt->range == BEYOND_PKT_END) 14787 /* pkt has at last one extra byte beyond pkt_end */ 14788 return opcode == BPF_JGT; 14789 break; 14790 case BPF_JLT: 14791 /* pkt < pkt_end */ 14792 fallthrough; 14793 case BPF_JGE: 14794 /* pkt >= pkt_end */ 14795 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 14796 return opcode == BPF_JGE; 14797 break; 14798 } 14799 return -1; 14800 } 14801 14802 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 14803 * and return: 14804 * 1 - branch will be taken and "goto target" will be executed 14805 * 0 - branch will not be taken and fall-through to next insn 14806 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 14807 * range [0,10] 14808 */ 14809 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14810 u8 opcode, bool is_jmp32) 14811 { 14812 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 14813 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 14814 14815 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 14816 u64 val; 14817 14818 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 14819 if (!is_reg_const(reg2, is_jmp32)) { 14820 opcode = flip_opcode(opcode); 14821 swap(reg1, reg2); 14822 } 14823 /* and ensure that reg2 is a constant */ 14824 if (!is_reg_const(reg2, is_jmp32)) 14825 return -1; 14826 14827 if (!reg_not_null(reg1)) 14828 return -1; 14829 14830 /* If pointer is valid tests against zero will fail so we can 14831 * use this to direct branch taken. 14832 */ 14833 val = reg_const_value(reg2, is_jmp32); 14834 if (val != 0) 14835 return -1; 14836 14837 switch (opcode) { 14838 case BPF_JEQ: 14839 return 0; 14840 case BPF_JNE: 14841 return 1; 14842 default: 14843 return -1; 14844 } 14845 } 14846 14847 /* now deal with two scalars, but not necessarily constants */ 14848 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32); 14849 } 14850 14851 /* Opcode that corresponds to a *false* branch condition. 14852 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 14853 */ 14854 static u8 rev_opcode(u8 opcode) 14855 { 14856 switch (opcode) { 14857 case BPF_JEQ: return BPF_JNE; 14858 case BPF_JNE: return BPF_JEQ; 14859 /* JSET doesn't have it's reverse opcode in BPF, so add 14860 * BPF_X flag to denote the reverse of that operation 14861 */ 14862 case BPF_JSET: return BPF_JSET | BPF_X; 14863 case BPF_JSET | BPF_X: return BPF_JSET; 14864 case BPF_JGE: return BPF_JLT; 14865 case BPF_JGT: return BPF_JLE; 14866 case BPF_JLE: return BPF_JGT; 14867 case BPF_JLT: return BPF_JGE; 14868 case BPF_JSGE: return BPF_JSLT; 14869 case BPF_JSGT: return BPF_JSLE; 14870 case BPF_JSLE: return BPF_JSGT; 14871 case BPF_JSLT: return BPF_JSGE; 14872 default: return 0; 14873 } 14874 } 14875 14876 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 14877 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14878 u8 opcode, bool is_jmp32) 14879 { 14880 struct tnum t; 14881 u64 val; 14882 14883 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */ 14884 switch (opcode) { 14885 case BPF_JGE: 14886 case BPF_JGT: 14887 case BPF_JSGE: 14888 case BPF_JSGT: 14889 opcode = flip_opcode(opcode); 14890 swap(reg1, reg2); 14891 break; 14892 default: 14893 break; 14894 } 14895 14896 switch (opcode) { 14897 case BPF_JEQ: 14898 if (is_jmp32) { 14899 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14900 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14901 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14902 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14903 reg2->u32_min_value = reg1->u32_min_value; 14904 reg2->u32_max_value = reg1->u32_max_value; 14905 reg2->s32_min_value = reg1->s32_min_value; 14906 reg2->s32_max_value = reg1->s32_max_value; 14907 14908 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 14909 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14910 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 14911 } else { 14912 reg1->umin_value = max(reg1->umin_value, reg2->umin_value); 14913 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14914 reg1->smin_value = max(reg1->smin_value, reg2->smin_value); 14915 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14916 reg2->umin_value = reg1->umin_value; 14917 reg2->umax_value = reg1->umax_value; 14918 reg2->smin_value = reg1->smin_value; 14919 reg2->smax_value = reg1->smax_value; 14920 14921 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 14922 reg2->var_off = reg1->var_off; 14923 } 14924 break; 14925 case BPF_JNE: 14926 if (!is_reg_const(reg2, is_jmp32)) 14927 swap(reg1, reg2); 14928 if (!is_reg_const(reg2, is_jmp32)) 14929 break; 14930 14931 /* try to recompute the bound of reg1 if reg2 is a const and 14932 * is exactly the edge of reg1. 14933 */ 14934 val = reg_const_value(reg2, is_jmp32); 14935 if (is_jmp32) { 14936 /* u32_min_value is not equal to 0xffffffff at this point, 14937 * because otherwise u32_max_value is 0xffffffff as well, 14938 * in such a case both reg1 and reg2 would be constants, 14939 * jump would be predicted and reg_set_min_max() won't 14940 * be called. 14941 * 14942 * Same reasoning works for all {u,s}{min,max}{32,64} cases 14943 * below. 14944 */ 14945 if (reg1->u32_min_value == (u32)val) 14946 reg1->u32_min_value++; 14947 if (reg1->u32_max_value == (u32)val) 14948 reg1->u32_max_value--; 14949 if (reg1->s32_min_value == (s32)val) 14950 reg1->s32_min_value++; 14951 if (reg1->s32_max_value == (s32)val) 14952 reg1->s32_max_value--; 14953 } else { 14954 if (reg1->umin_value == (u64)val) 14955 reg1->umin_value++; 14956 if (reg1->umax_value == (u64)val) 14957 reg1->umax_value--; 14958 if (reg1->smin_value == (s64)val) 14959 reg1->smin_value++; 14960 if (reg1->smax_value == (s64)val) 14961 reg1->smax_value--; 14962 } 14963 break; 14964 case BPF_JSET: 14965 if (!is_reg_const(reg2, is_jmp32)) 14966 swap(reg1, reg2); 14967 if (!is_reg_const(reg2, is_jmp32)) 14968 break; 14969 val = reg_const_value(reg2, is_jmp32); 14970 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 14971 * requires single bit to learn something useful. E.g., if we 14972 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 14973 * are actually set? We can learn something definite only if 14974 * it's a single-bit value to begin with. 14975 * 14976 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 14977 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 14978 * bit 1 is set, which we can readily use in adjustments. 14979 */ 14980 if (!is_power_of_2(val)) 14981 break; 14982 if (is_jmp32) { 14983 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 14984 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14985 } else { 14986 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 14987 } 14988 break; 14989 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 14990 if (!is_reg_const(reg2, is_jmp32)) 14991 swap(reg1, reg2); 14992 if (!is_reg_const(reg2, is_jmp32)) 14993 break; 14994 val = reg_const_value(reg2, is_jmp32); 14995 if (is_jmp32) { 14996 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 14997 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14998 } else { 14999 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 15000 } 15001 break; 15002 case BPF_JLE: 15003 if (is_jmp32) { 15004 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 15005 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 15006 } else { 15007 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 15008 reg2->umin_value = max(reg1->umin_value, reg2->umin_value); 15009 } 15010 break; 15011 case BPF_JLT: 15012 if (is_jmp32) { 15013 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1); 15014 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value); 15015 } else { 15016 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1); 15017 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value); 15018 } 15019 break; 15020 case BPF_JSLE: 15021 if (is_jmp32) { 15022 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 15023 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 15024 } else { 15025 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 15026 reg2->smin_value = max(reg1->smin_value, reg2->smin_value); 15027 } 15028 break; 15029 case BPF_JSLT: 15030 if (is_jmp32) { 15031 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1); 15032 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value); 15033 } else { 15034 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1); 15035 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value); 15036 } 15037 break; 15038 default: 15039 return; 15040 } 15041 } 15042 15043 /* Adjusts the register min/max values in the case that the dst_reg and 15044 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K 15045 * check, in which case we have a fake SCALAR_VALUE representing insn->imm). 15046 * Technically we can do similar adjustments for pointers to the same object, 15047 * but we don't support that right now. 15048 */ 15049 static int reg_set_min_max(struct bpf_verifier_env *env, 15050 struct bpf_reg_state *true_reg1, 15051 struct bpf_reg_state *true_reg2, 15052 struct bpf_reg_state *false_reg1, 15053 struct bpf_reg_state *false_reg2, 15054 u8 opcode, bool is_jmp32) 15055 { 15056 int err; 15057 15058 /* If either register is a pointer, we can't learn anything about its 15059 * variable offset from the compare (unless they were a pointer into 15060 * the same object, but we don't bother with that). 15061 */ 15062 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE) 15063 return 0; 15064 15065 /* fallthrough (FALSE) branch */ 15066 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32); 15067 reg_bounds_sync(false_reg1); 15068 reg_bounds_sync(false_reg2); 15069 15070 /* jump (TRUE) branch */ 15071 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32); 15072 reg_bounds_sync(true_reg1); 15073 reg_bounds_sync(true_reg2); 15074 15075 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1"); 15076 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2"); 15077 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1"); 15078 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2"); 15079 return err; 15080 } 15081 15082 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 15083 struct bpf_reg_state *reg, u32 id, 15084 bool is_null) 15085 { 15086 if (type_may_be_null(reg->type) && reg->id == id && 15087 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 15088 /* Old offset (both fixed and variable parts) should have been 15089 * known-zero, because we don't allow pointer arithmetic on 15090 * pointers that might be NULL. If we see this happening, don't 15091 * convert the register. 15092 * 15093 * But in some cases, some helpers that return local kptrs 15094 * advance offset for the returned pointer. In those cases, it 15095 * is fine to expect to see reg->off. 15096 */ 15097 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 15098 return; 15099 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 15100 WARN_ON_ONCE(reg->off)) 15101 return; 15102 15103 if (is_null) { 15104 reg->type = SCALAR_VALUE; 15105 /* We don't need id and ref_obj_id from this point 15106 * onwards anymore, thus we should better reset it, 15107 * so that state pruning has chances to take effect. 15108 */ 15109 reg->id = 0; 15110 reg->ref_obj_id = 0; 15111 15112 return; 15113 } 15114 15115 mark_ptr_not_null_reg(reg); 15116 15117 if (!reg_may_point_to_spin_lock(reg)) { 15118 /* For not-NULL ptr, reg->ref_obj_id will be reset 15119 * in release_reference(). 15120 * 15121 * reg->id is still used by spin_lock ptr. Other 15122 * than spin_lock ptr type, reg->id can be reset. 15123 */ 15124 reg->id = 0; 15125 } 15126 } 15127 } 15128 15129 /* The logic is similar to find_good_pkt_pointers(), both could eventually 15130 * be folded together at some point. 15131 */ 15132 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 15133 bool is_null) 15134 { 15135 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 15136 struct bpf_reg_state *regs = state->regs, *reg; 15137 u32 ref_obj_id = regs[regno].ref_obj_id; 15138 u32 id = regs[regno].id; 15139 15140 if (ref_obj_id && ref_obj_id == id && is_null) 15141 /* regs[regno] is in the " == NULL" branch. 15142 * No one could have freed the reference state before 15143 * doing the NULL check. 15144 */ 15145 WARN_ON_ONCE(release_reference_state(state, id)); 15146 15147 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15148 mark_ptr_or_null_reg(state, reg, id, is_null); 15149 })); 15150 } 15151 15152 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 15153 struct bpf_reg_state *dst_reg, 15154 struct bpf_reg_state *src_reg, 15155 struct bpf_verifier_state *this_branch, 15156 struct bpf_verifier_state *other_branch) 15157 { 15158 if (BPF_SRC(insn->code) != BPF_X) 15159 return false; 15160 15161 /* Pointers are always 64-bit. */ 15162 if (BPF_CLASS(insn->code) == BPF_JMP32) 15163 return false; 15164 15165 switch (BPF_OP(insn->code)) { 15166 case BPF_JGT: 15167 if ((dst_reg->type == PTR_TO_PACKET && 15168 src_reg->type == PTR_TO_PACKET_END) || 15169 (dst_reg->type == PTR_TO_PACKET_META && 15170 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15171 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 15172 find_good_pkt_pointers(this_branch, dst_reg, 15173 dst_reg->type, false); 15174 mark_pkt_end(other_branch, insn->dst_reg, true); 15175 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15176 src_reg->type == PTR_TO_PACKET) || 15177 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15178 src_reg->type == PTR_TO_PACKET_META)) { 15179 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 15180 find_good_pkt_pointers(other_branch, src_reg, 15181 src_reg->type, true); 15182 mark_pkt_end(this_branch, insn->src_reg, false); 15183 } else { 15184 return false; 15185 } 15186 break; 15187 case BPF_JLT: 15188 if ((dst_reg->type == PTR_TO_PACKET && 15189 src_reg->type == PTR_TO_PACKET_END) || 15190 (dst_reg->type == PTR_TO_PACKET_META && 15191 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15192 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 15193 find_good_pkt_pointers(other_branch, dst_reg, 15194 dst_reg->type, true); 15195 mark_pkt_end(this_branch, insn->dst_reg, false); 15196 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15197 src_reg->type == PTR_TO_PACKET) || 15198 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15199 src_reg->type == PTR_TO_PACKET_META)) { 15200 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 15201 find_good_pkt_pointers(this_branch, src_reg, 15202 src_reg->type, false); 15203 mark_pkt_end(other_branch, insn->src_reg, true); 15204 } else { 15205 return false; 15206 } 15207 break; 15208 case BPF_JGE: 15209 if ((dst_reg->type == PTR_TO_PACKET && 15210 src_reg->type == PTR_TO_PACKET_END) || 15211 (dst_reg->type == PTR_TO_PACKET_META && 15212 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15213 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 15214 find_good_pkt_pointers(this_branch, dst_reg, 15215 dst_reg->type, true); 15216 mark_pkt_end(other_branch, insn->dst_reg, false); 15217 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15218 src_reg->type == PTR_TO_PACKET) || 15219 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15220 src_reg->type == PTR_TO_PACKET_META)) { 15221 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 15222 find_good_pkt_pointers(other_branch, src_reg, 15223 src_reg->type, false); 15224 mark_pkt_end(this_branch, insn->src_reg, true); 15225 } else { 15226 return false; 15227 } 15228 break; 15229 case BPF_JLE: 15230 if ((dst_reg->type == PTR_TO_PACKET && 15231 src_reg->type == PTR_TO_PACKET_END) || 15232 (dst_reg->type == PTR_TO_PACKET_META && 15233 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15234 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 15235 find_good_pkt_pointers(other_branch, dst_reg, 15236 dst_reg->type, false); 15237 mark_pkt_end(this_branch, insn->dst_reg, true); 15238 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15239 src_reg->type == PTR_TO_PACKET) || 15240 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15241 src_reg->type == PTR_TO_PACKET_META)) { 15242 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 15243 find_good_pkt_pointers(this_branch, src_reg, 15244 src_reg->type, true); 15245 mark_pkt_end(other_branch, insn->src_reg, false); 15246 } else { 15247 return false; 15248 } 15249 break; 15250 default: 15251 return false; 15252 } 15253 15254 return true; 15255 } 15256 15257 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg, 15258 u32 id, u32 frameno, u32 spi_or_reg, bool is_reg) 15259 { 15260 struct linked_reg *e; 15261 15262 if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id) 15263 return; 15264 15265 e = linked_regs_push(reg_set); 15266 if (e) { 15267 e->frameno = frameno; 15268 e->is_reg = is_reg; 15269 e->regno = spi_or_reg; 15270 } else { 15271 reg->id = 0; 15272 } 15273 } 15274 15275 /* For all R being scalar registers or spilled scalar registers 15276 * in verifier state, save R in linked_regs if R->id == id. 15277 * If there are too many Rs sharing same id, reset id for leftover Rs. 15278 */ 15279 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id, 15280 struct linked_regs *linked_regs) 15281 { 15282 struct bpf_func_state *func; 15283 struct bpf_reg_state *reg; 15284 int i, j; 15285 15286 id = id & ~BPF_ADD_CONST; 15287 for (i = vstate->curframe; i >= 0; i--) { 15288 func = vstate->frame[i]; 15289 for (j = 0; j < BPF_REG_FP; j++) { 15290 reg = &func->regs[j]; 15291 __collect_linked_regs(linked_regs, reg, id, i, j, true); 15292 } 15293 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 15294 if (!is_spilled_reg(&func->stack[j])) 15295 continue; 15296 reg = &func->stack[j].spilled_ptr; 15297 __collect_linked_regs(linked_regs, reg, id, i, j, false); 15298 } 15299 } 15300 } 15301 15302 /* For all R in linked_regs, copy known_reg range into R 15303 * if R->id == known_reg->id. 15304 */ 15305 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg, 15306 struct linked_regs *linked_regs) 15307 { 15308 struct bpf_reg_state fake_reg; 15309 struct bpf_reg_state *reg; 15310 struct linked_reg *e; 15311 int i; 15312 15313 for (i = 0; i < linked_regs->cnt; ++i) { 15314 e = &linked_regs->entries[i]; 15315 reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno] 15316 : &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr; 15317 if (reg->type != SCALAR_VALUE || reg == known_reg) 15318 continue; 15319 if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST)) 15320 continue; 15321 if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) || 15322 reg->off == known_reg->off) { 15323 s32 saved_subreg_def = reg->subreg_def; 15324 15325 copy_register_state(reg, known_reg); 15326 reg->subreg_def = saved_subreg_def; 15327 } else { 15328 s32 saved_subreg_def = reg->subreg_def; 15329 s32 saved_off = reg->off; 15330 15331 fake_reg.type = SCALAR_VALUE; 15332 __mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off); 15333 15334 /* reg = known_reg; reg += delta */ 15335 copy_register_state(reg, known_reg); 15336 /* 15337 * Must preserve off, id and add_const flag, 15338 * otherwise another sync_linked_regs() will be incorrect. 15339 */ 15340 reg->off = saved_off; 15341 reg->subreg_def = saved_subreg_def; 15342 15343 scalar32_min_max_add(reg, &fake_reg); 15344 scalar_min_max_add(reg, &fake_reg); 15345 reg->var_off = tnum_add(reg->var_off, fake_reg.var_off); 15346 } 15347 } 15348 } 15349 15350 static int check_cond_jmp_op(struct bpf_verifier_env *env, 15351 struct bpf_insn *insn, int *insn_idx) 15352 { 15353 struct bpf_verifier_state *this_branch = env->cur_state; 15354 struct bpf_verifier_state *other_branch; 15355 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 15356 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 15357 struct bpf_reg_state *eq_branch_regs; 15358 struct linked_regs linked_regs = {}; 15359 u8 opcode = BPF_OP(insn->code); 15360 bool is_jmp32; 15361 int pred = -1; 15362 int err; 15363 15364 /* Only conditional jumps are expected to reach here. */ 15365 if (opcode == BPF_JA || opcode > BPF_JCOND) { 15366 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 15367 return -EINVAL; 15368 } 15369 15370 if (opcode == BPF_JCOND) { 15371 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 15372 int idx = *insn_idx; 15373 15374 if (insn->code != (BPF_JMP | BPF_JCOND) || 15375 insn->src_reg != BPF_MAY_GOTO || 15376 insn->dst_reg || insn->imm || insn->off == 0) { 15377 verbose(env, "invalid may_goto off %d imm %d\n", 15378 insn->off, insn->imm); 15379 return -EINVAL; 15380 } 15381 prev_st = find_prev_entry(env, cur_st->parent, idx); 15382 15383 /* branch out 'fallthrough' insn as a new state to explore */ 15384 queued_st = push_stack(env, idx + 1, idx, false); 15385 if (!queued_st) 15386 return -ENOMEM; 15387 15388 queued_st->may_goto_depth++; 15389 if (prev_st) 15390 widen_imprecise_scalars(env, prev_st, queued_st); 15391 *insn_idx += insn->off; 15392 return 0; 15393 } 15394 15395 /* check src2 operand */ 15396 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15397 if (err) 15398 return err; 15399 15400 dst_reg = ®s[insn->dst_reg]; 15401 if (BPF_SRC(insn->code) == BPF_X) { 15402 if (insn->imm != 0) { 15403 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 15404 return -EINVAL; 15405 } 15406 15407 /* check src1 operand */ 15408 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15409 if (err) 15410 return err; 15411 15412 src_reg = ®s[insn->src_reg]; 15413 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 15414 is_pointer_value(env, insn->src_reg)) { 15415 verbose(env, "R%d pointer comparison prohibited\n", 15416 insn->src_reg); 15417 return -EACCES; 15418 } 15419 } else { 15420 if (insn->src_reg != BPF_REG_0) { 15421 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 15422 return -EINVAL; 15423 } 15424 src_reg = &env->fake_reg[0]; 15425 memset(src_reg, 0, sizeof(*src_reg)); 15426 src_reg->type = SCALAR_VALUE; 15427 __mark_reg_known(src_reg, insn->imm); 15428 } 15429 15430 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 15431 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32); 15432 if (pred >= 0) { 15433 /* If we get here with a dst_reg pointer type it is because 15434 * above is_branch_taken() special cased the 0 comparison. 15435 */ 15436 if (!__is_pointer_value(false, dst_reg)) 15437 err = mark_chain_precision(env, insn->dst_reg); 15438 if (BPF_SRC(insn->code) == BPF_X && !err && 15439 !__is_pointer_value(false, src_reg)) 15440 err = mark_chain_precision(env, insn->src_reg); 15441 if (err) 15442 return err; 15443 } 15444 15445 if (pred == 1) { 15446 /* Only follow the goto, ignore fall-through. If needed, push 15447 * the fall-through branch for simulation under speculative 15448 * execution. 15449 */ 15450 if (!env->bypass_spec_v1 && 15451 !sanitize_speculative_path(env, insn, *insn_idx + 1, 15452 *insn_idx)) 15453 return -EFAULT; 15454 if (env->log.level & BPF_LOG_LEVEL) 15455 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15456 *insn_idx += insn->off; 15457 return 0; 15458 } else if (pred == 0) { 15459 /* Only follow the fall-through branch, since that's where the 15460 * program will go. If needed, push the goto branch for 15461 * simulation under speculative execution. 15462 */ 15463 if (!env->bypass_spec_v1 && 15464 !sanitize_speculative_path(env, insn, 15465 *insn_idx + insn->off + 1, 15466 *insn_idx)) 15467 return -EFAULT; 15468 if (env->log.level & BPF_LOG_LEVEL) 15469 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15470 return 0; 15471 } 15472 15473 /* Push scalar registers sharing same ID to jump history, 15474 * do this before creating 'other_branch', so that both 15475 * 'this_branch' and 'other_branch' share this history 15476 * if parent state is created. 15477 */ 15478 if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id) 15479 collect_linked_regs(this_branch, src_reg->id, &linked_regs); 15480 if (dst_reg->type == SCALAR_VALUE && dst_reg->id) 15481 collect_linked_regs(this_branch, dst_reg->id, &linked_regs); 15482 if (linked_regs.cnt > 1) { 15483 err = push_jmp_history(env, this_branch, 0, linked_regs_pack(&linked_regs)); 15484 if (err) 15485 return err; 15486 } 15487 15488 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 15489 false); 15490 if (!other_branch) 15491 return -EFAULT; 15492 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 15493 15494 if (BPF_SRC(insn->code) == BPF_X) { 15495 err = reg_set_min_max(env, 15496 &other_branch_regs[insn->dst_reg], 15497 &other_branch_regs[insn->src_reg], 15498 dst_reg, src_reg, opcode, is_jmp32); 15499 } else /* BPF_SRC(insn->code) == BPF_K */ { 15500 /* reg_set_min_max() can mangle the fake_reg. Make a copy 15501 * so that these are two different memory locations. The 15502 * src_reg is not used beyond here in context of K. 15503 */ 15504 memcpy(&env->fake_reg[1], &env->fake_reg[0], 15505 sizeof(env->fake_reg[0])); 15506 err = reg_set_min_max(env, 15507 &other_branch_regs[insn->dst_reg], 15508 &env->fake_reg[0], 15509 dst_reg, &env->fake_reg[1], 15510 opcode, is_jmp32); 15511 } 15512 if (err) 15513 return err; 15514 15515 if (BPF_SRC(insn->code) == BPF_X && 15516 src_reg->type == SCALAR_VALUE && src_reg->id && 15517 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 15518 sync_linked_regs(this_branch, src_reg, &linked_regs); 15519 sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs); 15520 } 15521 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 15522 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 15523 sync_linked_regs(this_branch, dst_reg, &linked_regs); 15524 sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs); 15525 } 15526 15527 /* if one pointer register is compared to another pointer 15528 * register check if PTR_MAYBE_NULL could be lifted. 15529 * E.g. register A - maybe null 15530 * register B - not null 15531 * for JNE A, B, ... - A is not null in the false branch; 15532 * for JEQ A, B, ... - A is not null in the true branch. 15533 * 15534 * Since PTR_TO_BTF_ID points to a kernel struct that does 15535 * not need to be null checked by the BPF program, i.e., 15536 * could be null even without PTR_MAYBE_NULL marking, so 15537 * only propagate nullness when neither reg is that type. 15538 */ 15539 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 15540 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 15541 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 15542 base_type(src_reg->type) != PTR_TO_BTF_ID && 15543 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 15544 eq_branch_regs = NULL; 15545 switch (opcode) { 15546 case BPF_JEQ: 15547 eq_branch_regs = other_branch_regs; 15548 break; 15549 case BPF_JNE: 15550 eq_branch_regs = regs; 15551 break; 15552 default: 15553 /* do nothing */ 15554 break; 15555 } 15556 if (eq_branch_regs) { 15557 if (type_may_be_null(src_reg->type)) 15558 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 15559 else 15560 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 15561 } 15562 } 15563 15564 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 15565 * NOTE: these optimizations below are related with pointer comparison 15566 * which will never be JMP32. 15567 */ 15568 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 15569 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 15570 type_may_be_null(dst_reg->type)) { 15571 /* Mark all identical registers in each branch as either 15572 * safe or unknown depending R == 0 or R != 0 conditional. 15573 */ 15574 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 15575 opcode == BPF_JNE); 15576 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 15577 opcode == BPF_JEQ); 15578 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 15579 this_branch, other_branch) && 15580 is_pointer_value(env, insn->dst_reg)) { 15581 verbose(env, "R%d pointer comparison prohibited\n", 15582 insn->dst_reg); 15583 return -EACCES; 15584 } 15585 if (env->log.level & BPF_LOG_LEVEL) 15586 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15587 return 0; 15588 } 15589 15590 /* verify BPF_LD_IMM64 instruction */ 15591 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 15592 { 15593 struct bpf_insn_aux_data *aux = cur_aux(env); 15594 struct bpf_reg_state *regs = cur_regs(env); 15595 struct bpf_reg_state *dst_reg; 15596 struct bpf_map *map; 15597 int err; 15598 15599 if (BPF_SIZE(insn->code) != BPF_DW) { 15600 verbose(env, "invalid BPF_LD_IMM insn\n"); 15601 return -EINVAL; 15602 } 15603 if (insn->off != 0) { 15604 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 15605 return -EINVAL; 15606 } 15607 15608 err = check_reg_arg(env, insn->dst_reg, DST_OP); 15609 if (err) 15610 return err; 15611 15612 dst_reg = ®s[insn->dst_reg]; 15613 if (insn->src_reg == 0) { 15614 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 15615 15616 dst_reg->type = SCALAR_VALUE; 15617 __mark_reg_known(®s[insn->dst_reg], imm); 15618 return 0; 15619 } 15620 15621 /* All special src_reg cases are listed below. From this point onwards 15622 * we either succeed and assign a corresponding dst_reg->type after 15623 * zeroing the offset, or fail and reject the program. 15624 */ 15625 mark_reg_known_zero(env, regs, insn->dst_reg); 15626 15627 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 15628 dst_reg->type = aux->btf_var.reg_type; 15629 switch (base_type(dst_reg->type)) { 15630 case PTR_TO_MEM: 15631 dst_reg->mem_size = aux->btf_var.mem_size; 15632 break; 15633 case PTR_TO_BTF_ID: 15634 dst_reg->btf = aux->btf_var.btf; 15635 dst_reg->btf_id = aux->btf_var.btf_id; 15636 break; 15637 default: 15638 verbose(env, "bpf verifier is misconfigured\n"); 15639 return -EFAULT; 15640 } 15641 return 0; 15642 } 15643 15644 if (insn->src_reg == BPF_PSEUDO_FUNC) { 15645 struct bpf_prog_aux *aux = env->prog->aux; 15646 u32 subprogno = find_subprog(env, 15647 env->insn_idx + insn->imm + 1); 15648 15649 if (!aux->func_info) { 15650 verbose(env, "missing btf func_info\n"); 15651 return -EINVAL; 15652 } 15653 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 15654 verbose(env, "callback function not static\n"); 15655 return -EINVAL; 15656 } 15657 15658 dst_reg->type = PTR_TO_FUNC; 15659 dst_reg->subprogno = subprogno; 15660 return 0; 15661 } 15662 15663 map = env->used_maps[aux->map_index]; 15664 dst_reg->map_ptr = map; 15665 15666 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 15667 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 15668 if (map->map_type == BPF_MAP_TYPE_ARENA) { 15669 __mark_reg_unknown(env, dst_reg); 15670 return 0; 15671 } 15672 dst_reg->type = PTR_TO_MAP_VALUE; 15673 dst_reg->off = aux->map_off; 15674 WARN_ON_ONCE(map->max_entries != 1); 15675 /* We want reg->id to be same (0) as map_value is not distinct */ 15676 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 15677 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 15678 dst_reg->type = CONST_PTR_TO_MAP; 15679 } else { 15680 verbose(env, "bpf verifier is misconfigured\n"); 15681 return -EINVAL; 15682 } 15683 15684 return 0; 15685 } 15686 15687 static bool may_access_skb(enum bpf_prog_type type) 15688 { 15689 switch (type) { 15690 case BPF_PROG_TYPE_SOCKET_FILTER: 15691 case BPF_PROG_TYPE_SCHED_CLS: 15692 case BPF_PROG_TYPE_SCHED_ACT: 15693 return true; 15694 default: 15695 return false; 15696 } 15697 } 15698 15699 /* verify safety of LD_ABS|LD_IND instructions: 15700 * - they can only appear in the programs where ctx == skb 15701 * - since they are wrappers of function calls, they scratch R1-R5 registers, 15702 * preserve R6-R9, and store return value into R0 15703 * 15704 * Implicit input: 15705 * ctx == skb == R6 == CTX 15706 * 15707 * Explicit input: 15708 * SRC == any register 15709 * IMM == 32-bit immediate 15710 * 15711 * Output: 15712 * R0 - 8/16/32-bit skb data converted to cpu endianness 15713 */ 15714 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 15715 { 15716 struct bpf_reg_state *regs = cur_regs(env); 15717 static const int ctx_reg = BPF_REG_6; 15718 u8 mode = BPF_MODE(insn->code); 15719 int i, err; 15720 15721 if (!may_access_skb(resolve_prog_type(env->prog))) { 15722 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 15723 return -EINVAL; 15724 } 15725 15726 if (!env->ops->gen_ld_abs) { 15727 verbose(env, "bpf verifier is misconfigured\n"); 15728 return -EINVAL; 15729 } 15730 15731 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 15732 BPF_SIZE(insn->code) == BPF_DW || 15733 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 15734 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 15735 return -EINVAL; 15736 } 15737 15738 /* check whether implicit source operand (register R6) is readable */ 15739 err = check_reg_arg(env, ctx_reg, SRC_OP); 15740 if (err) 15741 return err; 15742 15743 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 15744 * gen_ld_abs() may terminate the program at runtime, leading to 15745 * reference leak. 15746 */ 15747 err = check_reference_leak(env, false); 15748 if (err) { 15749 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 15750 return err; 15751 } 15752 15753 if (env->cur_state->active_lock.ptr) { 15754 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 15755 return -EINVAL; 15756 } 15757 15758 if (env->cur_state->active_rcu_lock) { 15759 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 15760 return -EINVAL; 15761 } 15762 15763 if (env->cur_state->active_preempt_lock) { 15764 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_preempt_disable-ed region\n"); 15765 return -EINVAL; 15766 } 15767 15768 if (regs[ctx_reg].type != PTR_TO_CTX) { 15769 verbose(env, 15770 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 15771 return -EINVAL; 15772 } 15773 15774 if (mode == BPF_IND) { 15775 /* check explicit source operand */ 15776 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15777 if (err) 15778 return err; 15779 } 15780 15781 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 15782 if (err < 0) 15783 return err; 15784 15785 /* reset caller saved regs to unreadable */ 15786 for (i = 0; i < CALLER_SAVED_REGS; i++) { 15787 mark_reg_not_init(env, regs, caller_saved[i]); 15788 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 15789 } 15790 15791 /* mark destination R0 register as readable, since it contains 15792 * the value fetched from the packet. 15793 * Already marked as written above. 15794 */ 15795 mark_reg_unknown(env, regs, BPF_REG_0); 15796 /* ld_abs load up to 32-bit skb data. */ 15797 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 15798 return 0; 15799 } 15800 15801 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 15802 { 15803 const char *exit_ctx = "At program exit"; 15804 struct tnum enforce_attach_type_range = tnum_unknown; 15805 const struct bpf_prog *prog = env->prog; 15806 struct bpf_reg_state *reg; 15807 struct bpf_retval_range range = retval_range(0, 1); 15808 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 15809 int err; 15810 struct bpf_func_state *frame = env->cur_state->frame[0]; 15811 const bool is_subprog = frame->subprogno; 15812 bool return_32bit = false; 15813 15814 /* LSM and struct_ops func-ptr's return type could be "void" */ 15815 if (!is_subprog || frame->in_exception_callback_fn) { 15816 switch (prog_type) { 15817 case BPF_PROG_TYPE_LSM: 15818 if (prog->expected_attach_type == BPF_LSM_CGROUP) 15819 /* See below, can be 0 or 0-1 depending on hook. */ 15820 break; 15821 fallthrough; 15822 case BPF_PROG_TYPE_STRUCT_OPS: 15823 if (!prog->aux->attach_func_proto->type) 15824 return 0; 15825 break; 15826 default: 15827 break; 15828 } 15829 } 15830 15831 /* eBPF calling convention is such that R0 is used 15832 * to return the value from eBPF program. 15833 * Make sure that it's readable at this time 15834 * of bpf_exit, which means that program wrote 15835 * something into it earlier 15836 */ 15837 err = check_reg_arg(env, regno, SRC_OP); 15838 if (err) 15839 return err; 15840 15841 if (is_pointer_value(env, regno)) { 15842 verbose(env, "R%d leaks addr as return value\n", regno); 15843 return -EACCES; 15844 } 15845 15846 reg = cur_regs(env) + regno; 15847 15848 if (frame->in_async_callback_fn) { 15849 /* enforce return zero from async callbacks like timer */ 15850 exit_ctx = "At async callback return"; 15851 range = retval_range(0, 0); 15852 goto enforce_retval; 15853 } 15854 15855 if (is_subprog && !frame->in_exception_callback_fn) { 15856 if (reg->type != SCALAR_VALUE) { 15857 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 15858 regno, reg_type_str(env, reg->type)); 15859 return -EINVAL; 15860 } 15861 return 0; 15862 } 15863 15864 switch (prog_type) { 15865 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 15866 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 15867 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 15868 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG || 15869 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 15870 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 15871 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME || 15872 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 15873 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME || 15874 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME) 15875 range = retval_range(1, 1); 15876 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 15877 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 15878 range = retval_range(0, 3); 15879 break; 15880 case BPF_PROG_TYPE_CGROUP_SKB: 15881 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 15882 range = retval_range(0, 3); 15883 enforce_attach_type_range = tnum_range(2, 3); 15884 } 15885 break; 15886 case BPF_PROG_TYPE_CGROUP_SOCK: 15887 case BPF_PROG_TYPE_SOCK_OPS: 15888 case BPF_PROG_TYPE_CGROUP_DEVICE: 15889 case BPF_PROG_TYPE_CGROUP_SYSCTL: 15890 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 15891 break; 15892 case BPF_PROG_TYPE_RAW_TRACEPOINT: 15893 if (!env->prog->aux->attach_btf_id) 15894 return 0; 15895 range = retval_range(0, 0); 15896 break; 15897 case BPF_PROG_TYPE_TRACING: 15898 switch (env->prog->expected_attach_type) { 15899 case BPF_TRACE_FENTRY: 15900 case BPF_TRACE_FEXIT: 15901 range = retval_range(0, 0); 15902 break; 15903 case BPF_TRACE_RAW_TP: 15904 case BPF_MODIFY_RETURN: 15905 return 0; 15906 case BPF_TRACE_ITER: 15907 break; 15908 default: 15909 return -ENOTSUPP; 15910 } 15911 break; 15912 case BPF_PROG_TYPE_SK_LOOKUP: 15913 range = retval_range(SK_DROP, SK_PASS); 15914 break; 15915 15916 case BPF_PROG_TYPE_LSM: 15917 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 15918 /* no range found, any return value is allowed */ 15919 if (!get_func_retval_range(env->prog, &range)) 15920 return 0; 15921 /* no restricted range, any return value is allowed */ 15922 if (range.minval == S32_MIN && range.maxval == S32_MAX) 15923 return 0; 15924 return_32bit = true; 15925 } else if (!env->prog->aux->attach_func_proto->type) { 15926 /* Make sure programs that attach to void 15927 * hooks don't try to modify return value. 15928 */ 15929 range = retval_range(1, 1); 15930 } 15931 break; 15932 15933 case BPF_PROG_TYPE_NETFILTER: 15934 range = retval_range(NF_DROP, NF_ACCEPT); 15935 break; 15936 case BPF_PROG_TYPE_EXT: 15937 /* freplace program can return anything as its return value 15938 * depends on the to-be-replaced kernel func or bpf program. 15939 */ 15940 default: 15941 return 0; 15942 } 15943 15944 enforce_retval: 15945 if (reg->type != SCALAR_VALUE) { 15946 verbose(env, "%s the register R%d is not a known value (%s)\n", 15947 exit_ctx, regno, reg_type_str(env, reg->type)); 15948 return -EINVAL; 15949 } 15950 15951 err = mark_chain_precision(env, regno); 15952 if (err) 15953 return err; 15954 15955 if (!retval_range_within(range, reg, return_32bit)) { 15956 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 15957 if (!is_subprog && 15958 prog->expected_attach_type == BPF_LSM_CGROUP && 15959 prog_type == BPF_PROG_TYPE_LSM && 15960 !prog->aux->attach_func_proto->type) 15961 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 15962 return -EINVAL; 15963 } 15964 15965 if (!tnum_is_unknown(enforce_attach_type_range) && 15966 tnum_in(enforce_attach_type_range, reg->var_off)) 15967 env->prog->enforce_expected_attach_type = 1; 15968 return 0; 15969 } 15970 15971 /* non-recursive DFS pseudo code 15972 * 1 procedure DFS-iterative(G,v): 15973 * 2 label v as discovered 15974 * 3 let S be a stack 15975 * 4 S.push(v) 15976 * 5 while S is not empty 15977 * 6 t <- S.peek() 15978 * 7 if t is what we're looking for: 15979 * 8 return t 15980 * 9 for all edges e in G.adjacentEdges(t) do 15981 * 10 if edge e is already labelled 15982 * 11 continue with the next edge 15983 * 12 w <- G.adjacentVertex(t,e) 15984 * 13 if vertex w is not discovered and not explored 15985 * 14 label e as tree-edge 15986 * 15 label w as discovered 15987 * 16 S.push(w) 15988 * 17 continue at 5 15989 * 18 else if vertex w is discovered 15990 * 19 label e as back-edge 15991 * 20 else 15992 * 21 // vertex w is explored 15993 * 22 label e as forward- or cross-edge 15994 * 23 label t as explored 15995 * 24 S.pop() 15996 * 15997 * convention: 15998 * 0x10 - discovered 15999 * 0x11 - discovered and fall-through edge labelled 16000 * 0x12 - discovered and fall-through and branch edges labelled 16001 * 0x20 - explored 16002 */ 16003 16004 enum { 16005 DISCOVERED = 0x10, 16006 EXPLORED = 0x20, 16007 FALLTHROUGH = 1, 16008 BRANCH = 2, 16009 }; 16010 16011 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 16012 { 16013 env->insn_aux_data[idx].prune_point = true; 16014 } 16015 16016 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 16017 { 16018 return env->insn_aux_data[insn_idx].prune_point; 16019 } 16020 16021 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 16022 { 16023 env->insn_aux_data[idx].force_checkpoint = true; 16024 } 16025 16026 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 16027 { 16028 return env->insn_aux_data[insn_idx].force_checkpoint; 16029 } 16030 16031 static void mark_calls_callback(struct bpf_verifier_env *env, int idx) 16032 { 16033 env->insn_aux_data[idx].calls_callback = true; 16034 } 16035 16036 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx) 16037 { 16038 return env->insn_aux_data[insn_idx].calls_callback; 16039 } 16040 16041 enum { 16042 DONE_EXPLORING = 0, 16043 KEEP_EXPLORING = 1, 16044 }; 16045 16046 /* t, w, e - match pseudo-code above: 16047 * t - index of current instruction 16048 * w - next instruction 16049 * e - edge 16050 */ 16051 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 16052 { 16053 int *insn_stack = env->cfg.insn_stack; 16054 int *insn_state = env->cfg.insn_state; 16055 16056 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 16057 return DONE_EXPLORING; 16058 16059 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 16060 return DONE_EXPLORING; 16061 16062 if (w < 0 || w >= env->prog->len) { 16063 verbose_linfo(env, t, "%d: ", t); 16064 verbose(env, "jump out of range from insn %d to %d\n", t, w); 16065 return -EINVAL; 16066 } 16067 16068 if (e == BRANCH) { 16069 /* mark branch target for state pruning */ 16070 mark_prune_point(env, w); 16071 mark_jmp_point(env, w); 16072 } 16073 16074 if (insn_state[w] == 0) { 16075 /* tree-edge */ 16076 insn_state[t] = DISCOVERED | e; 16077 insn_state[w] = DISCOVERED; 16078 if (env->cfg.cur_stack >= env->prog->len) 16079 return -E2BIG; 16080 insn_stack[env->cfg.cur_stack++] = w; 16081 return KEEP_EXPLORING; 16082 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 16083 if (env->bpf_capable) 16084 return DONE_EXPLORING; 16085 verbose_linfo(env, t, "%d: ", t); 16086 verbose_linfo(env, w, "%d: ", w); 16087 verbose(env, "back-edge from insn %d to %d\n", t, w); 16088 return -EINVAL; 16089 } else if (insn_state[w] == EXPLORED) { 16090 /* forward- or cross-edge */ 16091 insn_state[t] = DISCOVERED | e; 16092 } else { 16093 verbose(env, "insn state internal bug\n"); 16094 return -EFAULT; 16095 } 16096 return DONE_EXPLORING; 16097 } 16098 16099 static int visit_func_call_insn(int t, struct bpf_insn *insns, 16100 struct bpf_verifier_env *env, 16101 bool visit_callee) 16102 { 16103 int ret, insn_sz; 16104 16105 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 16106 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 16107 if (ret) 16108 return ret; 16109 16110 mark_prune_point(env, t + insn_sz); 16111 /* when we exit from subprog, we need to record non-linear history */ 16112 mark_jmp_point(env, t + insn_sz); 16113 16114 if (visit_callee) { 16115 mark_prune_point(env, t); 16116 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env); 16117 } 16118 return ret; 16119 } 16120 16121 /* Bitmask with 1s for all caller saved registers */ 16122 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 16123 16124 /* Return a bitmask specifying which caller saved registers are 16125 * clobbered by a call to a helper *as if* this helper follows 16126 * bpf_fastcall contract: 16127 * - includes R0 if function is non-void; 16128 * - includes R1-R5 if corresponding parameter has is described 16129 * in the function prototype. 16130 */ 16131 static u32 helper_fastcall_clobber_mask(const struct bpf_func_proto *fn) 16132 { 16133 u32 mask; 16134 int i; 16135 16136 mask = 0; 16137 if (fn->ret_type != RET_VOID) 16138 mask |= BIT(BPF_REG_0); 16139 for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) 16140 if (fn->arg_type[i] != ARG_DONTCARE) 16141 mask |= BIT(BPF_REG_1 + i); 16142 return mask; 16143 } 16144 16145 /* True if do_misc_fixups() replaces calls to helper number 'imm', 16146 * replacement patch is presumed to follow bpf_fastcall contract 16147 * (see mark_fastcall_pattern_for_call() below). 16148 */ 16149 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm) 16150 { 16151 switch (imm) { 16152 #ifdef CONFIG_X86_64 16153 case BPF_FUNC_get_smp_processor_id: 16154 return env->prog->jit_requested && bpf_jit_supports_percpu_insn(); 16155 #endif 16156 default: 16157 return false; 16158 } 16159 } 16160 16161 /* Same as helper_fastcall_clobber_mask() but for kfuncs, see comment above */ 16162 static u32 kfunc_fastcall_clobber_mask(struct bpf_kfunc_call_arg_meta *meta) 16163 { 16164 u32 vlen, i, mask; 16165 16166 vlen = btf_type_vlen(meta->func_proto); 16167 mask = 0; 16168 if (!btf_type_is_void(btf_type_by_id(meta->btf, meta->func_proto->type))) 16169 mask |= BIT(BPF_REG_0); 16170 for (i = 0; i < vlen; ++i) 16171 mask |= BIT(BPF_REG_1 + i); 16172 return mask; 16173 } 16174 16175 /* Same as verifier_inlines_helper_call() but for kfuncs, see comment above */ 16176 static bool is_fastcall_kfunc_call(struct bpf_kfunc_call_arg_meta *meta) 16177 { 16178 if (meta->btf == btf_vmlinux) 16179 return meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 16180 meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]; 16181 return false; 16182 } 16183 16184 /* LLVM define a bpf_fastcall function attribute. 16185 * This attribute means that function scratches only some of 16186 * the caller saved registers defined by ABI. 16187 * For BPF the set of such registers could be defined as follows: 16188 * - R0 is scratched only if function is non-void; 16189 * - R1-R5 are scratched only if corresponding parameter type is defined 16190 * in the function prototype. 16191 * 16192 * The contract between kernel and clang allows to simultaneously use 16193 * such functions and maintain backwards compatibility with old 16194 * kernels that don't understand bpf_fastcall calls: 16195 * 16196 * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5 16197 * registers are not scratched by the call; 16198 * 16199 * - as a post-processing step, clang visits each bpf_fastcall call and adds 16200 * spill/fill for every live r0-r5; 16201 * 16202 * - stack offsets used for the spill/fill are allocated as lowest 16203 * stack offsets in whole function and are not used for any other 16204 * purposes; 16205 * 16206 * - when kernel loads a program, it looks for such patterns 16207 * (bpf_fastcall function surrounded by spills/fills) and checks if 16208 * spill/fill stack offsets are used exclusively in fastcall patterns; 16209 * 16210 * - if so, and if verifier or current JIT inlines the call to the 16211 * bpf_fastcall function (e.g. a helper call), kernel removes unnecessary 16212 * spill/fill pairs; 16213 * 16214 * - when old kernel loads a program, presence of spill/fill pairs 16215 * keeps BPF program valid, albeit slightly less efficient. 16216 * 16217 * For example: 16218 * 16219 * r1 = 1; 16220 * r2 = 2; 16221 * *(u64 *)(r10 - 8) = r1; r1 = 1; 16222 * *(u64 *)(r10 - 16) = r2; r2 = 2; 16223 * call %[to_be_inlined] --> call %[to_be_inlined] 16224 * r2 = *(u64 *)(r10 - 16); r0 = r1; 16225 * r1 = *(u64 *)(r10 - 8); r0 += r2; 16226 * r0 = r1; exit; 16227 * r0 += r2; 16228 * exit; 16229 * 16230 * The purpose of mark_fastcall_pattern_for_call is to: 16231 * - look for such patterns; 16232 * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern; 16233 * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction; 16234 * - update env->subprog_info[*]->fastcall_stack_off to find an offset 16235 * at which bpf_fastcall spill/fill stack slots start; 16236 * - update env->subprog_info[*]->keep_fastcall_stack. 16237 * 16238 * The .fastcall_pattern and .fastcall_stack_off are used by 16239 * check_fastcall_stack_contract() to check if every stack access to 16240 * fastcall spill/fill stack slot originates from spill/fill 16241 * instructions, members of fastcall patterns. 16242 * 16243 * If such condition holds true for a subprogram, fastcall patterns could 16244 * be rewritten by remove_fastcall_spills_fills(). 16245 * Otherwise bpf_fastcall patterns are not changed in the subprogram 16246 * (code, presumably, generated by an older clang version). 16247 * 16248 * For example, it is *not* safe to remove spill/fill below: 16249 * 16250 * r1 = 1; 16251 * *(u64 *)(r10 - 8) = r1; r1 = 1; 16252 * call %[to_be_inlined] --> call %[to_be_inlined] 16253 * r1 = *(u64 *)(r10 - 8); r0 = *(u64 *)(r10 - 8); <---- wrong !!! 16254 * r0 = *(u64 *)(r10 - 8); r0 += r1; 16255 * r0 += r1; exit; 16256 * exit; 16257 */ 16258 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env, 16259 struct bpf_subprog_info *subprog, 16260 int insn_idx, s16 lowest_off) 16261 { 16262 struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx; 16263 struct bpf_insn *call = &env->prog->insnsi[insn_idx]; 16264 const struct bpf_func_proto *fn; 16265 u32 clobbered_regs_mask = ALL_CALLER_SAVED_REGS; 16266 u32 expected_regs_mask; 16267 bool can_be_inlined = false; 16268 s16 off; 16269 int i; 16270 16271 if (bpf_helper_call(call)) { 16272 if (get_helper_proto(env, call->imm, &fn) < 0) 16273 /* error would be reported later */ 16274 return; 16275 clobbered_regs_mask = helper_fastcall_clobber_mask(fn); 16276 can_be_inlined = fn->allow_fastcall && 16277 (verifier_inlines_helper_call(env, call->imm) || 16278 bpf_jit_inlines_helper_call(call->imm)); 16279 } 16280 16281 if (bpf_pseudo_kfunc_call(call)) { 16282 struct bpf_kfunc_call_arg_meta meta; 16283 int err; 16284 16285 err = fetch_kfunc_meta(env, call, &meta, NULL); 16286 if (err < 0) 16287 /* error would be reported later */ 16288 return; 16289 16290 clobbered_regs_mask = kfunc_fastcall_clobber_mask(&meta); 16291 can_be_inlined = is_fastcall_kfunc_call(&meta); 16292 } 16293 16294 if (clobbered_regs_mask == ALL_CALLER_SAVED_REGS) 16295 return; 16296 16297 /* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */ 16298 expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS; 16299 16300 /* match pairs of form: 16301 * 16302 * *(u64 *)(r10 - Y) = rX (where Y % 8 == 0) 16303 * ... 16304 * call %[to_be_inlined] 16305 * ... 16306 * rX = *(u64 *)(r10 - Y) 16307 */ 16308 for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) { 16309 if (insn_idx - i < 0 || insn_idx + i >= env->prog->len) 16310 break; 16311 stx = &insns[insn_idx - i]; 16312 ldx = &insns[insn_idx + i]; 16313 /* must be a stack spill/fill pair */ 16314 if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) || 16315 ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) || 16316 stx->dst_reg != BPF_REG_10 || 16317 ldx->src_reg != BPF_REG_10) 16318 break; 16319 /* must be a spill/fill for the same reg */ 16320 if (stx->src_reg != ldx->dst_reg) 16321 break; 16322 /* must be one of the previously unseen registers */ 16323 if ((BIT(stx->src_reg) & expected_regs_mask) == 0) 16324 break; 16325 /* must be a spill/fill for the same expected offset, 16326 * no need to check offset alignment, BPF_DW stack access 16327 * is always 8-byte aligned. 16328 */ 16329 if (stx->off != off || ldx->off != off) 16330 break; 16331 expected_regs_mask &= ~BIT(stx->src_reg); 16332 env->insn_aux_data[insn_idx - i].fastcall_pattern = 1; 16333 env->insn_aux_data[insn_idx + i].fastcall_pattern = 1; 16334 } 16335 if (i == 1) 16336 return; 16337 16338 /* Conditionally set 'fastcall_spills_num' to allow forward 16339 * compatibility when more helper functions are marked as 16340 * bpf_fastcall at compile time than current kernel supports, e.g: 16341 * 16342 * 1: *(u64 *)(r10 - 8) = r1 16343 * 2: call A ;; assume A is bpf_fastcall for current kernel 16344 * 3: r1 = *(u64 *)(r10 - 8) 16345 * 4: *(u64 *)(r10 - 8) = r1 16346 * 5: call B ;; assume B is not bpf_fastcall for current kernel 16347 * 6: r1 = *(u64 *)(r10 - 8) 16348 * 16349 * There is no need to block bpf_fastcall rewrite for such program. 16350 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy, 16351 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills() 16352 * does not remove spill/fill pair {4,6}. 16353 */ 16354 if (can_be_inlined) 16355 env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1; 16356 else 16357 subprog->keep_fastcall_stack = 1; 16358 subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off); 16359 } 16360 16361 static int mark_fastcall_patterns(struct bpf_verifier_env *env) 16362 { 16363 struct bpf_subprog_info *subprog = env->subprog_info; 16364 struct bpf_insn *insn; 16365 s16 lowest_off; 16366 int s, i; 16367 16368 for (s = 0; s < env->subprog_cnt; ++s, ++subprog) { 16369 /* find lowest stack spill offset used in this subprog */ 16370 lowest_off = 0; 16371 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 16372 insn = env->prog->insnsi + i; 16373 if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) || 16374 insn->dst_reg != BPF_REG_10) 16375 continue; 16376 lowest_off = min(lowest_off, insn->off); 16377 } 16378 /* use this offset to find fastcall patterns */ 16379 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 16380 insn = env->prog->insnsi + i; 16381 if (insn->code != (BPF_JMP | BPF_CALL)) 16382 continue; 16383 mark_fastcall_pattern_for_call(env, subprog, i, lowest_off); 16384 } 16385 } 16386 return 0; 16387 } 16388 16389 /* Visits the instruction at index t and returns one of the following: 16390 * < 0 - an error occurred 16391 * DONE_EXPLORING - the instruction was fully explored 16392 * KEEP_EXPLORING - there is still work to be done before it is fully explored 16393 */ 16394 static int visit_insn(int t, struct bpf_verifier_env *env) 16395 { 16396 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 16397 int ret, off, insn_sz; 16398 16399 if (bpf_pseudo_func(insn)) 16400 return visit_func_call_insn(t, insns, env, true); 16401 16402 /* All non-branch instructions have a single fall-through edge. */ 16403 if (BPF_CLASS(insn->code) != BPF_JMP && 16404 BPF_CLASS(insn->code) != BPF_JMP32) { 16405 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 16406 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 16407 } 16408 16409 switch (BPF_OP(insn->code)) { 16410 case BPF_EXIT: 16411 return DONE_EXPLORING; 16412 16413 case BPF_CALL: 16414 if (is_async_callback_calling_insn(insn)) 16415 /* Mark this call insn as a prune point to trigger 16416 * is_state_visited() check before call itself is 16417 * processed by __check_func_call(). Otherwise new 16418 * async state will be pushed for further exploration. 16419 */ 16420 mark_prune_point(env, t); 16421 /* For functions that invoke callbacks it is not known how many times 16422 * callback would be called. Verifier models callback calling functions 16423 * by repeatedly visiting callback bodies and returning to origin call 16424 * instruction. 16425 * In order to stop such iteration verifier needs to identify when a 16426 * state identical some state from a previous iteration is reached. 16427 * Check below forces creation of checkpoint before callback calling 16428 * instruction to allow search for such identical states. 16429 */ 16430 if (is_sync_callback_calling_insn(insn)) { 16431 mark_calls_callback(env, t); 16432 mark_force_checkpoint(env, t); 16433 mark_prune_point(env, t); 16434 mark_jmp_point(env, t); 16435 } 16436 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 16437 struct bpf_kfunc_call_arg_meta meta; 16438 16439 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 16440 if (ret == 0 && is_iter_next_kfunc(&meta)) { 16441 mark_prune_point(env, t); 16442 /* Checking and saving state checkpoints at iter_next() call 16443 * is crucial for fast convergence of open-coded iterator loop 16444 * logic, so we need to force it. If we don't do that, 16445 * is_state_visited() might skip saving a checkpoint, causing 16446 * unnecessarily long sequence of not checkpointed 16447 * instructions and jumps, leading to exhaustion of jump 16448 * history buffer, and potentially other undesired outcomes. 16449 * It is expected that with correct open-coded iterators 16450 * convergence will happen quickly, so we don't run a risk of 16451 * exhausting memory. 16452 */ 16453 mark_force_checkpoint(env, t); 16454 } 16455 } 16456 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 16457 16458 case BPF_JA: 16459 if (BPF_SRC(insn->code) != BPF_K) 16460 return -EINVAL; 16461 16462 if (BPF_CLASS(insn->code) == BPF_JMP) 16463 off = insn->off; 16464 else 16465 off = insn->imm; 16466 16467 /* unconditional jump with single edge */ 16468 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 16469 if (ret) 16470 return ret; 16471 16472 mark_prune_point(env, t + off + 1); 16473 mark_jmp_point(env, t + off + 1); 16474 16475 return ret; 16476 16477 default: 16478 /* conditional jump with two edges */ 16479 mark_prune_point(env, t); 16480 if (is_may_goto_insn(insn)) 16481 mark_force_checkpoint(env, t); 16482 16483 ret = push_insn(t, t + 1, FALLTHROUGH, env); 16484 if (ret) 16485 return ret; 16486 16487 return push_insn(t, t + insn->off + 1, BRANCH, env); 16488 } 16489 } 16490 16491 /* non-recursive depth-first-search to detect loops in BPF program 16492 * loop == back-edge in directed graph 16493 */ 16494 static int check_cfg(struct bpf_verifier_env *env) 16495 { 16496 int insn_cnt = env->prog->len; 16497 int *insn_stack, *insn_state; 16498 int ex_insn_beg, i, ret = 0; 16499 bool ex_done = false; 16500 16501 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 16502 if (!insn_state) 16503 return -ENOMEM; 16504 16505 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 16506 if (!insn_stack) { 16507 kvfree(insn_state); 16508 return -ENOMEM; 16509 } 16510 16511 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 16512 insn_stack[0] = 0; /* 0 is the first instruction */ 16513 env->cfg.cur_stack = 1; 16514 16515 walk_cfg: 16516 while (env->cfg.cur_stack > 0) { 16517 int t = insn_stack[env->cfg.cur_stack - 1]; 16518 16519 ret = visit_insn(t, env); 16520 switch (ret) { 16521 case DONE_EXPLORING: 16522 insn_state[t] = EXPLORED; 16523 env->cfg.cur_stack--; 16524 break; 16525 case KEEP_EXPLORING: 16526 break; 16527 default: 16528 if (ret > 0) { 16529 verbose(env, "visit_insn internal bug\n"); 16530 ret = -EFAULT; 16531 } 16532 goto err_free; 16533 } 16534 } 16535 16536 if (env->cfg.cur_stack < 0) { 16537 verbose(env, "pop stack internal bug\n"); 16538 ret = -EFAULT; 16539 goto err_free; 16540 } 16541 16542 if (env->exception_callback_subprog && !ex_done) { 16543 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start; 16544 16545 insn_state[ex_insn_beg] = DISCOVERED; 16546 insn_stack[0] = ex_insn_beg; 16547 env->cfg.cur_stack = 1; 16548 ex_done = true; 16549 goto walk_cfg; 16550 } 16551 16552 for (i = 0; i < insn_cnt; i++) { 16553 struct bpf_insn *insn = &env->prog->insnsi[i]; 16554 16555 if (insn_state[i] != EXPLORED) { 16556 verbose(env, "unreachable insn %d\n", i); 16557 ret = -EINVAL; 16558 goto err_free; 16559 } 16560 if (bpf_is_ldimm64(insn)) { 16561 if (insn_state[i + 1] != 0) { 16562 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 16563 ret = -EINVAL; 16564 goto err_free; 16565 } 16566 i++; /* skip second half of ldimm64 */ 16567 } 16568 } 16569 ret = 0; /* cfg looks good */ 16570 16571 err_free: 16572 kvfree(insn_state); 16573 kvfree(insn_stack); 16574 env->cfg.insn_state = env->cfg.insn_stack = NULL; 16575 return ret; 16576 } 16577 16578 static int check_abnormal_return(struct bpf_verifier_env *env) 16579 { 16580 int i; 16581 16582 for (i = 1; i < env->subprog_cnt; i++) { 16583 if (env->subprog_info[i].has_ld_abs) { 16584 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 16585 return -EINVAL; 16586 } 16587 if (env->subprog_info[i].has_tail_call) { 16588 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 16589 return -EINVAL; 16590 } 16591 } 16592 return 0; 16593 } 16594 16595 /* The minimum supported BTF func info size */ 16596 #define MIN_BPF_FUNCINFO_SIZE 8 16597 #define MAX_FUNCINFO_REC_SIZE 252 16598 16599 static int check_btf_func_early(struct bpf_verifier_env *env, 16600 const union bpf_attr *attr, 16601 bpfptr_t uattr) 16602 { 16603 u32 krec_size = sizeof(struct bpf_func_info); 16604 const struct btf_type *type, *func_proto; 16605 u32 i, nfuncs, urec_size, min_size; 16606 struct bpf_func_info *krecord; 16607 struct bpf_prog *prog; 16608 const struct btf *btf; 16609 u32 prev_offset = 0; 16610 bpfptr_t urecord; 16611 int ret = -ENOMEM; 16612 16613 nfuncs = attr->func_info_cnt; 16614 if (!nfuncs) { 16615 if (check_abnormal_return(env)) 16616 return -EINVAL; 16617 return 0; 16618 } 16619 16620 urec_size = attr->func_info_rec_size; 16621 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 16622 urec_size > MAX_FUNCINFO_REC_SIZE || 16623 urec_size % sizeof(u32)) { 16624 verbose(env, "invalid func info rec size %u\n", urec_size); 16625 return -EINVAL; 16626 } 16627 16628 prog = env->prog; 16629 btf = prog->aux->btf; 16630 16631 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 16632 min_size = min_t(u32, krec_size, urec_size); 16633 16634 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 16635 if (!krecord) 16636 return -ENOMEM; 16637 16638 for (i = 0; i < nfuncs; i++) { 16639 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 16640 if (ret) { 16641 if (ret == -E2BIG) { 16642 verbose(env, "nonzero tailing record in func info"); 16643 /* set the size kernel expects so loader can zero 16644 * out the rest of the record. 16645 */ 16646 if (copy_to_bpfptr_offset(uattr, 16647 offsetof(union bpf_attr, func_info_rec_size), 16648 &min_size, sizeof(min_size))) 16649 ret = -EFAULT; 16650 } 16651 goto err_free; 16652 } 16653 16654 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 16655 ret = -EFAULT; 16656 goto err_free; 16657 } 16658 16659 /* check insn_off */ 16660 ret = -EINVAL; 16661 if (i == 0) { 16662 if (krecord[i].insn_off) { 16663 verbose(env, 16664 "nonzero insn_off %u for the first func info record", 16665 krecord[i].insn_off); 16666 goto err_free; 16667 } 16668 } else if (krecord[i].insn_off <= prev_offset) { 16669 verbose(env, 16670 "same or smaller insn offset (%u) than previous func info record (%u)", 16671 krecord[i].insn_off, prev_offset); 16672 goto err_free; 16673 } 16674 16675 /* check type_id */ 16676 type = btf_type_by_id(btf, krecord[i].type_id); 16677 if (!type || !btf_type_is_func(type)) { 16678 verbose(env, "invalid type id %d in func info", 16679 krecord[i].type_id); 16680 goto err_free; 16681 } 16682 16683 func_proto = btf_type_by_id(btf, type->type); 16684 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 16685 /* btf_func_check() already verified it during BTF load */ 16686 goto err_free; 16687 16688 prev_offset = krecord[i].insn_off; 16689 bpfptr_add(&urecord, urec_size); 16690 } 16691 16692 prog->aux->func_info = krecord; 16693 prog->aux->func_info_cnt = nfuncs; 16694 return 0; 16695 16696 err_free: 16697 kvfree(krecord); 16698 return ret; 16699 } 16700 16701 static int check_btf_func(struct bpf_verifier_env *env, 16702 const union bpf_attr *attr, 16703 bpfptr_t uattr) 16704 { 16705 const struct btf_type *type, *func_proto, *ret_type; 16706 u32 i, nfuncs, urec_size; 16707 struct bpf_func_info *krecord; 16708 struct bpf_func_info_aux *info_aux = NULL; 16709 struct bpf_prog *prog; 16710 const struct btf *btf; 16711 bpfptr_t urecord; 16712 bool scalar_return; 16713 int ret = -ENOMEM; 16714 16715 nfuncs = attr->func_info_cnt; 16716 if (!nfuncs) { 16717 if (check_abnormal_return(env)) 16718 return -EINVAL; 16719 return 0; 16720 } 16721 if (nfuncs != env->subprog_cnt) { 16722 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 16723 return -EINVAL; 16724 } 16725 16726 urec_size = attr->func_info_rec_size; 16727 16728 prog = env->prog; 16729 btf = prog->aux->btf; 16730 16731 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 16732 16733 krecord = prog->aux->func_info; 16734 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 16735 if (!info_aux) 16736 return -ENOMEM; 16737 16738 for (i = 0; i < nfuncs; i++) { 16739 /* check insn_off */ 16740 ret = -EINVAL; 16741 16742 if (env->subprog_info[i].start != krecord[i].insn_off) { 16743 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 16744 goto err_free; 16745 } 16746 16747 /* Already checked type_id */ 16748 type = btf_type_by_id(btf, krecord[i].type_id); 16749 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 16750 /* Already checked func_proto */ 16751 func_proto = btf_type_by_id(btf, type->type); 16752 16753 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 16754 scalar_return = 16755 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 16756 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 16757 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 16758 goto err_free; 16759 } 16760 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 16761 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 16762 goto err_free; 16763 } 16764 16765 bpfptr_add(&urecord, urec_size); 16766 } 16767 16768 prog->aux->func_info_aux = info_aux; 16769 return 0; 16770 16771 err_free: 16772 kfree(info_aux); 16773 return ret; 16774 } 16775 16776 static void adjust_btf_func(struct bpf_verifier_env *env) 16777 { 16778 struct bpf_prog_aux *aux = env->prog->aux; 16779 int i; 16780 16781 if (!aux->func_info) 16782 return; 16783 16784 /* func_info is not available for hidden subprogs */ 16785 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 16786 aux->func_info[i].insn_off = env->subprog_info[i].start; 16787 } 16788 16789 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 16790 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 16791 16792 static int check_btf_line(struct bpf_verifier_env *env, 16793 const union bpf_attr *attr, 16794 bpfptr_t uattr) 16795 { 16796 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 16797 struct bpf_subprog_info *sub; 16798 struct bpf_line_info *linfo; 16799 struct bpf_prog *prog; 16800 const struct btf *btf; 16801 bpfptr_t ulinfo; 16802 int err; 16803 16804 nr_linfo = attr->line_info_cnt; 16805 if (!nr_linfo) 16806 return 0; 16807 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 16808 return -EINVAL; 16809 16810 rec_size = attr->line_info_rec_size; 16811 if (rec_size < MIN_BPF_LINEINFO_SIZE || 16812 rec_size > MAX_LINEINFO_REC_SIZE || 16813 rec_size & (sizeof(u32) - 1)) 16814 return -EINVAL; 16815 16816 /* Need to zero it in case the userspace may 16817 * pass in a smaller bpf_line_info object. 16818 */ 16819 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 16820 GFP_KERNEL | __GFP_NOWARN); 16821 if (!linfo) 16822 return -ENOMEM; 16823 16824 prog = env->prog; 16825 btf = prog->aux->btf; 16826 16827 s = 0; 16828 sub = env->subprog_info; 16829 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 16830 expected_size = sizeof(struct bpf_line_info); 16831 ncopy = min_t(u32, expected_size, rec_size); 16832 for (i = 0; i < nr_linfo; i++) { 16833 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 16834 if (err) { 16835 if (err == -E2BIG) { 16836 verbose(env, "nonzero tailing record in line_info"); 16837 if (copy_to_bpfptr_offset(uattr, 16838 offsetof(union bpf_attr, line_info_rec_size), 16839 &expected_size, sizeof(expected_size))) 16840 err = -EFAULT; 16841 } 16842 goto err_free; 16843 } 16844 16845 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 16846 err = -EFAULT; 16847 goto err_free; 16848 } 16849 16850 /* 16851 * Check insn_off to ensure 16852 * 1) strictly increasing AND 16853 * 2) bounded by prog->len 16854 * 16855 * The linfo[0].insn_off == 0 check logically falls into 16856 * the later "missing bpf_line_info for func..." case 16857 * because the first linfo[0].insn_off must be the 16858 * first sub also and the first sub must have 16859 * subprog_info[0].start == 0. 16860 */ 16861 if ((i && linfo[i].insn_off <= prev_offset) || 16862 linfo[i].insn_off >= prog->len) { 16863 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 16864 i, linfo[i].insn_off, prev_offset, 16865 prog->len); 16866 err = -EINVAL; 16867 goto err_free; 16868 } 16869 16870 if (!prog->insnsi[linfo[i].insn_off].code) { 16871 verbose(env, 16872 "Invalid insn code at line_info[%u].insn_off\n", 16873 i); 16874 err = -EINVAL; 16875 goto err_free; 16876 } 16877 16878 if (!btf_name_by_offset(btf, linfo[i].line_off) || 16879 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 16880 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 16881 err = -EINVAL; 16882 goto err_free; 16883 } 16884 16885 if (s != env->subprog_cnt) { 16886 if (linfo[i].insn_off == sub[s].start) { 16887 sub[s].linfo_idx = i; 16888 s++; 16889 } else if (sub[s].start < linfo[i].insn_off) { 16890 verbose(env, "missing bpf_line_info for func#%u\n", s); 16891 err = -EINVAL; 16892 goto err_free; 16893 } 16894 } 16895 16896 prev_offset = linfo[i].insn_off; 16897 bpfptr_add(&ulinfo, rec_size); 16898 } 16899 16900 if (s != env->subprog_cnt) { 16901 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 16902 env->subprog_cnt - s, s); 16903 err = -EINVAL; 16904 goto err_free; 16905 } 16906 16907 prog->aux->linfo = linfo; 16908 prog->aux->nr_linfo = nr_linfo; 16909 16910 return 0; 16911 16912 err_free: 16913 kvfree(linfo); 16914 return err; 16915 } 16916 16917 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 16918 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 16919 16920 static int check_core_relo(struct bpf_verifier_env *env, 16921 const union bpf_attr *attr, 16922 bpfptr_t uattr) 16923 { 16924 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 16925 struct bpf_core_relo core_relo = {}; 16926 struct bpf_prog *prog = env->prog; 16927 const struct btf *btf = prog->aux->btf; 16928 struct bpf_core_ctx ctx = { 16929 .log = &env->log, 16930 .btf = btf, 16931 }; 16932 bpfptr_t u_core_relo; 16933 int err; 16934 16935 nr_core_relo = attr->core_relo_cnt; 16936 if (!nr_core_relo) 16937 return 0; 16938 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 16939 return -EINVAL; 16940 16941 rec_size = attr->core_relo_rec_size; 16942 if (rec_size < MIN_CORE_RELO_SIZE || 16943 rec_size > MAX_CORE_RELO_SIZE || 16944 rec_size % sizeof(u32)) 16945 return -EINVAL; 16946 16947 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 16948 expected_size = sizeof(struct bpf_core_relo); 16949 ncopy = min_t(u32, expected_size, rec_size); 16950 16951 /* Unlike func_info and line_info, copy and apply each CO-RE 16952 * relocation record one at a time. 16953 */ 16954 for (i = 0; i < nr_core_relo; i++) { 16955 /* future proofing when sizeof(bpf_core_relo) changes */ 16956 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 16957 if (err) { 16958 if (err == -E2BIG) { 16959 verbose(env, "nonzero tailing record in core_relo"); 16960 if (copy_to_bpfptr_offset(uattr, 16961 offsetof(union bpf_attr, core_relo_rec_size), 16962 &expected_size, sizeof(expected_size))) 16963 err = -EFAULT; 16964 } 16965 break; 16966 } 16967 16968 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 16969 err = -EFAULT; 16970 break; 16971 } 16972 16973 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 16974 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 16975 i, core_relo.insn_off, prog->len); 16976 err = -EINVAL; 16977 break; 16978 } 16979 16980 err = bpf_core_apply(&ctx, &core_relo, i, 16981 &prog->insnsi[core_relo.insn_off / 8]); 16982 if (err) 16983 break; 16984 bpfptr_add(&u_core_relo, rec_size); 16985 } 16986 return err; 16987 } 16988 16989 static int check_btf_info_early(struct bpf_verifier_env *env, 16990 const union bpf_attr *attr, 16991 bpfptr_t uattr) 16992 { 16993 struct btf *btf; 16994 int err; 16995 16996 if (!attr->func_info_cnt && !attr->line_info_cnt) { 16997 if (check_abnormal_return(env)) 16998 return -EINVAL; 16999 return 0; 17000 } 17001 17002 btf = btf_get_by_fd(attr->prog_btf_fd); 17003 if (IS_ERR(btf)) 17004 return PTR_ERR(btf); 17005 if (btf_is_kernel(btf)) { 17006 btf_put(btf); 17007 return -EACCES; 17008 } 17009 env->prog->aux->btf = btf; 17010 17011 err = check_btf_func_early(env, attr, uattr); 17012 if (err) 17013 return err; 17014 return 0; 17015 } 17016 17017 static int check_btf_info(struct bpf_verifier_env *env, 17018 const union bpf_attr *attr, 17019 bpfptr_t uattr) 17020 { 17021 int err; 17022 17023 if (!attr->func_info_cnt && !attr->line_info_cnt) { 17024 if (check_abnormal_return(env)) 17025 return -EINVAL; 17026 return 0; 17027 } 17028 17029 err = check_btf_func(env, attr, uattr); 17030 if (err) 17031 return err; 17032 17033 err = check_btf_line(env, attr, uattr); 17034 if (err) 17035 return err; 17036 17037 err = check_core_relo(env, attr, uattr); 17038 if (err) 17039 return err; 17040 17041 return 0; 17042 } 17043 17044 /* check %cur's range satisfies %old's */ 17045 static bool range_within(const struct bpf_reg_state *old, 17046 const struct bpf_reg_state *cur) 17047 { 17048 return old->umin_value <= cur->umin_value && 17049 old->umax_value >= cur->umax_value && 17050 old->smin_value <= cur->smin_value && 17051 old->smax_value >= cur->smax_value && 17052 old->u32_min_value <= cur->u32_min_value && 17053 old->u32_max_value >= cur->u32_max_value && 17054 old->s32_min_value <= cur->s32_min_value && 17055 old->s32_max_value >= cur->s32_max_value; 17056 } 17057 17058 /* If in the old state two registers had the same id, then they need to have 17059 * the same id in the new state as well. But that id could be different from 17060 * the old state, so we need to track the mapping from old to new ids. 17061 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 17062 * regs with old id 5 must also have new id 9 for the new state to be safe. But 17063 * regs with a different old id could still have new id 9, we don't care about 17064 * that. 17065 * So we look through our idmap to see if this old id has been seen before. If 17066 * so, we require the new id to match; otherwise, we add the id pair to the map. 17067 */ 17068 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 17069 { 17070 struct bpf_id_pair *map = idmap->map; 17071 unsigned int i; 17072 17073 /* either both IDs should be set or both should be zero */ 17074 if (!!old_id != !!cur_id) 17075 return false; 17076 17077 if (old_id == 0) /* cur_id == 0 as well */ 17078 return true; 17079 17080 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 17081 if (!map[i].old) { 17082 /* Reached an empty slot; haven't seen this id before */ 17083 map[i].old = old_id; 17084 map[i].cur = cur_id; 17085 return true; 17086 } 17087 if (map[i].old == old_id) 17088 return map[i].cur == cur_id; 17089 if (map[i].cur == cur_id) 17090 return false; 17091 } 17092 /* We ran out of idmap slots, which should be impossible */ 17093 WARN_ON_ONCE(1); 17094 return false; 17095 } 17096 17097 /* Similar to check_ids(), but allocate a unique temporary ID 17098 * for 'old_id' or 'cur_id' of zero. 17099 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 17100 */ 17101 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 17102 { 17103 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 17104 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 17105 17106 return check_ids(old_id, cur_id, idmap); 17107 } 17108 17109 static void clean_func_state(struct bpf_verifier_env *env, 17110 struct bpf_func_state *st) 17111 { 17112 enum bpf_reg_liveness live; 17113 int i, j; 17114 17115 for (i = 0; i < BPF_REG_FP; i++) { 17116 live = st->regs[i].live; 17117 /* liveness must not touch this register anymore */ 17118 st->regs[i].live |= REG_LIVE_DONE; 17119 if (!(live & REG_LIVE_READ)) 17120 /* since the register is unused, clear its state 17121 * to make further comparison simpler 17122 */ 17123 __mark_reg_not_init(env, &st->regs[i]); 17124 } 17125 17126 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 17127 live = st->stack[i].spilled_ptr.live; 17128 /* liveness must not touch this stack slot anymore */ 17129 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 17130 if (!(live & REG_LIVE_READ)) { 17131 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 17132 for (j = 0; j < BPF_REG_SIZE; j++) 17133 st->stack[i].slot_type[j] = STACK_INVALID; 17134 } 17135 } 17136 } 17137 17138 static void clean_verifier_state(struct bpf_verifier_env *env, 17139 struct bpf_verifier_state *st) 17140 { 17141 int i; 17142 17143 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 17144 /* all regs in this state in all frames were already marked */ 17145 return; 17146 17147 for (i = 0; i <= st->curframe; i++) 17148 clean_func_state(env, st->frame[i]); 17149 } 17150 17151 /* the parentage chains form a tree. 17152 * the verifier states are added to state lists at given insn and 17153 * pushed into state stack for future exploration. 17154 * when the verifier reaches bpf_exit insn some of the verifer states 17155 * stored in the state lists have their final liveness state already, 17156 * but a lot of states will get revised from liveness point of view when 17157 * the verifier explores other branches. 17158 * Example: 17159 * 1: r0 = 1 17160 * 2: if r1 == 100 goto pc+1 17161 * 3: r0 = 2 17162 * 4: exit 17163 * when the verifier reaches exit insn the register r0 in the state list of 17164 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 17165 * of insn 2 and goes exploring further. At the insn 4 it will walk the 17166 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 17167 * 17168 * Since the verifier pushes the branch states as it sees them while exploring 17169 * the program the condition of walking the branch instruction for the second 17170 * time means that all states below this branch were already explored and 17171 * their final liveness marks are already propagated. 17172 * Hence when the verifier completes the search of state list in is_state_visited() 17173 * we can call this clean_live_states() function to mark all liveness states 17174 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 17175 * will not be used. 17176 * This function also clears the registers and stack for states that !READ 17177 * to simplify state merging. 17178 * 17179 * Important note here that walking the same branch instruction in the callee 17180 * doesn't meant that the states are DONE. The verifier has to compare 17181 * the callsites 17182 */ 17183 static void clean_live_states(struct bpf_verifier_env *env, int insn, 17184 struct bpf_verifier_state *cur) 17185 { 17186 struct bpf_verifier_state_list *sl; 17187 17188 sl = *explored_state(env, insn); 17189 while (sl) { 17190 if (sl->state.branches) 17191 goto next; 17192 if (sl->state.insn_idx != insn || 17193 !same_callsites(&sl->state, cur)) 17194 goto next; 17195 clean_verifier_state(env, &sl->state); 17196 next: 17197 sl = sl->next; 17198 } 17199 } 17200 17201 static bool regs_exact(const struct bpf_reg_state *rold, 17202 const struct bpf_reg_state *rcur, 17203 struct bpf_idmap *idmap) 17204 { 17205 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 17206 check_ids(rold->id, rcur->id, idmap) && 17207 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 17208 } 17209 17210 enum exact_level { 17211 NOT_EXACT, 17212 EXACT, 17213 RANGE_WITHIN 17214 }; 17215 17216 /* Returns true if (rold safe implies rcur safe) */ 17217 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 17218 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, 17219 enum exact_level exact) 17220 { 17221 if (exact == EXACT) 17222 return regs_exact(rold, rcur, idmap); 17223 17224 if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT) 17225 /* explored state didn't use this */ 17226 return true; 17227 if (rold->type == NOT_INIT) { 17228 if (exact == NOT_EXACT || rcur->type == NOT_INIT) 17229 /* explored state can't have used this */ 17230 return true; 17231 } 17232 17233 /* Enforce that register types have to match exactly, including their 17234 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 17235 * rule. 17236 * 17237 * One can make a point that using a pointer register as unbounded 17238 * SCALAR would be technically acceptable, but this could lead to 17239 * pointer leaks because scalars are allowed to leak while pointers 17240 * are not. We could make this safe in special cases if root is 17241 * calling us, but it's probably not worth the hassle. 17242 * 17243 * Also, register types that are *not* MAYBE_NULL could technically be 17244 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 17245 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 17246 * to the same map). 17247 * However, if the old MAYBE_NULL register then got NULL checked, 17248 * doing so could have affected others with the same id, and we can't 17249 * check for that because we lost the id when we converted to 17250 * a non-MAYBE_NULL variant. 17251 * So, as a general rule we don't allow mixing MAYBE_NULL and 17252 * non-MAYBE_NULL registers as well. 17253 */ 17254 if (rold->type != rcur->type) 17255 return false; 17256 17257 switch (base_type(rold->type)) { 17258 case SCALAR_VALUE: 17259 if (env->explore_alu_limits) { 17260 /* explore_alu_limits disables tnum_in() and range_within() 17261 * logic and requires everything to be strict 17262 */ 17263 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 17264 check_scalar_ids(rold->id, rcur->id, idmap); 17265 } 17266 if (!rold->precise && exact == NOT_EXACT) 17267 return true; 17268 if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST)) 17269 return false; 17270 if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off)) 17271 return false; 17272 /* Why check_ids() for scalar registers? 17273 * 17274 * Consider the following BPF code: 17275 * 1: r6 = ... unbound scalar, ID=a ... 17276 * 2: r7 = ... unbound scalar, ID=b ... 17277 * 3: if (r6 > r7) goto +1 17278 * 4: r6 = r7 17279 * 5: if (r6 > X) goto ... 17280 * 6: ... memory operation using r7 ... 17281 * 17282 * First verification path is [1-6]: 17283 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 17284 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark 17285 * r7 <= X, because r6 and r7 share same id. 17286 * Next verification path is [1-4, 6]. 17287 * 17288 * Instruction (6) would be reached in two states: 17289 * I. r6{.id=b}, r7{.id=b} via path 1-6; 17290 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 17291 * 17292 * Use check_ids() to distinguish these states. 17293 * --- 17294 * Also verify that new value satisfies old value range knowledge. 17295 */ 17296 return range_within(rold, rcur) && 17297 tnum_in(rold->var_off, rcur->var_off) && 17298 check_scalar_ids(rold->id, rcur->id, idmap); 17299 case PTR_TO_MAP_KEY: 17300 case PTR_TO_MAP_VALUE: 17301 case PTR_TO_MEM: 17302 case PTR_TO_BUF: 17303 case PTR_TO_TP_BUFFER: 17304 /* If the new min/max/var_off satisfy the old ones and 17305 * everything else matches, we are OK. 17306 */ 17307 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 17308 range_within(rold, rcur) && 17309 tnum_in(rold->var_off, rcur->var_off) && 17310 check_ids(rold->id, rcur->id, idmap) && 17311 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 17312 case PTR_TO_PACKET_META: 17313 case PTR_TO_PACKET: 17314 /* We must have at least as much range as the old ptr 17315 * did, so that any accesses which were safe before are 17316 * still safe. This is true even if old range < old off, 17317 * since someone could have accessed through (ptr - k), or 17318 * even done ptr -= k in a register, to get a safe access. 17319 */ 17320 if (rold->range > rcur->range) 17321 return false; 17322 /* If the offsets don't match, we can't trust our alignment; 17323 * nor can we be sure that we won't fall out of range. 17324 */ 17325 if (rold->off != rcur->off) 17326 return false; 17327 /* id relations must be preserved */ 17328 if (!check_ids(rold->id, rcur->id, idmap)) 17329 return false; 17330 /* new val must satisfy old val knowledge */ 17331 return range_within(rold, rcur) && 17332 tnum_in(rold->var_off, rcur->var_off); 17333 case PTR_TO_STACK: 17334 /* two stack pointers are equal only if they're pointing to 17335 * the same stack frame, since fp-8 in foo != fp-8 in bar 17336 */ 17337 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 17338 case PTR_TO_ARENA: 17339 return true; 17340 default: 17341 return regs_exact(rold, rcur, idmap); 17342 } 17343 } 17344 17345 static struct bpf_reg_state unbound_reg; 17346 17347 static __init int unbound_reg_init(void) 17348 { 17349 __mark_reg_unknown_imprecise(&unbound_reg); 17350 unbound_reg.live |= REG_LIVE_READ; 17351 return 0; 17352 } 17353 late_initcall(unbound_reg_init); 17354 17355 static bool is_stack_all_misc(struct bpf_verifier_env *env, 17356 struct bpf_stack_state *stack) 17357 { 17358 u32 i; 17359 17360 for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) { 17361 if ((stack->slot_type[i] == STACK_MISC) || 17362 (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack)) 17363 continue; 17364 return false; 17365 } 17366 17367 return true; 17368 } 17369 17370 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env, 17371 struct bpf_stack_state *stack) 17372 { 17373 if (is_spilled_scalar_reg64(stack)) 17374 return &stack->spilled_ptr; 17375 17376 if (is_stack_all_misc(env, stack)) 17377 return &unbound_reg; 17378 17379 return NULL; 17380 } 17381 17382 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 17383 struct bpf_func_state *cur, struct bpf_idmap *idmap, 17384 enum exact_level exact) 17385 { 17386 int i, spi; 17387 17388 /* walk slots of the explored stack and ignore any additional 17389 * slots in the current stack, since explored(safe) state 17390 * didn't use them 17391 */ 17392 for (i = 0; i < old->allocated_stack; i++) { 17393 struct bpf_reg_state *old_reg, *cur_reg; 17394 17395 spi = i / BPF_REG_SIZE; 17396 17397 if (exact != NOT_EXACT && 17398 (i >= cur->allocated_stack || 17399 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 17400 cur->stack[spi].slot_type[i % BPF_REG_SIZE])) 17401 return false; 17402 17403 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) 17404 && exact == NOT_EXACT) { 17405 i += BPF_REG_SIZE - 1; 17406 /* explored state didn't use this */ 17407 continue; 17408 } 17409 17410 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 17411 continue; 17412 17413 if (env->allow_uninit_stack && 17414 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 17415 continue; 17416 17417 /* explored stack has more populated slots than current stack 17418 * and these slots were used 17419 */ 17420 if (i >= cur->allocated_stack) 17421 return false; 17422 17423 /* 64-bit scalar spill vs all slots MISC and vice versa. 17424 * Load from all slots MISC produces unbound scalar. 17425 * Construct a fake register for such stack and call 17426 * regsafe() to ensure scalar ids are compared. 17427 */ 17428 old_reg = scalar_reg_for_stack(env, &old->stack[spi]); 17429 cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]); 17430 if (old_reg && cur_reg) { 17431 if (!regsafe(env, old_reg, cur_reg, idmap, exact)) 17432 return false; 17433 i += BPF_REG_SIZE - 1; 17434 continue; 17435 } 17436 17437 /* if old state was safe with misc data in the stack 17438 * it will be safe with zero-initialized stack. 17439 * The opposite is not true 17440 */ 17441 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 17442 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 17443 continue; 17444 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 17445 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 17446 /* Ex: old explored (safe) state has STACK_SPILL in 17447 * this stack slot, but current has STACK_MISC -> 17448 * this verifier states are not equivalent, 17449 * return false to continue verification of this path 17450 */ 17451 return false; 17452 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 17453 continue; 17454 /* Both old and cur are having same slot_type */ 17455 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 17456 case STACK_SPILL: 17457 /* when explored and current stack slot are both storing 17458 * spilled registers, check that stored pointers types 17459 * are the same as well. 17460 * Ex: explored safe path could have stored 17461 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 17462 * but current path has stored: 17463 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 17464 * such verifier states are not equivalent. 17465 * return false to continue verification of this path 17466 */ 17467 if (!regsafe(env, &old->stack[spi].spilled_ptr, 17468 &cur->stack[spi].spilled_ptr, idmap, exact)) 17469 return false; 17470 break; 17471 case STACK_DYNPTR: 17472 old_reg = &old->stack[spi].spilled_ptr; 17473 cur_reg = &cur->stack[spi].spilled_ptr; 17474 if (old_reg->dynptr.type != cur_reg->dynptr.type || 17475 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 17476 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 17477 return false; 17478 break; 17479 case STACK_ITER: 17480 old_reg = &old->stack[spi].spilled_ptr; 17481 cur_reg = &cur->stack[spi].spilled_ptr; 17482 /* iter.depth is not compared between states as it 17483 * doesn't matter for correctness and would otherwise 17484 * prevent convergence; we maintain it only to prevent 17485 * infinite loop check triggering, see 17486 * iter_active_depths_differ() 17487 */ 17488 if (old_reg->iter.btf != cur_reg->iter.btf || 17489 old_reg->iter.btf_id != cur_reg->iter.btf_id || 17490 old_reg->iter.state != cur_reg->iter.state || 17491 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 17492 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 17493 return false; 17494 break; 17495 case STACK_MISC: 17496 case STACK_ZERO: 17497 case STACK_INVALID: 17498 continue; 17499 /* Ensure that new unhandled slot types return false by default */ 17500 default: 17501 return false; 17502 } 17503 } 17504 return true; 17505 } 17506 17507 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 17508 struct bpf_idmap *idmap) 17509 { 17510 int i; 17511 17512 if (old->acquired_refs != cur->acquired_refs) 17513 return false; 17514 17515 for (i = 0; i < old->acquired_refs; i++) { 17516 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 17517 return false; 17518 } 17519 17520 return true; 17521 } 17522 17523 /* compare two verifier states 17524 * 17525 * all states stored in state_list are known to be valid, since 17526 * verifier reached 'bpf_exit' instruction through them 17527 * 17528 * this function is called when verifier exploring different branches of 17529 * execution popped from the state stack. If it sees an old state that has 17530 * more strict register state and more strict stack state then this execution 17531 * branch doesn't need to be explored further, since verifier already 17532 * concluded that more strict state leads to valid finish. 17533 * 17534 * Therefore two states are equivalent if register state is more conservative 17535 * and explored stack state is more conservative than the current one. 17536 * Example: 17537 * explored current 17538 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 17539 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 17540 * 17541 * In other words if current stack state (one being explored) has more 17542 * valid slots than old one that already passed validation, it means 17543 * the verifier can stop exploring and conclude that current state is valid too 17544 * 17545 * Similarly with registers. If explored state has register type as invalid 17546 * whereas register type in current state is meaningful, it means that 17547 * the current state will reach 'bpf_exit' instruction safely 17548 */ 17549 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 17550 struct bpf_func_state *cur, enum exact_level exact) 17551 { 17552 int i; 17553 17554 if (old->callback_depth > cur->callback_depth) 17555 return false; 17556 17557 for (i = 0; i < MAX_BPF_REG; i++) 17558 if (!regsafe(env, &old->regs[i], &cur->regs[i], 17559 &env->idmap_scratch, exact)) 17560 return false; 17561 17562 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 17563 return false; 17564 17565 if (!refsafe(old, cur, &env->idmap_scratch)) 17566 return false; 17567 17568 return true; 17569 } 17570 17571 static void reset_idmap_scratch(struct bpf_verifier_env *env) 17572 { 17573 env->idmap_scratch.tmp_id_gen = env->id_gen; 17574 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 17575 } 17576 17577 static bool states_equal(struct bpf_verifier_env *env, 17578 struct bpf_verifier_state *old, 17579 struct bpf_verifier_state *cur, 17580 enum exact_level exact) 17581 { 17582 int i; 17583 17584 if (old->curframe != cur->curframe) 17585 return false; 17586 17587 reset_idmap_scratch(env); 17588 17589 /* Verification state from speculative execution simulation 17590 * must never prune a non-speculative execution one. 17591 */ 17592 if (old->speculative && !cur->speculative) 17593 return false; 17594 17595 if (old->active_lock.ptr != cur->active_lock.ptr) 17596 return false; 17597 17598 /* Old and cur active_lock's have to be either both present 17599 * or both absent. 17600 */ 17601 if (!!old->active_lock.id != !!cur->active_lock.id) 17602 return false; 17603 17604 if (old->active_lock.id && 17605 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch)) 17606 return false; 17607 17608 if (old->active_rcu_lock != cur->active_rcu_lock) 17609 return false; 17610 17611 if (old->active_preempt_lock != cur->active_preempt_lock) 17612 return false; 17613 17614 if (old->in_sleepable != cur->in_sleepable) 17615 return false; 17616 17617 /* for states to be equal callsites have to be the same 17618 * and all frame states need to be equivalent 17619 */ 17620 for (i = 0; i <= old->curframe; i++) { 17621 if (old->frame[i]->callsite != cur->frame[i]->callsite) 17622 return false; 17623 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact)) 17624 return false; 17625 } 17626 return true; 17627 } 17628 17629 /* Return 0 if no propagation happened. Return negative error code if error 17630 * happened. Otherwise, return the propagated bit. 17631 */ 17632 static int propagate_liveness_reg(struct bpf_verifier_env *env, 17633 struct bpf_reg_state *reg, 17634 struct bpf_reg_state *parent_reg) 17635 { 17636 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 17637 u8 flag = reg->live & REG_LIVE_READ; 17638 int err; 17639 17640 /* When comes here, read flags of PARENT_REG or REG could be any of 17641 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 17642 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 17643 */ 17644 if (parent_flag == REG_LIVE_READ64 || 17645 /* Or if there is no read flag from REG. */ 17646 !flag || 17647 /* Or if the read flag from REG is the same as PARENT_REG. */ 17648 parent_flag == flag) 17649 return 0; 17650 17651 err = mark_reg_read(env, reg, parent_reg, flag); 17652 if (err) 17653 return err; 17654 17655 return flag; 17656 } 17657 17658 /* A write screens off any subsequent reads; but write marks come from the 17659 * straight-line code between a state and its parent. When we arrive at an 17660 * equivalent state (jump target or such) we didn't arrive by the straight-line 17661 * code, so read marks in the state must propagate to the parent regardless 17662 * of the state's write marks. That's what 'parent == state->parent' comparison 17663 * in mark_reg_read() is for. 17664 */ 17665 static int propagate_liveness(struct bpf_verifier_env *env, 17666 const struct bpf_verifier_state *vstate, 17667 struct bpf_verifier_state *vparent) 17668 { 17669 struct bpf_reg_state *state_reg, *parent_reg; 17670 struct bpf_func_state *state, *parent; 17671 int i, frame, err = 0; 17672 17673 if (vparent->curframe != vstate->curframe) { 17674 WARN(1, "propagate_live: parent frame %d current frame %d\n", 17675 vparent->curframe, vstate->curframe); 17676 return -EFAULT; 17677 } 17678 /* Propagate read liveness of registers... */ 17679 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 17680 for (frame = 0; frame <= vstate->curframe; frame++) { 17681 parent = vparent->frame[frame]; 17682 state = vstate->frame[frame]; 17683 parent_reg = parent->regs; 17684 state_reg = state->regs; 17685 /* We don't need to worry about FP liveness, it's read-only */ 17686 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 17687 err = propagate_liveness_reg(env, &state_reg[i], 17688 &parent_reg[i]); 17689 if (err < 0) 17690 return err; 17691 if (err == REG_LIVE_READ64) 17692 mark_insn_zext(env, &parent_reg[i]); 17693 } 17694 17695 /* Propagate stack slots. */ 17696 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 17697 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 17698 parent_reg = &parent->stack[i].spilled_ptr; 17699 state_reg = &state->stack[i].spilled_ptr; 17700 err = propagate_liveness_reg(env, state_reg, 17701 parent_reg); 17702 if (err < 0) 17703 return err; 17704 } 17705 } 17706 return 0; 17707 } 17708 17709 /* find precise scalars in the previous equivalent state and 17710 * propagate them into the current state 17711 */ 17712 static int propagate_precision(struct bpf_verifier_env *env, 17713 const struct bpf_verifier_state *old) 17714 { 17715 struct bpf_reg_state *state_reg; 17716 struct bpf_func_state *state; 17717 int i, err = 0, fr; 17718 bool first; 17719 17720 for (fr = old->curframe; fr >= 0; fr--) { 17721 state = old->frame[fr]; 17722 state_reg = state->regs; 17723 first = true; 17724 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 17725 if (state_reg->type != SCALAR_VALUE || 17726 !state_reg->precise || 17727 !(state_reg->live & REG_LIVE_READ)) 17728 continue; 17729 if (env->log.level & BPF_LOG_LEVEL2) { 17730 if (first) 17731 verbose(env, "frame %d: propagating r%d", fr, i); 17732 else 17733 verbose(env, ",r%d", i); 17734 } 17735 bt_set_frame_reg(&env->bt, fr, i); 17736 first = false; 17737 } 17738 17739 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 17740 if (!is_spilled_reg(&state->stack[i])) 17741 continue; 17742 state_reg = &state->stack[i].spilled_ptr; 17743 if (state_reg->type != SCALAR_VALUE || 17744 !state_reg->precise || 17745 !(state_reg->live & REG_LIVE_READ)) 17746 continue; 17747 if (env->log.level & BPF_LOG_LEVEL2) { 17748 if (first) 17749 verbose(env, "frame %d: propagating fp%d", 17750 fr, (-i - 1) * BPF_REG_SIZE); 17751 else 17752 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 17753 } 17754 bt_set_frame_slot(&env->bt, fr, i); 17755 first = false; 17756 } 17757 if (!first) 17758 verbose(env, "\n"); 17759 } 17760 17761 err = mark_chain_precision_batch(env); 17762 if (err < 0) 17763 return err; 17764 17765 return 0; 17766 } 17767 17768 static bool states_maybe_looping(struct bpf_verifier_state *old, 17769 struct bpf_verifier_state *cur) 17770 { 17771 struct bpf_func_state *fold, *fcur; 17772 int i, fr = cur->curframe; 17773 17774 if (old->curframe != fr) 17775 return false; 17776 17777 fold = old->frame[fr]; 17778 fcur = cur->frame[fr]; 17779 for (i = 0; i < MAX_BPF_REG; i++) 17780 if (memcmp(&fold->regs[i], &fcur->regs[i], 17781 offsetof(struct bpf_reg_state, parent))) 17782 return false; 17783 return true; 17784 } 17785 17786 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 17787 { 17788 return env->insn_aux_data[insn_idx].is_iter_next; 17789 } 17790 17791 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 17792 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 17793 * states to match, which otherwise would look like an infinite loop. So while 17794 * iter_next() calls are taken care of, we still need to be careful and 17795 * prevent erroneous and too eager declaration of "ininite loop", when 17796 * iterators are involved. 17797 * 17798 * Here's a situation in pseudo-BPF assembly form: 17799 * 17800 * 0: again: ; set up iter_next() call args 17801 * 1: r1 = &it ; <CHECKPOINT HERE> 17802 * 2: call bpf_iter_num_next ; this is iter_next() call 17803 * 3: if r0 == 0 goto done 17804 * 4: ... something useful here ... 17805 * 5: goto again ; another iteration 17806 * 6: done: 17807 * 7: r1 = &it 17808 * 8: call bpf_iter_num_destroy ; clean up iter state 17809 * 9: exit 17810 * 17811 * This is a typical loop. Let's assume that we have a prune point at 1:, 17812 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 17813 * again`, assuming other heuristics don't get in a way). 17814 * 17815 * When we first time come to 1:, let's say we have some state X. We proceed 17816 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 17817 * Now we come back to validate that forked ACTIVE state. We proceed through 17818 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 17819 * are converging. But the problem is that we don't know that yet, as this 17820 * convergence has to happen at iter_next() call site only. So if nothing is 17821 * done, at 1: verifier will use bounded loop logic and declare infinite 17822 * looping (and would be *technically* correct, if not for iterator's 17823 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 17824 * don't want that. So what we do in process_iter_next_call() when we go on 17825 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 17826 * a different iteration. So when we suspect an infinite loop, we additionally 17827 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 17828 * pretend we are not looping and wait for next iter_next() call. 17829 * 17830 * This only applies to ACTIVE state. In DRAINED state we don't expect to 17831 * loop, because that would actually mean infinite loop, as DRAINED state is 17832 * "sticky", and so we'll keep returning into the same instruction with the 17833 * same state (at least in one of possible code paths). 17834 * 17835 * This approach allows to keep infinite loop heuristic even in the face of 17836 * active iterator. E.g., C snippet below is and will be detected as 17837 * inifintely looping: 17838 * 17839 * struct bpf_iter_num it; 17840 * int *p, x; 17841 * 17842 * bpf_iter_num_new(&it, 0, 10); 17843 * while ((p = bpf_iter_num_next(&t))) { 17844 * x = p; 17845 * while (x--) {} // <<-- infinite loop here 17846 * } 17847 * 17848 */ 17849 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 17850 { 17851 struct bpf_reg_state *slot, *cur_slot; 17852 struct bpf_func_state *state; 17853 int i, fr; 17854 17855 for (fr = old->curframe; fr >= 0; fr--) { 17856 state = old->frame[fr]; 17857 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 17858 if (state->stack[i].slot_type[0] != STACK_ITER) 17859 continue; 17860 17861 slot = &state->stack[i].spilled_ptr; 17862 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 17863 continue; 17864 17865 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 17866 if (cur_slot->iter.depth != slot->iter.depth) 17867 return true; 17868 } 17869 } 17870 return false; 17871 } 17872 17873 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 17874 { 17875 struct bpf_verifier_state_list *new_sl; 17876 struct bpf_verifier_state_list *sl, **pprev; 17877 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry; 17878 int i, j, n, err, states_cnt = 0; 17879 bool force_new_state, add_new_state, force_exact; 17880 17881 force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) || 17882 /* Avoid accumulating infinitely long jmp history */ 17883 cur->jmp_history_cnt > 40; 17884 17885 /* bpf progs typically have pruning point every 4 instructions 17886 * http://vger.kernel.org/bpfconf2019.html#session-1 17887 * Do not add new state for future pruning if the verifier hasn't seen 17888 * at least 2 jumps and at least 8 instructions. 17889 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 17890 * In tests that amounts to up to 50% reduction into total verifier 17891 * memory consumption and 20% verifier time speedup. 17892 */ 17893 add_new_state = force_new_state; 17894 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 17895 env->insn_processed - env->prev_insn_processed >= 8) 17896 add_new_state = true; 17897 17898 pprev = explored_state(env, insn_idx); 17899 sl = *pprev; 17900 17901 clean_live_states(env, insn_idx, cur); 17902 17903 while (sl) { 17904 states_cnt++; 17905 if (sl->state.insn_idx != insn_idx) 17906 goto next; 17907 17908 if (sl->state.branches) { 17909 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 17910 17911 if (frame->in_async_callback_fn && 17912 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 17913 /* Different async_entry_cnt means that the verifier is 17914 * processing another entry into async callback. 17915 * Seeing the same state is not an indication of infinite 17916 * loop or infinite recursion. 17917 * But finding the same state doesn't mean that it's safe 17918 * to stop processing the current state. The previous state 17919 * hasn't yet reached bpf_exit, since state.branches > 0. 17920 * Checking in_async_callback_fn alone is not enough either. 17921 * Since the verifier still needs to catch infinite loops 17922 * inside async callbacks. 17923 */ 17924 goto skip_inf_loop_check; 17925 } 17926 /* BPF open-coded iterators loop detection is special. 17927 * states_maybe_looping() logic is too simplistic in detecting 17928 * states that *might* be equivalent, because it doesn't know 17929 * about ID remapping, so don't even perform it. 17930 * See process_iter_next_call() and iter_active_depths_differ() 17931 * for overview of the logic. When current and one of parent 17932 * states are detected as equivalent, it's a good thing: we prove 17933 * convergence and can stop simulating further iterations. 17934 * It's safe to assume that iterator loop will finish, taking into 17935 * account iter_next() contract of eventually returning 17936 * sticky NULL result. 17937 * 17938 * Note, that states have to be compared exactly in this case because 17939 * read and precision marks might not be finalized inside the loop. 17940 * E.g. as in the program below: 17941 * 17942 * 1. r7 = -16 17943 * 2. r6 = bpf_get_prandom_u32() 17944 * 3. while (bpf_iter_num_next(&fp[-8])) { 17945 * 4. if (r6 != 42) { 17946 * 5. r7 = -32 17947 * 6. r6 = bpf_get_prandom_u32() 17948 * 7. continue 17949 * 8. } 17950 * 9. r0 = r10 17951 * 10. r0 += r7 17952 * 11. r8 = *(u64 *)(r0 + 0) 17953 * 12. r6 = bpf_get_prandom_u32() 17954 * 13. } 17955 * 17956 * Here verifier would first visit path 1-3, create a checkpoint at 3 17957 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 17958 * not have read or precision mark for r7 yet, thus inexact states 17959 * comparison would discard current state with r7=-32 17960 * => unsafe memory access at 11 would not be caught. 17961 */ 17962 if (is_iter_next_insn(env, insn_idx)) { 17963 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 17964 struct bpf_func_state *cur_frame; 17965 struct bpf_reg_state *iter_state, *iter_reg; 17966 int spi; 17967 17968 cur_frame = cur->frame[cur->curframe]; 17969 /* btf_check_iter_kfuncs() enforces that 17970 * iter state pointer is always the first arg 17971 */ 17972 iter_reg = &cur_frame->regs[BPF_REG_1]; 17973 /* current state is valid due to states_equal(), 17974 * so we can assume valid iter and reg state, 17975 * no need for extra (re-)validations 17976 */ 17977 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 17978 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 17979 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 17980 update_loop_entry(cur, &sl->state); 17981 goto hit; 17982 } 17983 } 17984 goto skip_inf_loop_check; 17985 } 17986 if (is_may_goto_insn_at(env, insn_idx)) { 17987 if (sl->state.may_goto_depth != cur->may_goto_depth && 17988 states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 17989 update_loop_entry(cur, &sl->state); 17990 goto hit; 17991 } 17992 } 17993 if (calls_callback(env, insn_idx)) { 17994 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) 17995 goto hit; 17996 goto skip_inf_loop_check; 17997 } 17998 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 17999 if (states_maybe_looping(&sl->state, cur) && 18000 states_equal(env, &sl->state, cur, EXACT) && 18001 !iter_active_depths_differ(&sl->state, cur) && 18002 sl->state.may_goto_depth == cur->may_goto_depth && 18003 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 18004 verbose_linfo(env, insn_idx, "; "); 18005 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 18006 verbose(env, "cur state:"); 18007 print_verifier_state(env, cur->frame[cur->curframe], true); 18008 verbose(env, "old state:"); 18009 print_verifier_state(env, sl->state.frame[cur->curframe], true); 18010 return -EINVAL; 18011 } 18012 /* if the verifier is processing a loop, avoid adding new state 18013 * too often, since different loop iterations have distinct 18014 * states and may not help future pruning. 18015 * This threshold shouldn't be too low to make sure that 18016 * a loop with large bound will be rejected quickly. 18017 * The most abusive loop will be: 18018 * r1 += 1 18019 * if r1 < 1000000 goto pc-2 18020 * 1M insn_procssed limit / 100 == 10k peak states. 18021 * This threshold shouldn't be too high either, since states 18022 * at the end of the loop are likely to be useful in pruning. 18023 */ 18024 skip_inf_loop_check: 18025 if (!force_new_state && 18026 env->jmps_processed - env->prev_jmps_processed < 20 && 18027 env->insn_processed - env->prev_insn_processed < 100) 18028 add_new_state = false; 18029 goto miss; 18030 } 18031 /* If sl->state is a part of a loop and this loop's entry is a part of 18032 * current verification path then states have to be compared exactly. 18033 * 'force_exact' is needed to catch the following case: 18034 * 18035 * initial Here state 'succ' was processed first, 18036 * | it was eventually tracked to produce a 18037 * V state identical to 'hdr'. 18038 * .---------> hdr All branches from 'succ' had been explored 18039 * | | and thus 'succ' has its .branches == 0. 18040 * | V 18041 * | .------... Suppose states 'cur' and 'succ' correspond 18042 * | | | to the same instruction + callsites. 18043 * | V V In such case it is necessary to check 18044 * | ... ... if 'succ' and 'cur' are states_equal(). 18045 * | | | If 'succ' and 'cur' are a part of the 18046 * | V V same loop exact flag has to be set. 18047 * | succ <- cur To check if that is the case, verify 18048 * | | if loop entry of 'succ' is in current 18049 * | V DFS path. 18050 * | ... 18051 * | | 18052 * '----' 18053 * 18054 * Additional details are in the comment before get_loop_entry(). 18055 */ 18056 loop_entry = get_loop_entry(&sl->state); 18057 force_exact = loop_entry && loop_entry->branches > 0; 18058 if (states_equal(env, &sl->state, cur, force_exact ? RANGE_WITHIN : NOT_EXACT)) { 18059 if (force_exact) 18060 update_loop_entry(cur, loop_entry); 18061 hit: 18062 sl->hit_cnt++; 18063 /* reached equivalent register/stack state, 18064 * prune the search. 18065 * Registers read by the continuation are read by us. 18066 * If we have any write marks in env->cur_state, they 18067 * will prevent corresponding reads in the continuation 18068 * from reaching our parent (an explored_state). Our 18069 * own state will get the read marks recorded, but 18070 * they'll be immediately forgotten as we're pruning 18071 * this state and will pop a new one. 18072 */ 18073 err = propagate_liveness(env, &sl->state, cur); 18074 18075 /* if previous state reached the exit with precision and 18076 * current state is equivalent to it (except precision marks) 18077 * the precision needs to be propagated back in 18078 * the current state. 18079 */ 18080 if (is_jmp_point(env, env->insn_idx)) 18081 err = err ? : push_jmp_history(env, cur, 0, 0); 18082 err = err ? : propagate_precision(env, &sl->state); 18083 if (err) 18084 return err; 18085 return 1; 18086 } 18087 miss: 18088 /* when new state is not going to be added do not increase miss count. 18089 * Otherwise several loop iterations will remove the state 18090 * recorded earlier. The goal of these heuristics is to have 18091 * states from some iterations of the loop (some in the beginning 18092 * and some at the end) to help pruning. 18093 */ 18094 if (add_new_state) 18095 sl->miss_cnt++; 18096 /* heuristic to determine whether this state is beneficial 18097 * to keep checking from state equivalence point of view. 18098 * Higher numbers increase max_states_per_insn and verification time, 18099 * but do not meaningfully decrease insn_processed. 18100 * 'n' controls how many times state could miss before eviction. 18101 * Use bigger 'n' for checkpoints because evicting checkpoint states 18102 * too early would hinder iterator convergence. 18103 */ 18104 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 18105 if (sl->miss_cnt > sl->hit_cnt * n + n) { 18106 /* the state is unlikely to be useful. Remove it to 18107 * speed up verification 18108 */ 18109 *pprev = sl->next; 18110 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE && 18111 !sl->state.used_as_loop_entry) { 18112 u32 br = sl->state.branches; 18113 18114 WARN_ONCE(br, 18115 "BUG live_done but branches_to_explore %d\n", 18116 br); 18117 free_verifier_state(&sl->state, false); 18118 kfree(sl); 18119 env->peak_states--; 18120 } else { 18121 /* cannot free this state, since parentage chain may 18122 * walk it later. Add it for free_list instead to 18123 * be freed at the end of verification 18124 */ 18125 sl->next = env->free_list; 18126 env->free_list = sl; 18127 } 18128 sl = *pprev; 18129 continue; 18130 } 18131 next: 18132 pprev = &sl->next; 18133 sl = *pprev; 18134 } 18135 18136 if (env->max_states_per_insn < states_cnt) 18137 env->max_states_per_insn = states_cnt; 18138 18139 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 18140 return 0; 18141 18142 if (!add_new_state) 18143 return 0; 18144 18145 /* There were no equivalent states, remember the current one. 18146 * Technically the current state is not proven to be safe yet, 18147 * but it will either reach outer most bpf_exit (which means it's safe) 18148 * or it will be rejected. When there are no loops the verifier won't be 18149 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 18150 * again on the way to bpf_exit. 18151 * When looping the sl->state.branches will be > 0 and this state 18152 * will not be considered for equivalence until branches == 0. 18153 */ 18154 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 18155 if (!new_sl) 18156 return -ENOMEM; 18157 env->total_states++; 18158 env->peak_states++; 18159 env->prev_jmps_processed = env->jmps_processed; 18160 env->prev_insn_processed = env->insn_processed; 18161 18162 /* forget precise markings we inherited, see __mark_chain_precision */ 18163 if (env->bpf_capable) 18164 mark_all_scalars_imprecise(env, cur); 18165 18166 /* add new state to the head of linked list */ 18167 new = &new_sl->state; 18168 err = copy_verifier_state(new, cur); 18169 if (err) { 18170 free_verifier_state(new, false); 18171 kfree(new_sl); 18172 return err; 18173 } 18174 new->insn_idx = insn_idx; 18175 WARN_ONCE(new->branches != 1, 18176 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 18177 18178 cur->parent = new; 18179 cur->first_insn_idx = insn_idx; 18180 cur->dfs_depth = new->dfs_depth + 1; 18181 clear_jmp_history(cur); 18182 new_sl->next = *explored_state(env, insn_idx); 18183 *explored_state(env, insn_idx) = new_sl; 18184 /* connect new state to parentage chain. Current frame needs all 18185 * registers connected. Only r6 - r9 of the callers are alive (pushed 18186 * to the stack implicitly by JITs) so in callers' frames connect just 18187 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 18188 * the state of the call instruction (with WRITTEN set), and r0 comes 18189 * from callee with its full parentage chain, anyway. 18190 */ 18191 /* clear write marks in current state: the writes we did are not writes 18192 * our child did, so they don't screen off its reads from us. 18193 * (There are no read marks in current state, because reads always mark 18194 * their parent and current state never has children yet. Only 18195 * explored_states can get read marks.) 18196 */ 18197 for (j = 0; j <= cur->curframe; j++) { 18198 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 18199 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 18200 for (i = 0; i < BPF_REG_FP; i++) 18201 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 18202 } 18203 18204 /* all stack frames are accessible from callee, clear them all */ 18205 for (j = 0; j <= cur->curframe; j++) { 18206 struct bpf_func_state *frame = cur->frame[j]; 18207 struct bpf_func_state *newframe = new->frame[j]; 18208 18209 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 18210 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 18211 frame->stack[i].spilled_ptr.parent = 18212 &newframe->stack[i].spilled_ptr; 18213 } 18214 } 18215 return 0; 18216 } 18217 18218 /* Return true if it's OK to have the same insn return a different type. */ 18219 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 18220 { 18221 switch (base_type(type)) { 18222 case PTR_TO_CTX: 18223 case PTR_TO_SOCKET: 18224 case PTR_TO_SOCK_COMMON: 18225 case PTR_TO_TCP_SOCK: 18226 case PTR_TO_XDP_SOCK: 18227 case PTR_TO_BTF_ID: 18228 case PTR_TO_ARENA: 18229 return false; 18230 default: 18231 return true; 18232 } 18233 } 18234 18235 /* If an instruction was previously used with particular pointer types, then we 18236 * need to be careful to avoid cases such as the below, where it may be ok 18237 * for one branch accessing the pointer, but not ok for the other branch: 18238 * 18239 * R1 = sock_ptr 18240 * goto X; 18241 * ... 18242 * R1 = some_other_valid_ptr; 18243 * goto X; 18244 * ... 18245 * R2 = *(u32 *)(R1 + 0); 18246 */ 18247 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 18248 { 18249 return src != prev && (!reg_type_mismatch_ok(src) || 18250 !reg_type_mismatch_ok(prev)); 18251 } 18252 18253 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 18254 bool allow_trust_mismatch) 18255 { 18256 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 18257 18258 if (*prev_type == NOT_INIT) { 18259 /* Saw a valid insn 18260 * dst_reg = *(u32 *)(src_reg + off) 18261 * save type to validate intersecting paths 18262 */ 18263 *prev_type = type; 18264 } else if (reg_type_mismatch(type, *prev_type)) { 18265 /* Abuser program is trying to use the same insn 18266 * dst_reg = *(u32*) (src_reg + off) 18267 * with different pointer types: 18268 * src_reg == ctx in one branch and 18269 * src_reg == stack|map in some other branch. 18270 * Reject it. 18271 */ 18272 if (allow_trust_mismatch && 18273 base_type(type) == PTR_TO_BTF_ID && 18274 base_type(*prev_type) == PTR_TO_BTF_ID) { 18275 /* 18276 * Have to support a use case when one path through 18277 * the program yields TRUSTED pointer while another 18278 * is UNTRUSTED. Fallback to UNTRUSTED to generate 18279 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 18280 */ 18281 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 18282 } else { 18283 verbose(env, "same insn cannot be used with different pointers\n"); 18284 return -EINVAL; 18285 } 18286 } 18287 18288 return 0; 18289 } 18290 18291 static int do_check(struct bpf_verifier_env *env) 18292 { 18293 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 18294 struct bpf_verifier_state *state = env->cur_state; 18295 struct bpf_insn *insns = env->prog->insnsi; 18296 struct bpf_reg_state *regs; 18297 int insn_cnt = env->prog->len; 18298 bool do_print_state = false; 18299 int prev_insn_idx = -1; 18300 18301 for (;;) { 18302 bool exception_exit = false; 18303 struct bpf_insn *insn; 18304 u8 class; 18305 int err; 18306 18307 /* reset current history entry on each new instruction */ 18308 env->cur_hist_ent = NULL; 18309 18310 env->prev_insn_idx = prev_insn_idx; 18311 if (env->insn_idx >= insn_cnt) { 18312 verbose(env, "invalid insn idx %d insn_cnt %d\n", 18313 env->insn_idx, insn_cnt); 18314 return -EFAULT; 18315 } 18316 18317 insn = &insns[env->insn_idx]; 18318 class = BPF_CLASS(insn->code); 18319 18320 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 18321 verbose(env, 18322 "BPF program is too large. Processed %d insn\n", 18323 env->insn_processed); 18324 return -E2BIG; 18325 } 18326 18327 state->last_insn_idx = env->prev_insn_idx; 18328 18329 if (is_prune_point(env, env->insn_idx)) { 18330 err = is_state_visited(env, env->insn_idx); 18331 if (err < 0) 18332 return err; 18333 if (err == 1) { 18334 /* found equivalent state, can prune the search */ 18335 if (env->log.level & BPF_LOG_LEVEL) { 18336 if (do_print_state) 18337 verbose(env, "\nfrom %d to %d%s: safe\n", 18338 env->prev_insn_idx, env->insn_idx, 18339 env->cur_state->speculative ? 18340 " (speculative execution)" : ""); 18341 else 18342 verbose(env, "%d: safe\n", env->insn_idx); 18343 } 18344 goto process_bpf_exit; 18345 } 18346 } 18347 18348 if (is_jmp_point(env, env->insn_idx)) { 18349 err = push_jmp_history(env, state, 0, 0); 18350 if (err) 18351 return err; 18352 } 18353 18354 if (signal_pending(current)) 18355 return -EAGAIN; 18356 18357 if (need_resched()) 18358 cond_resched(); 18359 18360 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 18361 verbose(env, "\nfrom %d to %d%s:", 18362 env->prev_insn_idx, env->insn_idx, 18363 env->cur_state->speculative ? 18364 " (speculative execution)" : ""); 18365 print_verifier_state(env, state->frame[state->curframe], true); 18366 do_print_state = false; 18367 } 18368 18369 if (env->log.level & BPF_LOG_LEVEL) { 18370 const struct bpf_insn_cbs cbs = { 18371 .cb_call = disasm_kfunc_name, 18372 .cb_print = verbose, 18373 .private_data = env, 18374 }; 18375 18376 if (verifier_state_scratched(env)) 18377 print_insn_state(env, state->frame[state->curframe]); 18378 18379 verbose_linfo(env, env->insn_idx, "; "); 18380 env->prev_log_pos = env->log.end_pos; 18381 verbose(env, "%d: ", env->insn_idx); 18382 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 18383 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 18384 env->prev_log_pos = env->log.end_pos; 18385 } 18386 18387 if (bpf_prog_is_offloaded(env->prog->aux)) { 18388 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 18389 env->prev_insn_idx); 18390 if (err) 18391 return err; 18392 } 18393 18394 regs = cur_regs(env); 18395 sanitize_mark_insn_seen(env); 18396 prev_insn_idx = env->insn_idx; 18397 18398 if (class == BPF_ALU || class == BPF_ALU64) { 18399 err = check_alu_op(env, insn); 18400 if (err) 18401 return err; 18402 18403 } else if (class == BPF_LDX) { 18404 enum bpf_reg_type src_reg_type; 18405 18406 /* check for reserved fields is already done */ 18407 18408 /* check src operand */ 18409 err = check_reg_arg(env, insn->src_reg, SRC_OP); 18410 if (err) 18411 return err; 18412 18413 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 18414 if (err) 18415 return err; 18416 18417 src_reg_type = regs[insn->src_reg].type; 18418 18419 /* check that memory (src_reg + off) is readable, 18420 * the state of dst_reg will be updated by this func 18421 */ 18422 err = check_mem_access(env, env->insn_idx, insn->src_reg, 18423 insn->off, BPF_SIZE(insn->code), 18424 BPF_READ, insn->dst_reg, false, 18425 BPF_MODE(insn->code) == BPF_MEMSX); 18426 err = err ?: save_aux_ptr_type(env, src_reg_type, true); 18427 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], "ldx"); 18428 if (err) 18429 return err; 18430 } else if (class == BPF_STX) { 18431 enum bpf_reg_type dst_reg_type; 18432 18433 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 18434 err = check_atomic(env, env->insn_idx, insn); 18435 if (err) 18436 return err; 18437 env->insn_idx++; 18438 continue; 18439 } 18440 18441 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 18442 verbose(env, "BPF_STX uses reserved fields\n"); 18443 return -EINVAL; 18444 } 18445 18446 /* check src1 operand */ 18447 err = check_reg_arg(env, insn->src_reg, SRC_OP); 18448 if (err) 18449 return err; 18450 /* check src2 operand */ 18451 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 18452 if (err) 18453 return err; 18454 18455 dst_reg_type = regs[insn->dst_reg].type; 18456 18457 /* check that memory (dst_reg + off) is writeable */ 18458 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 18459 insn->off, BPF_SIZE(insn->code), 18460 BPF_WRITE, insn->src_reg, false, false); 18461 if (err) 18462 return err; 18463 18464 err = save_aux_ptr_type(env, dst_reg_type, false); 18465 if (err) 18466 return err; 18467 } else if (class == BPF_ST) { 18468 enum bpf_reg_type dst_reg_type; 18469 18470 if (BPF_MODE(insn->code) != BPF_MEM || 18471 insn->src_reg != BPF_REG_0) { 18472 verbose(env, "BPF_ST uses reserved fields\n"); 18473 return -EINVAL; 18474 } 18475 /* check src 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, -1, 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_JMP || class == BPF_JMP32) { 18493 u8 opcode = BPF_OP(insn->code); 18494 18495 env->jmps_processed++; 18496 if (opcode == BPF_CALL) { 18497 if (BPF_SRC(insn->code) != BPF_K || 18498 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 18499 && insn->off != 0) || 18500 (insn->src_reg != BPF_REG_0 && 18501 insn->src_reg != BPF_PSEUDO_CALL && 18502 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 18503 insn->dst_reg != BPF_REG_0 || 18504 class == BPF_JMP32) { 18505 verbose(env, "BPF_CALL uses reserved fields\n"); 18506 return -EINVAL; 18507 } 18508 18509 if (env->cur_state->active_lock.ptr) { 18510 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 18511 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 18512 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 18513 verbose(env, "function calls are not allowed while holding a lock\n"); 18514 return -EINVAL; 18515 } 18516 } 18517 if (insn->src_reg == BPF_PSEUDO_CALL) { 18518 err = check_func_call(env, insn, &env->insn_idx); 18519 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 18520 err = check_kfunc_call(env, insn, &env->insn_idx); 18521 if (!err && is_bpf_throw_kfunc(insn)) { 18522 exception_exit = true; 18523 goto process_bpf_exit_full; 18524 } 18525 } else { 18526 err = check_helper_call(env, insn, &env->insn_idx); 18527 } 18528 if (err) 18529 return err; 18530 18531 mark_reg_scratched(env, BPF_REG_0); 18532 } else if (opcode == BPF_JA) { 18533 if (BPF_SRC(insn->code) != BPF_K || 18534 insn->src_reg != BPF_REG_0 || 18535 insn->dst_reg != BPF_REG_0 || 18536 (class == BPF_JMP && insn->imm != 0) || 18537 (class == BPF_JMP32 && insn->off != 0)) { 18538 verbose(env, "BPF_JA uses reserved fields\n"); 18539 return -EINVAL; 18540 } 18541 18542 if (class == BPF_JMP) 18543 env->insn_idx += insn->off + 1; 18544 else 18545 env->insn_idx += insn->imm + 1; 18546 continue; 18547 18548 } else if (opcode == BPF_EXIT) { 18549 if (BPF_SRC(insn->code) != BPF_K || 18550 insn->imm != 0 || 18551 insn->src_reg != BPF_REG_0 || 18552 insn->dst_reg != BPF_REG_0 || 18553 class == BPF_JMP32) { 18554 verbose(env, "BPF_EXIT uses reserved fields\n"); 18555 return -EINVAL; 18556 } 18557 process_bpf_exit_full: 18558 if (env->cur_state->active_lock.ptr && !env->cur_state->curframe) { 18559 verbose(env, "bpf_spin_unlock is missing\n"); 18560 return -EINVAL; 18561 } 18562 18563 if (env->cur_state->active_rcu_lock && !env->cur_state->curframe) { 18564 verbose(env, "bpf_rcu_read_unlock is missing\n"); 18565 return -EINVAL; 18566 } 18567 18568 if (env->cur_state->active_preempt_lock && !env->cur_state->curframe) { 18569 verbose(env, "%d bpf_preempt_enable%s missing\n", 18570 env->cur_state->active_preempt_lock, 18571 env->cur_state->active_preempt_lock == 1 ? " is" : "(s) are"); 18572 return -EINVAL; 18573 } 18574 18575 /* We must do check_reference_leak here before 18576 * prepare_func_exit to handle the case when 18577 * state->curframe > 0, it may be a callback 18578 * function, for which reference_state must 18579 * match caller reference state when it exits. 18580 */ 18581 err = check_reference_leak(env, exception_exit); 18582 if (err) 18583 return err; 18584 18585 /* The side effect of the prepare_func_exit 18586 * which is being skipped is that it frees 18587 * bpf_func_state. Typically, process_bpf_exit 18588 * will only be hit with outermost exit. 18589 * copy_verifier_state in pop_stack will handle 18590 * freeing of any extra bpf_func_state left over 18591 * from not processing all nested function 18592 * exits. We also skip return code checks as 18593 * they are not needed for exceptional exits. 18594 */ 18595 if (exception_exit) 18596 goto process_bpf_exit; 18597 18598 if (state->curframe) { 18599 /* exit from nested function */ 18600 err = prepare_func_exit(env, &env->insn_idx); 18601 if (err) 18602 return err; 18603 do_print_state = true; 18604 continue; 18605 } 18606 18607 err = check_return_code(env, BPF_REG_0, "R0"); 18608 if (err) 18609 return err; 18610 process_bpf_exit: 18611 mark_verifier_state_scratched(env); 18612 update_branch_counts(env, env->cur_state); 18613 err = pop_stack(env, &prev_insn_idx, 18614 &env->insn_idx, pop_log); 18615 if (err < 0) { 18616 if (err != -ENOENT) 18617 return err; 18618 break; 18619 } else { 18620 do_print_state = true; 18621 continue; 18622 } 18623 } else { 18624 err = check_cond_jmp_op(env, insn, &env->insn_idx); 18625 if (err) 18626 return err; 18627 } 18628 } else if (class == BPF_LD) { 18629 u8 mode = BPF_MODE(insn->code); 18630 18631 if (mode == BPF_ABS || mode == BPF_IND) { 18632 err = check_ld_abs(env, insn); 18633 if (err) 18634 return err; 18635 18636 } else if (mode == BPF_IMM) { 18637 err = check_ld_imm(env, insn); 18638 if (err) 18639 return err; 18640 18641 env->insn_idx++; 18642 sanitize_mark_insn_seen(env); 18643 } else { 18644 verbose(env, "invalid BPF_LD mode\n"); 18645 return -EINVAL; 18646 } 18647 } else { 18648 verbose(env, "unknown insn class %d\n", class); 18649 return -EINVAL; 18650 } 18651 18652 env->insn_idx++; 18653 } 18654 18655 return 0; 18656 } 18657 18658 static int find_btf_percpu_datasec(struct btf *btf) 18659 { 18660 const struct btf_type *t; 18661 const char *tname; 18662 int i, n; 18663 18664 /* 18665 * Both vmlinux and module each have their own ".data..percpu" 18666 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 18667 * types to look at only module's own BTF types. 18668 */ 18669 n = btf_nr_types(btf); 18670 if (btf_is_module(btf)) 18671 i = btf_nr_types(btf_vmlinux); 18672 else 18673 i = 1; 18674 18675 for(; i < n; i++) { 18676 t = btf_type_by_id(btf, i); 18677 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 18678 continue; 18679 18680 tname = btf_name_by_offset(btf, t->name_off); 18681 if (!strcmp(tname, ".data..percpu")) 18682 return i; 18683 } 18684 18685 return -ENOENT; 18686 } 18687 18688 /* replace pseudo btf_id with kernel symbol address */ 18689 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 18690 struct bpf_insn *insn, 18691 struct bpf_insn_aux_data *aux) 18692 { 18693 const struct btf_var_secinfo *vsi; 18694 const struct btf_type *datasec; 18695 struct btf_mod_pair *btf_mod; 18696 const struct btf_type *t; 18697 const char *sym_name; 18698 bool percpu = false; 18699 u32 type, id = insn->imm; 18700 struct btf *btf; 18701 s32 datasec_id; 18702 u64 addr; 18703 int i, btf_fd, err; 18704 18705 btf_fd = insn[1].imm; 18706 if (btf_fd) { 18707 btf = btf_get_by_fd(btf_fd); 18708 if (IS_ERR(btf)) { 18709 verbose(env, "invalid module BTF object FD specified.\n"); 18710 return -EINVAL; 18711 } 18712 } else { 18713 if (!btf_vmlinux) { 18714 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 18715 return -EINVAL; 18716 } 18717 btf = btf_vmlinux; 18718 btf_get(btf); 18719 } 18720 18721 t = btf_type_by_id(btf, id); 18722 if (!t) { 18723 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 18724 err = -ENOENT; 18725 goto err_put; 18726 } 18727 18728 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 18729 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 18730 err = -EINVAL; 18731 goto err_put; 18732 } 18733 18734 sym_name = btf_name_by_offset(btf, t->name_off); 18735 addr = kallsyms_lookup_name(sym_name); 18736 if (!addr) { 18737 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 18738 sym_name); 18739 err = -ENOENT; 18740 goto err_put; 18741 } 18742 insn[0].imm = (u32)addr; 18743 insn[1].imm = addr >> 32; 18744 18745 if (btf_type_is_func(t)) { 18746 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 18747 aux->btf_var.mem_size = 0; 18748 goto check_btf; 18749 } 18750 18751 datasec_id = find_btf_percpu_datasec(btf); 18752 if (datasec_id > 0) { 18753 datasec = btf_type_by_id(btf, datasec_id); 18754 for_each_vsi(i, datasec, vsi) { 18755 if (vsi->type == id) { 18756 percpu = true; 18757 break; 18758 } 18759 } 18760 } 18761 18762 type = t->type; 18763 t = btf_type_skip_modifiers(btf, type, NULL); 18764 if (percpu) { 18765 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 18766 aux->btf_var.btf = btf; 18767 aux->btf_var.btf_id = type; 18768 } else if (!btf_type_is_struct(t)) { 18769 const struct btf_type *ret; 18770 const char *tname; 18771 u32 tsize; 18772 18773 /* resolve the type size of ksym. */ 18774 ret = btf_resolve_size(btf, t, &tsize); 18775 if (IS_ERR(ret)) { 18776 tname = btf_name_by_offset(btf, t->name_off); 18777 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 18778 tname, PTR_ERR(ret)); 18779 err = -EINVAL; 18780 goto err_put; 18781 } 18782 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 18783 aux->btf_var.mem_size = tsize; 18784 } else { 18785 aux->btf_var.reg_type = PTR_TO_BTF_ID; 18786 aux->btf_var.btf = btf; 18787 aux->btf_var.btf_id = type; 18788 } 18789 check_btf: 18790 /* check whether we recorded this BTF (and maybe module) already */ 18791 for (i = 0; i < env->used_btf_cnt; i++) { 18792 if (env->used_btfs[i].btf == btf) { 18793 btf_put(btf); 18794 return 0; 18795 } 18796 } 18797 18798 if (env->used_btf_cnt >= MAX_USED_BTFS) { 18799 err = -E2BIG; 18800 goto err_put; 18801 } 18802 18803 btf_mod = &env->used_btfs[env->used_btf_cnt]; 18804 btf_mod->btf = btf; 18805 btf_mod->module = NULL; 18806 18807 /* if we reference variables from kernel module, bump its refcount */ 18808 if (btf_is_module(btf)) { 18809 btf_mod->module = btf_try_get_module(btf); 18810 if (!btf_mod->module) { 18811 err = -ENXIO; 18812 goto err_put; 18813 } 18814 } 18815 18816 env->used_btf_cnt++; 18817 18818 return 0; 18819 err_put: 18820 btf_put(btf); 18821 return err; 18822 } 18823 18824 static bool is_tracing_prog_type(enum bpf_prog_type type) 18825 { 18826 switch (type) { 18827 case BPF_PROG_TYPE_KPROBE: 18828 case BPF_PROG_TYPE_TRACEPOINT: 18829 case BPF_PROG_TYPE_PERF_EVENT: 18830 case BPF_PROG_TYPE_RAW_TRACEPOINT: 18831 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 18832 return true; 18833 default: 18834 return false; 18835 } 18836 } 18837 18838 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 18839 struct bpf_map *map, 18840 struct bpf_prog *prog) 18841 18842 { 18843 enum bpf_prog_type prog_type = resolve_prog_type(prog); 18844 18845 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 18846 btf_record_has_field(map->record, BPF_RB_ROOT)) { 18847 if (is_tracing_prog_type(prog_type)) { 18848 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 18849 return -EINVAL; 18850 } 18851 } 18852 18853 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 18854 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 18855 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 18856 return -EINVAL; 18857 } 18858 18859 if (is_tracing_prog_type(prog_type)) { 18860 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 18861 return -EINVAL; 18862 } 18863 } 18864 18865 if (btf_record_has_field(map->record, BPF_TIMER)) { 18866 if (is_tracing_prog_type(prog_type)) { 18867 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 18868 return -EINVAL; 18869 } 18870 } 18871 18872 if (btf_record_has_field(map->record, BPF_WORKQUEUE)) { 18873 if (is_tracing_prog_type(prog_type)) { 18874 verbose(env, "tracing progs cannot use bpf_wq yet\n"); 18875 return -EINVAL; 18876 } 18877 } 18878 18879 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 18880 !bpf_offload_prog_map_match(prog, map)) { 18881 verbose(env, "offload device mismatch between prog and map\n"); 18882 return -EINVAL; 18883 } 18884 18885 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 18886 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 18887 return -EINVAL; 18888 } 18889 18890 if (prog->sleepable) 18891 switch (map->map_type) { 18892 case BPF_MAP_TYPE_HASH: 18893 case BPF_MAP_TYPE_LRU_HASH: 18894 case BPF_MAP_TYPE_ARRAY: 18895 case BPF_MAP_TYPE_PERCPU_HASH: 18896 case BPF_MAP_TYPE_PERCPU_ARRAY: 18897 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 18898 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 18899 case BPF_MAP_TYPE_HASH_OF_MAPS: 18900 case BPF_MAP_TYPE_RINGBUF: 18901 case BPF_MAP_TYPE_USER_RINGBUF: 18902 case BPF_MAP_TYPE_INODE_STORAGE: 18903 case BPF_MAP_TYPE_SK_STORAGE: 18904 case BPF_MAP_TYPE_TASK_STORAGE: 18905 case BPF_MAP_TYPE_CGRP_STORAGE: 18906 case BPF_MAP_TYPE_QUEUE: 18907 case BPF_MAP_TYPE_STACK: 18908 case BPF_MAP_TYPE_ARENA: 18909 break; 18910 default: 18911 verbose(env, 18912 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 18913 return -EINVAL; 18914 } 18915 18916 return 0; 18917 } 18918 18919 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 18920 { 18921 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 18922 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 18923 } 18924 18925 /* Add map behind fd to used maps list, if it's not already there, and return 18926 * its index. Also set *reused to true if this map was already in the list of 18927 * used maps. 18928 * Returns <0 on error, or >= 0 index, on success. 18929 */ 18930 static int add_used_map_from_fd(struct bpf_verifier_env *env, int fd, bool *reused) 18931 { 18932 CLASS(fd, f)(fd); 18933 struct bpf_map *map; 18934 int i; 18935 18936 map = __bpf_map_get(f); 18937 if (IS_ERR(map)) { 18938 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 18939 return PTR_ERR(map); 18940 } 18941 18942 /* check whether we recorded this map already */ 18943 for (i = 0; i < env->used_map_cnt; i++) { 18944 if (env->used_maps[i] == map) { 18945 *reused = true; 18946 return i; 18947 } 18948 } 18949 18950 if (env->used_map_cnt >= MAX_USED_MAPS) { 18951 verbose(env, "The total number of maps per program has reached the limit of %u\n", 18952 MAX_USED_MAPS); 18953 return -E2BIG; 18954 } 18955 18956 if (env->prog->sleepable) 18957 atomic64_inc(&map->sleepable_refcnt); 18958 18959 /* hold the map. If the program is rejected by verifier, 18960 * the map will be released by release_maps() or it 18961 * will be used by the valid program until it's unloaded 18962 * and all maps are released in bpf_free_used_maps() 18963 */ 18964 bpf_map_inc(map); 18965 18966 *reused = false; 18967 env->used_maps[env->used_map_cnt++] = map; 18968 18969 return env->used_map_cnt - 1; 18970 } 18971 18972 /* find and rewrite pseudo imm in ld_imm64 instructions: 18973 * 18974 * 1. if it accesses map FD, replace it with actual map pointer. 18975 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 18976 * 18977 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 18978 */ 18979 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 18980 { 18981 struct bpf_insn *insn = env->prog->insnsi; 18982 int insn_cnt = env->prog->len; 18983 int i, err; 18984 18985 err = bpf_prog_calc_tag(env->prog); 18986 if (err) 18987 return err; 18988 18989 for (i = 0; i < insn_cnt; i++, insn++) { 18990 if (BPF_CLASS(insn->code) == BPF_LDX && 18991 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 18992 insn->imm != 0)) { 18993 verbose(env, "BPF_LDX uses reserved fields\n"); 18994 return -EINVAL; 18995 } 18996 18997 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 18998 struct bpf_insn_aux_data *aux; 18999 struct bpf_map *map; 19000 int map_idx; 19001 u64 addr; 19002 u32 fd; 19003 bool reused; 19004 19005 if (i == insn_cnt - 1 || insn[1].code != 0 || 19006 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 19007 insn[1].off != 0) { 19008 verbose(env, "invalid bpf_ld_imm64 insn\n"); 19009 return -EINVAL; 19010 } 19011 19012 if (insn[0].src_reg == 0) 19013 /* valid generic load 64-bit imm */ 19014 goto next_insn; 19015 19016 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 19017 aux = &env->insn_aux_data[i]; 19018 err = check_pseudo_btf_id(env, insn, aux); 19019 if (err) 19020 return err; 19021 goto next_insn; 19022 } 19023 19024 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 19025 aux = &env->insn_aux_data[i]; 19026 aux->ptr_type = PTR_TO_FUNC; 19027 goto next_insn; 19028 } 19029 19030 /* In final convert_pseudo_ld_imm64() step, this is 19031 * converted into regular 64-bit imm load insn. 19032 */ 19033 switch (insn[0].src_reg) { 19034 case BPF_PSEUDO_MAP_VALUE: 19035 case BPF_PSEUDO_MAP_IDX_VALUE: 19036 break; 19037 case BPF_PSEUDO_MAP_FD: 19038 case BPF_PSEUDO_MAP_IDX: 19039 if (insn[1].imm == 0) 19040 break; 19041 fallthrough; 19042 default: 19043 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 19044 return -EINVAL; 19045 } 19046 19047 switch (insn[0].src_reg) { 19048 case BPF_PSEUDO_MAP_IDX_VALUE: 19049 case BPF_PSEUDO_MAP_IDX: 19050 if (bpfptr_is_null(env->fd_array)) { 19051 verbose(env, "fd_idx without fd_array is invalid\n"); 19052 return -EPROTO; 19053 } 19054 if (copy_from_bpfptr_offset(&fd, env->fd_array, 19055 insn[0].imm * sizeof(fd), 19056 sizeof(fd))) 19057 return -EFAULT; 19058 break; 19059 default: 19060 fd = insn[0].imm; 19061 break; 19062 } 19063 19064 map_idx = add_used_map_from_fd(env, fd, &reused); 19065 if (map_idx < 0) 19066 return map_idx; 19067 map = env->used_maps[map_idx]; 19068 19069 aux = &env->insn_aux_data[i]; 19070 aux->map_index = map_idx; 19071 19072 err = check_map_prog_compatibility(env, map, env->prog); 19073 if (err) 19074 return err; 19075 19076 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 19077 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 19078 addr = (unsigned long)map; 19079 } else { 19080 u32 off = insn[1].imm; 19081 19082 if (off >= BPF_MAX_VAR_OFF) { 19083 verbose(env, "direct value offset of %u is not allowed\n", off); 19084 return -EINVAL; 19085 } 19086 19087 if (!map->ops->map_direct_value_addr) { 19088 verbose(env, "no direct value access support for this map type\n"); 19089 return -EINVAL; 19090 } 19091 19092 err = map->ops->map_direct_value_addr(map, &addr, off); 19093 if (err) { 19094 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 19095 map->value_size, off); 19096 return err; 19097 } 19098 19099 aux->map_off = off; 19100 addr += off; 19101 } 19102 19103 insn[0].imm = (u32)addr; 19104 insn[1].imm = addr >> 32; 19105 19106 /* proceed with extra checks only if its newly added used map */ 19107 if (reused) 19108 goto next_insn; 19109 19110 if (bpf_map_is_cgroup_storage(map) && 19111 bpf_cgroup_storage_assign(env->prog->aux, map)) { 19112 verbose(env, "only one cgroup storage of each type is allowed\n"); 19113 return -EBUSY; 19114 } 19115 if (map->map_type == BPF_MAP_TYPE_ARENA) { 19116 if (env->prog->aux->arena) { 19117 verbose(env, "Only one arena per program\n"); 19118 return -EBUSY; 19119 } 19120 if (!env->allow_ptr_leaks || !env->bpf_capable) { 19121 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n"); 19122 return -EPERM; 19123 } 19124 if (!env->prog->jit_requested) { 19125 verbose(env, "JIT is required to use arena\n"); 19126 return -EOPNOTSUPP; 19127 } 19128 if (!bpf_jit_supports_arena()) { 19129 verbose(env, "JIT doesn't support arena\n"); 19130 return -EOPNOTSUPP; 19131 } 19132 env->prog->aux->arena = (void *)map; 19133 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) { 19134 verbose(env, "arena's user address must be set via map_extra or mmap()\n"); 19135 return -EINVAL; 19136 } 19137 } 19138 19139 next_insn: 19140 insn++; 19141 i++; 19142 continue; 19143 } 19144 19145 /* Basic sanity check before we invest more work here. */ 19146 if (!bpf_opcode_in_insntable(insn->code)) { 19147 verbose(env, "unknown opcode %02x\n", insn->code); 19148 return -EINVAL; 19149 } 19150 } 19151 19152 /* now all pseudo BPF_LD_IMM64 instructions load valid 19153 * 'struct bpf_map *' into a register instead of user map_fd. 19154 * These pointers will be used later by verifier to validate map access. 19155 */ 19156 return 0; 19157 } 19158 19159 /* drop refcnt of maps used by the rejected program */ 19160 static void release_maps(struct bpf_verifier_env *env) 19161 { 19162 __bpf_free_used_maps(env->prog->aux, env->used_maps, 19163 env->used_map_cnt); 19164 } 19165 19166 /* drop refcnt of maps used by the rejected program */ 19167 static void release_btfs(struct bpf_verifier_env *env) 19168 { 19169 __bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt); 19170 } 19171 19172 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 19173 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 19174 { 19175 struct bpf_insn *insn = env->prog->insnsi; 19176 int insn_cnt = env->prog->len; 19177 int i; 19178 19179 for (i = 0; i < insn_cnt; i++, insn++) { 19180 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 19181 continue; 19182 if (insn->src_reg == BPF_PSEUDO_FUNC) 19183 continue; 19184 insn->src_reg = 0; 19185 } 19186 } 19187 19188 /* single env->prog->insni[off] instruction was replaced with the range 19189 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 19190 * [0, off) and [off, end) to new locations, so the patched range stays zero 19191 */ 19192 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 19193 struct bpf_insn_aux_data *new_data, 19194 struct bpf_prog *new_prog, u32 off, u32 cnt) 19195 { 19196 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 19197 struct bpf_insn *insn = new_prog->insnsi; 19198 u32 old_seen = old_data[off].seen; 19199 u32 prog_len; 19200 int i; 19201 19202 /* aux info at OFF always needs adjustment, no matter fast path 19203 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 19204 * original insn at old prog. 19205 */ 19206 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 19207 19208 if (cnt == 1) 19209 return; 19210 prog_len = new_prog->len; 19211 19212 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 19213 memcpy(new_data + off + cnt - 1, old_data + off, 19214 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 19215 for (i = off; i < off + cnt - 1; i++) { 19216 /* Expand insni[off]'s seen count to the patched range. */ 19217 new_data[i].seen = old_seen; 19218 new_data[i].zext_dst = insn_has_def32(env, insn + i); 19219 } 19220 env->insn_aux_data = new_data; 19221 vfree(old_data); 19222 } 19223 19224 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 19225 { 19226 int i; 19227 19228 if (len == 1) 19229 return; 19230 /* NOTE: fake 'exit' subprog should be updated as well. */ 19231 for (i = 0; i <= env->subprog_cnt; i++) { 19232 if (env->subprog_info[i].start <= off) 19233 continue; 19234 env->subprog_info[i].start += len - 1; 19235 } 19236 } 19237 19238 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 19239 { 19240 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 19241 int i, sz = prog->aux->size_poke_tab; 19242 struct bpf_jit_poke_descriptor *desc; 19243 19244 for (i = 0; i < sz; i++) { 19245 desc = &tab[i]; 19246 if (desc->insn_idx <= off) 19247 continue; 19248 desc->insn_idx += len - 1; 19249 } 19250 } 19251 19252 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 19253 const struct bpf_insn *patch, u32 len) 19254 { 19255 struct bpf_prog *new_prog; 19256 struct bpf_insn_aux_data *new_data = NULL; 19257 19258 if (len > 1) { 19259 new_data = vzalloc(array_size(env->prog->len + len - 1, 19260 sizeof(struct bpf_insn_aux_data))); 19261 if (!new_data) 19262 return NULL; 19263 } 19264 19265 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 19266 if (IS_ERR(new_prog)) { 19267 if (PTR_ERR(new_prog) == -ERANGE) 19268 verbose(env, 19269 "insn %d cannot be patched due to 16-bit range\n", 19270 env->insn_aux_data[off].orig_idx); 19271 vfree(new_data); 19272 return NULL; 19273 } 19274 adjust_insn_aux_data(env, new_data, new_prog, off, len); 19275 adjust_subprog_starts(env, off, len); 19276 adjust_poke_descs(new_prog, off, len); 19277 return new_prog; 19278 } 19279 19280 /* 19281 * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the 19282 * jump offset by 'delta'. 19283 */ 19284 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta) 19285 { 19286 struct bpf_insn *insn = prog->insnsi; 19287 u32 insn_cnt = prog->len, i; 19288 s32 imm; 19289 s16 off; 19290 19291 for (i = 0; i < insn_cnt; i++, insn++) { 19292 u8 code = insn->code; 19293 19294 if (tgt_idx <= i && i < tgt_idx + delta) 19295 continue; 19296 19297 if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) || 19298 BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT) 19299 continue; 19300 19301 if (insn->code == (BPF_JMP32 | BPF_JA)) { 19302 if (i + 1 + insn->imm != tgt_idx) 19303 continue; 19304 if (check_add_overflow(insn->imm, delta, &imm)) 19305 return -ERANGE; 19306 insn->imm = imm; 19307 } else { 19308 if (i + 1 + insn->off != tgt_idx) 19309 continue; 19310 if (check_add_overflow(insn->off, delta, &off)) 19311 return -ERANGE; 19312 insn->off = off; 19313 } 19314 } 19315 return 0; 19316 } 19317 19318 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 19319 u32 off, u32 cnt) 19320 { 19321 int i, j; 19322 19323 /* find first prog starting at or after off (first to remove) */ 19324 for (i = 0; i < env->subprog_cnt; i++) 19325 if (env->subprog_info[i].start >= off) 19326 break; 19327 /* find first prog starting at or after off + cnt (first to stay) */ 19328 for (j = i; j < env->subprog_cnt; j++) 19329 if (env->subprog_info[j].start >= off + cnt) 19330 break; 19331 /* if j doesn't start exactly at off + cnt, we are just removing 19332 * the front of previous prog 19333 */ 19334 if (env->subprog_info[j].start != off + cnt) 19335 j--; 19336 19337 if (j > i) { 19338 struct bpf_prog_aux *aux = env->prog->aux; 19339 int move; 19340 19341 /* move fake 'exit' subprog as well */ 19342 move = env->subprog_cnt + 1 - j; 19343 19344 memmove(env->subprog_info + i, 19345 env->subprog_info + j, 19346 sizeof(*env->subprog_info) * move); 19347 env->subprog_cnt -= j - i; 19348 19349 /* remove func_info */ 19350 if (aux->func_info) { 19351 move = aux->func_info_cnt - j; 19352 19353 memmove(aux->func_info + i, 19354 aux->func_info + j, 19355 sizeof(*aux->func_info) * move); 19356 aux->func_info_cnt -= j - i; 19357 /* func_info->insn_off is set after all code rewrites, 19358 * in adjust_btf_func() - no need to adjust 19359 */ 19360 } 19361 } else { 19362 /* convert i from "first prog to remove" to "first to adjust" */ 19363 if (env->subprog_info[i].start == off) 19364 i++; 19365 } 19366 19367 /* update fake 'exit' subprog as well */ 19368 for (; i <= env->subprog_cnt; i++) 19369 env->subprog_info[i].start -= cnt; 19370 19371 return 0; 19372 } 19373 19374 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 19375 u32 cnt) 19376 { 19377 struct bpf_prog *prog = env->prog; 19378 u32 i, l_off, l_cnt, nr_linfo; 19379 struct bpf_line_info *linfo; 19380 19381 nr_linfo = prog->aux->nr_linfo; 19382 if (!nr_linfo) 19383 return 0; 19384 19385 linfo = prog->aux->linfo; 19386 19387 /* find first line info to remove, count lines to be removed */ 19388 for (i = 0; i < nr_linfo; i++) 19389 if (linfo[i].insn_off >= off) 19390 break; 19391 19392 l_off = i; 19393 l_cnt = 0; 19394 for (; i < nr_linfo; i++) 19395 if (linfo[i].insn_off < off + cnt) 19396 l_cnt++; 19397 else 19398 break; 19399 19400 /* First live insn doesn't match first live linfo, it needs to "inherit" 19401 * last removed linfo. prog is already modified, so prog->len == off 19402 * means no live instructions after (tail of the program was removed). 19403 */ 19404 if (prog->len != off && l_cnt && 19405 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 19406 l_cnt--; 19407 linfo[--i].insn_off = off + cnt; 19408 } 19409 19410 /* remove the line info which refer to the removed instructions */ 19411 if (l_cnt) { 19412 memmove(linfo + l_off, linfo + i, 19413 sizeof(*linfo) * (nr_linfo - i)); 19414 19415 prog->aux->nr_linfo -= l_cnt; 19416 nr_linfo = prog->aux->nr_linfo; 19417 } 19418 19419 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 19420 for (i = l_off; i < nr_linfo; i++) 19421 linfo[i].insn_off -= cnt; 19422 19423 /* fix up all subprogs (incl. 'exit') which start >= off */ 19424 for (i = 0; i <= env->subprog_cnt; i++) 19425 if (env->subprog_info[i].linfo_idx > l_off) { 19426 /* program may have started in the removed region but 19427 * may not be fully removed 19428 */ 19429 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 19430 env->subprog_info[i].linfo_idx -= l_cnt; 19431 else 19432 env->subprog_info[i].linfo_idx = l_off; 19433 } 19434 19435 return 0; 19436 } 19437 19438 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 19439 { 19440 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 19441 unsigned int orig_prog_len = env->prog->len; 19442 int err; 19443 19444 if (bpf_prog_is_offloaded(env->prog->aux)) 19445 bpf_prog_offload_remove_insns(env, off, cnt); 19446 19447 err = bpf_remove_insns(env->prog, off, cnt); 19448 if (err) 19449 return err; 19450 19451 err = adjust_subprog_starts_after_remove(env, off, cnt); 19452 if (err) 19453 return err; 19454 19455 err = bpf_adj_linfo_after_remove(env, off, cnt); 19456 if (err) 19457 return err; 19458 19459 memmove(aux_data + off, aux_data + off + cnt, 19460 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 19461 19462 return 0; 19463 } 19464 19465 /* The verifier does more data flow analysis than llvm and will not 19466 * explore branches that are dead at run time. Malicious programs can 19467 * have dead code too. Therefore replace all dead at-run-time code 19468 * with 'ja -1'. 19469 * 19470 * Just nops are not optimal, e.g. if they would sit at the end of the 19471 * program and through another bug we would manage to jump there, then 19472 * we'd execute beyond program memory otherwise. Returning exception 19473 * code also wouldn't work since we can have subprogs where the dead 19474 * code could be located. 19475 */ 19476 static void sanitize_dead_code(struct bpf_verifier_env *env) 19477 { 19478 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 19479 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 19480 struct bpf_insn *insn = env->prog->insnsi; 19481 const int insn_cnt = env->prog->len; 19482 int i; 19483 19484 for (i = 0; i < insn_cnt; i++) { 19485 if (aux_data[i].seen) 19486 continue; 19487 memcpy(insn + i, &trap, sizeof(trap)); 19488 aux_data[i].zext_dst = false; 19489 } 19490 } 19491 19492 static bool insn_is_cond_jump(u8 code) 19493 { 19494 u8 op; 19495 19496 op = BPF_OP(code); 19497 if (BPF_CLASS(code) == BPF_JMP32) 19498 return op != BPF_JA; 19499 19500 if (BPF_CLASS(code) != BPF_JMP) 19501 return false; 19502 19503 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 19504 } 19505 19506 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 19507 { 19508 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 19509 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 19510 struct bpf_insn *insn = env->prog->insnsi; 19511 const int insn_cnt = env->prog->len; 19512 int i; 19513 19514 for (i = 0; i < insn_cnt; i++, insn++) { 19515 if (!insn_is_cond_jump(insn->code)) 19516 continue; 19517 19518 if (!aux_data[i + 1].seen) 19519 ja.off = insn->off; 19520 else if (!aux_data[i + 1 + insn->off].seen) 19521 ja.off = 0; 19522 else 19523 continue; 19524 19525 if (bpf_prog_is_offloaded(env->prog->aux)) 19526 bpf_prog_offload_replace_insn(env, i, &ja); 19527 19528 memcpy(insn, &ja, sizeof(ja)); 19529 } 19530 } 19531 19532 static int opt_remove_dead_code(struct bpf_verifier_env *env) 19533 { 19534 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 19535 int insn_cnt = env->prog->len; 19536 int i, err; 19537 19538 for (i = 0; i < insn_cnt; i++) { 19539 int j; 19540 19541 j = 0; 19542 while (i + j < insn_cnt && !aux_data[i + j].seen) 19543 j++; 19544 if (!j) 19545 continue; 19546 19547 err = verifier_remove_insns(env, i, j); 19548 if (err) 19549 return err; 19550 insn_cnt = env->prog->len; 19551 } 19552 19553 return 0; 19554 } 19555 19556 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 19557 19558 static int opt_remove_nops(struct bpf_verifier_env *env) 19559 { 19560 const struct bpf_insn ja = NOP; 19561 struct bpf_insn *insn = env->prog->insnsi; 19562 int insn_cnt = env->prog->len; 19563 int i, err; 19564 19565 for (i = 0; i < insn_cnt; i++) { 19566 if (memcmp(&insn[i], &ja, sizeof(ja))) 19567 continue; 19568 19569 err = verifier_remove_insns(env, i, 1); 19570 if (err) 19571 return err; 19572 insn_cnt--; 19573 i--; 19574 } 19575 19576 return 0; 19577 } 19578 19579 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 19580 const union bpf_attr *attr) 19581 { 19582 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 19583 struct bpf_insn_aux_data *aux = env->insn_aux_data; 19584 int i, patch_len, delta = 0, len = env->prog->len; 19585 struct bpf_insn *insns = env->prog->insnsi; 19586 struct bpf_prog *new_prog; 19587 bool rnd_hi32; 19588 19589 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 19590 zext_patch[1] = BPF_ZEXT_REG(0); 19591 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 19592 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 19593 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 19594 for (i = 0; i < len; i++) { 19595 int adj_idx = i + delta; 19596 struct bpf_insn insn; 19597 int load_reg; 19598 19599 insn = insns[adj_idx]; 19600 load_reg = insn_def_regno(&insn); 19601 if (!aux[adj_idx].zext_dst) { 19602 u8 code, class; 19603 u32 imm_rnd; 19604 19605 if (!rnd_hi32) 19606 continue; 19607 19608 code = insn.code; 19609 class = BPF_CLASS(code); 19610 if (load_reg == -1) 19611 continue; 19612 19613 /* NOTE: arg "reg" (the fourth one) is only used for 19614 * BPF_STX + SRC_OP, so it is safe to pass NULL 19615 * here. 19616 */ 19617 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 19618 if (class == BPF_LD && 19619 BPF_MODE(code) == BPF_IMM) 19620 i++; 19621 continue; 19622 } 19623 19624 /* ctx load could be transformed into wider load. */ 19625 if (class == BPF_LDX && 19626 aux[adj_idx].ptr_type == PTR_TO_CTX) 19627 continue; 19628 19629 imm_rnd = get_random_u32(); 19630 rnd_hi32_patch[0] = insn; 19631 rnd_hi32_patch[1].imm = imm_rnd; 19632 rnd_hi32_patch[3].dst_reg = load_reg; 19633 patch = rnd_hi32_patch; 19634 patch_len = 4; 19635 goto apply_patch_buffer; 19636 } 19637 19638 /* Add in an zero-extend instruction if a) the JIT has requested 19639 * it or b) it's a CMPXCHG. 19640 * 19641 * The latter is because: BPF_CMPXCHG always loads a value into 19642 * R0, therefore always zero-extends. However some archs' 19643 * equivalent instruction only does this load when the 19644 * comparison is successful. This detail of CMPXCHG is 19645 * orthogonal to the general zero-extension behaviour of the 19646 * CPU, so it's treated independently of bpf_jit_needs_zext. 19647 */ 19648 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 19649 continue; 19650 19651 /* Zero-extension is done by the caller. */ 19652 if (bpf_pseudo_kfunc_call(&insn)) 19653 continue; 19654 19655 if (WARN_ON(load_reg == -1)) { 19656 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 19657 return -EFAULT; 19658 } 19659 19660 zext_patch[0] = insn; 19661 zext_patch[1].dst_reg = load_reg; 19662 zext_patch[1].src_reg = load_reg; 19663 patch = zext_patch; 19664 patch_len = 2; 19665 apply_patch_buffer: 19666 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 19667 if (!new_prog) 19668 return -ENOMEM; 19669 env->prog = new_prog; 19670 insns = new_prog->insnsi; 19671 aux = env->insn_aux_data; 19672 delta += patch_len - 1; 19673 } 19674 19675 return 0; 19676 } 19677 19678 /* convert load instructions that access fields of a context type into a 19679 * sequence of instructions that access fields of the underlying structure: 19680 * struct __sk_buff -> struct sk_buff 19681 * struct bpf_sock_ops -> struct sock 19682 */ 19683 static int convert_ctx_accesses(struct bpf_verifier_env *env) 19684 { 19685 struct bpf_subprog_info *subprogs = env->subprog_info; 19686 const struct bpf_verifier_ops *ops = env->ops; 19687 int i, cnt, size, ctx_field_size, delta = 0, epilogue_cnt = 0; 19688 const int insn_cnt = env->prog->len; 19689 struct bpf_insn *epilogue_buf = env->epilogue_buf; 19690 struct bpf_insn *insn_buf = env->insn_buf; 19691 struct bpf_insn *insn; 19692 u32 target_size, size_default, off; 19693 struct bpf_prog *new_prog; 19694 enum bpf_access_type type; 19695 bool is_narrower_load; 19696 int epilogue_idx = 0; 19697 19698 if (ops->gen_epilogue) { 19699 epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog, 19700 -(subprogs[0].stack_depth + 8)); 19701 if (epilogue_cnt >= INSN_BUF_SIZE) { 19702 verbose(env, "bpf verifier is misconfigured\n"); 19703 return -EINVAL; 19704 } else if (epilogue_cnt) { 19705 /* Save the ARG_PTR_TO_CTX for the epilogue to use */ 19706 cnt = 0; 19707 subprogs[0].stack_depth += 8; 19708 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1, 19709 -subprogs[0].stack_depth); 19710 insn_buf[cnt++] = env->prog->insnsi[0]; 19711 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 19712 if (!new_prog) 19713 return -ENOMEM; 19714 env->prog = new_prog; 19715 delta += cnt - 1; 19716 } 19717 } 19718 19719 if (ops->gen_prologue || env->seen_direct_write) { 19720 if (!ops->gen_prologue) { 19721 verbose(env, "bpf verifier is misconfigured\n"); 19722 return -EINVAL; 19723 } 19724 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 19725 env->prog); 19726 if (cnt >= INSN_BUF_SIZE) { 19727 verbose(env, "bpf verifier is misconfigured\n"); 19728 return -EINVAL; 19729 } else if (cnt) { 19730 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 19731 if (!new_prog) 19732 return -ENOMEM; 19733 19734 env->prog = new_prog; 19735 delta += cnt - 1; 19736 } 19737 } 19738 19739 if (delta) 19740 WARN_ON(adjust_jmp_off(env->prog, 0, delta)); 19741 19742 if (bpf_prog_is_offloaded(env->prog->aux)) 19743 return 0; 19744 19745 insn = env->prog->insnsi + delta; 19746 19747 for (i = 0; i < insn_cnt; i++, insn++) { 19748 bpf_convert_ctx_access_t convert_ctx_access; 19749 u8 mode; 19750 19751 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 19752 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 19753 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 19754 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 19755 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 19756 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 19757 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 19758 type = BPF_READ; 19759 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 19760 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 19761 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 19762 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 19763 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 19764 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 19765 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 19766 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 19767 type = BPF_WRITE; 19768 } else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) || 19769 insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) && 19770 env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) { 19771 insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code); 19772 env->prog->aux->num_exentries++; 19773 continue; 19774 } else if (insn->code == (BPF_JMP | BPF_EXIT) && 19775 epilogue_cnt && 19776 i + delta < subprogs[1].start) { 19777 /* Generate epilogue for the main prog */ 19778 if (epilogue_idx) { 19779 /* jump back to the earlier generated epilogue */ 19780 insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1); 19781 cnt = 1; 19782 } else { 19783 memcpy(insn_buf, epilogue_buf, 19784 epilogue_cnt * sizeof(*epilogue_buf)); 19785 cnt = epilogue_cnt; 19786 /* epilogue_idx cannot be 0. It must have at 19787 * least one ctx ptr saving insn before the 19788 * epilogue. 19789 */ 19790 epilogue_idx = i + delta; 19791 } 19792 goto patch_insn_buf; 19793 } else { 19794 continue; 19795 } 19796 19797 if (type == BPF_WRITE && 19798 env->insn_aux_data[i + delta].sanitize_stack_spill) { 19799 struct bpf_insn patch[] = { 19800 *insn, 19801 BPF_ST_NOSPEC(), 19802 }; 19803 19804 cnt = ARRAY_SIZE(patch); 19805 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 19806 if (!new_prog) 19807 return -ENOMEM; 19808 19809 delta += cnt - 1; 19810 env->prog = new_prog; 19811 insn = new_prog->insnsi + i + delta; 19812 continue; 19813 } 19814 19815 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 19816 case PTR_TO_CTX: 19817 if (!ops->convert_ctx_access) 19818 continue; 19819 convert_ctx_access = ops->convert_ctx_access; 19820 break; 19821 case PTR_TO_SOCKET: 19822 case PTR_TO_SOCK_COMMON: 19823 convert_ctx_access = bpf_sock_convert_ctx_access; 19824 break; 19825 case PTR_TO_TCP_SOCK: 19826 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 19827 break; 19828 case PTR_TO_XDP_SOCK: 19829 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 19830 break; 19831 case PTR_TO_BTF_ID: 19832 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 19833 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 19834 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 19835 * be said once it is marked PTR_UNTRUSTED, hence we must handle 19836 * any faults for loads into such types. BPF_WRITE is disallowed 19837 * for this case. 19838 */ 19839 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 19840 if (type == BPF_READ) { 19841 if (BPF_MODE(insn->code) == BPF_MEM) 19842 insn->code = BPF_LDX | BPF_PROBE_MEM | 19843 BPF_SIZE((insn)->code); 19844 else 19845 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 19846 BPF_SIZE((insn)->code); 19847 env->prog->aux->num_exentries++; 19848 } 19849 continue; 19850 case PTR_TO_ARENA: 19851 if (BPF_MODE(insn->code) == BPF_MEMSX) { 19852 verbose(env, "sign extending loads from arena are not supported yet\n"); 19853 return -EOPNOTSUPP; 19854 } 19855 insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code); 19856 env->prog->aux->num_exentries++; 19857 continue; 19858 default: 19859 continue; 19860 } 19861 19862 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 19863 size = BPF_LDST_BYTES(insn); 19864 mode = BPF_MODE(insn->code); 19865 19866 /* If the read access is a narrower load of the field, 19867 * convert to a 4/8-byte load, to minimum program type specific 19868 * convert_ctx_access changes. If conversion is successful, 19869 * we will apply proper mask to the result. 19870 */ 19871 is_narrower_load = size < ctx_field_size; 19872 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 19873 off = insn->off; 19874 if (is_narrower_load) { 19875 u8 size_code; 19876 19877 if (type == BPF_WRITE) { 19878 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 19879 return -EINVAL; 19880 } 19881 19882 size_code = BPF_H; 19883 if (ctx_field_size == 4) 19884 size_code = BPF_W; 19885 else if (ctx_field_size == 8) 19886 size_code = BPF_DW; 19887 19888 insn->off = off & ~(size_default - 1); 19889 insn->code = BPF_LDX | BPF_MEM | size_code; 19890 } 19891 19892 target_size = 0; 19893 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 19894 &target_size); 19895 if (cnt == 0 || cnt >= INSN_BUF_SIZE || 19896 (ctx_field_size && !target_size)) { 19897 verbose(env, "bpf verifier is misconfigured\n"); 19898 return -EINVAL; 19899 } 19900 19901 if (is_narrower_load && size < target_size) { 19902 u8 shift = bpf_ctx_narrow_access_offset( 19903 off, size, size_default) * 8; 19904 if (shift && cnt + 1 >= INSN_BUF_SIZE) { 19905 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 19906 return -EINVAL; 19907 } 19908 if (ctx_field_size <= 4) { 19909 if (shift) 19910 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 19911 insn->dst_reg, 19912 shift); 19913 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 19914 (1 << size * 8) - 1); 19915 } else { 19916 if (shift) 19917 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 19918 insn->dst_reg, 19919 shift); 19920 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 19921 (1ULL << size * 8) - 1); 19922 } 19923 } 19924 if (mode == BPF_MEMSX) 19925 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 19926 insn->dst_reg, insn->dst_reg, 19927 size * 8, 0); 19928 19929 patch_insn_buf: 19930 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19931 if (!new_prog) 19932 return -ENOMEM; 19933 19934 delta += cnt - 1; 19935 19936 /* keep walking new program and skip insns we just inserted */ 19937 env->prog = new_prog; 19938 insn = new_prog->insnsi + i + delta; 19939 } 19940 19941 return 0; 19942 } 19943 19944 static int jit_subprogs(struct bpf_verifier_env *env) 19945 { 19946 struct bpf_prog *prog = env->prog, **func, *tmp; 19947 int i, j, subprog_start, subprog_end = 0, len, subprog; 19948 struct bpf_map *map_ptr; 19949 struct bpf_insn *insn; 19950 void *old_bpf_func; 19951 int err, num_exentries; 19952 19953 if (env->subprog_cnt <= 1) 19954 return 0; 19955 19956 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 19957 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 19958 continue; 19959 19960 /* Upon error here we cannot fall back to interpreter but 19961 * need a hard reject of the program. Thus -EFAULT is 19962 * propagated in any case. 19963 */ 19964 subprog = find_subprog(env, i + insn->imm + 1); 19965 if (subprog < 0) { 19966 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 19967 i + insn->imm + 1); 19968 return -EFAULT; 19969 } 19970 /* temporarily remember subprog id inside insn instead of 19971 * aux_data, since next loop will split up all insns into funcs 19972 */ 19973 insn->off = subprog; 19974 /* remember original imm in case JIT fails and fallback 19975 * to interpreter will be needed 19976 */ 19977 env->insn_aux_data[i].call_imm = insn->imm; 19978 /* point imm to __bpf_call_base+1 from JITs point of view */ 19979 insn->imm = 1; 19980 if (bpf_pseudo_func(insn)) { 19981 #if defined(MODULES_VADDR) 19982 u64 addr = MODULES_VADDR; 19983 #else 19984 u64 addr = VMALLOC_START; 19985 #endif 19986 /* jit (e.g. x86_64) may emit fewer instructions 19987 * if it learns a u32 imm is the same as a u64 imm. 19988 * Set close enough to possible prog address. 19989 */ 19990 insn[0].imm = (u32)addr; 19991 insn[1].imm = addr >> 32; 19992 } 19993 } 19994 19995 err = bpf_prog_alloc_jited_linfo(prog); 19996 if (err) 19997 goto out_undo_insn; 19998 19999 err = -ENOMEM; 20000 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 20001 if (!func) 20002 goto out_undo_insn; 20003 20004 for (i = 0; i < env->subprog_cnt; i++) { 20005 subprog_start = subprog_end; 20006 subprog_end = env->subprog_info[i + 1].start; 20007 20008 len = subprog_end - subprog_start; 20009 /* bpf_prog_run() doesn't call subprogs directly, 20010 * hence main prog stats include the runtime of subprogs. 20011 * subprogs don't have IDs and not reachable via prog_get_next_id 20012 * func[i]->stats will never be accessed and stays NULL 20013 */ 20014 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 20015 if (!func[i]) 20016 goto out_free; 20017 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 20018 len * sizeof(struct bpf_insn)); 20019 func[i]->type = prog->type; 20020 func[i]->len = len; 20021 if (bpf_prog_calc_tag(func[i])) 20022 goto out_free; 20023 func[i]->is_func = 1; 20024 func[i]->sleepable = prog->sleepable; 20025 func[i]->aux->func_idx = i; 20026 /* Below members will be freed only at prog->aux */ 20027 func[i]->aux->btf = prog->aux->btf; 20028 func[i]->aux->func_info = prog->aux->func_info; 20029 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 20030 func[i]->aux->poke_tab = prog->aux->poke_tab; 20031 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 20032 20033 for (j = 0; j < prog->aux->size_poke_tab; j++) { 20034 struct bpf_jit_poke_descriptor *poke; 20035 20036 poke = &prog->aux->poke_tab[j]; 20037 if (poke->insn_idx < subprog_end && 20038 poke->insn_idx >= subprog_start) 20039 poke->aux = func[i]->aux; 20040 } 20041 20042 func[i]->aux->name[0] = 'F'; 20043 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 20044 func[i]->jit_requested = 1; 20045 func[i]->blinding_requested = prog->blinding_requested; 20046 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 20047 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 20048 func[i]->aux->linfo = prog->aux->linfo; 20049 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 20050 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 20051 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 20052 func[i]->aux->arena = prog->aux->arena; 20053 num_exentries = 0; 20054 insn = func[i]->insnsi; 20055 for (j = 0; j < func[i]->len; j++, insn++) { 20056 if (BPF_CLASS(insn->code) == BPF_LDX && 20057 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 20058 BPF_MODE(insn->code) == BPF_PROBE_MEM32 || 20059 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 20060 num_exentries++; 20061 if ((BPF_CLASS(insn->code) == BPF_STX || 20062 BPF_CLASS(insn->code) == BPF_ST) && 20063 BPF_MODE(insn->code) == BPF_PROBE_MEM32) 20064 num_exentries++; 20065 if (BPF_CLASS(insn->code) == BPF_STX && 20066 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) 20067 num_exentries++; 20068 } 20069 func[i]->aux->num_exentries = num_exentries; 20070 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 20071 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb; 20072 if (!i) 20073 func[i]->aux->exception_boundary = env->seen_exception; 20074 func[i] = bpf_int_jit_compile(func[i]); 20075 if (!func[i]->jited) { 20076 err = -ENOTSUPP; 20077 goto out_free; 20078 } 20079 cond_resched(); 20080 } 20081 20082 /* at this point all bpf functions were successfully JITed 20083 * now populate all bpf_calls with correct addresses and 20084 * run last pass of JIT 20085 */ 20086 for (i = 0; i < env->subprog_cnt; i++) { 20087 insn = func[i]->insnsi; 20088 for (j = 0; j < func[i]->len; j++, insn++) { 20089 if (bpf_pseudo_func(insn)) { 20090 subprog = insn->off; 20091 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 20092 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 20093 continue; 20094 } 20095 if (!bpf_pseudo_call(insn)) 20096 continue; 20097 subprog = insn->off; 20098 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 20099 } 20100 20101 /* we use the aux data to keep a list of the start addresses 20102 * of the JITed images for each function in the program 20103 * 20104 * for some architectures, such as powerpc64, the imm field 20105 * might not be large enough to hold the offset of the start 20106 * address of the callee's JITed image from __bpf_call_base 20107 * 20108 * in such cases, we can lookup the start address of a callee 20109 * by using its subprog id, available from the off field of 20110 * the call instruction, as an index for this list 20111 */ 20112 func[i]->aux->func = func; 20113 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 20114 func[i]->aux->real_func_cnt = env->subprog_cnt; 20115 } 20116 for (i = 0; i < env->subprog_cnt; i++) { 20117 old_bpf_func = func[i]->bpf_func; 20118 tmp = bpf_int_jit_compile(func[i]); 20119 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 20120 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 20121 err = -ENOTSUPP; 20122 goto out_free; 20123 } 20124 cond_resched(); 20125 } 20126 20127 /* finally lock prog and jit images for all functions and 20128 * populate kallsysm. Begin at the first subprogram, since 20129 * bpf_prog_load will add the kallsyms for the main program. 20130 */ 20131 for (i = 1; i < env->subprog_cnt; i++) { 20132 err = bpf_prog_lock_ro(func[i]); 20133 if (err) 20134 goto out_free; 20135 } 20136 20137 for (i = 1; i < env->subprog_cnt; i++) 20138 bpf_prog_kallsyms_add(func[i]); 20139 20140 /* Last step: make now unused interpreter insns from main 20141 * prog consistent for later dump requests, so they can 20142 * later look the same as if they were interpreted only. 20143 */ 20144 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 20145 if (bpf_pseudo_func(insn)) { 20146 insn[0].imm = env->insn_aux_data[i].call_imm; 20147 insn[1].imm = insn->off; 20148 insn->off = 0; 20149 continue; 20150 } 20151 if (!bpf_pseudo_call(insn)) 20152 continue; 20153 insn->off = env->insn_aux_data[i].call_imm; 20154 subprog = find_subprog(env, i + insn->off + 1); 20155 insn->imm = subprog; 20156 } 20157 20158 prog->jited = 1; 20159 prog->bpf_func = func[0]->bpf_func; 20160 prog->jited_len = func[0]->jited_len; 20161 prog->aux->extable = func[0]->aux->extable; 20162 prog->aux->num_exentries = func[0]->aux->num_exentries; 20163 prog->aux->func = func; 20164 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 20165 prog->aux->real_func_cnt = env->subprog_cnt; 20166 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func; 20167 prog->aux->exception_boundary = func[0]->aux->exception_boundary; 20168 bpf_prog_jit_attempt_done(prog); 20169 return 0; 20170 out_free: 20171 /* We failed JIT'ing, so at this point we need to unregister poke 20172 * descriptors from subprogs, so that kernel is not attempting to 20173 * patch it anymore as we're freeing the subprog JIT memory. 20174 */ 20175 for (i = 0; i < prog->aux->size_poke_tab; i++) { 20176 map_ptr = prog->aux->poke_tab[i].tail_call.map; 20177 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 20178 } 20179 /* At this point we're guaranteed that poke descriptors are not 20180 * live anymore. We can just unlink its descriptor table as it's 20181 * released with the main prog. 20182 */ 20183 for (i = 0; i < env->subprog_cnt; i++) { 20184 if (!func[i]) 20185 continue; 20186 func[i]->aux->poke_tab = NULL; 20187 bpf_jit_free(func[i]); 20188 } 20189 kfree(func); 20190 out_undo_insn: 20191 /* cleanup main prog to be interpreted */ 20192 prog->jit_requested = 0; 20193 prog->blinding_requested = 0; 20194 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 20195 if (!bpf_pseudo_call(insn)) 20196 continue; 20197 insn->off = 0; 20198 insn->imm = env->insn_aux_data[i].call_imm; 20199 } 20200 bpf_prog_jit_attempt_done(prog); 20201 return err; 20202 } 20203 20204 static int fixup_call_args(struct bpf_verifier_env *env) 20205 { 20206 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 20207 struct bpf_prog *prog = env->prog; 20208 struct bpf_insn *insn = prog->insnsi; 20209 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 20210 int i, depth; 20211 #endif 20212 int err = 0; 20213 20214 if (env->prog->jit_requested && 20215 !bpf_prog_is_offloaded(env->prog->aux)) { 20216 err = jit_subprogs(env); 20217 if (err == 0) 20218 return 0; 20219 if (err == -EFAULT) 20220 return err; 20221 } 20222 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 20223 if (has_kfunc_call) { 20224 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 20225 return -EINVAL; 20226 } 20227 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 20228 /* When JIT fails the progs with bpf2bpf calls and tail_calls 20229 * have to be rejected, since interpreter doesn't support them yet. 20230 */ 20231 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 20232 return -EINVAL; 20233 } 20234 for (i = 0; i < prog->len; i++, insn++) { 20235 if (bpf_pseudo_func(insn)) { 20236 /* When JIT fails the progs with callback calls 20237 * have to be rejected, since interpreter doesn't support them yet. 20238 */ 20239 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 20240 return -EINVAL; 20241 } 20242 20243 if (!bpf_pseudo_call(insn)) 20244 continue; 20245 depth = get_callee_stack_depth(env, insn, i); 20246 if (depth < 0) 20247 return depth; 20248 bpf_patch_call_args(insn, depth); 20249 } 20250 err = 0; 20251 #endif 20252 return err; 20253 } 20254 20255 /* replace a generic kfunc with a specialized version if necessary */ 20256 static void specialize_kfunc(struct bpf_verifier_env *env, 20257 u32 func_id, u16 offset, unsigned long *addr) 20258 { 20259 struct bpf_prog *prog = env->prog; 20260 bool seen_direct_write; 20261 void *xdp_kfunc; 20262 bool is_rdonly; 20263 20264 if (bpf_dev_bound_kfunc_id(func_id)) { 20265 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 20266 if (xdp_kfunc) { 20267 *addr = (unsigned long)xdp_kfunc; 20268 return; 20269 } 20270 /* fallback to default kfunc when not supported by netdev */ 20271 } 20272 20273 if (offset) 20274 return; 20275 20276 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 20277 seen_direct_write = env->seen_direct_write; 20278 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 20279 20280 if (is_rdonly) 20281 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 20282 20283 /* restore env->seen_direct_write to its original value, since 20284 * may_access_direct_pkt_data mutates it 20285 */ 20286 env->seen_direct_write = seen_direct_write; 20287 } 20288 } 20289 20290 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 20291 u16 struct_meta_reg, 20292 u16 node_offset_reg, 20293 struct bpf_insn *insn, 20294 struct bpf_insn *insn_buf, 20295 int *cnt) 20296 { 20297 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 20298 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 20299 20300 insn_buf[0] = addr[0]; 20301 insn_buf[1] = addr[1]; 20302 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 20303 insn_buf[3] = *insn; 20304 *cnt = 4; 20305 } 20306 20307 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 20308 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 20309 { 20310 const struct bpf_kfunc_desc *desc; 20311 20312 if (!insn->imm) { 20313 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 20314 return -EINVAL; 20315 } 20316 20317 *cnt = 0; 20318 20319 /* insn->imm has the btf func_id. Replace it with an offset relative to 20320 * __bpf_call_base, unless the JIT needs to call functions that are 20321 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 20322 */ 20323 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 20324 if (!desc) { 20325 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 20326 insn->imm); 20327 return -EFAULT; 20328 } 20329 20330 if (!bpf_jit_supports_far_kfunc_call()) 20331 insn->imm = BPF_CALL_IMM(desc->addr); 20332 if (insn->off) 20333 return 0; 20334 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 20335 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 20336 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 20337 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 20338 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 20339 20340 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) { 20341 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 20342 insn_idx); 20343 return -EFAULT; 20344 } 20345 20346 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 20347 insn_buf[1] = addr[0]; 20348 insn_buf[2] = addr[1]; 20349 insn_buf[3] = *insn; 20350 *cnt = 4; 20351 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 20352 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] || 20353 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 20354 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 20355 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 20356 20357 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) { 20358 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 20359 insn_idx); 20360 return -EFAULT; 20361 } 20362 20363 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 20364 !kptr_struct_meta) { 20365 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 20366 insn_idx); 20367 return -EFAULT; 20368 } 20369 20370 insn_buf[0] = addr[0]; 20371 insn_buf[1] = addr[1]; 20372 insn_buf[2] = *insn; 20373 *cnt = 3; 20374 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 20375 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 20376 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 20377 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 20378 int struct_meta_reg = BPF_REG_3; 20379 int node_offset_reg = BPF_REG_4; 20380 20381 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 20382 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 20383 struct_meta_reg = BPF_REG_4; 20384 node_offset_reg = BPF_REG_5; 20385 } 20386 20387 if (!kptr_struct_meta) { 20388 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 20389 insn_idx); 20390 return -EFAULT; 20391 } 20392 20393 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 20394 node_offset_reg, insn, insn_buf, cnt); 20395 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 20396 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 20397 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 20398 *cnt = 1; 20399 } else if (is_bpf_wq_set_callback_impl_kfunc(desc->func_id)) { 20400 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(BPF_REG_4, (long)env->prog->aux) }; 20401 20402 insn_buf[0] = ld_addrs[0]; 20403 insn_buf[1] = ld_addrs[1]; 20404 insn_buf[2] = *insn; 20405 *cnt = 3; 20406 } 20407 return 0; 20408 } 20409 20410 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */ 20411 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len) 20412 { 20413 struct bpf_subprog_info *info = env->subprog_info; 20414 int cnt = env->subprog_cnt; 20415 struct bpf_prog *prog; 20416 20417 /* We only reserve one slot for hidden subprogs in subprog_info. */ 20418 if (env->hidden_subprog_cnt) { 20419 verbose(env, "verifier internal error: only one hidden subprog supported\n"); 20420 return -EFAULT; 20421 } 20422 /* We're not patching any existing instruction, just appending the new 20423 * ones for the hidden subprog. Hence all of the adjustment operations 20424 * in bpf_patch_insn_data are no-ops. 20425 */ 20426 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len); 20427 if (!prog) 20428 return -ENOMEM; 20429 env->prog = prog; 20430 info[cnt + 1].start = info[cnt].start; 20431 info[cnt].start = prog->len - len + 1; 20432 env->subprog_cnt++; 20433 env->hidden_subprog_cnt++; 20434 return 0; 20435 } 20436 20437 /* Do various post-verification rewrites in a single program pass. 20438 * These rewrites simplify JIT and interpreter implementations. 20439 */ 20440 static int do_misc_fixups(struct bpf_verifier_env *env) 20441 { 20442 struct bpf_prog *prog = env->prog; 20443 enum bpf_attach_type eatype = prog->expected_attach_type; 20444 enum bpf_prog_type prog_type = resolve_prog_type(prog); 20445 struct bpf_insn *insn = prog->insnsi; 20446 const struct bpf_func_proto *fn; 20447 const int insn_cnt = prog->len; 20448 const struct bpf_map_ops *ops; 20449 struct bpf_insn_aux_data *aux; 20450 struct bpf_insn *insn_buf = env->insn_buf; 20451 struct bpf_prog *new_prog; 20452 struct bpf_map *map_ptr; 20453 int i, ret, cnt, delta = 0, cur_subprog = 0; 20454 struct bpf_subprog_info *subprogs = env->subprog_info; 20455 u16 stack_depth = subprogs[cur_subprog].stack_depth; 20456 u16 stack_depth_extra = 0; 20457 20458 if (env->seen_exception && !env->exception_callback_subprog) { 20459 struct bpf_insn patch[] = { 20460 env->prog->insnsi[insn_cnt - 1], 20461 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1), 20462 BPF_EXIT_INSN(), 20463 }; 20464 20465 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch)); 20466 if (ret < 0) 20467 return ret; 20468 prog = env->prog; 20469 insn = prog->insnsi; 20470 20471 env->exception_callback_subprog = env->subprog_cnt - 1; 20472 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */ 20473 mark_subprog_exc_cb(env, env->exception_callback_subprog); 20474 } 20475 20476 for (i = 0; i < insn_cnt;) { 20477 if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) { 20478 if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) || 20479 (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) { 20480 /* convert to 32-bit mov that clears upper 32-bit */ 20481 insn->code = BPF_ALU | BPF_MOV | BPF_X; 20482 /* clear off and imm, so it's a normal 'wX = wY' from JIT pov */ 20483 insn->off = 0; 20484 insn->imm = 0; 20485 } /* cast from as(0) to as(1) should be handled by JIT */ 20486 goto next_insn; 20487 } 20488 20489 if (env->insn_aux_data[i + delta].needs_zext) 20490 /* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */ 20491 insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code); 20492 20493 /* Make sdiv/smod divide-by-minus-one exceptions impossible. */ 20494 if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) || 20495 insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) || 20496 insn->code == (BPF_ALU | BPF_MOD | BPF_K) || 20497 insn->code == (BPF_ALU | BPF_DIV | BPF_K)) && 20498 insn->off == 1 && insn->imm == -1) { 20499 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 20500 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 20501 struct bpf_insn *patchlet; 20502 struct bpf_insn chk_and_sdiv[] = { 20503 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 20504 BPF_NEG | BPF_K, insn->dst_reg, 20505 0, 0, 0), 20506 }; 20507 struct bpf_insn chk_and_smod[] = { 20508 BPF_MOV32_IMM(insn->dst_reg, 0), 20509 }; 20510 20511 patchlet = isdiv ? chk_and_sdiv : chk_and_smod; 20512 cnt = isdiv ? ARRAY_SIZE(chk_and_sdiv) : ARRAY_SIZE(chk_and_smod); 20513 20514 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 20515 if (!new_prog) 20516 return -ENOMEM; 20517 20518 delta += cnt - 1; 20519 env->prog = prog = new_prog; 20520 insn = new_prog->insnsi + i + delta; 20521 goto next_insn; 20522 } 20523 20524 /* Make divide-by-zero and divide-by-minus-one exceptions impossible. */ 20525 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 20526 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 20527 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 20528 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 20529 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 20530 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 20531 bool is_sdiv = isdiv && insn->off == 1; 20532 bool is_smod = !isdiv && insn->off == 1; 20533 struct bpf_insn *patchlet; 20534 struct bpf_insn chk_and_div[] = { 20535 /* [R,W]x div 0 -> 0 */ 20536 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 20537 BPF_JNE | BPF_K, insn->src_reg, 20538 0, 2, 0), 20539 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 20540 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 20541 *insn, 20542 }; 20543 struct bpf_insn chk_and_mod[] = { 20544 /* [R,W]x mod 0 -> [R,W]x */ 20545 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 20546 BPF_JEQ | BPF_K, insn->src_reg, 20547 0, 1 + (is64 ? 0 : 1), 0), 20548 *insn, 20549 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 20550 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 20551 }; 20552 struct bpf_insn chk_and_sdiv[] = { 20553 /* [R,W]x sdiv 0 -> 0 20554 * LLONG_MIN sdiv -1 -> LLONG_MIN 20555 * INT_MIN sdiv -1 -> INT_MIN 20556 */ 20557 BPF_MOV64_REG(BPF_REG_AX, insn->src_reg), 20558 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 20559 BPF_ADD | BPF_K, BPF_REG_AX, 20560 0, 0, 1), 20561 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 20562 BPF_JGT | BPF_K, BPF_REG_AX, 20563 0, 4, 1), 20564 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 20565 BPF_JEQ | BPF_K, BPF_REG_AX, 20566 0, 1, 0), 20567 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 20568 BPF_MOV | BPF_K, insn->dst_reg, 20569 0, 0, 0), 20570 /* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */ 20571 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 20572 BPF_NEG | BPF_K, insn->dst_reg, 20573 0, 0, 0), 20574 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 20575 *insn, 20576 }; 20577 struct bpf_insn chk_and_smod[] = { 20578 /* [R,W]x mod 0 -> [R,W]x */ 20579 /* [R,W]x mod -1 -> 0 */ 20580 BPF_MOV64_REG(BPF_REG_AX, insn->src_reg), 20581 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 20582 BPF_ADD | BPF_K, BPF_REG_AX, 20583 0, 0, 1), 20584 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 20585 BPF_JGT | BPF_K, BPF_REG_AX, 20586 0, 3, 1), 20587 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 20588 BPF_JEQ | BPF_K, BPF_REG_AX, 20589 0, 3 + (is64 ? 0 : 1), 1), 20590 BPF_MOV32_IMM(insn->dst_reg, 0), 20591 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 20592 *insn, 20593 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 20594 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 20595 }; 20596 20597 if (is_sdiv) { 20598 patchlet = chk_and_sdiv; 20599 cnt = ARRAY_SIZE(chk_and_sdiv); 20600 } else if (is_smod) { 20601 patchlet = chk_and_smod; 20602 cnt = ARRAY_SIZE(chk_and_smod) - (is64 ? 2 : 0); 20603 } else { 20604 patchlet = isdiv ? chk_and_div : chk_and_mod; 20605 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 20606 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 20607 } 20608 20609 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 20610 if (!new_prog) 20611 return -ENOMEM; 20612 20613 delta += cnt - 1; 20614 env->prog = prog = new_prog; 20615 insn = new_prog->insnsi + i + delta; 20616 goto next_insn; 20617 } 20618 20619 /* Make it impossible to de-reference a userspace address */ 20620 if (BPF_CLASS(insn->code) == BPF_LDX && 20621 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 20622 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) { 20623 struct bpf_insn *patch = &insn_buf[0]; 20624 u64 uaddress_limit = bpf_arch_uaddress_limit(); 20625 20626 if (!uaddress_limit) 20627 goto next_insn; 20628 20629 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg); 20630 if (insn->off) 20631 *patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off); 20632 *patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32); 20633 *patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2); 20634 *patch++ = *insn; 20635 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 20636 *patch++ = BPF_MOV64_IMM(insn->dst_reg, 0); 20637 20638 cnt = patch - insn_buf; 20639 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20640 if (!new_prog) 20641 return -ENOMEM; 20642 20643 delta += cnt - 1; 20644 env->prog = prog = new_prog; 20645 insn = new_prog->insnsi + i + delta; 20646 goto next_insn; 20647 } 20648 20649 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 20650 if (BPF_CLASS(insn->code) == BPF_LD && 20651 (BPF_MODE(insn->code) == BPF_ABS || 20652 BPF_MODE(insn->code) == BPF_IND)) { 20653 cnt = env->ops->gen_ld_abs(insn, insn_buf); 20654 if (cnt == 0 || cnt >= INSN_BUF_SIZE) { 20655 verbose(env, "bpf verifier is misconfigured\n"); 20656 return -EINVAL; 20657 } 20658 20659 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20660 if (!new_prog) 20661 return -ENOMEM; 20662 20663 delta += cnt - 1; 20664 env->prog = prog = new_prog; 20665 insn = new_prog->insnsi + i + delta; 20666 goto next_insn; 20667 } 20668 20669 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 20670 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 20671 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 20672 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 20673 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 20674 struct bpf_insn *patch = &insn_buf[0]; 20675 bool issrc, isneg, isimm; 20676 u32 off_reg; 20677 20678 aux = &env->insn_aux_data[i + delta]; 20679 if (!aux->alu_state || 20680 aux->alu_state == BPF_ALU_NON_POINTER) 20681 goto next_insn; 20682 20683 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 20684 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 20685 BPF_ALU_SANITIZE_SRC; 20686 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 20687 20688 off_reg = issrc ? insn->src_reg : insn->dst_reg; 20689 if (isimm) { 20690 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 20691 } else { 20692 if (isneg) 20693 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 20694 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 20695 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 20696 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 20697 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 20698 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 20699 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 20700 } 20701 if (!issrc) 20702 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 20703 insn->src_reg = BPF_REG_AX; 20704 if (isneg) 20705 insn->code = insn->code == code_add ? 20706 code_sub : code_add; 20707 *patch++ = *insn; 20708 if (issrc && isneg && !isimm) 20709 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 20710 cnt = patch - insn_buf; 20711 20712 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20713 if (!new_prog) 20714 return -ENOMEM; 20715 20716 delta += cnt - 1; 20717 env->prog = prog = new_prog; 20718 insn = new_prog->insnsi + i + delta; 20719 goto next_insn; 20720 } 20721 20722 if (is_may_goto_insn(insn)) { 20723 int stack_off = -stack_depth - 8; 20724 20725 stack_depth_extra = 8; 20726 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off); 20727 if (insn->off >= 0) 20728 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2); 20729 else 20730 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1); 20731 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1); 20732 insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off); 20733 cnt = 4; 20734 20735 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20736 if (!new_prog) 20737 return -ENOMEM; 20738 20739 delta += cnt - 1; 20740 env->prog = prog = new_prog; 20741 insn = new_prog->insnsi + i + delta; 20742 goto next_insn; 20743 } 20744 20745 if (insn->code != (BPF_JMP | BPF_CALL)) 20746 goto next_insn; 20747 if (insn->src_reg == BPF_PSEUDO_CALL) 20748 goto next_insn; 20749 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 20750 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 20751 if (ret) 20752 return ret; 20753 if (cnt == 0) 20754 goto next_insn; 20755 20756 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20757 if (!new_prog) 20758 return -ENOMEM; 20759 20760 delta += cnt - 1; 20761 env->prog = prog = new_prog; 20762 insn = new_prog->insnsi + i + delta; 20763 goto next_insn; 20764 } 20765 20766 /* Skip inlining the helper call if the JIT does it. */ 20767 if (bpf_jit_inlines_helper_call(insn->imm)) 20768 goto next_insn; 20769 20770 if (insn->imm == BPF_FUNC_get_route_realm) 20771 prog->dst_needed = 1; 20772 if (insn->imm == BPF_FUNC_get_prandom_u32) 20773 bpf_user_rnd_init_once(); 20774 if (insn->imm == BPF_FUNC_override_return) 20775 prog->kprobe_override = 1; 20776 if (insn->imm == BPF_FUNC_tail_call) { 20777 /* If we tail call into other programs, we 20778 * cannot make any assumptions since they can 20779 * be replaced dynamically during runtime in 20780 * the program array. 20781 */ 20782 prog->cb_access = 1; 20783 if (!allow_tail_call_in_subprogs(env)) 20784 prog->aux->stack_depth = MAX_BPF_STACK; 20785 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 20786 20787 /* mark bpf_tail_call as different opcode to avoid 20788 * conditional branch in the interpreter for every normal 20789 * call and to prevent accidental JITing by JIT compiler 20790 * that doesn't support bpf_tail_call yet 20791 */ 20792 insn->imm = 0; 20793 insn->code = BPF_JMP | BPF_TAIL_CALL; 20794 20795 aux = &env->insn_aux_data[i + delta]; 20796 if (env->bpf_capable && !prog->blinding_requested && 20797 prog->jit_requested && 20798 !bpf_map_key_poisoned(aux) && 20799 !bpf_map_ptr_poisoned(aux) && 20800 !bpf_map_ptr_unpriv(aux)) { 20801 struct bpf_jit_poke_descriptor desc = { 20802 .reason = BPF_POKE_REASON_TAIL_CALL, 20803 .tail_call.map = aux->map_ptr_state.map_ptr, 20804 .tail_call.key = bpf_map_key_immediate(aux), 20805 .insn_idx = i + delta, 20806 }; 20807 20808 ret = bpf_jit_add_poke_descriptor(prog, &desc); 20809 if (ret < 0) { 20810 verbose(env, "adding tail call poke descriptor failed\n"); 20811 return ret; 20812 } 20813 20814 insn->imm = ret + 1; 20815 goto next_insn; 20816 } 20817 20818 if (!bpf_map_ptr_unpriv(aux)) 20819 goto next_insn; 20820 20821 /* instead of changing every JIT dealing with tail_call 20822 * emit two extra insns: 20823 * if (index >= max_entries) goto out; 20824 * index &= array->index_mask; 20825 * to avoid out-of-bounds cpu speculation 20826 */ 20827 if (bpf_map_ptr_poisoned(aux)) { 20828 verbose(env, "tail_call abusing map_ptr\n"); 20829 return -EINVAL; 20830 } 20831 20832 map_ptr = aux->map_ptr_state.map_ptr; 20833 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 20834 map_ptr->max_entries, 2); 20835 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 20836 container_of(map_ptr, 20837 struct bpf_array, 20838 map)->index_mask); 20839 insn_buf[2] = *insn; 20840 cnt = 3; 20841 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20842 if (!new_prog) 20843 return -ENOMEM; 20844 20845 delta += cnt - 1; 20846 env->prog = prog = new_prog; 20847 insn = new_prog->insnsi + i + delta; 20848 goto next_insn; 20849 } 20850 20851 if (insn->imm == BPF_FUNC_timer_set_callback) { 20852 /* The verifier will process callback_fn as many times as necessary 20853 * with different maps and the register states prepared by 20854 * set_timer_callback_state will be accurate. 20855 * 20856 * The following use case is valid: 20857 * map1 is shared by prog1, prog2, prog3. 20858 * prog1 calls bpf_timer_init for some map1 elements 20859 * prog2 calls bpf_timer_set_callback for some map1 elements. 20860 * Those that were not bpf_timer_init-ed will return -EINVAL. 20861 * prog3 calls bpf_timer_start for some map1 elements. 20862 * Those that were not both bpf_timer_init-ed and 20863 * bpf_timer_set_callback-ed will return -EINVAL. 20864 */ 20865 struct bpf_insn ld_addrs[2] = { 20866 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 20867 }; 20868 20869 insn_buf[0] = ld_addrs[0]; 20870 insn_buf[1] = ld_addrs[1]; 20871 insn_buf[2] = *insn; 20872 cnt = 3; 20873 20874 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20875 if (!new_prog) 20876 return -ENOMEM; 20877 20878 delta += cnt - 1; 20879 env->prog = prog = new_prog; 20880 insn = new_prog->insnsi + i + delta; 20881 goto patch_call_imm; 20882 } 20883 20884 if (is_storage_get_function(insn->imm)) { 20885 if (!in_sleepable(env) || 20886 env->insn_aux_data[i + delta].storage_get_func_atomic) 20887 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 20888 else 20889 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 20890 insn_buf[1] = *insn; 20891 cnt = 2; 20892 20893 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20894 if (!new_prog) 20895 return -ENOMEM; 20896 20897 delta += cnt - 1; 20898 env->prog = prog = new_prog; 20899 insn = new_prog->insnsi + i + delta; 20900 goto patch_call_imm; 20901 } 20902 20903 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */ 20904 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) { 20905 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data, 20906 * bpf_mem_alloc() returns a ptr to the percpu data ptr. 20907 */ 20908 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0); 20909 insn_buf[1] = *insn; 20910 cnt = 2; 20911 20912 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20913 if (!new_prog) 20914 return -ENOMEM; 20915 20916 delta += cnt - 1; 20917 env->prog = prog = new_prog; 20918 insn = new_prog->insnsi + i + delta; 20919 goto patch_call_imm; 20920 } 20921 20922 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 20923 * and other inlining handlers are currently limited to 64 bit 20924 * only. 20925 */ 20926 if (prog->jit_requested && BITS_PER_LONG == 64 && 20927 (insn->imm == BPF_FUNC_map_lookup_elem || 20928 insn->imm == BPF_FUNC_map_update_elem || 20929 insn->imm == BPF_FUNC_map_delete_elem || 20930 insn->imm == BPF_FUNC_map_push_elem || 20931 insn->imm == BPF_FUNC_map_pop_elem || 20932 insn->imm == BPF_FUNC_map_peek_elem || 20933 insn->imm == BPF_FUNC_redirect_map || 20934 insn->imm == BPF_FUNC_for_each_map_elem || 20935 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 20936 aux = &env->insn_aux_data[i + delta]; 20937 if (bpf_map_ptr_poisoned(aux)) 20938 goto patch_call_imm; 20939 20940 map_ptr = aux->map_ptr_state.map_ptr; 20941 ops = map_ptr->ops; 20942 if (insn->imm == BPF_FUNC_map_lookup_elem && 20943 ops->map_gen_lookup) { 20944 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 20945 if (cnt == -EOPNOTSUPP) 20946 goto patch_map_ops_generic; 20947 if (cnt <= 0 || cnt >= INSN_BUF_SIZE) { 20948 verbose(env, "bpf verifier is misconfigured\n"); 20949 return -EINVAL; 20950 } 20951 20952 new_prog = bpf_patch_insn_data(env, i + delta, 20953 insn_buf, cnt); 20954 if (!new_prog) 20955 return -ENOMEM; 20956 20957 delta += cnt - 1; 20958 env->prog = prog = new_prog; 20959 insn = new_prog->insnsi + i + delta; 20960 goto next_insn; 20961 } 20962 20963 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 20964 (void *(*)(struct bpf_map *map, void *key))NULL)); 20965 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 20966 (long (*)(struct bpf_map *map, void *key))NULL)); 20967 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 20968 (long (*)(struct bpf_map *map, void *key, void *value, 20969 u64 flags))NULL)); 20970 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 20971 (long (*)(struct bpf_map *map, void *value, 20972 u64 flags))NULL)); 20973 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 20974 (long (*)(struct bpf_map *map, void *value))NULL)); 20975 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 20976 (long (*)(struct bpf_map *map, void *value))NULL)); 20977 BUILD_BUG_ON(!__same_type(ops->map_redirect, 20978 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 20979 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 20980 (long (*)(struct bpf_map *map, 20981 bpf_callback_t callback_fn, 20982 void *callback_ctx, 20983 u64 flags))NULL)); 20984 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 20985 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 20986 20987 patch_map_ops_generic: 20988 switch (insn->imm) { 20989 case BPF_FUNC_map_lookup_elem: 20990 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 20991 goto next_insn; 20992 case BPF_FUNC_map_update_elem: 20993 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 20994 goto next_insn; 20995 case BPF_FUNC_map_delete_elem: 20996 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 20997 goto next_insn; 20998 case BPF_FUNC_map_push_elem: 20999 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 21000 goto next_insn; 21001 case BPF_FUNC_map_pop_elem: 21002 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 21003 goto next_insn; 21004 case BPF_FUNC_map_peek_elem: 21005 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 21006 goto next_insn; 21007 case BPF_FUNC_redirect_map: 21008 insn->imm = BPF_CALL_IMM(ops->map_redirect); 21009 goto next_insn; 21010 case BPF_FUNC_for_each_map_elem: 21011 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 21012 goto next_insn; 21013 case BPF_FUNC_map_lookup_percpu_elem: 21014 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 21015 goto next_insn; 21016 } 21017 21018 goto patch_call_imm; 21019 } 21020 21021 /* Implement bpf_jiffies64 inline. */ 21022 if (prog->jit_requested && BITS_PER_LONG == 64 && 21023 insn->imm == BPF_FUNC_jiffies64) { 21024 struct bpf_insn ld_jiffies_addr[2] = { 21025 BPF_LD_IMM64(BPF_REG_0, 21026 (unsigned long)&jiffies), 21027 }; 21028 21029 insn_buf[0] = ld_jiffies_addr[0]; 21030 insn_buf[1] = ld_jiffies_addr[1]; 21031 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 21032 BPF_REG_0, 0); 21033 cnt = 3; 21034 21035 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 21036 cnt); 21037 if (!new_prog) 21038 return -ENOMEM; 21039 21040 delta += cnt - 1; 21041 env->prog = prog = new_prog; 21042 insn = new_prog->insnsi + i + delta; 21043 goto next_insn; 21044 } 21045 21046 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML) 21047 /* Implement bpf_get_smp_processor_id() inline. */ 21048 if (insn->imm == BPF_FUNC_get_smp_processor_id && 21049 verifier_inlines_helper_call(env, insn->imm)) { 21050 /* BPF_FUNC_get_smp_processor_id inlining is an 21051 * optimization, so if pcpu_hot.cpu_number is ever 21052 * changed in some incompatible and hard to support 21053 * way, it's fine to back out this inlining logic 21054 */ 21055 insn_buf[0] = BPF_MOV32_IMM(BPF_REG_0, (u32)(unsigned long)&pcpu_hot.cpu_number); 21056 insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0); 21057 insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0); 21058 cnt = 3; 21059 21060 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21061 if (!new_prog) 21062 return -ENOMEM; 21063 21064 delta += cnt - 1; 21065 env->prog = prog = new_prog; 21066 insn = new_prog->insnsi + i + delta; 21067 goto next_insn; 21068 } 21069 #endif 21070 /* Implement bpf_get_func_arg inline. */ 21071 if (prog_type == BPF_PROG_TYPE_TRACING && 21072 insn->imm == BPF_FUNC_get_func_arg) { 21073 /* Load nr_args from ctx - 8 */ 21074 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 21075 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 21076 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 21077 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 21078 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 21079 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 21080 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 21081 insn_buf[7] = BPF_JMP_A(1); 21082 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 21083 cnt = 9; 21084 21085 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21086 if (!new_prog) 21087 return -ENOMEM; 21088 21089 delta += cnt - 1; 21090 env->prog = prog = new_prog; 21091 insn = new_prog->insnsi + i + delta; 21092 goto next_insn; 21093 } 21094 21095 /* Implement bpf_get_func_ret inline. */ 21096 if (prog_type == BPF_PROG_TYPE_TRACING && 21097 insn->imm == BPF_FUNC_get_func_ret) { 21098 if (eatype == BPF_TRACE_FEXIT || 21099 eatype == BPF_MODIFY_RETURN) { 21100 /* Load nr_args from ctx - 8 */ 21101 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 21102 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 21103 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 21104 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 21105 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 21106 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 21107 cnt = 6; 21108 } else { 21109 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 21110 cnt = 1; 21111 } 21112 21113 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21114 if (!new_prog) 21115 return -ENOMEM; 21116 21117 delta += cnt - 1; 21118 env->prog = prog = new_prog; 21119 insn = new_prog->insnsi + i + delta; 21120 goto next_insn; 21121 } 21122 21123 /* Implement get_func_arg_cnt inline. */ 21124 if (prog_type == BPF_PROG_TYPE_TRACING && 21125 insn->imm == BPF_FUNC_get_func_arg_cnt) { 21126 /* Load nr_args from ctx - 8 */ 21127 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 21128 21129 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 21130 if (!new_prog) 21131 return -ENOMEM; 21132 21133 env->prog = prog = new_prog; 21134 insn = new_prog->insnsi + i + delta; 21135 goto next_insn; 21136 } 21137 21138 /* Implement bpf_get_func_ip inline. */ 21139 if (prog_type == BPF_PROG_TYPE_TRACING && 21140 insn->imm == BPF_FUNC_get_func_ip) { 21141 /* Load IP address from ctx - 16 */ 21142 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 21143 21144 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 21145 if (!new_prog) 21146 return -ENOMEM; 21147 21148 env->prog = prog = new_prog; 21149 insn = new_prog->insnsi + i + delta; 21150 goto next_insn; 21151 } 21152 21153 /* Implement bpf_get_branch_snapshot inline. */ 21154 if (IS_ENABLED(CONFIG_PERF_EVENTS) && 21155 prog->jit_requested && BITS_PER_LONG == 64 && 21156 insn->imm == BPF_FUNC_get_branch_snapshot) { 21157 /* We are dealing with the following func protos: 21158 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags); 21159 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt); 21160 */ 21161 const u32 br_entry_size = sizeof(struct perf_branch_entry); 21162 21163 /* struct perf_branch_entry is part of UAPI and is 21164 * used as an array element, so extremely unlikely to 21165 * ever grow or shrink 21166 */ 21167 BUILD_BUG_ON(br_entry_size != 24); 21168 21169 /* if (unlikely(flags)) return -EINVAL */ 21170 insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7); 21171 21172 /* Transform size (bytes) into number of entries (cnt = size / 24). 21173 * But to avoid expensive division instruction, we implement 21174 * divide-by-3 through multiplication, followed by further 21175 * division by 8 through 3-bit right shift. 21176 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr., 21177 * p. 227, chapter "Unsigned Division by 3" for details and proofs. 21178 * 21179 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab. 21180 */ 21181 insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab); 21182 insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0); 21183 insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36); 21184 21185 /* call perf_snapshot_branch_stack implementation */ 21186 insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack)); 21187 /* if (entry_cnt == 0) return -ENOENT */ 21188 insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4); 21189 /* return entry_cnt * sizeof(struct perf_branch_entry) */ 21190 insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size); 21191 insn_buf[7] = BPF_JMP_A(3); 21192 /* return -EINVAL; */ 21193 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 21194 insn_buf[9] = BPF_JMP_A(1); 21195 /* return -ENOENT; */ 21196 insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT); 21197 cnt = 11; 21198 21199 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21200 if (!new_prog) 21201 return -ENOMEM; 21202 21203 delta += cnt - 1; 21204 env->prog = prog = new_prog; 21205 insn = new_prog->insnsi + i + delta; 21206 goto next_insn; 21207 } 21208 21209 /* Implement bpf_kptr_xchg inline */ 21210 if (prog->jit_requested && BITS_PER_LONG == 64 && 21211 insn->imm == BPF_FUNC_kptr_xchg && 21212 bpf_jit_supports_ptr_xchg()) { 21213 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2); 21214 insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0); 21215 cnt = 2; 21216 21217 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21218 if (!new_prog) 21219 return -ENOMEM; 21220 21221 delta += cnt - 1; 21222 env->prog = prog = new_prog; 21223 insn = new_prog->insnsi + i + delta; 21224 goto next_insn; 21225 } 21226 patch_call_imm: 21227 fn = env->ops->get_func_proto(insn->imm, env->prog); 21228 /* all functions that have prototype and verifier allowed 21229 * programs to call them, must be real in-kernel functions 21230 */ 21231 if (!fn->func) { 21232 verbose(env, 21233 "kernel subsystem misconfigured func %s#%d\n", 21234 func_id_name(insn->imm), insn->imm); 21235 return -EFAULT; 21236 } 21237 insn->imm = fn->func - __bpf_call_base; 21238 next_insn: 21239 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 21240 subprogs[cur_subprog].stack_depth += stack_depth_extra; 21241 subprogs[cur_subprog].stack_extra = stack_depth_extra; 21242 cur_subprog++; 21243 stack_depth = subprogs[cur_subprog].stack_depth; 21244 stack_depth_extra = 0; 21245 } 21246 i++; 21247 insn++; 21248 } 21249 21250 env->prog->aux->stack_depth = subprogs[0].stack_depth; 21251 for (i = 0; i < env->subprog_cnt; i++) { 21252 int subprog_start = subprogs[i].start; 21253 int stack_slots = subprogs[i].stack_extra / 8; 21254 21255 if (!stack_slots) 21256 continue; 21257 if (stack_slots > 1) { 21258 verbose(env, "verifier bug: stack_slots supports may_goto only\n"); 21259 return -EFAULT; 21260 } 21261 21262 /* Add ST insn to subprog prologue to init extra stack */ 21263 insn_buf[0] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, 21264 -subprogs[i].stack_depth, BPF_MAX_LOOPS); 21265 /* Copy first actual insn to preserve it */ 21266 insn_buf[1] = env->prog->insnsi[subprog_start]; 21267 21268 new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, 2); 21269 if (!new_prog) 21270 return -ENOMEM; 21271 env->prog = prog = new_prog; 21272 /* 21273 * If may_goto is a first insn of a prog there could be a jmp 21274 * insn that points to it, hence adjust all such jmps to point 21275 * to insn after BPF_ST that inits may_goto count. 21276 * Adjustment will succeed because bpf_patch_insn_data() didn't fail. 21277 */ 21278 WARN_ON(adjust_jmp_off(env->prog, subprog_start, 1)); 21279 } 21280 21281 /* Since poke tab is now finalized, publish aux to tracker. */ 21282 for (i = 0; i < prog->aux->size_poke_tab; i++) { 21283 map_ptr = prog->aux->poke_tab[i].tail_call.map; 21284 if (!map_ptr->ops->map_poke_track || 21285 !map_ptr->ops->map_poke_untrack || 21286 !map_ptr->ops->map_poke_run) { 21287 verbose(env, "bpf verifier is misconfigured\n"); 21288 return -EINVAL; 21289 } 21290 21291 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 21292 if (ret < 0) { 21293 verbose(env, "tracking tail call prog failed\n"); 21294 return ret; 21295 } 21296 } 21297 21298 sort_kfunc_descs_by_imm_off(env->prog); 21299 21300 return 0; 21301 } 21302 21303 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 21304 int position, 21305 s32 stack_base, 21306 u32 callback_subprogno, 21307 u32 *total_cnt) 21308 { 21309 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 21310 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 21311 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 21312 int reg_loop_max = BPF_REG_6; 21313 int reg_loop_cnt = BPF_REG_7; 21314 int reg_loop_ctx = BPF_REG_8; 21315 21316 struct bpf_insn *insn_buf = env->insn_buf; 21317 struct bpf_prog *new_prog; 21318 u32 callback_start; 21319 u32 call_insn_offset; 21320 s32 callback_offset; 21321 u32 cnt = 0; 21322 21323 /* This represents an inlined version of bpf_iter.c:bpf_loop, 21324 * be careful to modify this code in sync. 21325 */ 21326 21327 /* Return error and jump to the end of the patch if 21328 * expected number of iterations is too big. 21329 */ 21330 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2); 21331 insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG); 21332 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16); 21333 /* spill R6, R7, R8 to use these as loop vars */ 21334 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset); 21335 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset); 21336 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset); 21337 /* initialize loop vars */ 21338 insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1); 21339 insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0); 21340 insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3); 21341 /* loop header, 21342 * if reg_loop_cnt >= reg_loop_max skip the loop body 21343 */ 21344 insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5); 21345 /* callback call, 21346 * correct callback offset would be set after patching 21347 */ 21348 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt); 21349 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx); 21350 insn_buf[cnt++] = BPF_CALL_REL(0); 21351 /* increment loop counter */ 21352 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1); 21353 /* jump to loop header if callback returned 0 */ 21354 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6); 21355 /* return value of bpf_loop, 21356 * set R0 to the number of iterations 21357 */ 21358 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt); 21359 /* restore original values of R6, R7, R8 */ 21360 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset); 21361 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset); 21362 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset); 21363 21364 *total_cnt = cnt; 21365 new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt); 21366 if (!new_prog) 21367 return new_prog; 21368 21369 /* callback start is known only after patching */ 21370 callback_start = env->subprog_info[callback_subprogno].start; 21371 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 21372 call_insn_offset = position + 12; 21373 callback_offset = callback_start - call_insn_offset - 1; 21374 new_prog->insnsi[call_insn_offset].imm = callback_offset; 21375 21376 return new_prog; 21377 } 21378 21379 static bool is_bpf_loop_call(struct bpf_insn *insn) 21380 { 21381 return insn->code == (BPF_JMP | BPF_CALL) && 21382 insn->src_reg == 0 && 21383 insn->imm == BPF_FUNC_loop; 21384 } 21385 21386 /* For all sub-programs in the program (including main) check 21387 * insn_aux_data to see if there are bpf_loop calls that require 21388 * inlining. If such calls are found the calls are replaced with a 21389 * sequence of instructions produced by `inline_bpf_loop` function and 21390 * subprog stack_depth is increased by the size of 3 registers. 21391 * This stack space is used to spill values of the R6, R7, R8. These 21392 * registers are used to store the loop bound, counter and context 21393 * variables. 21394 */ 21395 static int optimize_bpf_loop(struct bpf_verifier_env *env) 21396 { 21397 struct bpf_subprog_info *subprogs = env->subprog_info; 21398 int i, cur_subprog = 0, cnt, delta = 0; 21399 struct bpf_insn *insn = env->prog->insnsi; 21400 int insn_cnt = env->prog->len; 21401 u16 stack_depth = subprogs[cur_subprog].stack_depth; 21402 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 21403 u16 stack_depth_extra = 0; 21404 21405 for (i = 0; i < insn_cnt; i++, insn++) { 21406 struct bpf_loop_inline_state *inline_state = 21407 &env->insn_aux_data[i + delta].loop_inline_state; 21408 21409 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 21410 struct bpf_prog *new_prog; 21411 21412 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 21413 new_prog = inline_bpf_loop(env, 21414 i + delta, 21415 -(stack_depth + stack_depth_extra), 21416 inline_state->callback_subprogno, 21417 &cnt); 21418 if (!new_prog) 21419 return -ENOMEM; 21420 21421 delta += cnt - 1; 21422 env->prog = new_prog; 21423 insn = new_prog->insnsi + i + delta; 21424 } 21425 21426 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 21427 subprogs[cur_subprog].stack_depth += stack_depth_extra; 21428 cur_subprog++; 21429 stack_depth = subprogs[cur_subprog].stack_depth; 21430 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 21431 stack_depth_extra = 0; 21432 } 21433 } 21434 21435 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 21436 21437 return 0; 21438 } 21439 21440 /* Remove unnecessary spill/fill pairs, members of fastcall pattern, 21441 * adjust subprograms stack depth when possible. 21442 */ 21443 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env) 21444 { 21445 struct bpf_subprog_info *subprog = env->subprog_info; 21446 struct bpf_insn_aux_data *aux = env->insn_aux_data; 21447 struct bpf_insn *insn = env->prog->insnsi; 21448 int insn_cnt = env->prog->len; 21449 u32 spills_num; 21450 bool modified = false; 21451 int i, j; 21452 21453 for (i = 0; i < insn_cnt; i++, insn++) { 21454 if (aux[i].fastcall_spills_num > 0) { 21455 spills_num = aux[i].fastcall_spills_num; 21456 /* NOPs would be removed by opt_remove_nops() */ 21457 for (j = 1; j <= spills_num; ++j) { 21458 *(insn - j) = NOP; 21459 *(insn + j) = NOP; 21460 } 21461 modified = true; 21462 } 21463 if ((subprog + 1)->start == i + 1) { 21464 if (modified && !subprog->keep_fastcall_stack) 21465 subprog->stack_depth = -subprog->fastcall_stack_off; 21466 subprog++; 21467 modified = false; 21468 } 21469 } 21470 21471 return 0; 21472 } 21473 21474 static void free_states(struct bpf_verifier_env *env) 21475 { 21476 struct bpf_verifier_state_list *sl, *sln; 21477 int i; 21478 21479 sl = env->free_list; 21480 while (sl) { 21481 sln = sl->next; 21482 free_verifier_state(&sl->state, false); 21483 kfree(sl); 21484 sl = sln; 21485 } 21486 env->free_list = NULL; 21487 21488 if (!env->explored_states) 21489 return; 21490 21491 for (i = 0; i < state_htab_size(env); i++) { 21492 sl = env->explored_states[i]; 21493 21494 while (sl) { 21495 sln = sl->next; 21496 free_verifier_state(&sl->state, false); 21497 kfree(sl); 21498 sl = sln; 21499 } 21500 env->explored_states[i] = NULL; 21501 } 21502 } 21503 21504 static int do_check_common(struct bpf_verifier_env *env, int subprog) 21505 { 21506 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 21507 struct bpf_subprog_info *sub = subprog_info(env, subprog); 21508 struct bpf_verifier_state *state; 21509 struct bpf_reg_state *regs; 21510 int ret, i; 21511 21512 env->prev_linfo = NULL; 21513 env->pass_cnt++; 21514 21515 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 21516 if (!state) 21517 return -ENOMEM; 21518 state->curframe = 0; 21519 state->speculative = false; 21520 state->branches = 1; 21521 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 21522 if (!state->frame[0]) { 21523 kfree(state); 21524 return -ENOMEM; 21525 } 21526 env->cur_state = state; 21527 init_func_state(env, state->frame[0], 21528 BPF_MAIN_FUNC /* callsite */, 21529 0 /* frameno */, 21530 subprog); 21531 state->first_insn_idx = env->subprog_info[subprog].start; 21532 state->last_insn_idx = -1; 21533 21534 regs = state->frame[state->curframe]->regs; 21535 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 21536 const char *sub_name = subprog_name(env, subprog); 21537 struct bpf_subprog_arg_info *arg; 21538 struct bpf_reg_state *reg; 21539 21540 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 21541 ret = btf_prepare_func_args(env, subprog); 21542 if (ret) 21543 goto out; 21544 21545 if (subprog_is_exc_cb(env, subprog)) { 21546 state->frame[0]->in_exception_callback_fn = true; 21547 /* We have already ensured that the callback returns an integer, just 21548 * like all global subprogs. We need to determine it only has a single 21549 * scalar argument. 21550 */ 21551 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 21552 verbose(env, "exception cb only supports single integer argument\n"); 21553 ret = -EINVAL; 21554 goto out; 21555 } 21556 } 21557 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) { 21558 arg = &sub->args[i - BPF_REG_1]; 21559 reg = ®s[i]; 21560 21561 if (arg->arg_type == ARG_PTR_TO_CTX) { 21562 reg->type = PTR_TO_CTX; 21563 mark_reg_known_zero(env, regs, i); 21564 } else if (arg->arg_type == ARG_ANYTHING) { 21565 reg->type = SCALAR_VALUE; 21566 mark_reg_unknown(env, regs, i); 21567 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 21568 /* assume unspecial LOCAL dynptr type */ 21569 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen); 21570 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 21571 reg->type = PTR_TO_MEM; 21572 if (arg->arg_type & PTR_MAYBE_NULL) 21573 reg->type |= PTR_MAYBE_NULL; 21574 mark_reg_known_zero(env, regs, i); 21575 reg->mem_size = arg->mem_size; 21576 reg->id = ++env->id_gen; 21577 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 21578 reg->type = PTR_TO_BTF_ID; 21579 if (arg->arg_type & PTR_MAYBE_NULL) 21580 reg->type |= PTR_MAYBE_NULL; 21581 if (arg->arg_type & PTR_UNTRUSTED) 21582 reg->type |= PTR_UNTRUSTED; 21583 if (arg->arg_type & PTR_TRUSTED) 21584 reg->type |= PTR_TRUSTED; 21585 mark_reg_known_zero(env, regs, i); 21586 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */ 21587 reg->btf_id = arg->btf_id; 21588 reg->id = ++env->id_gen; 21589 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 21590 /* caller can pass either PTR_TO_ARENA or SCALAR */ 21591 mark_reg_unknown(env, regs, i); 21592 } else { 21593 WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n", 21594 i - BPF_REG_1, arg->arg_type); 21595 ret = -EFAULT; 21596 goto out; 21597 } 21598 } 21599 } else { 21600 /* if main BPF program has associated BTF info, validate that 21601 * it's matching expected signature, and otherwise mark BTF 21602 * info for main program as unreliable 21603 */ 21604 if (env->prog->aux->func_info_aux) { 21605 ret = btf_prepare_func_args(env, 0); 21606 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) 21607 env->prog->aux->func_info_aux[0].unreliable = true; 21608 } 21609 21610 /* 1st arg to a function */ 21611 regs[BPF_REG_1].type = PTR_TO_CTX; 21612 mark_reg_known_zero(env, regs, BPF_REG_1); 21613 } 21614 21615 ret = do_check(env); 21616 out: 21617 /* check for NULL is necessary, since cur_state can be freed inside 21618 * do_check() under memory pressure. 21619 */ 21620 if (env->cur_state) { 21621 free_verifier_state(env->cur_state, true); 21622 env->cur_state = NULL; 21623 } 21624 while (!pop_stack(env, NULL, NULL, false)); 21625 if (!ret && pop_log) 21626 bpf_vlog_reset(&env->log, 0); 21627 free_states(env); 21628 return ret; 21629 } 21630 21631 /* Lazily verify all global functions based on their BTF, if they are called 21632 * from main BPF program or any of subprograms transitively. 21633 * BPF global subprogs called from dead code are not validated. 21634 * All callable global functions must pass verification. 21635 * Otherwise the whole program is rejected. 21636 * Consider: 21637 * int bar(int); 21638 * int foo(int f) 21639 * { 21640 * return bar(f); 21641 * } 21642 * int bar(int b) 21643 * { 21644 * ... 21645 * } 21646 * foo() will be verified first for R1=any_scalar_value. During verification it 21647 * will be assumed that bar() already verified successfully and call to bar() 21648 * from foo() will be checked for type match only. Later bar() will be verified 21649 * independently to check that it's safe for R1=any_scalar_value. 21650 */ 21651 static int do_check_subprogs(struct bpf_verifier_env *env) 21652 { 21653 struct bpf_prog_aux *aux = env->prog->aux; 21654 struct bpf_func_info_aux *sub_aux; 21655 int i, ret, new_cnt; 21656 21657 if (!aux->func_info) 21658 return 0; 21659 21660 /* exception callback is presumed to be always called */ 21661 if (env->exception_callback_subprog) 21662 subprog_aux(env, env->exception_callback_subprog)->called = true; 21663 21664 again: 21665 new_cnt = 0; 21666 for (i = 1; i < env->subprog_cnt; i++) { 21667 if (!subprog_is_global(env, i)) 21668 continue; 21669 21670 sub_aux = subprog_aux(env, i); 21671 if (!sub_aux->called || sub_aux->verified) 21672 continue; 21673 21674 env->insn_idx = env->subprog_info[i].start; 21675 WARN_ON_ONCE(env->insn_idx == 0); 21676 ret = do_check_common(env, i); 21677 if (ret) { 21678 return ret; 21679 } else if (env->log.level & BPF_LOG_LEVEL) { 21680 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 21681 i, subprog_name(env, i)); 21682 } 21683 21684 /* We verified new global subprog, it might have called some 21685 * more global subprogs that we haven't verified yet, so we 21686 * need to do another pass over subprogs to verify those. 21687 */ 21688 sub_aux->verified = true; 21689 new_cnt++; 21690 } 21691 21692 /* We can't loop forever as we verify at least one global subprog on 21693 * each pass. 21694 */ 21695 if (new_cnt) 21696 goto again; 21697 21698 return 0; 21699 } 21700 21701 static int do_check_main(struct bpf_verifier_env *env) 21702 { 21703 int ret; 21704 21705 env->insn_idx = 0; 21706 ret = do_check_common(env, 0); 21707 if (!ret) 21708 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 21709 return ret; 21710 } 21711 21712 21713 static void print_verification_stats(struct bpf_verifier_env *env) 21714 { 21715 int i; 21716 21717 if (env->log.level & BPF_LOG_STATS) { 21718 verbose(env, "verification time %lld usec\n", 21719 div_u64(env->verification_time, 1000)); 21720 verbose(env, "stack depth "); 21721 for (i = 0; i < env->subprog_cnt; i++) { 21722 u32 depth = env->subprog_info[i].stack_depth; 21723 21724 verbose(env, "%d", depth); 21725 if (i + 1 < env->subprog_cnt) 21726 verbose(env, "+"); 21727 } 21728 verbose(env, "\n"); 21729 } 21730 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 21731 "total_states %d peak_states %d mark_read %d\n", 21732 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 21733 env->max_states_per_insn, env->total_states, 21734 env->peak_states, env->longest_mark_read_walk); 21735 } 21736 21737 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 21738 { 21739 const struct btf_type *t, *func_proto; 21740 const struct bpf_struct_ops_desc *st_ops_desc; 21741 const struct bpf_struct_ops *st_ops; 21742 const struct btf_member *member; 21743 struct bpf_prog *prog = env->prog; 21744 u32 btf_id, member_idx; 21745 struct btf *btf; 21746 const char *mname; 21747 int err; 21748 21749 if (!prog->gpl_compatible) { 21750 verbose(env, "struct ops programs must have a GPL compatible license\n"); 21751 return -EINVAL; 21752 } 21753 21754 if (!prog->aux->attach_btf_id) 21755 return -ENOTSUPP; 21756 21757 btf = prog->aux->attach_btf; 21758 if (btf_is_module(btf)) { 21759 /* Make sure st_ops is valid through the lifetime of env */ 21760 env->attach_btf_mod = btf_try_get_module(btf); 21761 if (!env->attach_btf_mod) { 21762 verbose(env, "struct_ops module %s is not found\n", 21763 btf_get_name(btf)); 21764 return -ENOTSUPP; 21765 } 21766 } 21767 21768 btf_id = prog->aux->attach_btf_id; 21769 st_ops_desc = bpf_struct_ops_find(btf, btf_id); 21770 if (!st_ops_desc) { 21771 verbose(env, "attach_btf_id %u is not a supported struct\n", 21772 btf_id); 21773 return -ENOTSUPP; 21774 } 21775 st_ops = st_ops_desc->st_ops; 21776 21777 t = st_ops_desc->type; 21778 member_idx = prog->expected_attach_type; 21779 if (member_idx >= btf_type_vlen(t)) { 21780 verbose(env, "attach to invalid member idx %u of struct %s\n", 21781 member_idx, st_ops->name); 21782 return -EINVAL; 21783 } 21784 21785 member = &btf_type_member(t)[member_idx]; 21786 mname = btf_name_by_offset(btf, member->name_off); 21787 func_proto = btf_type_resolve_func_ptr(btf, member->type, 21788 NULL); 21789 if (!func_proto) { 21790 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 21791 mname, member_idx, st_ops->name); 21792 return -EINVAL; 21793 } 21794 21795 err = bpf_struct_ops_supported(st_ops, __btf_member_bit_offset(t, member) / 8); 21796 if (err) { 21797 verbose(env, "attach to unsupported member %s of struct %s\n", 21798 mname, st_ops->name); 21799 return err; 21800 } 21801 21802 if (st_ops->check_member) { 21803 err = st_ops->check_member(t, member, prog); 21804 21805 if (err) { 21806 verbose(env, "attach to unsupported member %s of struct %s\n", 21807 mname, st_ops->name); 21808 return err; 21809 } 21810 } 21811 21812 /* btf_ctx_access() used this to provide argument type info */ 21813 prog->aux->ctx_arg_info = 21814 st_ops_desc->arg_info[member_idx].info; 21815 prog->aux->ctx_arg_info_size = 21816 st_ops_desc->arg_info[member_idx].cnt; 21817 21818 prog->aux->attach_func_proto = func_proto; 21819 prog->aux->attach_func_name = mname; 21820 env->ops = st_ops->verifier_ops; 21821 21822 return 0; 21823 } 21824 #define SECURITY_PREFIX "security_" 21825 21826 static int check_attach_modify_return(unsigned long addr, const char *func_name) 21827 { 21828 if (within_error_injection_list(addr) || 21829 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 21830 return 0; 21831 21832 return -EINVAL; 21833 } 21834 21835 /* list of non-sleepable functions that are otherwise on 21836 * ALLOW_ERROR_INJECTION list 21837 */ 21838 BTF_SET_START(btf_non_sleepable_error_inject) 21839 /* Three functions below can be called from sleepable and non-sleepable context. 21840 * Assume non-sleepable from bpf safety point of view. 21841 */ 21842 BTF_ID(func, __filemap_add_folio) 21843 #ifdef CONFIG_FAIL_PAGE_ALLOC 21844 BTF_ID(func, should_fail_alloc_page) 21845 #endif 21846 #ifdef CONFIG_FAILSLAB 21847 BTF_ID(func, should_failslab) 21848 #endif 21849 BTF_SET_END(btf_non_sleepable_error_inject) 21850 21851 static int check_non_sleepable_error_inject(u32 btf_id) 21852 { 21853 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 21854 } 21855 21856 int bpf_check_attach_target(struct bpf_verifier_log *log, 21857 const struct bpf_prog *prog, 21858 const struct bpf_prog *tgt_prog, 21859 u32 btf_id, 21860 struct bpf_attach_target_info *tgt_info) 21861 { 21862 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 21863 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 21864 char trace_symbol[KSYM_SYMBOL_LEN]; 21865 const char prefix[] = "btf_trace_"; 21866 struct bpf_raw_event_map *btp; 21867 int ret = 0, subprog = -1, i; 21868 const struct btf_type *t; 21869 bool conservative = true; 21870 const char *tname, *fname; 21871 struct btf *btf; 21872 long addr = 0; 21873 struct module *mod = NULL; 21874 21875 if (!btf_id) { 21876 bpf_log(log, "Tracing programs must provide btf_id\n"); 21877 return -EINVAL; 21878 } 21879 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 21880 if (!btf) { 21881 bpf_log(log, 21882 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 21883 return -EINVAL; 21884 } 21885 t = btf_type_by_id(btf, btf_id); 21886 if (!t) { 21887 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 21888 return -EINVAL; 21889 } 21890 tname = btf_name_by_offset(btf, t->name_off); 21891 if (!tname) { 21892 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 21893 return -EINVAL; 21894 } 21895 if (tgt_prog) { 21896 struct bpf_prog_aux *aux = tgt_prog->aux; 21897 21898 if (bpf_prog_is_dev_bound(prog->aux) && 21899 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 21900 bpf_log(log, "Target program bound device mismatch"); 21901 return -EINVAL; 21902 } 21903 21904 for (i = 0; i < aux->func_info_cnt; i++) 21905 if (aux->func_info[i].type_id == btf_id) { 21906 subprog = i; 21907 break; 21908 } 21909 if (subprog == -1) { 21910 bpf_log(log, "Subprog %s doesn't exist\n", tname); 21911 return -EINVAL; 21912 } 21913 if (aux->func && aux->func[subprog]->aux->exception_cb) { 21914 bpf_log(log, 21915 "%s programs cannot attach to exception callback\n", 21916 prog_extension ? "Extension" : "FENTRY/FEXIT"); 21917 return -EINVAL; 21918 } 21919 conservative = aux->func_info_aux[subprog].unreliable; 21920 if (prog_extension) { 21921 if (conservative) { 21922 bpf_log(log, 21923 "Cannot replace static functions\n"); 21924 return -EINVAL; 21925 } 21926 if (!prog->jit_requested) { 21927 bpf_log(log, 21928 "Extension programs should be JITed\n"); 21929 return -EINVAL; 21930 } 21931 } 21932 if (!tgt_prog->jited) { 21933 bpf_log(log, "Can attach to only JITed progs\n"); 21934 return -EINVAL; 21935 } 21936 if (prog_tracing) { 21937 if (aux->attach_tracing_prog) { 21938 /* 21939 * Target program is an fentry/fexit which is already attached 21940 * to another tracing program. More levels of nesting 21941 * attachment are not allowed. 21942 */ 21943 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 21944 return -EINVAL; 21945 } 21946 } else if (tgt_prog->type == prog->type) { 21947 /* 21948 * To avoid potential call chain cycles, prevent attaching of a 21949 * program extension to another extension. It's ok to attach 21950 * fentry/fexit to extension program. 21951 */ 21952 bpf_log(log, "Cannot recursively attach\n"); 21953 return -EINVAL; 21954 } 21955 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 21956 prog_extension && 21957 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 21958 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 21959 /* Program extensions can extend all program types 21960 * except fentry/fexit. The reason is the following. 21961 * The fentry/fexit programs are used for performance 21962 * analysis, stats and can be attached to any program 21963 * type. When extension program is replacing XDP function 21964 * it is necessary to allow performance analysis of all 21965 * functions. Both original XDP program and its program 21966 * extension. Hence attaching fentry/fexit to 21967 * BPF_PROG_TYPE_EXT is allowed. If extending of 21968 * fentry/fexit was allowed it would be possible to create 21969 * long call chain fentry->extension->fentry->extension 21970 * beyond reasonable stack size. Hence extending fentry 21971 * is not allowed. 21972 */ 21973 bpf_log(log, "Cannot extend fentry/fexit\n"); 21974 return -EINVAL; 21975 } 21976 } else { 21977 if (prog_extension) { 21978 bpf_log(log, "Cannot replace kernel functions\n"); 21979 return -EINVAL; 21980 } 21981 } 21982 21983 switch (prog->expected_attach_type) { 21984 case BPF_TRACE_RAW_TP: 21985 if (tgt_prog) { 21986 bpf_log(log, 21987 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 21988 return -EINVAL; 21989 } 21990 if (!btf_type_is_typedef(t)) { 21991 bpf_log(log, "attach_btf_id %u is not a typedef\n", 21992 btf_id); 21993 return -EINVAL; 21994 } 21995 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 21996 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 21997 btf_id, tname); 21998 return -EINVAL; 21999 } 22000 tname += sizeof(prefix) - 1; 22001 22002 /* The func_proto of "btf_trace_##tname" is generated from typedef without argument 22003 * names. Thus using bpf_raw_event_map to get argument names. 22004 */ 22005 btp = bpf_get_raw_tracepoint(tname); 22006 if (!btp) 22007 return -EINVAL; 22008 fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL, 22009 trace_symbol); 22010 bpf_put_raw_tracepoint(btp); 22011 22012 if (fname) 22013 ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC); 22014 22015 if (!fname || ret < 0) { 22016 bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n", 22017 prefix, tname); 22018 t = btf_type_by_id(btf, t->type); 22019 if (!btf_type_is_ptr(t)) 22020 /* should never happen in valid vmlinux build */ 22021 return -EINVAL; 22022 } else { 22023 t = btf_type_by_id(btf, ret); 22024 if (!btf_type_is_func(t)) 22025 /* should never happen in valid vmlinux build */ 22026 return -EINVAL; 22027 } 22028 22029 t = btf_type_by_id(btf, t->type); 22030 if (!btf_type_is_func_proto(t)) 22031 /* should never happen in valid vmlinux build */ 22032 return -EINVAL; 22033 22034 break; 22035 case BPF_TRACE_ITER: 22036 if (!btf_type_is_func(t)) { 22037 bpf_log(log, "attach_btf_id %u is not a function\n", 22038 btf_id); 22039 return -EINVAL; 22040 } 22041 t = btf_type_by_id(btf, t->type); 22042 if (!btf_type_is_func_proto(t)) 22043 return -EINVAL; 22044 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 22045 if (ret) 22046 return ret; 22047 break; 22048 default: 22049 if (!prog_extension) 22050 return -EINVAL; 22051 fallthrough; 22052 case BPF_MODIFY_RETURN: 22053 case BPF_LSM_MAC: 22054 case BPF_LSM_CGROUP: 22055 case BPF_TRACE_FENTRY: 22056 case BPF_TRACE_FEXIT: 22057 if (!btf_type_is_func(t)) { 22058 bpf_log(log, "attach_btf_id %u is not a function\n", 22059 btf_id); 22060 return -EINVAL; 22061 } 22062 if (prog_extension && 22063 btf_check_type_match(log, prog, btf, t)) 22064 return -EINVAL; 22065 t = btf_type_by_id(btf, t->type); 22066 if (!btf_type_is_func_proto(t)) 22067 return -EINVAL; 22068 22069 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 22070 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 22071 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 22072 return -EINVAL; 22073 22074 if (tgt_prog && conservative) 22075 t = NULL; 22076 22077 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 22078 if (ret < 0) 22079 return ret; 22080 22081 if (tgt_prog) { 22082 if (subprog == 0) 22083 addr = (long) tgt_prog->bpf_func; 22084 else 22085 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 22086 } else { 22087 if (btf_is_module(btf)) { 22088 mod = btf_try_get_module(btf); 22089 if (mod) 22090 addr = find_kallsyms_symbol_value(mod, tname); 22091 else 22092 addr = 0; 22093 } else { 22094 addr = kallsyms_lookup_name(tname); 22095 } 22096 if (!addr) { 22097 module_put(mod); 22098 bpf_log(log, 22099 "The address of function %s cannot be found\n", 22100 tname); 22101 return -ENOENT; 22102 } 22103 } 22104 22105 if (prog->sleepable) { 22106 ret = -EINVAL; 22107 switch (prog->type) { 22108 case BPF_PROG_TYPE_TRACING: 22109 22110 /* fentry/fexit/fmod_ret progs can be sleepable if they are 22111 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 22112 */ 22113 if (!check_non_sleepable_error_inject(btf_id) && 22114 within_error_injection_list(addr)) 22115 ret = 0; 22116 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 22117 * in the fmodret id set with the KF_SLEEPABLE flag. 22118 */ 22119 else { 22120 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 22121 prog); 22122 22123 if (flags && (*flags & KF_SLEEPABLE)) 22124 ret = 0; 22125 } 22126 break; 22127 case BPF_PROG_TYPE_LSM: 22128 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 22129 * Only some of them are sleepable. 22130 */ 22131 if (bpf_lsm_is_sleepable_hook(btf_id)) 22132 ret = 0; 22133 break; 22134 default: 22135 break; 22136 } 22137 if (ret) { 22138 module_put(mod); 22139 bpf_log(log, "%s is not sleepable\n", tname); 22140 return ret; 22141 } 22142 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 22143 if (tgt_prog) { 22144 module_put(mod); 22145 bpf_log(log, "can't modify return codes of BPF programs\n"); 22146 return -EINVAL; 22147 } 22148 ret = -EINVAL; 22149 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 22150 !check_attach_modify_return(addr, tname)) 22151 ret = 0; 22152 if (ret) { 22153 module_put(mod); 22154 bpf_log(log, "%s() is not modifiable\n", tname); 22155 return ret; 22156 } 22157 } 22158 22159 break; 22160 } 22161 tgt_info->tgt_addr = addr; 22162 tgt_info->tgt_name = tname; 22163 tgt_info->tgt_type = t; 22164 tgt_info->tgt_mod = mod; 22165 return 0; 22166 } 22167 22168 BTF_SET_START(btf_id_deny) 22169 BTF_ID_UNUSED 22170 #ifdef CONFIG_SMP 22171 BTF_ID(func, migrate_disable) 22172 BTF_ID(func, migrate_enable) 22173 #endif 22174 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 22175 BTF_ID(func, rcu_read_unlock_strict) 22176 #endif 22177 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 22178 BTF_ID(func, preempt_count_add) 22179 BTF_ID(func, preempt_count_sub) 22180 #endif 22181 #ifdef CONFIG_PREEMPT_RCU 22182 BTF_ID(func, __rcu_read_lock) 22183 BTF_ID(func, __rcu_read_unlock) 22184 #endif 22185 BTF_SET_END(btf_id_deny) 22186 22187 static bool can_be_sleepable(struct bpf_prog *prog) 22188 { 22189 if (prog->type == BPF_PROG_TYPE_TRACING) { 22190 switch (prog->expected_attach_type) { 22191 case BPF_TRACE_FENTRY: 22192 case BPF_TRACE_FEXIT: 22193 case BPF_MODIFY_RETURN: 22194 case BPF_TRACE_ITER: 22195 return true; 22196 default: 22197 return false; 22198 } 22199 } 22200 return prog->type == BPF_PROG_TYPE_LSM || 22201 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 22202 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 22203 } 22204 22205 static int check_attach_btf_id(struct bpf_verifier_env *env) 22206 { 22207 struct bpf_prog *prog = env->prog; 22208 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 22209 struct bpf_attach_target_info tgt_info = {}; 22210 u32 btf_id = prog->aux->attach_btf_id; 22211 struct bpf_trampoline *tr; 22212 int ret; 22213 u64 key; 22214 22215 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 22216 if (prog->sleepable) 22217 /* attach_btf_id checked to be zero already */ 22218 return 0; 22219 verbose(env, "Syscall programs can only be sleepable\n"); 22220 return -EINVAL; 22221 } 22222 22223 if (prog->sleepable && !can_be_sleepable(prog)) { 22224 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 22225 return -EINVAL; 22226 } 22227 22228 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 22229 return check_struct_ops_btf_id(env); 22230 22231 if (prog->type != BPF_PROG_TYPE_TRACING && 22232 prog->type != BPF_PROG_TYPE_LSM && 22233 prog->type != BPF_PROG_TYPE_EXT) 22234 return 0; 22235 22236 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 22237 if (ret) 22238 return ret; 22239 22240 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 22241 /* to make freplace equivalent to their targets, they need to 22242 * inherit env->ops and expected_attach_type for the rest of the 22243 * verification 22244 */ 22245 env->ops = bpf_verifier_ops[tgt_prog->type]; 22246 prog->expected_attach_type = tgt_prog->expected_attach_type; 22247 } 22248 22249 /* store info about the attachment target that will be used later */ 22250 prog->aux->attach_func_proto = tgt_info.tgt_type; 22251 prog->aux->attach_func_name = tgt_info.tgt_name; 22252 prog->aux->mod = tgt_info.tgt_mod; 22253 22254 if (tgt_prog) { 22255 prog->aux->saved_dst_prog_type = tgt_prog->type; 22256 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 22257 } 22258 22259 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 22260 prog->aux->attach_btf_trace = true; 22261 return 0; 22262 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 22263 if (!bpf_iter_prog_supported(prog)) 22264 return -EINVAL; 22265 return 0; 22266 } 22267 22268 if (prog->type == BPF_PROG_TYPE_LSM) { 22269 ret = bpf_lsm_verify_prog(&env->log, prog); 22270 if (ret < 0) 22271 return ret; 22272 } else if (prog->type == BPF_PROG_TYPE_TRACING && 22273 btf_id_set_contains(&btf_id_deny, btf_id)) { 22274 return -EINVAL; 22275 } 22276 22277 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 22278 tr = bpf_trampoline_get(key, &tgt_info); 22279 if (!tr) 22280 return -ENOMEM; 22281 22282 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 22283 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 22284 22285 prog->aux->dst_trampoline = tr; 22286 return 0; 22287 } 22288 22289 struct btf *bpf_get_btf_vmlinux(void) 22290 { 22291 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 22292 mutex_lock(&bpf_verifier_lock); 22293 if (!btf_vmlinux) 22294 btf_vmlinux = btf_parse_vmlinux(); 22295 mutex_unlock(&bpf_verifier_lock); 22296 } 22297 return btf_vmlinux; 22298 } 22299 22300 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 22301 { 22302 u64 start_time = ktime_get_ns(); 22303 struct bpf_verifier_env *env; 22304 int i, len, ret = -EINVAL, err; 22305 u32 log_true_size; 22306 bool is_priv; 22307 22308 /* no program is valid */ 22309 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 22310 return -EINVAL; 22311 22312 /* 'struct bpf_verifier_env' can be global, but since it's not small, 22313 * allocate/free it every time bpf_check() is called 22314 */ 22315 env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 22316 if (!env) 22317 return -ENOMEM; 22318 22319 env->bt.env = env; 22320 22321 len = (*prog)->len; 22322 env->insn_aux_data = 22323 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 22324 ret = -ENOMEM; 22325 if (!env->insn_aux_data) 22326 goto err_free_env; 22327 for (i = 0; i < len; i++) 22328 env->insn_aux_data[i].orig_idx = i; 22329 env->prog = *prog; 22330 env->ops = bpf_verifier_ops[env->prog->type]; 22331 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 22332 22333 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 22334 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 22335 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 22336 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 22337 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 22338 22339 bpf_get_btf_vmlinux(); 22340 22341 /* grab the mutex to protect few globals used by verifier */ 22342 if (!is_priv) 22343 mutex_lock(&bpf_verifier_lock); 22344 22345 /* user could have requested verbose verifier output 22346 * and supplied buffer to store the verification trace 22347 */ 22348 ret = bpf_vlog_init(&env->log, attr->log_level, 22349 (char __user *) (unsigned long) attr->log_buf, 22350 attr->log_size); 22351 if (ret) 22352 goto err_unlock; 22353 22354 mark_verifier_state_clean(env); 22355 22356 if (IS_ERR(btf_vmlinux)) { 22357 /* Either gcc or pahole or kernel are broken. */ 22358 verbose(env, "in-kernel BTF is malformed\n"); 22359 ret = PTR_ERR(btf_vmlinux); 22360 goto skip_full_check; 22361 } 22362 22363 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 22364 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 22365 env->strict_alignment = true; 22366 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 22367 env->strict_alignment = false; 22368 22369 if (is_priv) 22370 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 22371 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 22372 22373 env->explored_states = kvcalloc(state_htab_size(env), 22374 sizeof(struct bpf_verifier_state_list *), 22375 GFP_USER); 22376 ret = -ENOMEM; 22377 if (!env->explored_states) 22378 goto skip_full_check; 22379 22380 ret = check_btf_info_early(env, attr, uattr); 22381 if (ret < 0) 22382 goto skip_full_check; 22383 22384 ret = add_subprog_and_kfunc(env); 22385 if (ret < 0) 22386 goto skip_full_check; 22387 22388 ret = check_subprogs(env); 22389 if (ret < 0) 22390 goto skip_full_check; 22391 22392 ret = check_btf_info(env, attr, uattr); 22393 if (ret < 0) 22394 goto skip_full_check; 22395 22396 ret = check_attach_btf_id(env); 22397 if (ret) 22398 goto skip_full_check; 22399 22400 ret = resolve_pseudo_ldimm64(env); 22401 if (ret < 0) 22402 goto skip_full_check; 22403 22404 if (bpf_prog_is_offloaded(env->prog->aux)) { 22405 ret = bpf_prog_offload_verifier_prep(env->prog); 22406 if (ret) 22407 goto skip_full_check; 22408 } 22409 22410 ret = check_cfg(env); 22411 if (ret < 0) 22412 goto skip_full_check; 22413 22414 ret = mark_fastcall_patterns(env); 22415 if (ret < 0) 22416 goto skip_full_check; 22417 22418 ret = do_check_main(env); 22419 ret = ret ?: do_check_subprogs(env); 22420 22421 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 22422 ret = bpf_prog_offload_finalize(env); 22423 22424 skip_full_check: 22425 kvfree(env->explored_states); 22426 22427 /* might decrease stack depth, keep it before passes that 22428 * allocate additional slots. 22429 */ 22430 if (ret == 0) 22431 ret = remove_fastcall_spills_fills(env); 22432 22433 if (ret == 0) 22434 ret = check_max_stack_depth(env); 22435 22436 /* instruction rewrites happen after this point */ 22437 if (ret == 0) 22438 ret = optimize_bpf_loop(env); 22439 22440 if (is_priv) { 22441 if (ret == 0) 22442 opt_hard_wire_dead_code_branches(env); 22443 if (ret == 0) 22444 ret = opt_remove_dead_code(env); 22445 if (ret == 0) 22446 ret = opt_remove_nops(env); 22447 } else { 22448 if (ret == 0) 22449 sanitize_dead_code(env); 22450 } 22451 22452 if (ret == 0) 22453 /* program is valid, convert *(u32*)(ctx + off) accesses */ 22454 ret = convert_ctx_accesses(env); 22455 22456 if (ret == 0) 22457 ret = do_misc_fixups(env); 22458 22459 /* do 32-bit optimization after insn patching has done so those patched 22460 * insns could be handled correctly. 22461 */ 22462 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 22463 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 22464 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 22465 : false; 22466 } 22467 22468 if (ret == 0) 22469 ret = fixup_call_args(env); 22470 22471 env->verification_time = ktime_get_ns() - start_time; 22472 print_verification_stats(env); 22473 env->prog->aux->verified_insns = env->insn_processed; 22474 22475 /* preserve original error even if log finalization is successful */ 22476 err = bpf_vlog_finalize(&env->log, &log_true_size); 22477 if (err) 22478 ret = err; 22479 22480 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 22481 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 22482 &log_true_size, sizeof(log_true_size))) { 22483 ret = -EFAULT; 22484 goto err_release_maps; 22485 } 22486 22487 if (ret) 22488 goto err_release_maps; 22489 22490 if (env->used_map_cnt) { 22491 /* if program passed verifier, update used_maps in bpf_prog_info */ 22492 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 22493 sizeof(env->used_maps[0]), 22494 GFP_KERNEL); 22495 22496 if (!env->prog->aux->used_maps) { 22497 ret = -ENOMEM; 22498 goto err_release_maps; 22499 } 22500 22501 memcpy(env->prog->aux->used_maps, env->used_maps, 22502 sizeof(env->used_maps[0]) * env->used_map_cnt); 22503 env->prog->aux->used_map_cnt = env->used_map_cnt; 22504 } 22505 if (env->used_btf_cnt) { 22506 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 22507 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 22508 sizeof(env->used_btfs[0]), 22509 GFP_KERNEL); 22510 if (!env->prog->aux->used_btfs) { 22511 ret = -ENOMEM; 22512 goto err_release_maps; 22513 } 22514 22515 memcpy(env->prog->aux->used_btfs, env->used_btfs, 22516 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 22517 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 22518 } 22519 if (env->used_map_cnt || env->used_btf_cnt) { 22520 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 22521 * bpf_ld_imm64 instructions 22522 */ 22523 convert_pseudo_ld_imm64(env); 22524 } 22525 22526 adjust_btf_func(env); 22527 22528 err_release_maps: 22529 if (!env->prog->aux->used_maps) 22530 /* if we didn't copy map pointers into bpf_prog_info, release 22531 * them now. Otherwise free_used_maps() will release them. 22532 */ 22533 release_maps(env); 22534 if (!env->prog->aux->used_btfs) 22535 release_btfs(env); 22536 22537 /* extension progs temporarily inherit the attach_type of their targets 22538 for verification purposes, so set it back to zero before returning 22539 */ 22540 if (env->prog->type == BPF_PROG_TYPE_EXT) 22541 env->prog->expected_attach_type = 0; 22542 22543 *prog = env->prog; 22544 22545 module_put(env->attach_btf_mod); 22546 err_unlock: 22547 if (!is_priv) 22548 mutex_unlock(&bpf_verifier_lock); 22549 vfree(env->insn_aux_data); 22550 err_free_env: 22551 kvfree(env); 22552 return ret; 22553 } 22554