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 #define BPF_PRIV_STACK_MIN_SIZE 64 198 199 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx); 200 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id); 201 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 202 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 203 static int ref_set_non_owning(struct bpf_verifier_env *env, 204 struct bpf_reg_state *reg); 205 static void specialize_kfunc(struct bpf_verifier_env *env, 206 u32 func_id, u16 offset, unsigned long *addr); 207 static bool is_trusted_reg(const struct bpf_reg_state *reg); 208 209 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 210 { 211 return aux->map_ptr_state.poison; 212 } 213 214 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 215 { 216 return aux->map_ptr_state.unpriv; 217 } 218 219 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 220 struct bpf_map *map, 221 bool unpriv, bool poison) 222 { 223 unpriv |= bpf_map_ptr_unpriv(aux); 224 aux->map_ptr_state.unpriv = unpriv; 225 aux->map_ptr_state.poison = poison; 226 aux->map_ptr_state.map_ptr = map; 227 } 228 229 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 230 { 231 return aux->map_key_state & BPF_MAP_KEY_POISON; 232 } 233 234 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 235 { 236 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 237 } 238 239 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 240 { 241 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 242 } 243 244 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 245 { 246 bool poisoned = bpf_map_key_poisoned(aux); 247 248 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 249 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 250 } 251 252 static bool bpf_helper_call(const struct bpf_insn *insn) 253 { 254 return insn->code == (BPF_JMP | BPF_CALL) && 255 insn->src_reg == 0; 256 } 257 258 static bool bpf_pseudo_call(const struct bpf_insn *insn) 259 { 260 return insn->code == (BPF_JMP | BPF_CALL) && 261 insn->src_reg == BPF_PSEUDO_CALL; 262 } 263 264 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 265 { 266 return insn->code == (BPF_JMP | BPF_CALL) && 267 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 268 } 269 270 struct bpf_call_arg_meta { 271 struct bpf_map *map_ptr; 272 bool raw_mode; 273 bool pkt_access; 274 u8 release_regno; 275 int regno; 276 int access_size; 277 int mem_size; 278 u64 msize_max_value; 279 int ref_obj_id; 280 int dynptr_id; 281 int map_uid; 282 int func_id; 283 struct btf *btf; 284 u32 btf_id; 285 struct btf *ret_btf; 286 u32 ret_btf_id; 287 u32 subprogno; 288 struct btf_field *kptr_field; 289 }; 290 291 struct bpf_kfunc_call_arg_meta { 292 /* In parameters */ 293 struct btf *btf; 294 u32 func_id; 295 u32 kfunc_flags; 296 const struct btf_type *func_proto; 297 const char *func_name; 298 /* Out parameters */ 299 u32 ref_obj_id; 300 u8 release_regno; 301 bool r0_rdonly; 302 u32 ret_btf_id; 303 u64 r0_size; 304 u32 subprogno; 305 struct { 306 u64 value; 307 bool found; 308 } arg_constant; 309 310 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling, 311 * generally to pass info about user-defined local kptr types to later 312 * verification logic 313 * bpf_obj_drop/bpf_percpu_obj_drop 314 * Record the local kptr type to be drop'd 315 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type) 316 * Record the local kptr type to be refcount_incr'd and use 317 * arg_owning_ref to determine whether refcount_acquire should be 318 * fallible 319 */ 320 struct btf *arg_btf; 321 u32 arg_btf_id; 322 bool arg_owning_ref; 323 324 struct { 325 struct btf_field *field; 326 } arg_list_head; 327 struct { 328 struct btf_field *field; 329 } arg_rbtree_root; 330 struct { 331 enum bpf_dynptr_type type; 332 u32 id; 333 u32 ref_obj_id; 334 } initialized_dynptr; 335 struct { 336 u8 spi; 337 u8 frameno; 338 } iter; 339 struct { 340 struct bpf_map *ptr; 341 int uid; 342 } map; 343 u64 mem_size; 344 }; 345 346 struct btf *btf_vmlinux; 347 348 static const char *btf_type_name(const struct btf *btf, u32 id) 349 { 350 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 351 } 352 353 static DEFINE_MUTEX(bpf_verifier_lock); 354 static DEFINE_MUTEX(bpf_percpu_ma_lock); 355 356 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 357 { 358 struct bpf_verifier_env *env = private_data; 359 va_list args; 360 361 if (!bpf_verifier_log_needed(&env->log)) 362 return; 363 364 va_start(args, fmt); 365 bpf_verifier_vlog(&env->log, fmt, args); 366 va_end(args); 367 } 368 369 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 370 struct bpf_reg_state *reg, 371 struct bpf_retval_range range, const char *ctx, 372 const char *reg_name) 373 { 374 bool unknown = true; 375 376 verbose(env, "%s the register %s has", ctx, reg_name); 377 if (reg->smin_value > S64_MIN) { 378 verbose(env, " smin=%lld", reg->smin_value); 379 unknown = false; 380 } 381 if (reg->smax_value < S64_MAX) { 382 verbose(env, " smax=%lld", reg->smax_value); 383 unknown = false; 384 } 385 if (unknown) 386 verbose(env, " unknown scalar value"); 387 verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval); 388 } 389 390 static bool reg_not_null(const struct bpf_reg_state *reg) 391 { 392 enum bpf_reg_type type; 393 394 type = reg->type; 395 if (type_may_be_null(type)) 396 return false; 397 398 type = base_type(type); 399 return type == PTR_TO_SOCKET || 400 type == PTR_TO_TCP_SOCK || 401 type == PTR_TO_MAP_VALUE || 402 type == PTR_TO_MAP_KEY || 403 type == PTR_TO_SOCK_COMMON || 404 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) || 405 type == PTR_TO_MEM; 406 } 407 408 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 409 { 410 struct btf_record *rec = NULL; 411 struct btf_struct_meta *meta; 412 413 if (reg->type == PTR_TO_MAP_VALUE) { 414 rec = reg->map_ptr->record; 415 } else if (type_is_ptr_alloc_obj(reg->type)) { 416 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 417 if (meta) 418 rec = meta->record; 419 } 420 return rec; 421 } 422 423 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog) 424 { 425 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 426 427 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 428 } 429 430 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog) 431 { 432 struct bpf_func_info *info; 433 434 if (!env->prog->aux->func_info) 435 return ""; 436 437 info = &env->prog->aux->func_info[subprog]; 438 return btf_type_name(env->prog->aux->btf, info->type_id); 439 } 440 441 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog) 442 { 443 struct bpf_subprog_info *info = subprog_info(env, subprog); 444 445 info->is_cb = true; 446 info->is_async_cb = true; 447 info->is_exception_cb = true; 448 } 449 450 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog) 451 { 452 return subprog_info(env, subprog)->is_exception_cb; 453 } 454 455 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 456 { 457 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK); 458 } 459 460 static bool type_is_rdonly_mem(u32 type) 461 { 462 return type & MEM_RDONLY; 463 } 464 465 static bool is_acquire_function(enum bpf_func_id func_id, 466 const struct bpf_map *map) 467 { 468 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 469 470 if (func_id == BPF_FUNC_sk_lookup_tcp || 471 func_id == BPF_FUNC_sk_lookup_udp || 472 func_id == BPF_FUNC_skc_lookup_tcp || 473 func_id == BPF_FUNC_ringbuf_reserve || 474 func_id == BPF_FUNC_kptr_xchg) 475 return true; 476 477 if (func_id == BPF_FUNC_map_lookup_elem && 478 (map_type == BPF_MAP_TYPE_SOCKMAP || 479 map_type == BPF_MAP_TYPE_SOCKHASH)) 480 return true; 481 482 return false; 483 } 484 485 static bool is_ptr_cast_function(enum bpf_func_id func_id) 486 { 487 return func_id == BPF_FUNC_tcp_sock || 488 func_id == BPF_FUNC_sk_fullsock || 489 func_id == BPF_FUNC_skc_to_tcp_sock || 490 func_id == BPF_FUNC_skc_to_tcp6_sock || 491 func_id == BPF_FUNC_skc_to_udp6_sock || 492 func_id == BPF_FUNC_skc_to_mptcp_sock || 493 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 494 func_id == BPF_FUNC_skc_to_tcp_request_sock; 495 } 496 497 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 498 { 499 return func_id == BPF_FUNC_dynptr_data; 500 } 501 502 static bool is_sync_callback_calling_kfunc(u32 btf_id); 503 static bool is_async_callback_calling_kfunc(u32 btf_id); 504 static bool is_callback_calling_kfunc(u32 btf_id); 505 static bool is_bpf_throw_kfunc(struct bpf_insn *insn); 506 507 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id); 508 509 static bool is_sync_callback_calling_function(enum bpf_func_id func_id) 510 { 511 return func_id == BPF_FUNC_for_each_map_elem || 512 func_id == BPF_FUNC_find_vma || 513 func_id == BPF_FUNC_loop || 514 func_id == BPF_FUNC_user_ringbuf_drain; 515 } 516 517 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 518 { 519 return func_id == BPF_FUNC_timer_set_callback; 520 } 521 522 static bool is_callback_calling_function(enum bpf_func_id func_id) 523 { 524 return is_sync_callback_calling_function(func_id) || 525 is_async_callback_calling_function(func_id); 526 } 527 528 static bool is_sync_callback_calling_insn(struct bpf_insn *insn) 529 { 530 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) || 531 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm)); 532 } 533 534 static bool is_async_callback_calling_insn(struct bpf_insn *insn) 535 { 536 return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) || 537 (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm)); 538 } 539 540 static bool is_may_goto_insn(struct bpf_insn *insn) 541 { 542 return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO; 543 } 544 545 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx) 546 { 547 return is_may_goto_insn(&env->prog->insnsi[insn_idx]); 548 } 549 550 static bool is_storage_get_function(enum bpf_func_id func_id) 551 { 552 return func_id == BPF_FUNC_sk_storage_get || 553 func_id == BPF_FUNC_inode_storage_get || 554 func_id == BPF_FUNC_task_storage_get || 555 func_id == BPF_FUNC_cgrp_storage_get; 556 } 557 558 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 559 const struct bpf_map *map) 560 { 561 int ref_obj_uses = 0; 562 563 if (is_ptr_cast_function(func_id)) 564 ref_obj_uses++; 565 if (is_acquire_function(func_id, map)) 566 ref_obj_uses++; 567 if (is_dynptr_ref_function(func_id)) 568 ref_obj_uses++; 569 570 return ref_obj_uses > 1; 571 } 572 573 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 574 { 575 return BPF_CLASS(insn->code) == BPF_STX && 576 BPF_MODE(insn->code) == BPF_ATOMIC && 577 insn->imm == BPF_CMPXCHG; 578 } 579 580 static int __get_spi(s32 off) 581 { 582 return (-off - 1) / BPF_REG_SIZE; 583 } 584 585 static struct bpf_func_state *func(struct bpf_verifier_env *env, 586 const struct bpf_reg_state *reg) 587 { 588 struct bpf_verifier_state *cur = env->cur_state; 589 590 return cur->frame[reg->frameno]; 591 } 592 593 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 594 { 595 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 596 597 /* We need to check that slots between [spi - nr_slots + 1, spi] are 598 * within [0, allocated_stack). 599 * 600 * Please note that the spi grows downwards. For example, a dynptr 601 * takes the size of two stack slots; the first slot will be at 602 * spi and the second slot will be at spi - 1. 603 */ 604 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 605 } 606 607 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 608 const char *obj_kind, int nr_slots) 609 { 610 int off, spi; 611 612 if (!tnum_is_const(reg->var_off)) { 613 verbose(env, "%s has to be at a constant offset\n", obj_kind); 614 return -EINVAL; 615 } 616 617 off = reg->off + reg->var_off.value; 618 if (off % BPF_REG_SIZE) { 619 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 620 return -EINVAL; 621 } 622 623 spi = __get_spi(off); 624 if (spi + 1 < nr_slots) { 625 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 626 return -EINVAL; 627 } 628 629 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots)) 630 return -ERANGE; 631 return spi; 632 } 633 634 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 635 { 636 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 637 } 638 639 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 640 { 641 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 642 } 643 644 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 645 { 646 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 647 case DYNPTR_TYPE_LOCAL: 648 return BPF_DYNPTR_TYPE_LOCAL; 649 case DYNPTR_TYPE_RINGBUF: 650 return BPF_DYNPTR_TYPE_RINGBUF; 651 case DYNPTR_TYPE_SKB: 652 return BPF_DYNPTR_TYPE_SKB; 653 case DYNPTR_TYPE_XDP: 654 return BPF_DYNPTR_TYPE_XDP; 655 default: 656 return BPF_DYNPTR_TYPE_INVALID; 657 } 658 } 659 660 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 661 { 662 switch (type) { 663 case BPF_DYNPTR_TYPE_LOCAL: 664 return DYNPTR_TYPE_LOCAL; 665 case BPF_DYNPTR_TYPE_RINGBUF: 666 return DYNPTR_TYPE_RINGBUF; 667 case BPF_DYNPTR_TYPE_SKB: 668 return DYNPTR_TYPE_SKB; 669 case BPF_DYNPTR_TYPE_XDP: 670 return DYNPTR_TYPE_XDP; 671 default: 672 return 0; 673 } 674 } 675 676 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 677 { 678 return type == BPF_DYNPTR_TYPE_RINGBUF; 679 } 680 681 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 682 enum bpf_dynptr_type type, 683 bool first_slot, int dynptr_id); 684 685 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 686 struct bpf_reg_state *reg); 687 688 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 689 struct bpf_reg_state *sreg1, 690 struct bpf_reg_state *sreg2, 691 enum bpf_dynptr_type type) 692 { 693 int id = ++env->id_gen; 694 695 __mark_dynptr_reg(sreg1, type, true, id); 696 __mark_dynptr_reg(sreg2, type, false, id); 697 } 698 699 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 700 struct bpf_reg_state *reg, 701 enum bpf_dynptr_type type) 702 { 703 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 704 } 705 706 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 707 struct bpf_func_state *state, int spi); 708 709 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 710 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id) 711 { 712 struct bpf_func_state *state = func(env, reg); 713 enum bpf_dynptr_type type; 714 int spi, i, err; 715 716 spi = dynptr_get_spi(env, reg); 717 if (spi < 0) 718 return spi; 719 720 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 721 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 722 * to ensure that for the following example: 723 * [d1][d1][d2][d2] 724 * spi 3 2 1 0 725 * So marking spi = 2 should lead to destruction of both d1 and d2. In 726 * case they do belong to same dynptr, second call won't see slot_type 727 * as STACK_DYNPTR and will simply skip destruction. 728 */ 729 err = destroy_if_dynptr_stack_slot(env, state, spi); 730 if (err) 731 return err; 732 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 733 if (err) 734 return err; 735 736 for (i = 0; i < BPF_REG_SIZE; i++) { 737 state->stack[spi].slot_type[i] = STACK_DYNPTR; 738 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 739 } 740 741 type = arg_to_dynptr_type(arg_type); 742 if (type == BPF_DYNPTR_TYPE_INVALID) 743 return -EINVAL; 744 745 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 746 &state->stack[spi - 1].spilled_ptr, type); 747 748 if (dynptr_type_refcounted(type)) { 749 /* The id is used to track proper releasing */ 750 int id; 751 752 if (clone_ref_obj_id) 753 id = clone_ref_obj_id; 754 else 755 id = acquire_reference_state(env, insn_idx); 756 757 if (id < 0) 758 return id; 759 760 state->stack[spi].spilled_ptr.ref_obj_id = id; 761 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 762 } 763 764 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 765 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 766 767 return 0; 768 } 769 770 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi) 771 { 772 int i; 773 774 for (i = 0; i < BPF_REG_SIZE; i++) { 775 state->stack[spi].slot_type[i] = STACK_INVALID; 776 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 777 } 778 779 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 780 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 781 782 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot? 783 * 784 * While we don't allow reading STACK_INVALID, it is still possible to 785 * do <8 byte writes marking some but not all slots as STACK_MISC. Then, 786 * helpers or insns can do partial read of that part without failing, 787 * but check_stack_range_initialized, check_stack_read_var_off, and 788 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of 789 * the slot conservatively. Hence we need to prevent those liveness 790 * marking walks. 791 * 792 * This was not a problem before because STACK_INVALID is only set by 793 * default (where the default reg state has its reg->parent as NULL), or 794 * in clean_live_states after REG_LIVE_DONE (at which point 795 * mark_reg_read won't walk reg->parent chain), but not randomly during 796 * verifier state exploration (like we did above). Hence, for our case 797 * parentage chain will still be live (i.e. reg->parent may be 798 * non-NULL), while earlier reg->parent was NULL, so we need 799 * REG_LIVE_WRITTEN to screen off read marker propagation when it is 800 * done later on reads or by mark_dynptr_read as well to unnecessary 801 * mark registers in verifier state. 802 */ 803 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 804 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 805 } 806 807 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 808 { 809 struct bpf_func_state *state = func(env, reg); 810 int spi, ref_obj_id, i; 811 812 spi = dynptr_get_spi(env, reg); 813 if (spi < 0) 814 return spi; 815 816 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 817 invalidate_dynptr(env, state, spi); 818 return 0; 819 } 820 821 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 822 823 /* If the dynptr has a ref_obj_id, then we need to invalidate 824 * two things: 825 * 826 * 1) Any dynptrs with a matching ref_obj_id (clones) 827 * 2) Any slices derived from this dynptr. 828 */ 829 830 /* Invalidate any slices associated with this dynptr */ 831 WARN_ON_ONCE(release_reference(env, ref_obj_id)); 832 833 /* Invalidate any dynptr clones */ 834 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) { 835 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id) 836 continue; 837 838 /* it should always be the case that if the ref obj id 839 * matches then the stack slot also belongs to a 840 * dynptr 841 */ 842 if (state->stack[i].slot_type[0] != STACK_DYNPTR) { 843 verbose(env, "verifier internal error: misconfigured ref_obj_id\n"); 844 return -EFAULT; 845 } 846 if (state->stack[i].spilled_ptr.dynptr.first_slot) 847 invalidate_dynptr(env, state, i); 848 } 849 850 return 0; 851 } 852 853 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 854 struct bpf_reg_state *reg); 855 856 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 857 { 858 if (!env->allow_ptr_leaks) 859 __mark_reg_not_init(env, reg); 860 else 861 __mark_reg_unknown(env, reg); 862 } 863 864 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 865 struct bpf_func_state *state, int spi) 866 { 867 struct bpf_func_state *fstate; 868 struct bpf_reg_state *dreg; 869 int i, dynptr_id; 870 871 /* We always ensure that STACK_DYNPTR is never set partially, 872 * hence just checking for slot_type[0] is enough. This is 873 * different for STACK_SPILL, where it may be only set for 874 * 1 byte, so code has to use is_spilled_reg. 875 */ 876 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 877 return 0; 878 879 /* Reposition spi to first slot */ 880 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 881 spi = spi + 1; 882 883 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 884 verbose(env, "cannot overwrite referenced dynptr\n"); 885 return -EINVAL; 886 } 887 888 mark_stack_slot_scratched(env, spi); 889 mark_stack_slot_scratched(env, spi - 1); 890 891 /* Writing partially to one dynptr stack slot destroys both. */ 892 for (i = 0; i < BPF_REG_SIZE; i++) { 893 state->stack[spi].slot_type[i] = STACK_INVALID; 894 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 895 } 896 897 dynptr_id = state->stack[spi].spilled_ptr.id; 898 /* Invalidate any slices associated with this dynptr */ 899 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 900 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 901 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 902 continue; 903 if (dreg->dynptr_id == dynptr_id) 904 mark_reg_invalid(env, dreg); 905 })); 906 907 /* Do not release reference state, we are destroying dynptr on stack, 908 * not using some helper to release it. Just reset register. 909 */ 910 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 911 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 912 913 /* Same reason as unmark_stack_slots_dynptr above */ 914 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 915 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 916 917 return 0; 918 } 919 920 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 921 { 922 int spi; 923 924 if (reg->type == CONST_PTR_TO_DYNPTR) 925 return false; 926 927 spi = dynptr_get_spi(env, reg); 928 929 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 930 * error because this just means the stack state hasn't been updated yet. 931 * We will do check_mem_access to check and update stack bounds later. 932 */ 933 if (spi < 0 && spi != -ERANGE) 934 return false; 935 936 /* We don't need to check if the stack slots are marked by previous 937 * dynptr initializations because we allow overwriting existing unreferenced 938 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 939 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 940 * touching are completely destructed before we reinitialize them for a new 941 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 942 * instead of delaying it until the end where the user will get "Unreleased 943 * reference" error. 944 */ 945 return true; 946 } 947 948 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 949 { 950 struct bpf_func_state *state = func(env, reg); 951 int i, spi; 952 953 /* This already represents first slot of initialized bpf_dynptr. 954 * 955 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 956 * check_func_arg_reg_off's logic, so we don't need to check its 957 * offset and alignment. 958 */ 959 if (reg->type == CONST_PTR_TO_DYNPTR) 960 return true; 961 962 spi = dynptr_get_spi(env, reg); 963 if (spi < 0) 964 return false; 965 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 966 return false; 967 968 for (i = 0; i < BPF_REG_SIZE; i++) { 969 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 970 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 971 return false; 972 } 973 974 return true; 975 } 976 977 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 978 enum bpf_arg_type arg_type) 979 { 980 struct bpf_func_state *state = func(env, reg); 981 enum bpf_dynptr_type dynptr_type; 982 int spi; 983 984 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 985 if (arg_type == ARG_PTR_TO_DYNPTR) 986 return true; 987 988 dynptr_type = arg_to_dynptr_type(arg_type); 989 if (reg->type == CONST_PTR_TO_DYNPTR) { 990 return reg->dynptr.type == dynptr_type; 991 } else { 992 spi = dynptr_get_spi(env, reg); 993 if (spi < 0) 994 return false; 995 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 996 } 997 } 998 999 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 1000 1001 static bool in_rcu_cs(struct bpf_verifier_env *env); 1002 1003 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta); 1004 1005 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 1006 struct bpf_kfunc_call_arg_meta *meta, 1007 struct bpf_reg_state *reg, int insn_idx, 1008 struct btf *btf, u32 btf_id, int nr_slots) 1009 { 1010 struct bpf_func_state *state = func(env, reg); 1011 int spi, i, j, id; 1012 1013 spi = iter_get_spi(env, reg, nr_slots); 1014 if (spi < 0) 1015 return spi; 1016 1017 id = acquire_reference_state(env, insn_idx); 1018 if (id < 0) 1019 return id; 1020 1021 for (i = 0; i < nr_slots; i++) { 1022 struct bpf_stack_state *slot = &state->stack[spi - i]; 1023 struct bpf_reg_state *st = &slot->spilled_ptr; 1024 1025 __mark_reg_known_zero(st); 1026 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1027 if (is_kfunc_rcu_protected(meta)) { 1028 if (in_rcu_cs(env)) 1029 st->type |= MEM_RCU; 1030 else 1031 st->type |= PTR_UNTRUSTED; 1032 } 1033 st->live |= REG_LIVE_WRITTEN; 1034 st->ref_obj_id = i == 0 ? id : 0; 1035 st->iter.btf = btf; 1036 st->iter.btf_id = btf_id; 1037 st->iter.state = BPF_ITER_STATE_ACTIVE; 1038 st->iter.depth = 0; 1039 1040 for (j = 0; j < BPF_REG_SIZE; j++) 1041 slot->slot_type[j] = STACK_ITER; 1042 1043 mark_stack_slot_scratched(env, spi - i); 1044 } 1045 1046 return 0; 1047 } 1048 1049 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 1050 struct bpf_reg_state *reg, int nr_slots) 1051 { 1052 struct bpf_func_state *state = func(env, reg); 1053 int spi, i, j; 1054 1055 spi = iter_get_spi(env, reg, nr_slots); 1056 if (spi < 0) 1057 return spi; 1058 1059 for (i = 0; i < nr_slots; i++) { 1060 struct bpf_stack_state *slot = &state->stack[spi - i]; 1061 struct bpf_reg_state *st = &slot->spilled_ptr; 1062 1063 if (i == 0) 1064 WARN_ON_ONCE(release_reference(env, st->ref_obj_id)); 1065 1066 __mark_reg_not_init(env, st); 1067 1068 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1069 st->live |= REG_LIVE_WRITTEN; 1070 1071 for (j = 0; j < BPF_REG_SIZE; j++) 1072 slot->slot_type[j] = STACK_INVALID; 1073 1074 mark_stack_slot_scratched(env, spi - i); 1075 } 1076 1077 return 0; 1078 } 1079 1080 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1081 struct bpf_reg_state *reg, int nr_slots) 1082 { 1083 struct bpf_func_state *state = func(env, reg); 1084 int spi, i, j; 1085 1086 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1087 * will do check_mem_access to check and update stack bounds later, so 1088 * return true for that case. 1089 */ 1090 spi = iter_get_spi(env, reg, nr_slots); 1091 if (spi == -ERANGE) 1092 return true; 1093 if (spi < 0) 1094 return false; 1095 1096 for (i = 0; i < nr_slots; i++) { 1097 struct bpf_stack_state *slot = &state->stack[spi - i]; 1098 1099 for (j = 0; j < BPF_REG_SIZE; j++) 1100 if (slot->slot_type[j] == STACK_ITER) 1101 return false; 1102 } 1103 1104 return true; 1105 } 1106 1107 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1108 struct btf *btf, u32 btf_id, int nr_slots) 1109 { 1110 struct bpf_func_state *state = func(env, reg); 1111 int spi, i, j; 1112 1113 spi = iter_get_spi(env, reg, nr_slots); 1114 if (spi < 0) 1115 return -EINVAL; 1116 1117 for (i = 0; i < nr_slots; i++) { 1118 struct bpf_stack_state *slot = &state->stack[spi - i]; 1119 struct bpf_reg_state *st = &slot->spilled_ptr; 1120 1121 if (st->type & PTR_UNTRUSTED) 1122 return -EPROTO; 1123 /* only main (first) slot has ref_obj_id set */ 1124 if (i == 0 && !st->ref_obj_id) 1125 return -EINVAL; 1126 if (i != 0 && st->ref_obj_id) 1127 return -EINVAL; 1128 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1129 return -EINVAL; 1130 1131 for (j = 0; j < BPF_REG_SIZE; j++) 1132 if (slot->slot_type[j] != STACK_ITER) 1133 return -EINVAL; 1134 } 1135 1136 return 0; 1137 } 1138 1139 /* Check if given stack slot is "special": 1140 * - spilled register state (STACK_SPILL); 1141 * - dynptr state (STACK_DYNPTR); 1142 * - iter state (STACK_ITER). 1143 */ 1144 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1145 { 1146 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1147 1148 switch (type) { 1149 case STACK_SPILL: 1150 case STACK_DYNPTR: 1151 case STACK_ITER: 1152 return true; 1153 case STACK_INVALID: 1154 case STACK_MISC: 1155 case STACK_ZERO: 1156 return false; 1157 default: 1158 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1159 return true; 1160 } 1161 } 1162 1163 /* The reg state of a pointer or a bounded scalar was saved when 1164 * it was spilled to the stack. 1165 */ 1166 static bool is_spilled_reg(const struct bpf_stack_state *stack) 1167 { 1168 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1169 } 1170 1171 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack) 1172 { 1173 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL && 1174 stack->spilled_ptr.type == SCALAR_VALUE; 1175 } 1176 1177 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack) 1178 { 1179 return stack->slot_type[0] == STACK_SPILL && 1180 stack->spilled_ptr.type == SCALAR_VALUE; 1181 } 1182 1183 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which 1184 * case they are equivalent, or it's STACK_ZERO, in which case we preserve 1185 * more precise STACK_ZERO. 1186 * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged 1187 * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is 1188 * unnecessary as both are considered equivalent when loading data and pruning, 1189 * in case of unprivileged mode it will be incorrect to allow reads of invalid 1190 * slots. 1191 */ 1192 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype) 1193 { 1194 if (*stype == STACK_ZERO) 1195 return; 1196 if (*stype == STACK_INVALID) 1197 return; 1198 *stype = STACK_MISC; 1199 } 1200 1201 static void scrub_spilled_slot(u8 *stype) 1202 { 1203 if (*stype != STACK_INVALID) 1204 *stype = STACK_MISC; 1205 } 1206 1207 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1208 * small to hold src. This is different from krealloc since we don't want to preserve 1209 * the contents of dst. 1210 * 1211 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1212 * not be allocated. 1213 */ 1214 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1215 { 1216 size_t alloc_bytes; 1217 void *orig = dst; 1218 size_t bytes; 1219 1220 if (ZERO_OR_NULL_PTR(src)) 1221 goto out; 1222 1223 if (unlikely(check_mul_overflow(n, size, &bytes))) 1224 return NULL; 1225 1226 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1227 dst = krealloc(orig, alloc_bytes, flags); 1228 if (!dst) { 1229 kfree(orig); 1230 return NULL; 1231 } 1232 1233 memcpy(dst, src, bytes); 1234 out: 1235 return dst ? dst : ZERO_SIZE_PTR; 1236 } 1237 1238 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1239 * small to hold new_n items. new items are zeroed out if the array grows. 1240 * 1241 * Contrary to krealloc_array, does not free arr if new_n is zero. 1242 */ 1243 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1244 { 1245 size_t alloc_size; 1246 void *new_arr; 1247 1248 if (!new_n || old_n == new_n) 1249 goto out; 1250 1251 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1252 new_arr = krealloc(arr, alloc_size, GFP_KERNEL); 1253 if (!new_arr) { 1254 kfree(arr); 1255 return NULL; 1256 } 1257 arr = new_arr; 1258 1259 if (new_n > old_n) 1260 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1261 1262 out: 1263 return arr ? arr : ZERO_SIZE_PTR; 1264 } 1265 1266 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1267 { 1268 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1269 sizeof(struct bpf_reference_state), GFP_KERNEL); 1270 if (!dst->refs) 1271 return -ENOMEM; 1272 1273 dst->active_locks = src->active_locks; 1274 dst->acquired_refs = src->acquired_refs; 1275 return 0; 1276 } 1277 1278 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1279 { 1280 size_t n = src->allocated_stack / BPF_REG_SIZE; 1281 1282 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1283 GFP_KERNEL); 1284 if (!dst->stack) 1285 return -ENOMEM; 1286 1287 dst->allocated_stack = src->allocated_stack; 1288 return 0; 1289 } 1290 1291 static int resize_reference_state(struct bpf_func_state *state, size_t n) 1292 { 1293 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1294 sizeof(struct bpf_reference_state)); 1295 if (!state->refs) 1296 return -ENOMEM; 1297 1298 state->acquired_refs = n; 1299 return 0; 1300 } 1301 1302 /* Possibly update state->allocated_stack to be at least size bytes. Also 1303 * possibly update the function's high-water mark in its bpf_subprog_info. 1304 */ 1305 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) 1306 { 1307 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n; 1308 1309 /* The stack size is always a multiple of BPF_REG_SIZE. */ 1310 size = round_up(size, BPF_REG_SIZE); 1311 n = size / BPF_REG_SIZE; 1312 1313 if (old_n >= n) 1314 return 0; 1315 1316 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1317 if (!state->stack) 1318 return -ENOMEM; 1319 1320 state->allocated_stack = size; 1321 1322 /* update known max for given subprogram */ 1323 if (env->subprog_info[state->subprogno].stack_depth < size) 1324 env->subprog_info[state->subprogno].stack_depth = size; 1325 1326 return 0; 1327 } 1328 1329 /* Acquire a pointer id from the env and update the state->refs to include 1330 * this new pointer reference. 1331 * On success, returns a valid pointer id to associate with the register 1332 * On failure, returns a negative errno. 1333 */ 1334 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1335 { 1336 struct bpf_func_state *state = cur_func(env); 1337 int new_ofs = state->acquired_refs; 1338 int id, err; 1339 1340 err = resize_reference_state(state, state->acquired_refs + 1); 1341 if (err) 1342 return err; 1343 id = ++env->id_gen; 1344 state->refs[new_ofs].type = REF_TYPE_PTR; 1345 state->refs[new_ofs].id = id; 1346 state->refs[new_ofs].insn_idx = insn_idx; 1347 1348 return id; 1349 } 1350 1351 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type, 1352 int id, void *ptr) 1353 { 1354 struct bpf_func_state *state = cur_func(env); 1355 int new_ofs = state->acquired_refs; 1356 int err; 1357 1358 err = resize_reference_state(state, state->acquired_refs + 1); 1359 if (err) 1360 return err; 1361 state->refs[new_ofs].type = type; 1362 state->refs[new_ofs].id = id; 1363 state->refs[new_ofs].insn_idx = insn_idx; 1364 state->refs[new_ofs].ptr = ptr; 1365 1366 state->active_locks++; 1367 return 0; 1368 } 1369 1370 /* release function corresponding to acquire_reference_state(). Idempotent. */ 1371 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 1372 { 1373 int i, last_idx; 1374 1375 last_idx = state->acquired_refs - 1; 1376 for (i = 0; i < state->acquired_refs; i++) { 1377 if (state->refs[i].type != REF_TYPE_PTR) 1378 continue; 1379 if (state->refs[i].id == ptr_id) { 1380 if (last_idx && i != last_idx) 1381 memcpy(&state->refs[i], &state->refs[last_idx], 1382 sizeof(*state->refs)); 1383 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1384 state->acquired_refs--; 1385 return 0; 1386 } 1387 } 1388 return -EINVAL; 1389 } 1390 1391 static int release_lock_state(struct bpf_func_state *state, int type, int id, void *ptr) 1392 { 1393 int i, last_idx; 1394 1395 last_idx = state->acquired_refs - 1; 1396 for (i = 0; i < state->acquired_refs; i++) { 1397 if (state->refs[i].type != type) 1398 continue; 1399 if (state->refs[i].id == id && state->refs[i].ptr == ptr) { 1400 if (last_idx && i != last_idx) 1401 memcpy(&state->refs[i], &state->refs[last_idx], 1402 sizeof(*state->refs)); 1403 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1404 state->acquired_refs--; 1405 state->active_locks--; 1406 return 0; 1407 } 1408 } 1409 return -EINVAL; 1410 } 1411 1412 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_env *env, enum ref_state_type type, 1413 int id, void *ptr) 1414 { 1415 struct bpf_func_state *state = cur_func(env); 1416 int i; 1417 1418 for (i = 0; i < state->acquired_refs; i++) { 1419 struct bpf_reference_state *s = &state->refs[i]; 1420 1421 if (s->type == REF_TYPE_PTR || s->type != type) 1422 continue; 1423 1424 if (s->id == id && s->ptr == ptr) 1425 return s; 1426 } 1427 return NULL; 1428 } 1429 1430 static void free_func_state(struct bpf_func_state *state) 1431 { 1432 if (!state) 1433 return; 1434 kfree(state->refs); 1435 kfree(state->stack); 1436 kfree(state); 1437 } 1438 1439 static void free_verifier_state(struct bpf_verifier_state *state, 1440 bool free_self) 1441 { 1442 int i; 1443 1444 for (i = 0; i <= state->curframe; i++) { 1445 free_func_state(state->frame[i]); 1446 state->frame[i] = NULL; 1447 } 1448 if (free_self) 1449 kfree(state); 1450 } 1451 1452 /* copy verifier state from src to dst growing dst stack space 1453 * when necessary to accommodate larger src stack 1454 */ 1455 static int copy_func_state(struct bpf_func_state *dst, 1456 const struct bpf_func_state *src) 1457 { 1458 int err; 1459 1460 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 1461 err = copy_reference_state(dst, src); 1462 if (err) 1463 return err; 1464 return copy_stack_state(dst, src); 1465 } 1466 1467 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1468 const struct bpf_verifier_state *src) 1469 { 1470 struct bpf_func_state *dst; 1471 int i, err; 1472 1473 /* if dst has more stack frames then src frame, free them, this is also 1474 * necessary in case of exceptional exits using bpf_throw. 1475 */ 1476 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1477 free_func_state(dst_state->frame[i]); 1478 dst_state->frame[i] = NULL; 1479 } 1480 dst_state->speculative = src->speculative; 1481 dst_state->active_rcu_lock = src->active_rcu_lock; 1482 dst_state->active_preempt_lock = src->active_preempt_lock; 1483 dst_state->in_sleepable = src->in_sleepable; 1484 dst_state->curframe = src->curframe; 1485 dst_state->branches = src->branches; 1486 dst_state->parent = src->parent; 1487 dst_state->first_insn_idx = src->first_insn_idx; 1488 dst_state->last_insn_idx = src->last_insn_idx; 1489 dst_state->insn_hist_start = src->insn_hist_start; 1490 dst_state->insn_hist_end = src->insn_hist_end; 1491 dst_state->dfs_depth = src->dfs_depth; 1492 dst_state->callback_unroll_depth = src->callback_unroll_depth; 1493 dst_state->used_as_loop_entry = src->used_as_loop_entry; 1494 dst_state->may_goto_depth = src->may_goto_depth; 1495 for (i = 0; i <= src->curframe; i++) { 1496 dst = dst_state->frame[i]; 1497 if (!dst) { 1498 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1499 if (!dst) 1500 return -ENOMEM; 1501 dst_state->frame[i] = dst; 1502 } 1503 err = copy_func_state(dst, src->frame[i]); 1504 if (err) 1505 return err; 1506 } 1507 return 0; 1508 } 1509 1510 static u32 state_htab_size(struct bpf_verifier_env *env) 1511 { 1512 return env->prog->len; 1513 } 1514 1515 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx) 1516 { 1517 struct bpf_verifier_state *cur = env->cur_state; 1518 struct bpf_func_state *state = cur->frame[cur->curframe]; 1519 1520 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 1521 } 1522 1523 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b) 1524 { 1525 int fr; 1526 1527 if (a->curframe != b->curframe) 1528 return false; 1529 1530 for (fr = a->curframe; fr >= 0; fr--) 1531 if (a->frame[fr]->callsite != b->frame[fr]->callsite) 1532 return false; 1533 1534 return true; 1535 } 1536 1537 /* Open coded iterators allow back-edges in the state graph in order to 1538 * check unbounded loops that iterators. 1539 * 1540 * In is_state_visited() it is necessary to know if explored states are 1541 * part of some loops in order to decide whether non-exact states 1542 * comparison could be used: 1543 * - non-exact states comparison establishes sub-state relation and uses 1544 * read and precision marks to do so, these marks are propagated from 1545 * children states and thus are not guaranteed to be final in a loop; 1546 * - exact states comparison just checks if current and explored states 1547 * are identical (and thus form a back-edge). 1548 * 1549 * Paper "A New Algorithm for Identifying Loops in Decompilation" 1550 * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient 1551 * algorithm for loop structure detection and gives an overview of 1552 * relevant terminology. It also has helpful illustrations. 1553 * 1554 * [1] https://api.semanticscholar.org/CorpusID:15784067 1555 * 1556 * We use a similar algorithm but because loop nested structure is 1557 * irrelevant for verifier ours is significantly simpler and resembles 1558 * strongly connected components algorithm from Sedgewick's textbook. 1559 * 1560 * Define topmost loop entry as a first node of the loop traversed in a 1561 * depth first search starting from initial state. The goal of the loop 1562 * tracking algorithm is to associate topmost loop entries with states 1563 * derived from these entries. 1564 * 1565 * For each step in the DFS states traversal algorithm needs to identify 1566 * the following situations: 1567 * 1568 * initial initial initial 1569 * | | | 1570 * V V V 1571 * ... ... .---------> hdr 1572 * | | | | 1573 * V V | V 1574 * cur .-> succ | .------... 1575 * | | | | | | 1576 * V | V | V V 1577 * succ '-- cur | ... ... 1578 * | | | 1579 * | V V 1580 * | succ <- cur 1581 * | | 1582 * | V 1583 * | ... 1584 * | | 1585 * '----' 1586 * 1587 * (A) successor state of cur (B) successor state of cur or it's entry 1588 * not yet traversed are in current DFS path, thus cur and succ 1589 * are members of the same outermost loop 1590 * 1591 * initial initial 1592 * | | 1593 * V V 1594 * ... ... 1595 * | | 1596 * V V 1597 * .------... .------... 1598 * | | | | 1599 * V V V V 1600 * .-> hdr ... ... ... 1601 * | | | | | 1602 * | V V V V 1603 * | succ <- cur succ <- cur 1604 * | | | 1605 * | V V 1606 * | ... ... 1607 * | | | 1608 * '----' exit 1609 * 1610 * (C) successor state of cur is a part of some loop but this loop 1611 * does not include cur or successor state is not in a loop at all. 1612 * 1613 * Algorithm could be described as the following python code: 1614 * 1615 * traversed = set() # Set of traversed nodes 1616 * entries = {} # Mapping from node to loop entry 1617 * depths = {} # Depth level assigned to graph node 1618 * path = set() # Current DFS path 1619 * 1620 * # Find outermost loop entry known for n 1621 * def get_loop_entry(n): 1622 * h = entries.get(n, None) 1623 * while h in entries and entries[h] != h: 1624 * h = entries[h] 1625 * return h 1626 * 1627 * # Update n's loop entry if h's outermost entry comes 1628 * # before n's outermost entry in current DFS path. 1629 * def update_loop_entry(n, h): 1630 * n1 = get_loop_entry(n) or n 1631 * h1 = get_loop_entry(h) or h 1632 * if h1 in path and depths[h1] <= depths[n1]: 1633 * entries[n] = h1 1634 * 1635 * def dfs(n, depth): 1636 * traversed.add(n) 1637 * path.add(n) 1638 * depths[n] = depth 1639 * for succ in G.successors(n): 1640 * if succ not in traversed: 1641 * # Case A: explore succ and update cur's loop entry 1642 * # only if succ's entry is in current DFS path. 1643 * dfs(succ, depth + 1) 1644 * h = get_loop_entry(succ) 1645 * update_loop_entry(n, h) 1646 * else: 1647 * # Case B or C depending on `h1 in path` check in update_loop_entry(). 1648 * update_loop_entry(n, succ) 1649 * path.remove(n) 1650 * 1651 * To adapt this algorithm for use with verifier: 1652 * - use st->branch == 0 as a signal that DFS of succ had been finished 1653 * and cur's loop entry has to be updated (case A), handle this in 1654 * update_branch_counts(); 1655 * - use st->branch > 0 as a signal that st is in the current DFS path; 1656 * - handle cases B and C in is_state_visited(); 1657 * - update topmost loop entry for intermediate states in get_loop_entry(). 1658 */ 1659 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st) 1660 { 1661 struct bpf_verifier_state *topmost = st->loop_entry, *old; 1662 1663 while (topmost && topmost->loop_entry && topmost != topmost->loop_entry) 1664 topmost = topmost->loop_entry; 1665 /* Update loop entries for intermediate states to avoid this 1666 * traversal in future get_loop_entry() calls. 1667 */ 1668 while (st && st->loop_entry != topmost) { 1669 old = st->loop_entry; 1670 st->loop_entry = topmost; 1671 st = old; 1672 } 1673 return topmost; 1674 } 1675 1676 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr) 1677 { 1678 struct bpf_verifier_state *cur1, *hdr1; 1679 1680 cur1 = get_loop_entry(cur) ?: cur; 1681 hdr1 = get_loop_entry(hdr) ?: hdr; 1682 /* The head1->branches check decides between cases B and C in 1683 * comment for get_loop_entry(). If hdr1->branches == 0 then 1684 * head's topmost loop entry is not in current DFS path, 1685 * hence 'cur' and 'hdr' are not in the same loop and there is 1686 * no need to update cur->loop_entry. 1687 */ 1688 if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) { 1689 cur->loop_entry = hdr; 1690 hdr->used_as_loop_entry = true; 1691 } 1692 } 1693 1694 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1695 { 1696 while (st) { 1697 u32 br = --st->branches; 1698 1699 /* br == 0 signals that DFS exploration for 'st' is finished, 1700 * thus it is necessary to update parent's loop entry if it 1701 * turned out that st is a part of some loop. 1702 * This is a part of 'case A' in get_loop_entry() comment. 1703 */ 1704 if (br == 0 && st->parent && st->loop_entry) 1705 update_loop_entry(st->parent, st->loop_entry); 1706 1707 /* WARN_ON(br > 1) technically makes sense here, 1708 * but see comment in push_stack(), hence: 1709 */ 1710 WARN_ONCE((int)br < 0, 1711 "BUG update_branch_counts:branches_to_explore=%d\n", 1712 br); 1713 if (br) 1714 break; 1715 st = st->parent; 1716 } 1717 } 1718 1719 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1720 int *insn_idx, bool pop_log) 1721 { 1722 struct bpf_verifier_state *cur = env->cur_state; 1723 struct bpf_verifier_stack_elem *elem, *head = env->head; 1724 int err; 1725 1726 if (env->head == NULL) 1727 return -ENOENT; 1728 1729 if (cur) { 1730 err = copy_verifier_state(cur, &head->st); 1731 if (err) 1732 return err; 1733 } 1734 if (pop_log) 1735 bpf_vlog_reset(&env->log, head->log_pos); 1736 if (insn_idx) 1737 *insn_idx = head->insn_idx; 1738 if (prev_insn_idx) 1739 *prev_insn_idx = head->prev_insn_idx; 1740 elem = head->next; 1741 free_verifier_state(&head->st, false); 1742 kfree(head); 1743 env->head = elem; 1744 env->stack_size--; 1745 return 0; 1746 } 1747 1748 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1749 int insn_idx, int prev_insn_idx, 1750 bool speculative) 1751 { 1752 struct bpf_verifier_state *cur = env->cur_state; 1753 struct bpf_verifier_stack_elem *elem; 1754 int err; 1755 1756 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1757 if (!elem) 1758 goto err; 1759 1760 elem->insn_idx = insn_idx; 1761 elem->prev_insn_idx = prev_insn_idx; 1762 elem->next = env->head; 1763 elem->log_pos = env->log.end_pos; 1764 env->head = elem; 1765 env->stack_size++; 1766 err = copy_verifier_state(&elem->st, cur); 1767 if (err) 1768 goto err; 1769 elem->st.speculative |= speculative; 1770 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1771 verbose(env, "The sequence of %d jumps is too complex.\n", 1772 env->stack_size); 1773 goto err; 1774 } 1775 if (elem->st.parent) { 1776 ++elem->st.parent->branches; 1777 /* WARN_ON(branches > 2) technically makes sense here, 1778 * but 1779 * 1. speculative states will bump 'branches' for non-branch 1780 * instructions 1781 * 2. is_state_visited() heuristics may decide not to create 1782 * a new state for a sequence of branches and all such current 1783 * and cloned states will be pointing to a single parent state 1784 * which might have large 'branches' count. 1785 */ 1786 } 1787 return &elem->st; 1788 err: 1789 free_verifier_state(env->cur_state, true); 1790 env->cur_state = NULL; 1791 /* pop all elements and return */ 1792 while (!pop_stack(env, NULL, NULL, false)); 1793 return NULL; 1794 } 1795 1796 #define CALLER_SAVED_REGS 6 1797 static const int caller_saved[CALLER_SAVED_REGS] = { 1798 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1799 }; 1800 1801 /* This helper doesn't clear reg->id */ 1802 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1803 { 1804 reg->var_off = tnum_const(imm); 1805 reg->smin_value = (s64)imm; 1806 reg->smax_value = (s64)imm; 1807 reg->umin_value = imm; 1808 reg->umax_value = imm; 1809 1810 reg->s32_min_value = (s32)imm; 1811 reg->s32_max_value = (s32)imm; 1812 reg->u32_min_value = (u32)imm; 1813 reg->u32_max_value = (u32)imm; 1814 } 1815 1816 /* Mark the unknown part of a register (variable offset or scalar value) as 1817 * known to have the value @imm. 1818 */ 1819 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1820 { 1821 /* Clear off and union(map_ptr, range) */ 1822 memset(((u8 *)reg) + sizeof(reg->type), 0, 1823 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1824 reg->id = 0; 1825 reg->ref_obj_id = 0; 1826 ___mark_reg_known(reg, imm); 1827 } 1828 1829 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1830 { 1831 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1832 reg->s32_min_value = (s32)imm; 1833 reg->s32_max_value = (s32)imm; 1834 reg->u32_min_value = (u32)imm; 1835 reg->u32_max_value = (u32)imm; 1836 } 1837 1838 /* Mark the 'variable offset' part of a register as zero. This should be 1839 * used only on registers holding a pointer type. 1840 */ 1841 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1842 { 1843 __mark_reg_known(reg, 0); 1844 } 1845 1846 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1847 { 1848 __mark_reg_known(reg, 0); 1849 reg->type = SCALAR_VALUE; 1850 /* all scalars are assumed imprecise initially (unless unprivileged, 1851 * in which case everything is forced to be precise) 1852 */ 1853 reg->precise = !env->bpf_capable; 1854 } 1855 1856 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1857 struct bpf_reg_state *regs, u32 regno) 1858 { 1859 if (WARN_ON(regno >= MAX_BPF_REG)) { 1860 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1861 /* Something bad happened, let's kill all regs */ 1862 for (regno = 0; regno < MAX_BPF_REG; regno++) 1863 __mark_reg_not_init(env, regs + regno); 1864 return; 1865 } 1866 __mark_reg_known_zero(regs + regno); 1867 } 1868 1869 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1870 bool first_slot, int dynptr_id) 1871 { 1872 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1873 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1874 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1875 */ 1876 __mark_reg_known_zero(reg); 1877 reg->type = CONST_PTR_TO_DYNPTR; 1878 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1879 reg->id = dynptr_id; 1880 reg->dynptr.type = type; 1881 reg->dynptr.first_slot = first_slot; 1882 } 1883 1884 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1885 { 1886 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1887 const struct bpf_map *map = reg->map_ptr; 1888 1889 if (map->inner_map_meta) { 1890 reg->type = CONST_PTR_TO_MAP; 1891 reg->map_ptr = map->inner_map_meta; 1892 /* transfer reg's id which is unique for every map_lookup_elem 1893 * as UID of the inner map. 1894 */ 1895 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 1896 reg->map_uid = reg->id; 1897 if (btf_record_has_field(map->inner_map_meta->record, BPF_WORKQUEUE)) 1898 reg->map_uid = reg->id; 1899 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1900 reg->type = PTR_TO_XDP_SOCK; 1901 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1902 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1903 reg->type = PTR_TO_SOCKET; 1904 } else { 1905 reg->type = PTR_TO_MAP_VALUE; 1906 } 1907 return; 1908 } 1909 1910 reg->type &= ~PTR_MAYBE_NULL; 1911 } 1912 1913 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 1914 struct btf_field_graph_root *ds_head) 1915 { 1916 __mark_reg_known_zero(®s[regno]); 1917 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 1918 regs[regno].btf = ds_head->btf; 1919 regs[regno].btf_id = ds_head->value_btf_id; 1920 regs[regno].off = ds_head->node_offset; 1921 } 1922 1923 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1924 { 1925 return type_is_pkt_pointer(reg->type); 1926 } 1927 1928 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1929 { 1930 return reg_is_pkt_pointer(reg) || 1931 reg->type == PTR_TO_PACKET_END; 1932 } 1933 1934 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 1935 { 1936 return base_type(reg->type) == PTR_TO_MEM && 1937 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP); 1938 } 1939 1940 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1941 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1942 enum bpf_reg_type which) 1943 { 1944 /* The register can already have a range from prior markings. 1945 * This is fine as long as it hasn't been advanced from its 1946 * origin. 1947 */ 1948 return reg->type == which && 1949 reg->id == 0 && 1950 reg->off == 0 && 1951 tnum_equals_const(reg->var_off, 0); 1952 } 1953 1954 /* Reset the min/max bounds of a register */ 1955 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1956 { 1957 reg->smin_value = S64_MIN; 1958 reg->smax_value = S64_MAX; 1959 reg->umin_value = 0; 1960 reg->umax_value = U64_MAX; 1961 1962 reg->s32_min_value = S32_MIN; 1963 reg->s32_max_value = S32_MAX; 1964 reg->u32_min_value = 0; 1965 reg->u32_max_value = U32_MAX; 1966 } 1967 1968 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1969 { 1970 reg->smin_value = S64_MIN; 1971 reg->smax_value = S64_MAX; 1972 reg->umin_value = 0; 1973 reg->umax_value = U64_MAX; 1974 } 1975 1976 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1977 { 1978 reg->s32_min_value = S32_MIN; 1979 reg->s32_max_value = S32_MAX; 1980 reg->u32_min_value = 0; 1981 reg->u32_max_value = U32_MAX; 1982 } 1983 1984 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1985 { 1986 struct tnum var32_off = tnum_subreg(reg->var_off); 1987 1988 /* min signed is max(sign bit) | min(other bits) */ 1989 reg->s32_min_value = max_t(s32, reg->s32_min_value, 1990 var32_off.value | (var32_off.mask & S32_MIN)); 1991 /* max signed is min(sign bit) | max(other bits) */ 1992 reg->s32_max_value = min_t(s32, reg->s32_max_value, 1993 var32_off.value | (var32_off.mask & S32_MAX)); 1994 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 1995 reg->u32_max_value = min(reg->u32_max_value, 1996 (u32)(var32_off.value | var32_off.mask)); 1997 } 1998 1999 static void __update_reg64_bounds(struct bpf_reg_state *reg) 2000 { 2001 /* min signed is max(sign bit) | min(other bits) */ 2002 reg->smin_value = max_t(s64, reg->smin_value, 2003 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 2004 /* max signed is min(sign bit) | max(other bits) */ 2005 reg->smax_value = min_t(s64, reg->smax_value, 2006 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 2007 reg->umin_value = max(reg->umin_value, reg->var_off.value); 2008 reg->umax_value = min(reg->umax_value, 2009 reg->var_off.value | reg->var_off.mask); 2010 } 2011 2012 static void __update_reg_bounds(struct bpf_reg_state *reg) 2013 { 2014 __update_reg32_bounds(reg); 2015 __update_reg64_bounds(reg); 2016 } 2017 2018 /* Uses signed min/max values to inform unsigned, and vice-versa */ 2019 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 2020 { 2021 /* If upper 32 bits of u64/s64 range don't change, we can use lower 32 2022 * bits to improve our u32/s32 boundaries. 2023 * 2024 * E.g., the case where we have upper 32 bits as zero ([10, 20] in 2025 * u64) is pretty trivial, it's obvious that in u32 we'll also have 2026 * [10, 20] range. But this property holds for any 64-bit range as 2027 * long as upper 32 bits in that entire range of values stay the same. 2028 * 2029 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311] 2030 * in decimal) has the same upper 32 bits throughout all the values in 2031 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15]) 2032 * range. 2033 * 2034 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32, 2035 * following the rules outlined below about u64/s64 correspondence 2036 * (which equally applies to u32 vs s32 correspondence). In general it 2037 * depends on actual hexadecimal values of 32-bit range. They can form 2038 * only valid u32, or only valid s32 ranges in some cases. 2039 * 2040 * So we use all these insights to derive bounds for subregisters here. 2041 */ 2042 if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) { 2043 /* u64 to u32 casting preserves validity of low 32 bits as 2044 * a range, if upper 32 bits are the same 2045 */ 2046 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value); 2047 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value); 2048 2049 if ((s32)reg->umin_value <= (s32)reg->umax_value) { 2050 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 2051 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 2052 } 2053 } 2054 if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) { 2055 /* low 32 bits should form a proper u32 range */ 2056 if ((u32)reg->smin_value <= (u32)reg->smax_value) { 2057 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value); 2058 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value); 2059 } 2060 /* low 32 bits should form a proper s32 range */ 2061 if ((s32)reg->smin_value <= (s32)reg->smax_value) { 2062 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 2063 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 2064 } 2065 } 2066 /* Special case where upper bits form a small sequence of two 2067 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to 2068 * 0x00000000 is also valid), while lower bits form a proper s32 range 2069 * going from negative numbers to positive numbers. E.g., let's say we 2070 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]). 2071 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff, 2072 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits, 2073 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]). 2074 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in 2075 * upper 32 bits. As a random example, s64 range 2076 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range 2077 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister. 2078 */ 2079 if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) && 2080 (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) { 2081 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 2082 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 2083 } 2084 if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) && 2085 (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) { 2086 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 2087 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 2088 } 2089 /* if u32 range forms a valid s32 range (due to matching sign bit), 2090 * try to learn from that 2091 */ 2092 if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) { 2093 reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value); 2094 reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value); 2095 } 2096 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2097 * are the same, so combine. This works even in the negative case, e.g. 2098 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2099 */ 2100 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2101 reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value); 2102 reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value); 2103 } 2104 } 2105 2106 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 2107 { 2108 /* If u64 range forms a valid s64 range (due to matching sign bit), 2109 * try to learn from that. Let's do a bit of ASCII art to see when 2110 * this is happening. Let's take u64 range first: 2111 * 2112 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2113 * |-------------------------------|--------------------------------| 2114 * 2115 * Valid u64 range is formed when umin and umax are anywhere in the 2116 * range [0, U64_MAX], and umin <= umax. u64 case is simple and 2117 * straightforward. Let's see how s64 range maps onto the same range 2118 * of values, annotated below the line for comparison: 2119 * 2120 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2121 * |-------------------------------|--------------------------------| 2122 * 0 S64_MAX S64_MIN -1 2123 * 2124 * So s64 values basically start in the middle and they are logically 2125 * contiguous to the right of it, wrapping around from -1 to 0, and 2126 * then finishing as S64_MAX (0x7fffffffffffffff) right before 2127 * S64_MIN. We can try drawing the continuity of u64 vs s64 values 2128 * more visually as mapped to sign-agnostic range of hex values. 2129 * 2130 * u64 start u64 end 2131 * _______________________________________________________________ 2132 * / \ 2133 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2134 * |-------------------------------|--------------------------------| 2135 * 0 S64_MAX S64_MIN -1 2136 * / \ 2137 * >------------------------------ -------------------------------> 2138 * s64 continues... s64 end s64 start s64 "midpoint" 2139 * 2140 * What this means is that, in general, we can't always derive 2141 * something new about u64 from any random s64 range, and vice versa. 2142 * 2143 * But we can do that in two particular cases. One is when entire 2144 * u64/s64 range is *entirely* contained within left half of the above 2145 * diagram or when it is *entirely* contained in the right half. I.e.: 2146 * 2147 * |-------------------------------|--------------------------------| 2148 * ^ ^ ^ ^ 2149 * A B C D 2150 * 2151 * [A, B] and [C, D] are contained entirely in their respective halves 2152 * and form valid contiguous ranges as both u64 and s64 values. [A, B] 2153 * will be non-negative both as u64 and s64 (and in fact it will be 2154 * identical ranges no matter the signedness). [C, D] treated as s64 2155 * will be a range of negative values, while in u64 it will be 2156 * non-negative range of values larger than 0x8000000000000000. 2157 * 2158 * Now, any other range here can't be represented in both u64 and s64 2159 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid 2160 * contiguous u64 ranges, but they are discontinuous in s64. [B, C] 2161 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX], 2162 * for example. Similarly, valid s64 range [D, A] (going from negative 2163 * to positive values), would be two separate [D, U64_MAX] and [0, A] 2164 * ranges as u64. Currently reg_state can't represent two segments per 2165 * numeric domain, so in such situations we can only derive maximal 2166 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64). 2167 * 2168 * So we use these facts to derive umin/umax from smin/smax and vice 2169 * versa only if they stay within the same "half". This is equivalent 2170 * to checking sign bit: lower half will have sign bit as zero, upper 2171 * half have sign bit 1. Below in code we simplify this by just 2172 * casting umin/umax as smin/smax and checking if they form valid 2173 * range, and vice versa. Those are equivalent checks. 2174 */ 2175 if ((s64)reg->umin_value <= (s64)reg->umax_value) { 2176 reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value); 2177 reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value); 2178 } 2179 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2180 * are the same, so combine. This works even in the negative case, e.g. 2181 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2182 */ 2183 if ((u64)reg->smin_value <= (u64)reg->smax_value) { 2184 reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); 2185 reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); 2186 } 2187 } 2188 2189 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg) 2190 { 2191 /* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit 2192 * values on both sides of 64-bit range in hope to have tighter range. 2193 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from 2194 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff]. 2195 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound 2196 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of 2197 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a 2198 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff]. 2199 * We just need to make sure that derived bounds we are intersecting 2200 * with are well-formed ranges in respective s64 or u64 domain, just 2201 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments. 2202 */ 2203 __u64 new_umin, new_umax; 2204 __s64 new_smin, new_smax; 2205 2206 /* u32 -> u64 tightening, it's always well-formed */ 2207 new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value; 2208 new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value; 2209 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2210 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2211 /* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */ 2212 new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value; 2213 new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value; 2214 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2215 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2216 2217 /* if s32 can be treated as valid u32 range, we can use it as well */ 2218 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2219 /* s32 -> u64 tightening */ 2220 new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value; 2221 new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value; 2222 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2223 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2224 /* s32 -> s64 tightening */ 2225 new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value; 2226 new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value; 2227 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2228 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2229 } 2230 2231 /* Here we would like to handle a special case after sign extending load, 2232 * when upper bits for a 64-bit range are all 1s or all 0s. 2233 * 2234 * Upper bits are all 1s when register is in a range: 2235 * [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff] 2236 * Upper bits are all 0s when register is in a range: 2237 * [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff] 2238 * Together this forms are continuous range: 2239 * [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff] 2240 * 2241 * Now, suppose that register range is in fact tighter: 2242 * [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R) 2243 * Also suppose that it's 32-bit range is positive, 2244 * meaning that lower 32-bits of the full 64-bit register 2245 * are in the range: 2246 * [0x0000_0000, 0x7fff_ffff] (W) 2247 * 2248 * If this happens, then any value in a range: 2249 * [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff] 2250 * is smaller than a lowest bound of the range (R): 2251 * 0xffff_ffff_8000_0000 2252 * which means that upper bits of the full 64-bit register 2253 * can't be all 1s, when lower bits are in range (W). 2254 * 2255 * Note that: 2256 * - 0xffff_ffff_8000_0000 == (s64)S32_MIN 2257 * - 0x0000_0000_7fff_ffff == (s64)S32_MAX 2258 * These relations are used in the conditions below. 2259 */ 2260 if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) { 2261 reg->smin_value = reg->s32_min_value; 2262 reg->smax_value = reg->s32_max_value; 2263 reg->umin_value = reg->s32_min_value; 2264 reg->umax_value = reg->s32_max_value; 2265 reg->var_off = tnum_intersect(reg->var_off, 2266 tnum_range(reg->smin_value, reg->smax_value)); 2267 } 2268 } 2269 2270 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2271 { 2272 __reg32_deduce_bounds(reg); 2273 __reg64_deduce_bounds(reg); 2274 __reg_deduce_mixed_bounds(reg); 2275 } 2276 2277 /* Attempts to improve var_off based on unsigned min/max information */ 2278 static void __reg_bound_offset(struct bpf_reg_state *reg) 2279 { 2280 struct tnum var64_off = tnum_intersect(reg->var_off, 2281 tnum_range(reg->umin_value, 2282 reg->umax_value)); 2283 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2284 tnum_range(reg->u32_min_value, 2285 reg->u32_max_value)); 2286 2287 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2288 } 2289 2290 static void reg_bounds_sync(struct bpf_reg_state *reg) 2291 { 2292 /* We might have learned new bounds from the var_off. */ 2293 __update_reg_bounds(reg); 2294 /* We might have learned something about the sign bit. */ 2295 __reg_deduce_bounds(reg); 2296 __reg_deduce_bounds(reg); 2297 /* We might have learned some bits from the bounds. */ 2298 __reg_bound_offset(reg); 2299 /* Intersecting with the old var_off might have improved our bounds 2300 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2301 * then new var_off is (0; 0x7f...fc) which improves our umax. 2302 */ 2303 __update_reg_bounds(reg); 2304 } 2305 2306 static int reg_bounds_sanity_check(struct bpf_verifier_env *env, 2307 struct bpf_reg_state *reg, const char *ctx) 2308 { 2309 const char *msg; 2310 2311 if (reg->umin_value > reg->umax_value || 2312 reg->smin_value > reg->smax_value || 2313 reg->u32_min_value > reg->u32_max_value || 2314 reg->s32_min_value > reg->s32_max_value) { 2315 msg = "range bounds violation"; 2316 goto out; 2317 } 2318 2319 if (tnum_is_const(reg->var_off)) { 2320 u64 uval = reg->var_off.value; 2321 s64 sval = (s64)uval; 2322 2323 if (reg->umin_value != uval || reg->umax_value != uval || 2324 reg->smin_value != sval || reg->smax_value != sval) { 2325 msg = "const tnum out of sync with range bounds"; 2326 goto out; 2327 } 2328 } 2329 2330 if (tnum_subreg_is_const(reg->var_off)) { 2331 u32 uval32 = tnum_subreg(reg->var_off).value; 2332 s32 sval32 = (s32)uval32; 2333 2334 if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 || 2335 reg->s32_min_value != sval32 || reg->s32_max_value != sval32) { 2336 msg = "const subreg tnum out of sync with range bounds"; 2337 goto out; 2338 } 2339 } 2340 2341 return 0; 2342 out: 2343 verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] " 2344 "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n", 2345 ctx, msg, reg->umin_value, reg->umax_value, 2346 reg->smin_value, reg->smax_value, 2347 reg->u32_min_value, reg->u32_max_value, 2348 reg->s32_min_value, reg->s32_max_value, 2349 reg->var_off.value, reg->var_off.mask); 2350 if (env->test_reg_invariants) 2351 return -EFAULT; 2352 __mark_reg_unbounded(reg); 2353 return 0; 2354 } 2355 2356 static bool __reg32_bound_s64(s32 a) 2357 { 2358 return a >= 0 && a <= S32_MAX; 2359 } 2360 2361 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 2362 { 2363 reg->umin_value = reg->u32_min_value; 2364 reg->umax_value = reg->u32_max_value; 2365 2366 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 2367 * be positive otherwise set to worse case bounds and refine later 2368 * from tnum. 2369 */ 2370 if (__reg32_bound_s64(reg->s32_min_value) && 2371 __reg32_bound_s64(reg->s32_max_value)) { 2372 reg->smin_value = reg->s32_min_value; 2373 reg->smax_value = reg->s32_max_value; 2374 } else { 2375 reg->smin_value = 0; 2376 reg->smax_value = U32_MAX; 2377 } 2378 } 2379 2380 /* Mark a register as having a completely unknown (scalar) value. */ 2381 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg) 2382 { 2383 /* 2384 * Clear type, off, and union(map_ptr, range) and 2385 * padding between 'type' and union 2386 */ 2387 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2388 reg->type = SCALAR_VALUE; 2389 reg->id = 0; 2390 reg->ref_obj_id = 0; 2391 reg->var_off = tnum_unknown; 2392 reg->frameno = 0; 2393 reg->precise = false; 2394 __mark_reg_unbounded(reg); 2395 } 2396 2397 /* Mark a register as having a completely unknown (scalar) value, 2398 * initialize .precise as true when not bpf capable. 2399 */ 2400 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2401 struct bpf_reg_state *reg) 2402 { 2403 __mark_reg_unknown_imprecise(reg); 2404 reg->precise = !env->bpf_capable; 2405 } 2406 2407 static void mark_reg_unknown(struct bpf_verifier_env *env, 2408 struct bpf_reg_state *regs, u32 regno) 2409 { 2410 if (WARN_ON(regno >= MAX_BPF_REG)) { 2411 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 2412 /* Something bad happened, let's kill all regs except FP */ 2413 for (regno = 0; regno < BPF_REG_FP; regno++) 2414 __mark_reg_not_init(env, regs + regno); 2415 return; 2416 } 2417 __mark_reg_unknown(env, regs + regno); 2418 } 2419 2420 static int __mark_reg_s32_range(struct bpf_verifier_env *env, 2421 struct bpf_reg_state *regs, 2422 u32 regno, 2423 s32 s32_min, 2424 s32 s32_max) 2425 { 2426 struct bpf_reg_state *reg = regs + regno; 2427 2428 reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min); 2429 reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max); 2430 2431 reg->smin_value = max_t(s64, reg->smin_value, s32_min); 2432 reg->smax_value = min_t(s64, reg->smax_value, s32_max); 2433 2434 reg_bounds_sync(reg); 2435 2436 return reg_bounds_sanity_check(env, reg, "s32_range"); 2437 } 2438 2439 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 2440 struct bpf_reg_state *reg) 2441 { 2442 __mark_reg_unknown(env, reg); 2443 reg->type = NOT_INIT; 2444 } 2445 2446 static void mark_reg_not_init(struct bpf_verifier_env *env, 2447 struct bpf_reg_state *regs, u32 regno) 2448 { 2449 if (WARN_ON(regno >= MAX_BPF_REG)) { 2450 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 2451 /* Something bad happened, let's kill all regs except FP */ 2452 for (regno = 0; regno < BPF_REG_FP; regno++) 2453 __mark_reg_not_init(env, regs + regno); 2454 return; 2455 } 2456 __mark_reg_not_init(env, regs + regno); 2457 } 2458 2459 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 2460 struct bpf_reg_state *regs, u32 regno, 2461 enum bpf_reg_type reg_type, 2462 struct btf *btf, u32 btf_id, 2463 enum bpf_type_flag flag) 2464 { 2465 if (reg_type == SCALAR_VALUE) { 2466 mark_reg_unknown(env, regs, regno); 2467 return; 2468 } 2469 mark_reg_known_zero(env, regs, regno); 2470 regs[regno].type = PTR_TO_BTF_ID | flag; 2471 regs[regno].btf = btf; 2472 regs[regno].btf_id = btf_id; 2473 if (type_may_be_null(flag)) 2474 regs[regno].id = ++env->id_gen; 2475 } 2476 2477 #define DEF_NOT_SUBREG (0) 2478 static void init_reg_state(struct bpf_verifier_env *env, 2479 struct bpf_func_state *state) 2480 { 2481 struct bpf_reg_state *regs = state->regs; 2482 int i; 2483 2484 for (i = 0; i < MAX_BPF_REG; i++) { 2485 mark_reg_not_init(env, regs, i); 2486 regs[i].live = REG_LIVE_NONE; 2487 regs[i].parent = NULL; 2488 regs[i].subreg_def = DEF_NOT_SUBREG; 2489 } 2490 2491 /* frame pointer */ 2492 regs[BPF_REG_FP].type = PTR_TO_STACK; 2493 mark_reg_known_zero(env, regs, BPF_REG_FP); 2494 regs[BPF_REG_FP].frameno = state->frameno; 2495 } 2496 2497 static struct bpf_retval_range retval_range(s32 minval, s32 maxval) 2498 { 2499 return (struct bpf_retval_range){ minval, maxval }; 2500 } 2501 2502 #define BPF_MAIN_FUNC (-1) 2503 static void init_func_state(struct bpf_verifier_env *env, 2504 struct bpf_func_state *state, 2505 int callsite, int frameno, int subprogno) 2506 { 2507 state->callsite = callsite; 2508 state->frameno = frameno; 2509 state->subprogno = subprogno; 2510 state->callback_ret_range = retval_range(0, 0); 2511 init_reg_state(env, state); 2512 mark_verifier_state_scratched(env); 2513 } 2514 2515 /* Similar to push_stack(), but for async callbacks */ 2516 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2517 int insn_idx, int prev_insn_idx, 2518 int subprog, bool is_sleepable) 2519 { 2520 struct bpf_verifier_stack_elem *elem; 2521 struct bpf_func_state *frame; 2522 2523 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2524 if (!elem) 2525 goto err; 2526 2527 elem->insn_idx = insn_idx; 2528 elem->prev_insn_idx = prev_insn_idx; 2529 elem->next = env->head; 2530 elem->log_pos = env->log.end_pos; 2531 env->head = elem; 2532 env->stack_size++; 2533 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2534 verbose(env, 2535 "The sequence of %d jumps is too complex for async cb.\n", 2536 env->stack_size); 2537 goto err; 2538 } 2539 /* Unlike push_stack() do not copy_verifier_state(). 2540 * The caller state doesn't matter. 2541 * This is async callback. It starts in a fresh stack. 2542 * Initialize it similar to do_check_common(). 2543 * But we do need to make sure to not clobber insn_hist, so we keep 2544 * chaining insn_hist_start/insn_hist_end indices as for a normal 2545 * child state. 2546 */ 2547 elem->st.branches = 1; 2548 elem->st.in_sleepable = is_sleepable; 2549 elem->st.insn_hist_start = env->cur_state->insn_hist_end; 2550 elem->st.insn_hist_end = elem->st.insn_hist_start; 2551 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 2552 if (!frame) 2553 goto err; 2554 init_func_state(env, frame, 2555 BPF_MAIN_FUNC /* callsite */, 2556 0 /* frameno within this callchain */, 2557 subprog /* subprog number within this prog */); 2558 elem->st.frame[0] = frame; 2559 return &elem->st; 2560 err: 2561 free_verifier_state(env->cur_state, true); 2562 env->cur_state = NULL; 2563 /* pop all elements and return */ 2564 while (!pop_stack(env, NULL, NULL, false)); 2565 return NULL; 2566 } 2567 2568 2569 enum reg_arg_type { 2570 SRC_OP, /* register is used as source operand */ 2571 DST_OP, /* register is used as destination operand */ 2572 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2573 }; 2574 2575 static int cmp_subprogs(const void *a, const void *b) 2576 { 2577 return ((struct bpf_subprog_info *)a)->start - 2578 ((struct bpf_subprog_info *)b)->start; 2579 } 2580 2581 /* Find subprogram that contains instruction at 'off' */ 2582 static struct bpf_subprog_info *find_containing_subprog(struct bpf_verifier_env *env, int off) 2583 { 2584 struct bpf_subprog_info *vals = env->subprog_info; 2585 int l, r, m; 2586 2587 if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0) 2588 return NULL; 2589 2590 l = 0; 2591 r = env->subprog_cnt - 1; 2592 while (l < r) { 2593 m = l + (r - l + 1) / 2; 2594 if (vals[m].start <= off) 2595 l = m; 2596 else 2597 r = m - 1; 2598 } 2599 return &vals[l]; 2600 } 2601 2602 /* Find subprogram that starts exactly at 'off' */ 2603 static int find_subprog(struct bpf_verifier_env *env, int off) 2604 { 2605 struct bpf_subprog_info *p; 2606 2607 p = find_containing_subprog(env, off); 2608 if (!p || p->start != off) 2609 return -ENOENT; 2610 return p - env->subprog_info; 2611 } 2612 2613 static int add_subprog(struct bpf_verifier_env *env, int off) 2614 { 2615 int insn_cnt = env->prog->len; 2616 int ret; 2617 2618 if (off >= insn_cnt || off < 0) { 2619 verbose(env, "call to invalid destination\n"); 2620 return -EINVAL; 2621 } 2622 ret = find_subprog(env, off); 2623 if (ret >= 0) 2624 return ret; 2625 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2626 verbose(env, "too many subprograms\n"); 2627 return -E2BIG; 2628 } 2629 /* determine subprog starts. The end is one before the next starts */ 2630 env->subprog_info[env->subprog_cnt++].start = off; 2631 sort(env->subprog_info, env->subprog_cnt, 2632 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2633 return env->subprog_cnt - 1; 2634 } 2635 2636 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env) 2637 { 2638 struct bpf_prog_aux *aux = env->prog->aux; 2639 struct btf *btf = aux->btf; 2640 const struct btf_type *t; 2641 u32 main_btf_id, id; 2642 const char *name; 2643 int ret, i; 2644 2645 /* Non-zero func_info_cnt implies valid btf */ 2646 if (!aux->func_info_cnt) 2647 return 0; 2648 main_btf_id = aux->func_info[0].type_id; 2649 2650 t = btf_type_by_id(btf, main_btf_id); 2651 if (!t) { 2652 verbose(env, "invalid btf id for main subprog in func_info\n"); 2653 return -EINVAL; 2654 } 2655 2656 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:"); 2657 if (IS_ERR(name)) { 2658 ret = PTR_ERR(name); 2659 /* If there is no tag present, there is no exception callback */ 2660 if (ret == -ENOENT) 2661 ret = 0; 2662 else if (ret == -EEXIST) 2663 verbose(env, "multiple exception callback tags for main subprog\n"); 2664 return ret; 2665 } 2666 2667 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC); 2668 if (ret < 0) { 2669 verbose(env, "exception callback '%s' could not be found in BTF\n", name); 2670 return ret; 2671 } 2672 id = ret; 2673 t = btf_type_by_id(btf, id); 2674 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) { 2675 verbose(env, "exception callback '%s' must have global linkage\n", name); 2676 return -EINVAL; 2677 } 2678 ret = 0; 2679 for (i = 0; i < aux->func_info_cnt; i++) { 2680 if (aux->func_info[i].type_id != id) 2681 continue; 2682 ret = aux->func_info[i].insn_off; 2683 /* Further func_info and subprog checks will also happen 2684 * later, so assume this is the right insn_off for now. 2685 */ 2686 if (!ret) { 2687 verbose(env, "invalid exception callback insn_off in func_info: 0\n"); 2688 ret = -EINVAL; 2689 } 2690 } 2691 if (!ret) { 2692 verbose(env, "exception callback type id not found in func_info\n"); 2693 ret = -EINVAL; 2694 } 2695 return ret; 2696 } 2697 2698 #define MAX_KFUNC_DESCS 256 2699 #define MAX_KFUNC_BTFS 256 2700 2701 struct bpf_kfunc_desc { 2702 struct btf_func_model func_model; 2703 u32 func_id; 2704 s32 imm; 2705 u16 offset; 2706 unsigned long addr; 2707 }; 2708 2709 struct bpf_kfunc_btf { 2710 struct btf *btf; 2711 struct module *module; 2712 u16 offset; 2713 }; 2714 2715 struct bpf_kfunc_desc_tab { 2716 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during 2717 * verification. JITs do lookups by bpf_insn, where func_id may not be 2718 * available, therefore at the end of verification do_misc_fixups() 2719 * sorts this by imm and offset. 2720 */ 2721 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 2722 u32 nr_descs; 2723 }; 2724 2725 struct bpf_kfunc_btf_tab { 2726 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2727 u32 nr_descs; 2728 }; 2729 2730 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2731 { 2732 const struct bpf_kfunc_desc *d0 = a; 2733 const struct bpf_kfunc_desc *d1 = b; 2734 2735 /* func_id is not greater than BTF_MAX_TYPE */ 2736 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2737 } 2738 2739 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2740 { 2741 const struct bpf_kfunc_btf *d0 = a; 2742 const struct bpf_kfunc_btf *d1 = b; 2743 2744 return d0->offset - d1->offset; 2745 } 2746 2747 static const struct bpf_kfunc_desc * 2748 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2749 { 2750 struct bpf_kfunc_desc desc = { 2751 .func_id = func_id, 2752 .offset = offset, 2753 }; 2754 struct bpf_kfunc_desc_tab *tab; 2755 2756 tab = prog->aux->kfunc_tab; 2757 return bsearch(&desc, tab->descs, tab->nr_descs, 2758 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2759 } 2760 2761 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2762 u16 btf_fd_idx, u8 **func_addr) 2763 { 2764 const struct bpf_kfunc_desc *desc; 2765 2766 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2767 if (!desc) 2768 return -EFAULT; 2769 2770 *func_addr = (u8 *)desc->addr; 2771 return 0; 2772 } 2773 2774 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2775 s16 offset) 2776 { 2777 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2778 struct bpf_kfunc_btf_tab *tab; 2779 struct bpf_kfunc_btf *b; 2780 struct module *mod; 2781 struct btf *btf; 2782 int btf_fd; 2783 2784 tab = env->prog->aux->kfunc_btf_tab; 2785 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2786 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2787 if (!b) { 2788 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2789 verbose(env, "too many different module BTFs\n"); 2790 return ERR_PTR(-E2BIG); 2791 } 2792 2793 if (bpfptr_is_null(env->fd_array)) { 2794 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2795 return ERR_PTR(-EPROTO); 2796 } 2797 2798 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2799 offset * sizeof(btf_fd), 2800 sizeof(btf_fd))) 2801 return ERR_PTR(-EFAULT); 2802 2803 btf = btf_get_by_fd(btf_fd); 2804 if (IS_ERR(btf)) { 2805 verbose(env, "invalid module BTF fd specified\n"); 2806 return btf; 2807 } 2808 2809 if (!btf_is_module(btf)) { 2810 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2811 btf_put(btf); 2812 return ERR_PTR(-EINVAL); 2813 } 2814 2815 mod = btf_try_get_module(btf); 2816 if (!mod) { 2817 btf_put(btf); 2818 return ERR_PTR(-ENXIO); 2819 } 2820 2821 b = &tab->descs[tab->nr_descs++]; 2822 b->btf = btf; 2823 b->module = mod; 2824 b->offset = offset; 2825 2826 /* sort() reorders entries by value, so b may no longer point 2827 * to the right entry after this 2828 */ 2829 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2830 kfunc_btf_cmp_by_off, NULL); 2831 } else { 2832 btf = b->btf; 2833 } 2834 2835 return btf; 2836 } 2837 2838 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2839 { 2840 if (!tab) 2841 return; 2842 2843 while (tab->nr_descs--) { 2844 module_put(tab->descs[tab->nr_descs].module); 2845 btf_put(tab->descs[tab->nr_descs].btf); 2846 } 2847 kfree(tab); 2848 } 2849 2850 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2851 { 2852 if (offset) { 2853 if (offset < 0) { 2854 /* In the future, this can be allowed to increase limit 2855 * of fd index into fd_array, interpreted as u16. 2856 */ 2857 verbose(env, "negative offset disallowed for kernel module function call\n"); 2858 return ERR_PTR(-EINVAL); 2859 } 2860 2861 return __find_kfunc_desc_btf(env, offset); 2862 } 2863 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2864 } 2865 2866 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 2867 { 2868 const struct btf_type *func, *func_proto; 2869 struct bpf_kfunc_btf_tab *btf_tab; 2870 struct bpf_kfunc_desc_tab *tab; 2871 struct bpf_prog_aux *prog_aux; 2872 struct bpf_kfunc_desc *desc; 2873 const char *func_name; 2874 struct btf *desc_btf; 2875 unsigned long call_imm; 2876 unsigned long addr; 2877 int err; 2878 2879 prog_aux = env->prog->aux; 2880 tab = prog_aux->kfunc_tab; 2881 btf_tab = prog_aux->kfunc_btf_tab; 2882 if (!tab) { 2883 if (!btf_vmlinux) { 2884 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2885 return -ENOTSUPP; 2886 } 2887 2888 if (!env->prog->jit_requested) { 2889 verbose(env, "JIT is required for calling kernel function\n"); 2890 return -ENOTSUPP; 2891 } 2892 2893 if (!bpf_jit_supports_kfunc_call()) { 2894 verbose(env, "JIT does not support calling kernel function\n"); 2895 return -ENOTSUPP; 2896 } 2897 2898 if (!env->prog->gpl_compatible) { 2899 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2900 return -EINVAL; 2901 } 2902 2903 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 2904 if (!tab) 2905 return -ENOMEM; 2906 prog_aux->kfunc_tab = tab; 2907 } 2908 2909 /* func_id == 0 is always invalid, but instead of returning an error, be 2910 * conservative and wait until the code elimination pass before returning 2911 * error, so that invalid calls that get pruned out can be in BPF programs 2912 * loaded from userspace. It is also required that offset be untouched 2913 * for such calls. 2914 */ 2915 if (!func_id && !offset) 2916 return 0; 2917 2918 if (!btf_tab && offset) { 2919 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 2920 if (!btf_tab) 2921 return -ENOMEM; 2922 prog_aux->kfunc_btf_tab = btf_tab; 2923 } 2924 2925 desc_btf = find_kfunc_desc_btf(env, offset); 2926 if (IS_ERR(desc_btf)) { 2927 verbose(env, "failed to find BTF for kernel function\n"); 2928 return PTR_ERR(desc_btf); 2929 } 2930 2931 if (find_kfunc_desc(env->prog, func_id, offset)) 2932 return 0; 2933 2934 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2935 verbose(env, "too many different kernel function calls\n"); 2936 return -E2BIG; 2937 } 2938 2939 func = btf_type_by_id(desc_btf, func_id); 2940 if (!func || !btf_type_is_func(func)) { 2941 verbose(env, "kernel btf_id %u is not a function\n", 2942 func_id); 2943 return -EINVAL; 2944 } 2945 func_proto = btf_type_by_id(desc_btf, func->type); 2946 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2947 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 2948 func_id); 2949 return -EINVAL; 2950 } 2951 2952 func_name = btf_name_by_offset(desc_btf, func->name_off); 2953 addr = kallsyms_lookup_name(func_name); 2954 if (!addr) { 2955 verbose(env, "cannot find address for kernel function %s\n", 2956 func_name); 2957 return -EINVAL; 2958 } 2959 specialize_kfunc(env, func_id, offset, &addr); 2960 2961 if (bpf_jit_supports_far_kfunc_call()) { 2962 call_imm = func_id; 2963 } else { 2964 call_imm = BPF_CALL_IMM(addr); 2965 /* Check whether the relative offset overflows desc->imm */ 2966 if ((unsigned long)(s32)call_imm != call_imm) { 2967 verbose(env, "address of kernel function %s is out of range\n", 2968 func_name); 2969 return -EINVAL; 2970 } 2971 } 2972 2973 if (bpf_dev_bound_kfunc_id(func_id)) { 2974 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2975 if (err) 2976 return err; 2977 } 2978 2979 desc = &tab->descs[tab->nr_descs++]; 2980 desc->func_id = func_id; 2981 desc->imm = call_imm; 2982 desc->offset = offset; 2983 desc->addr = addr; 2984 err = btf_distill_func_proto(&env->log, desc_btf, 2985 func_proto, func_name, 2986 &desc->func_model); 2987 if (!err) 2988 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2989 kfunc_desc_cmp_by_id_off, NULL); 2990 return err; 2991 } 2992 2993 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b) 2994 { 2995 const struct bpf_kfunc_desc *d0 = a; 2996 const struct bpf_kfunc_desc *d1 = b; 2997 2998 if (d0->imm != d1->imm) 2999 return d0->imm < d1->imm ? -1 : 1; 3000 if (d0->offset != d1->offset) 3001 return d0->offset < d1->offset ? -1 : 1; 3002 return 0; 3003 } 3004 3005 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog) 3006 { 3007 struct bpf_kfunc_desc_tab *tab; 3008 3009 tab = prog->aux->kfunc_tab; 3010 if (!tab) 3011 return; 3012 3013 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 3014 kfunc_desc_cmp_by_imm_off, NULL); 3015 } 3016 3017 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 3018 { 3019 return !!prog->aux->kfunc_tab; 3020 } 3021 3022 const struct btf_func_model * 3023 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 3024 const struct bpf_insn *insn) 3025 { 3026 const struct bpf_kfunc_desc desc = { 3027 .imm = insn->imm, 3028 .offset = insn->off, 3029 }; 3030 const struct bpf_kfunc_desc *res; 3031 struct bpf_kfunc_desc_tab *tab; 3032 3033 tab = prog->aux->kfunc_tab; 3034 res = bsearch(&desc, tab->descs, tab->nr_descs, 3035 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off); 3036 3037 return res ? &res->func_model : NULL; 3038 } 3039 3040 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 3041 { 3042 struct bpf_subprog_info *subprog = env->subprog_info; 3043 int i, ret, insn_cnt = env->prog->len, ex_cb_insn; 3044 struct bpf_insn *insn = env->prog->insnsi; 3045 3046 /* Add entry function. */ 3047 ret = add_subprog(env, 0); 3048 if (ret) 3049 return ret; 3050 3051 for (i = 0; i < insn_cnt; i++, insn++) { 3052 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 3053 !bpf_pseudo_kfunc_call(insn)) 3054 continue; 3055 3056 if (!env->bpf_capable) { 3057 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 3058 return -EPERM; 3059 } 3060 3061 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 3062 ret = add_subprog(env, i + insn->imm + 1); 3063 else 3064 ret = add_kfunc_call(env, insn->imm, insn->off); 3065 3066 if (ret < 0) 3067 return ret; 3068 } 3069 3070 ret = bpf_find_exception_callback_insn_off(env); 3071 if (ret < 0) 3072 return ret; 3073 ex_cb_insn = ret; 3074 3075 /* If ex_cb_insn > 0, this means that the main program has a subprog 3076 * marked using BTF decl tag to serve as the exception callback. 3077 */ 3078 if (ex_cb_insn) { 3079 ret = add_subprog(env, ex_cb_insn); 3080 if (ret < 0) 3081 return ret; 3082 for (i = 1; i < env->subprog_cnt; i++) { 3083 if (env->subprog_info[i].start != ex_cb_insn) 3084 continue; 3085 env->exception_callback_subprog = i; 3086 mark_subprog_exc_cb(env, i); 3087 break; 3088 } 3089 } 3090 3091 /* Add a fake 'exit' subprog which could simplify subprog iteration 3092 * logic. 'subprog_cnt' should not be increased. 3093 */ 3094 subprog[env->subprog_cnt].start = insn_cnt; 3095 3096 if (env->log.level & BPF_LOG_LEVEL2) 3097 for (i = 0; i < env->subprog_cnt; i++) 3098 verbose(env, "func#%d @%d\n", i, subprog[i].start); 3099 3100 return 0; 3101 } 3102 3103 static int check_subprogs(struct bpf_verifier_env *env) 3104 { 3105 int i, subprog_start, subprog_end, off, cur_subprog = 0; 3106 struct bpf_subprog_info *subprog = env->subprog_info; 3107 struct bpf_insn *insn = env->prog->insnsi; 3108 int insn_cnt = env->prog->len; 3109 3110 /* now check that all jumps are within the same subprog */ 3111 subprog_start = subprog[cur_subprog].start; 3112 subprog_end = subprog[cur_subprog + 1].start; 3113 for (i = 0; i < insn_cnt; i++) { 3114 u8 code = insn[i].code; 3115 3116 if (code == (BPF_JMP | BPF_CALL) && 3117 insn[i].src_reg == 0 && 3118 insn[i].imm == BPF_FUNC_tail_call) { 3119 subprog[cur_subprog].has_tail_call = true; 3120 subprog[cur_subprog].tail_call_reachable = true; 3121 } 3122 if (BPF_CLASS(code) == BPF_LD && 3123 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 3124 subprog[cur_subprog].has_ld_abs = true; 3125 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 3126 goto next; 3127 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 3128 goto next; 3129 if (code == (BPF_JMP32 | BPF_JA)) 3130 off = i + insn[i].imm + 1; 3131 else 3132 off = i + insn[i].off + 1; 3133 if (off < subprog_start || off >= subprog_end) { 3134 verbose(env, "jump out of range from insn %d to %d\n", i, off); 3135 return -EINVAL; 3136 } 3137 next: 3138 if (i == subprog_end - 1) { 3139 /* to avoid fall-through from one subprog into another 3140 * the last insn of the subprog should be either exit 3141 * or unconditional jump back or bpf_throw call 3142 */ 3143 if (code != (BPF_JMP | BPF_EXIT) && 3144 code != (BPF_JMP32 | BPF_JA) && 3145 code != (BPF_JMP | BPF_JA)) { 3146 verbose(env, "last insn is not an exit or jmp\n"); 3147 return -EINVAL; 3148 } 3149 subprog_start = subprog_end; 3150 cur_subprog++; 3151 if (cur_subprog < env->subprog_cnt) 3152 subprog_end = subprog[cur_subprog + 1].start; 3153 } 3154 } 3155 return 0; 3156 } 3157 3158 /* Parentage chain of this register (or stack slot) should take care of all 3159 * issues like callee-saved registers, stack slot allocation time, etc. 3160 */ 3161 static int mark_reg_read(struct bpf_verifier_env *env, 3162 const struct bpf_reg_state *state, 3163 struct bpf_reg_state *parent, u8 flag) 3164 { 3165 bool writes = parent == state->parent; /* Observe write marks */ 3166 int cnt = 0; 3167 3168 while (parent) { 3169 /* if read wasn't screened by an earlier write ... */ 3170 if (writes && state->live & REG_LIVE_WRITTEN) 3171 break; 3172 if (parent->live & REG_LIVE_DONE) { 3173 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 3174 reg_type_str(env, parent->type), 3175 parent->var_off.value, parent->off); 3176 return -EFAULT; 3177 } 3178 /* The first condition is more likely to be true than the 3179 * second, checked it first. 3180 */ 3181 if ((parent->live & REG_LIVE_READ) == flag || 3182 parent->live & REG_LIVE_READ64) 3183 /* The parentage chain never changes and 3184 * this parent was already marked as LIVE_READ. 3185 * There is no need to keep walking the chain again and 3186 * keep re-marking all parents as LIVE_READ. 3187 * This case happens when the same register is read 3188 * multiple times without writes into it in-between. 3189 * Also, if parent has the stronger REG_LIVE_READ64 set, 3190 * then no need to set the weak REG_LIVE_READ32. 3191 */ 3192 break; 3193 /* ... then we depend on parent's value */ 3194 parent->live |= flag; 3195 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 3196 if (flag == REG_LIVE_READ64) 3197 parent->live &= ~REG_LIVE_READ32; 3198 state = parent; 3199 parent = state->parent; 3200 writes = true; 3201 cnt++; 3202 } 3203 3204 if (env->longest_mark_read_walk < cnt) 3205 env->longest_mark_read_walk = cnt; 3206 return 0; 3207 } 3208 3209 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3210 { 3211 struct bpf_func_state *state = func(env, reg); 3212 int spi, ret; 3213 3214 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 3215 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 3216 * check_kfunc_call. 3217 */ 3218 if (reg->type == CONST_PTR_TO_DYNPTR) 3219 return 0; 3220 spi = dynptr_get_spi(env, reg); 3221 if (spi < 0) 3222 return spi; 3223 /* Caller ensures dynptr is valid and initialized, which means spi is in 3224 * bounds and spi is the first dynptr slot. Simply mark stack slot as 3225 * read. 3226 */ 3227 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr, 3228 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64); 3229 if (ret) 3230 return ret; 3231 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr, 3232 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64); 3233 } 3234 3235 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3236 int spi, int nr_slots) 3237 { 3238 struct bpf_func_state *state = func(env, reg); 3239 int err, i; 3240 3241 for (i = 0; i < nr_slots; i++) { 3242 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr; 3243 3244 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64); 3245 if (err) 3246 return err; 3247 3248 mark_stack_slot_scratched(env, spi - i); 3249 } 3250 3251 return 0; 3252 } 3253 3254 /* This function is supposed to be used by the following 32-bit optimization 3255 * code only. It returns TRUE if the source or destination register operates 3256 * on 64-bit, otherwise return FALSE. 3257 */ 3258 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 3259 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 3260 { 3261 u8 code, class, op; 3262 3263 code = insn->code; 3264 class = BPF_CLASS(code); 3265 op = BPF_OP(code); 3266 if (class == BPF_JMP) { 3267 /* BPF_EXIT for "main" will reach here. Return TRUE 3268 * conservatively. 3269 */ 3270 if (op == BPF_EXIT) 3271 return true; 3272 if (op == BPF_CALL) { 3273 /* BPF to BPF call will reach here because of marking 3274 * caller saved clobber with DST_OP_NO_MARK for which we 3275 * don't care the register def because they are anyway 3276 * marked as NOT_INIT already. 3277 */ 3278 if (insn->src_reg == BPF_PSEUDO_CALL) 3279 return false; 3280 /* Helper call will reach here because of arg type 3281 * check, conservatively return TRUE. 3282 */ 3283 if (t == SRC_OP) 3284 return true; 3285 3286 return false; 3287 } 3288 } 3289 3290 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3291 return false; 3292 3293 if (class == BPF_ALU64 || class == BPF_JMP || 3294 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3295 return true; 3296 3297 if (class == BPF_ALU || class == BPF_JMP32) 3298 return false; 3299 3300 if (class == BPF_LDX) { 3301 if (t != SRC_OP) 3302 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX; 3303 /* LDX source must be ptr. */ 3304 return true; 3305 } 3306 3307 if (class == BPF_STX) { 3308 /* BPF_STX (including atomic variants) has multiple source 3309 * operands, one of which is a ptr. Check whether the caller is 3310 * asking about it. 3311 */ 3312 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3313 return true; 3314 return BPF_SIZE(code) == BPF_DW; 3315 } 3316 3317 if (class == BPF_LD) { 3318 u8 mode = BPF_MODE(code); 3319 3320 /* LD_IMM64 */ 3321 if (mode == BPF_IMM) 3322 return true; 3323 3324 /* Both LD_IND and LD_ABS return 32-bit data. */ 3325 if (t != SRC_OP) 3326 return false; 3327 3328 /* Implicit ctx ptr. */ 3329 if (regno == BPF_REG_6) 3330 return true; 3331 3332 /* Explicit source could be any width. */ 3333 return true; 3334 } 3335 3336 if (class == BPF_ST) 3337 /* The only source register for BPF_ST is a ptr. */ 3338 return true; 3339 3340 /* Conservatively return true at default. */ 3341 return true; 3342 } 3343 3344 /* Return the regno defined by the insn, or -1. */ 3345 static int insn_def_regno(const struct bpf_insn *insn) 3346 { 3347 switch (BPF_CLASS(insn->code)) { 3348 case BPF_JMP: 3349 case BPF_JMP32: 3350 case BPF_ST: 3351 return -1; 3352 case BPF_STX: 3353 if ((BPF_MODE(insn->code) == BPF_ATOMIC || 3354 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) && 3355 (insn->imm & BPF_FETCH)) { 3356 if (insn->imm == BPF_CMPXCHG) 3357 return BPF_REG_0; 3358 else 3359 return insn->src_reg; 3360 } else { 3361 return -1; 3362 } 3363 default: 3364 return insn->dst_reg; 3365 } 3366 } 3367 3368 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 3369 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 3370 { 3371 int dst_reg = insn_def_regno(insn); 3372 3373 if (dst_reg == -1) 3374 return false; 3375 3376 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 3377 } 3378 3379 static void mark_insn_zext(struct bpf_verifier_env *env, 3380 struct bpf_reg_state *reg) 3381 { 3382 s32 def_idx = reg->subreg_def; 3383 3384 if (def_idx == DEF_NOT_SUBREG) 3385 return; 3386 3387 env->insn_aux_data[def_idx - 1].zext_dst = true; 3388 /* The dst will be zero extended, so won't be sub-register anymore. */ 3389 reg->subreg_def = DEF_NOT_SUBREG; 3390 } 3391 3392 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno, 3393 enum reg_arg_type t) 3394 { 3395 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3396 struct bpf_reg_state *reg; 3397 bool rw64; 3398 3399 if (regno >= MAX_BPF_REG) { 3400 verbose(env, "R%d is invalid\n", regno); 3401 return -EINVAL; 3402 } 3403 3404 mark_reg_scratched(env, regno); 3405 3406 reg = ®s[regno]; 3407 rw64 = is_reg64(env, insn, regno, reg, t); 3408 if (t == SRC_OP) { 3409 /* check whether register used as source operand can be read */ 3410 if (reg->type == NOT_INIT) { 3411 verbose(env, "R%d !read_ok\n", regno); 3412 return -EACCES; 3413 } 3414 /* We don't need to worry about FP liveness because it's read-only */ 3415 if (regno == BPF_REG_FP) 3416 return 0; 3417 3418 if (rw64) 3419 mark_insn_zext(env, reg); 3420 3421 return mark_reg_read(env, reg, reg->parent, 3422 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 3423 } else { 3424 /* check whether register used as dest operand can be written to */ 3425 if (regno == BPF_REG_FP) { 3426 verbose(env, "frame pointer is read only\n"); 3427 return -EACCES; 3428 } 3429 reg->live |= REG_LIVE_WRITTEN; 3430 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3431 if (t == DST_OP) 3432 mark_reg_unknown(env, regs, regno); 3433 } 3434 return 0; 3435 } 3436 3437 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3438 enum reg_arg_type t) 3439 { 3440 struct bpf_verifier_state *vstate = env->cur_state; 3441 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3442 3443 return __check_reg_arg(env, state->regs, regno, t); 3444 } 3445 3446 static int insn_stack_access_flags(int frameno, int spi) 3447 { 3448 return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno; 3449 } 3450 3451 static int insn_stack_access_spi(int insn_flags) 3452 { 3453 return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK; 3454 } 3455 3456 static int insn_stack_access_frameno(int insn_flags) 3457 { 3458 return insn_flags & INSN_F_FRAMENO_MASK; 3459 } 3460 3461 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 3462 { 3463 env->insn_aux_data[idx].jmp_point = true; 3464 } 3465 3466 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 3467 { 3468 return env->insn_aux_data[insn_idx].jmp_point; 3469 } 3470 3471 #define LR_FRAMENO_BITS 3 3472 #define LR_SPI_BITS 6 3473 #define LR_ENTRY_BITS (LR_SPI_BITS + LR_FRAMENO_BITS + 1) 3474 #define LR_SIZE_BITS 4 3475 #define LR_FRAMENO_MASK ((1ull << LR_FRAMENO_BITS) - 1) 3476 #define LR_SPI_MASK ((1ull << LR_SPI_BITS) - 1) 3477 #define LR_SIZE_MASK ((1ull << LR_SIZE_BITS) - 1) 3478 #define LR_SPI_OFF LR_FRAMENO_BITS 3479 #define LR_IS_REG_OFF (LR_SPI_BITS + LR_FRAMENO_BITS) 3480 #define LINKED_REGS_MAX 6 3481 3482 struct linked_reg { 3483 u8 frameno; 3484 union { 3485 u8 spi; 3486 u8 regno; 3487 }; 3488 bool is_reg; 3489 }; 3490 3491 struct linked_regs { 3492 int cnt; 3493 struct linked_reg entries[LINKED_REGS_MAX]; 3494 }; 3495 3496 static struct linked_reg *linked_regs_push(struct linked_regs *s) 3497 { 3498 if (s->cnt < LINKED_REGS_MAX) 3499 return &s->entries[s->cnt++]; 3500 3501 return NULL; 3502 } 3503 3504 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track 3505 * number of elements currently in stack. 3506 * Pack one history entry for linked registers as 10 bits in the following format: 3507 * - 3-bits frameno 3508 * - 6-bits spi_or_reg 3509 * - 1-bit is_reg 3510 */ 3511 static u64 linked_regs_pack(struct linked_regs *s) 3512 { 3513 u64 val = 0; 3514 int i; 3515 3516 for (i = 0; i < s->cnt; ++i) { 3517 struct linked_reg *e = &s->entries[i]; 3518 u64 tmp = 0; 3519 3520 tmp |= e->frameno; 3521 tmp |= e->spi << LR_SPI_OFF; 3522 tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF; 3523 3524 val <<= LR_ENTRY_BITS; 3525 val |= tmp; 3526 } 3527 val <<= LR_SIZE_BITS; 3528 val |= s->cnt; 3529 return val; 3530 } 3531 3532 static void linked_regs_unpack(u64 val, struct linked_regs *s) 3533 { 3534 int i; 3535 3536 s->cnt = val & LR_SIZE_MASK; 3537 val >>= LR_SIZE_BITS; 3538 3539 for (i = 0; i < s->cnt; ++i) { 3540 struct linked_reg *e = &s->entries[i]; 3541 3542 e->frameno = val & LR_FRAMENO_MASK; 3543 e->spi = (val >> LR_SPI_OFF) & LR_SPI_MASK; 3544 e->is_reg = (val >> LR_IS_REG_OFF) & 0x1; 3545 val >>= LR_ENTRY_BITS; 3546 } 3547 } 3548 3549 /* for any branch, call, exit record the history of jmps in the given state */ 3550 static int push_insn_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur, 3551 int insn_flags, u64 linked_regs) 3552 { 3553 struct bpf_insn_hist_entry *p; 3554 size_t alloc_size; 3555 3556 /* combine instruction flags if we already recorded this instruction */ 3557 if (env->cur_hist_ent) { 3558 /* atomic instructions push insn_flags twice, for READ and 3559 * WRITE sides, but they should agree on stack slot 3560 */ 3561 WARN_ONCE((env->cur_hist_ent->flags & insn_flags) && 3562 (env->cur_hist_ent->flags & insn_flags) != insn_flags, 3563 "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n", 3564 env->insn_idx, env->cur_hist_ent->flags, insn_flags); 3565 env->cur_hist_ent->flags |= insn_flags; 3566 WARN_ONCE(env->cur_hist_ent->linked_regs != 0, 3567 "verifier insn history bug: insn_idx %d linked_regs != 0: %#llx\n", 3568 env->insn_idx, env->cur_hist_ent->linked_regs); 3569 env->cur_hist_ent->linked_regs = linked_regs; 3570 return 0; 3571 } 3572 3573 if (cur->insn_hist_end + 1 > env->insn_hist_cap) { 3574 alloc_size = size_mul(cur->insn_hist_end + 1, sizeof(*p)); 3575 p = kvrealloc(env->insn_hist, alloc_size, GFP_USER); 3576 if (!p) 3577 return -ENOMEM; 3578 env->insn_hist = p; 3579 env->insn_hist_cap = alloc_size / sizeof(*p); 3580 } 3581 3582 p = &env->insn_hist[cur->insn_hist_end]; 3583 p->idx = env->insn_idx; 3584 p->prev_idx = env->prev_insn_idx; 3585 p->flags = insn_flags; 3586 p->linked_regs = linked_regs; 3587 3588 cur->insn_hist_end++; 3589 env->cur_hist_ent = p; 3590 3591 return 0; 3592 } 3593 3594 static struct bpf_insn_hist_entry *get_insn_hist_entry(struct bpf_verifier_env *env, 3595 u32 hist_start, u32 hist_end, int insn_idx) 3596 { 3597 if (hist_end > hist_start && env->insn_hist[hist_end - 1].idx == insn_idx) 3598 return &env->insn_hist[hist_end - 1]; 3599 return NULL; 3600 } 3601 3602 /* Backtrack one insn at a time. If idx is not at the top of recorded 3603 * history then previous instruction came from straight line execution. 3604 * Return -ENOENT if we exhausted all instructions within given state. 3605 * 3606 * It's legal to have a bit of a looping with the same starting and ending 3607 * insn index within the same state, e.g.: 3->4->5->3, so just because current 3608 * instruction index is the same as state's first_idx doesn't mean we are 3609 * done. If there is still some jump history left, we should keep going. We 3610 * need to take into account that we might have a jump history between given 3611 * state's parent and itself, due to checkpointing. In this case, we'll have 3612 * history entry recording a jump from last instruction of parent state and 3613 * first instruction of given state. 3614 */ 3615 static int get_prev_insn_idx(const struct bpf_verifier_env *env, 3616 struct bpf_verifier_state *st, 3617 int insn_idx, u32 hist_start, u32 *hist_endp) 3618 { 3619 u32 hist_end = *hist_endp; 3620 u32 cnt = hist_end - hist_start; 3621 3622 if (insn_idx == st->first_insn_idx) { 3623 if (cnt == 0) 3624 return -ENOENT; 3625 if (cnt == 1 && env->insn_hist[hist_start].idx == insn_idx) 3626 return -ENOENT; 3627 } 3628 3629 if (cnt && env->insn_hist[hist_end - 1].idx == insn_idx) { 3630 (*hist_endp)--; 3631 return env->insn_hist[hist_end - 1].prev_idx; 3632 } else { 3633 return insn_idx - 1; 3634 } 3635 } 3636 3637 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3638 { 3639 const struct btf_type *func; 3640 struct btf *desc_btf; 3641 3642 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3643 return NULL; 3644 3645 desc_btf = find_kfunc_desc_btf(data, insn->off); 3646 if (IS_ERR(desc_btf)) 3647 return "<error>"; 3648 3649 func = btf_type_by_id(desc_btf, insn->imm); 3650 return btf_name_by_offset(desc_btf, func->name_off); 3651 } 3652 3653 static inline void bt_init(struct backtrack_state *bt, u32 frame) 3654 { 3655 bt->frame = frame; 3656 } 3657 3658 static inline void bt_reset(struct backtrack_state *bt) 3659 { 3660 struct bpf_verifier_env *env = bt->env; 3661 3662 memset(bt, 0, sizeof(*bt)); 3663 bt->env = env; 3664 } 3665 3666 static inline u32 bt_empty(struct backtrack_state *bt) 3667 { 3668 u64 mask = 0; 3669 int i; 3670 3671 for (i = 0; i <= bt->frame; i++) 3672 mask |= bt->reg_masks[i] | bt->stack_masks[i]; 3673 3674 return mask == 0; 3675 } 3676 3677 static inline int bt_subprog_enter(struct backtrack_state *bt) 3678 { 3679 if (bt->frame == MAX_CALL_FRAMES - 1) { 3680 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame); 3681 WARN_ONCE(1, "verifier backtracking bug"); 3682 return -EFAULT; 3683 } 3684 bt->frame++; 3685 return 0; 3686 } 3687 3688 static inline int bt_subprog_exit(struct backtrack_state *bt) 3689 { 3690 if (bt->frame == 0) { 3691 verbose(bt->env, "BUG subprog exit from frame 0\n"); 3692 WARN_ONCE(1, "verifier backtracking bug"); 3693 return -EFAULT; 3694 } 3695 bt->frame--; 3696 return 0; 3697 } 3698 3699 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3700 { 3701 bt->reg_masks[frame] |= 1 << reg; 3702 } 3703 3704 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3705 { 3706 bt->reg_masks[frame] &= ~(1 << reg); 3707 } 3708 3709 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg) 3710 { 3711 bt_set_frame_reg(bt, bt->frame, reg); 3712 } 3713 3714 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg) 3715 { 3716 bt_clear_frame_reg(bt, bt->frame, reg); 3717 } 3718 3719 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3720 { 3721 bt->stack_masks[frame] |= 1ull << slot; 3722 } 3723 3724 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3725 { 3726 bt->stack_masks[frame] &= ~(1ull << slot); 3727 } 3728 3729 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame) 3730 { 3731 return bt->reg_masks[frame]; 3732 } 3733 3734 static inline u32 bt_reg_mask(struct backtrack_state *bt) 3735 { 3736 return bt->reg_masks[bt->frame]; 3737 } 3738 3739 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame) 3740 { 3741 return bt->stack_masks[frame]; 3742 } 3743 3744 static inline u64 bt_stack_mask(struct backtrack_state *bt) 3745 { 3746 return bt->stack_masks[bt->frame]; 3747 } 3748 3749 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg) 3750 { 3751 return bt->reg_masks[bt->frame] & (1 << reg); 3752 } 3753 3754 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg) 3755 { 3756 return bt->reg_masks[frame] & (1 << reg); 3757 } 3758 3759 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot) 3760 { 3761 return bt->stack_masks[frame] & (1ull << slot); 3762 } 3763 3764 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */ 3765 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask) 3766 { 3767 DECLARE_BITMAP(mask, 64); 3768 bool first = true; 3769 int i, n; 3770 3771 buf[0] = '\0'; 3772 3773 bitmap_from_u64(mask, reg_mask); 3774 for_each_set_bit(i, mask, 32) { 3775 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i); 3776 first = false; 3777 buf += n; 3778 buf_sz -= n; 3779 if (buf_sz < 0) 3780 break; 3781 } 3782 } 3783 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */ 3784 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask) 3785 { 3786 DECLARE_BITMAP(mask, 64); 3787 bool first = true; 3788 int i, n; 3789 3790 buf[0] = '\0'; 3791 3792 bitmap_from_u64(mask, stack_mask); 3793 for_each_set_bit(i, mask, 64) { 3794 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8); 3795 first = false; 3796 buf += n; 3797 buf_sz -= n; 3798 if (buf_sz < 0) 3799 break; 3800 } 3801 } 3802 3803 /* If any register R in hist->linked_regs is marked as precise in bt, 3804 * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs. 3805 */ 3806 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_insn_hist_entry *hist) 3807 { 3808 struct linked_regs linked_regs; 3809 bool some_precise = false; 3810 int i; 3811 3812 if (!hist || hist->linked_regs == 0) 3813 return; 3814 3815 linked_regs_unpack(hist->linked_regs, &linked_regs); 3816 for (i = 0; i < linked_regs.cnt; ++i) { 3817 struct linked_reg *e = &linked_regs.entries[i]; 3818 3819 if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) || 3820 (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) { 3821 some_precise = true; 3822 break; 3823 } 3824 } 3825 3826 if (!some_precise) 3827 return; 3828 3829 for (i = 0; i < linked_regs.cnt; ++i) { 3830 struct linked_reg *e = &linked_regs.entries[i]; 3831 3832 if (e->is_reg) 3833 bt_set_frame_reg(bt, e->frameno, e->regno); 3834 else 3835 bt_set_frame_slot(bt, e->frameno, e->spi); 3836 } 3837 } 3838 3839 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx); 3840 3841 /* For given verifier state backtrack_insn() is called from the last insn to 3842 * the first insn. Its purpose is to compute a bitmask of registers and 3843 * stack slots that needs precision in the parent verifier state. 3844 * 3845 * @idx is an index of the instruction we are currently processing; 3846 * @subseq_idx is an index of the subsequent instruction that: 3847 * - *would be* executed next, if jump history is viewed in forward order; 3848 * - *was* processed previously during backtracking. 3849 */ 3850 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx, 3851 struct bpf_insn_hist_entry *hist, struct backtrack_state *bt) 3852 { 3853 const struct bpf_insn_cbs cbs = { 3854 .cb_call = disasm_kfunc_name, 3855 .cb_print = verbose, 3856 .private_data = env, 3857 }; 3858 struct bpf_insn *insn = env->prog->insnsi + idx; 3859 u8 class = BPF_CLASS(insn->code); 3860 u8 opcode = BPF_OP(insn->code); 3861 u8 mode = BPF_MODE(insn->code); 3862 u32 dreg = insn->dst_reg; 3863 u32 sreg = insn->src_reg; 3864 u32 spi, i, fr; 3865 3866 if (insn->code == 0) 3867 return 0; 3868 if (env->log.level & BPF_LOG_LEVEL2) { 3869 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt)); 3870 verbose(env, "mark_precise: frame%d: regs=%s ", 3871 bt->frame, env->tmp_str_buf); 3872 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt)); 3873 verbose(env, "stack=%s before ", env->tmp_str_buf); 3874 verbose(env, "%d: ", idx); 3875 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3876 } 3877 3878 /* If there is a history record that some registers gained range at this insn, 3879 * propagate precision marks to those registers, so that bt_is_reg_set() 3880 * accounts for these registers. 3881 */ 3882 bt_sync_linked_regs(bt, hist); 3883 3884 if (class == BPF_ALU || class == BPF_ALU64) { 3885 if (!bt_is_reg_set(bt, dreg)) 3886 return 0; 3887 if (opcode == BPF_END || opcode == BPF_NEG) { 3888 /* sreg is reserved and unused 3889 * dreg still need precision before this insn 3890 */ 3891 return 0; 3892 } else if (opcode == BPF_MOV) { 3893 if (BPF_SRC(insn->code) == BPF_X) { 3894 /* dreg = sreg or dreg = (s8, s16, s32)sreg 3895 * dreg needs precision after this insn 3896 * sreg needs precision before this insn 3897 */ 3898 bt_clear_reg(bt, dreg); 3899 if (sreg != BPF_REG_FP) 3900 bt_set_reg(bt, sreg); 3901 } else { 3902 /* dreg = K 3903 * dreg needs precision after this insn. 3904 * Corresponding register is already marked 3905 * as precise=true in this verifier state. 3906 * No further markings in parent are necessary 3907 */ 3908 bt_clear_reg(bt, dreg); 3909 } 3910 } else { 3911 if (BPF_SRC(insn->code) == BPF_X) { 3912 /* dreg += sreg 3913 * both dreg and sreg need precision 3914 * before this insn 3915 */ 3916 if (sreg != BPF_REG_FP) 3917 bt_set_reg(bt, sreg); 3918 } /* else dreg += K 3919 * dreg still needs precision before this insn 3920 */ 3921 } 3922 } else if (class == BPF_LDX) { 3923 if (!bt_is_reg_set(bt, dreg)) 3924 return 0; 3925 bt_clear_reg(bt, dreg); 3926 3927 /* scalars can only be spilled into stack w/o losing precision. 3928 * Load from any other memory can be zero extended. 3929 * The desire to keep that precision is already indicated 3930 * by 'precise' mark in corresponding register of this state. 3931 * No further tracking necessary. 3932 */ 3933 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 3934 return 0; 3935 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 3936 * that [fp - off] slot contains scalar that needs to be 3937 * tracked with precision 3938 */ 3939 spi = insn_stack_access_spi(hist->flags); 3940 fr = insn_stack_access_frameno(hist->flags); 3941 bt_set_frame_slot(bt, fr, spi); 3942 } else if (class == BPF_STX || class == BPF_ST) { 3943 if (bt_is_reg_set(bt, dreg)) 3944 /* stx & st shouldn't be using _scalar_ dst_reg 3945 * to access memory. It means backtracking 3946 * encountered a case of pointer subtraction. 3947 */ 3948 return -ENOTSUPP; 3949 /* scalars can only be spilled into stack */ 3950 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 3951 return 0; 3952 spi = insn_stack_access_spi(hist->flags); 3953 fr = insn_stack_access_frameno(hist->flags); 3954 if (!bt_is_frame_slot_set(bt, fr, spi)) 3955 return 0; 3956 bt_clear_frame_slot(bt, fr, spi); 3957 if (class == BPF_STX) 3958 bt_set_reg(bt, sreg); 3959 } else if (class == BPF_JMP || class == BPF_JMP32) { 3960 if (bpf_pseudo_call(insn)) { 3961 int subprog_insn_idx, subprog; 3962 3963 subprog_insn_idx = idx + insn->imm + 1; 3964 subprog = find_subprog(env, subprog_insn_idx); 3965 if (subprog < 0) 3966 return -EFAULT; 3967 3968 if (subprog_is_global(env, subprog)) { 3969 /* check that jump history doesn't have any 3970 * extra instructions from subprog; the next 3971 * instruction after call to global subprog 3972 * should be literally next instruction in 3973 * caller program 3974 */ 3975 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug"); 3976 /* r1-r5 are invalidated after subprog call, 3977 * so for global func call it shouldn't be set 3978 * anymore 3979 */ 3980 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3981 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3982 WARN_ONCE(1, "verifier backtracking bug"); 3983 return -EFAULT; 3984 } 3985 /* global subprog always sets R0 */ 3986 bt_clear_reg(bt, BPF_REG_0); 3987 return 0; 3988 } else { 3989 /* static subprog call instruction, which 3990 * means that we are exiting current subprog, 3991 * so only r1-r5 could be still requested as 3992 * precise, r0 and r6-r10 or any stack slot in 3993 * the current frame should be zero by now 3994 */ 3995 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3996 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3997 WARN_ONCE(1, "verifier backtracking bug"); 3998 return -EFAULT; 3999 } 4000 /* we are now tracking register spills correctly, 4001 * so any instance of leftover slots is a bug 4002 */ 4003 if (bt_stack_mask(bt) != 0) { 4004 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt)); 4005 WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)"); 4006 return -EFAULT; 4007 } 4008 /* propagate r1-r5 to the caller */ 4009 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 4010 if (bt_is_reg_set(bt, i)) { 4011 bt_clear_reg(bt, i); 4012 bt_set_frame_reg(bt, bt->frame - 1, i); 4013 } 4014 } 4015 if (bt_subprog_exit(bt)) 4016 return -EFAULT; 4017 return 0; 4018 } 4019 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) { 4020 /* exit from callback subprog to callback-calling helper or 4021 * kfunc call. Use idx/subseq_idx check to discern it from 4022 * straight line code backtracking. 4023 * Unlike the subprog call handling above, we shouldn't 4024 * propagate precision of r1-r5 (if any requested), as they are 4025 * not actually arguments passed directly to callback subprogs 4026 */ 4027 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 4028 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 4029 WARN_ONCE(1, "verifier backtracking bug"); 4030 return -EFAULT; 4031 } 4032 if (bt_stack_mask(bt) != 0) { 4033 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt)); 4034 WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)"); 4035 return -EFAULT; 4036 } 4037 /* clear r1-r5 in callback subprog's mask */ 4038 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 4039 bt_clear_reg(bt, i); 4040 if (bt_subprog_exit(bt)) 4041 return -EFAULT; 4042 return 0; 4043 } else if (opcode == BPF_CALL) { 4044 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 4045 * catch this error later. Make backtracking conservative 4046 * with ENOTSUPP. 4047 */ 4048 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 4049 return -ENOTSUPP; 4050 /* regular helper call sets R0 */ 4051 bt_clear_reg(bt, BPF_REG_0); 4052 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 4053 /* if backtracing was looking for registers R1-R5 4054 * they should have been found already. 4055 */ 4056 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 4057 WARN_ONCE(1, "verifier backtracking bug"); 4058 return -EFAULT; 4059 } 4060 } else if (opcode == BPF_EXIT) { 4061 bool r0_precise; 4062 4063 /* Backtracking to a nested function call, 'idx' is a part of 4064 * the inner frame 'subseq_idx' is a part of the outer frame. 4065 * In case of a regular function call, instructions giving 4066 * precision to registers R1-R5 should have been found already. 4067 * In case of a callback, it is ok to have R1-R5 marked for 4068 * backtracking, as these registers are set by the function 4069 * invoking callback. 4070 */ 4071 if (subseq_idx >= 0 && calls_callback(env, subseq_idx)) 4072 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 4073 bt_clear_reg(bt, i); 4074 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 4075 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 4076 WARN_ONCE(1, "verifier backtracking bug"); 4077 return -EFAULT; 4078 } 4079 4080 /* BPF_EXIT in subprog or callback always returns 4081 * right after the call instruction, so by checking 4082 * whether the instruction at subseq_idx-1 is subprog 4083 * call or not we can distinguish actual exit from 4084 * *subprog* from exit from *callback*. In the former 4085 * case, we need to propagate r0 precision, if 4086 * necessary. In the former we never do that. 4087 */ 4088 r0_precise = subseq_idx - 1 >= 0 && 4089 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) && 4090 bt_is_reg_set(bt, BPF_REG_0); 4091 4092 bt_clear_reg(bt, BPF_REG_0); 4093 if (bt_subprog_enter(bt)) 4094 return -EFAULT; 4095 4096 if (r0_precise) 4097 bt_set_reg(bt, BPF_REG_0); 4098 /* r6-r9 and stack slots will stay set in caller frame 4099 * bitmasks until we return back from callee(s) 4100 */ 4101 return 0; 4102 } else if (BPF_SRC(insn->code) == BPF_X) { 4103 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg)) 4104 return 0; 4105 /* dreg <cond> sreg 4106 * Both dreg and sreg need precision before 4107 * this insn. If only sreg was marked precise 4108 * before it would be equally necessary to 4109 * propagate it to dreg. 4110 */ 4111 bt_set_reg(bt, dreg); 4112 bt_set_reg(bt, sreg); 4113 } else if (BPF_SRC(insn->code) == BPF_K) { 4114 /* dreg <cond> K 4115 * Only dreg still needs precision before 4116 * this insn, so for the K-based conditional 4117 * there is nothing new to be marked. 4118 */ 4119 } 4120 } else if (class == BPF_LD) { 4121 if (!bt_is_reg_set(bt, dreg)) 4122 return 0; 4123 bt_clear_reg(bt, dreg); 4124 /* It's ld_imm64 or ld_abs or ld_ind. 4125 * For ld_imm64 no further tracking of precision 4126 * into parent is necessary 4127 */ 4128 if (mode == BPF_IND || mode == BPF_ABS) 4129 /* to be analyzed */ 4130 return -ENOTSUPP; 4131 } 4132 /* Propagate precision marks to linked registers, to account for 4133 * registers marked as precise in this function. 4134 */ 4135 bt_sync_linked_regs(bt, hist); 4136 return 0; 4137 } 4138 4139 /* the scalar precision tracking algorithm: 4140 * . at the start all registers have precise=false. 4141 * . scalar ranges are tracked as normal through alu and jmp insns. 4142 * . once precise value of the scalar register is used in: 4143 * . ptr + scalar alu 4144 * . if (scalar cond K|scalar) 4145 * . helper_call(.., scalar, ...) where ARG_CONST is expected 4146 * backtrack through the verifier states and mark all registers and 4147 * stack slots with spilled constants that these scalar regisers 4148 * should be precise. 4149 * . during state pruning two registers (or spilled stack slots) 4150 * are equivalent if both are not precise. 4151 * 4152 * Note the verifier cannot simply walk register parentage chain, 4153 * since many different registers and stack slots could have been 4154 * used to compute single precise scalar. 4155 * 4156 * The approach of starting with precise=true for all registers and then 4157 * backtrack to mark a register as not precise when the verifier detects 4158 * that program doesn't care about specific value (e.g., when helper 4159 * takes register as ARG_ANYTHING parameter) is not safe. 4160 * 4161 * It's ok to walk single parentage chain of the verifier states. 4162 * It's possible that this backtracking will go all the way till 1st insn. 4163 * All other branches will be explored for needing precision later. 4164 * 4165 * The backtracking needs to deal with cases like: 4166 * 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) 4167 * r9 -= r8 4168 * r5 = r9 4169 * if r5 > 0x79f goto pc+7 4170 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 4171 * r5 += 1 4172 * ... 4173 * call bpf_perf_event_output#25 4174 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 4175 * 4176 * and this case: 4177 * r6 = 1 4178 * call foo // uses callee's r6 inside to compute r0 4179 * r0 += r6 4180 * if r0 == 0 goto 4181 * 4182 * to track above reg_mask/stack_mask needs to be independent for each frame. 4183 * 4184 * Also if parent's curframe > frame where backtracking started, 4185 * the verifier need to mark registers in both frames, otherwise callees 4186 * may incorrectly prune callers. This is similar to 4187 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 4188 * 4189 * For now backtracking falls back into conservative marking. 4190 */ 4191 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 4192 struct bpf_verifier_state *st) 4193 { 4194 struct bpf_func_state *func; 4195 struct bpf_reg_state *reg; 4196 int i, j; 4197 4198 if (env->log.level & BPF_LOG_LEVEL2) { 4199 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n", 4200 st->curframe); 4201 } 4202 4203 /* big hammer: mark all scalars precise in this path. 4204 * pop_stack may still get !precise scalars. 4205 * We also skip current state and go straight to first parent state, 4206 * because precision markings in current non-checkpointed state are 4207 * not needed. See why in the comment in __mark_chain_precision below. 4208 */ 4209 for (st = st->parent; st; st = st->parent) { 4210 for (i = 0; i <= st->curframe; i++) { 4211 func = st->frame[i]; 4212 for (j = 0; j < BPF_REG_FP; j++) { 4213 reg = &func->regs[j]; 4214 if (reg->type != SCALAR_VALUE || reg->precise) 4215 continue; 4216 reg->precise = true; 4217 if (env->log.level & BPF_LOG_LEVEL2) { 4218 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n", 4219 i, j); 4220 } 4221 } 4222 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 4223 if (!is_spilled_reg(&func->stack[j])) 4224 continue; 4225 reg = &func->stack[j].spilled_ptr; 4226 if (reg->type != SCALAR_VALUE || reg->precise) 4227 continue; 4228 reg->precise = true; 4229 if (env->log.level & BPF_LOG_LEVEL2) { 4230 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n", 4231 i, -(j + 1) * 8); 4232 } 4233 } 4234 } 4235 } 4236 } 4237 4238 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 4239 { 4240 struct bpf_func_state *func; 4241 struct bpf_reg_state *reg; 4242 int i, j; 4243 4244 for (i = 0; i <= st->curframe; i++) { 4245 func = st->frame[i]; 4246 for (j = 0; j < BPF_REG_FP; j++) { 4247 reg = &func->regs[j]; 4248 if (reg->type != SCALAR_VALUE) 4249 continue; 4250 reg->precise = false; 4251 } 4252 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 4253 if (!is_spilled_reg(&func->stack[j])) 4254 continue; 4255 reg = &func->stack[j].spilled_ptr; 4256 if (reg->type != SCALAR_VALUE) 4257 continue; 4258 reg->precise = false; 4259 } 4260 } 4261 } 4262 4263 /* 4264 * __mark_chain_precision() backtracks BPF program instruction sequence and 4265 * chain of verifier states making sure that register *regno* (if regno >= 0) 4266 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 4267 * SCALARS, as well as any other registers and slots that contribute to 4268 * a tracked state of given registers/stack slots, depending on specific BPF 4269 * assembly instructions (see backtrack_insns() for exact instruction handling 4270 * logic). This backtracking relies on recorded insn_hist and is able to 4271 * traverse entire chain of parent states. This process ends only when all the 4272 * necessary registers/slots and their transitive dependencies are marked as 4273 * precise. 4274 * 4275 * One important and subtle aspect is that precise marks *do not matter* in 4276 * the currently verified state (current state). It is important to understand 4277 * why this is the case. 4278 * 4279 * First, note that current state is the state that is not yet "checkpointed", 4280 * i.e., it is not yet put into env->explored_states, and it has no children 4281 * states as well. It's ephemeral, and can end up either a) being discarded if 4282 * compatible explored state is found at some point or BPF_EXIT instruction is 4283 * reached or b) checkpointed and put into env->explored_states, branching out 4284 * into one or more children states. 4285 * 4286 * In the former case, precise markings in current state are completely 4287 * ignored by state comparison code (see regsafe() for details). Only 4288 * checkpointed ("old") state precise markings are important, and if old 4289 * state's register/slot is precise, regsafe() assumes current state's 4290 * register/slot as precise and checks value ranges exactly and precisely. If 4291 * states turn out to be compatible, current state's necessary precise 4292 * markings and any required parent states' precise markings are enforced 4293 * after the fact with propagate_precision() logic, after the fact. But it's 4294 * important to realize that in this case, even after marking current state 4295 * registers/slots as precise, we immediately discard current state. So what 4296 * actually matters is any of the precise markings propagated into current 4297 * state's parent states, which are always checkpointed (due to b) case above). 4298 * As such, for scenario a) it doesn't matter if current state has precise 4299 * markings set or not. 4300 * 4301 * Now, for the scenario b), checkpointing and forking into child(ren) 4302 * state(s). Note that before current state gets to checkpointing step, any 4303 * processed instruction always assumes precise SCALAR register/slot 4304 * knowledge: if precise value or range is useful to prune jump branch, BPF 4305 * verifier takes this opportunity enthusiastically. Similarly, when 4306 * register's value is used to calculate offset or memory address, exact 4307 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 4308 * what we mentioned above about state comparison ignoring precise markings 4309 * during state comparison, BPF verifier ignores and also assumes precise 4310 * markings *at will* during instruction verification process. But as verifier 4311 * assumes precision, it also propagates any precision dependencies across 4312 * parent states, which are not yet finalized, so can be further restricted 4313 * based on new knowledge gained from restrictions enforced by their children 4314 * states. This is so that once those parent states are finalized, i.e., when 4315 * they have no more active children state, state comparison logic in 4316 * is_state_visited() would enforce strict and precise SCALAR ranges, if 4317 * required for correctness. 4318 * 4319 * To build a bit more intuition, note also that once a state is checkpointed, 4320 * the path we took to get to that state is not important. This is crucial 4321 * property for state pruning. When state is checkpointed and finalized at 4322 * some instruction index, it can be correctly and safely used to "short 4323 * circuit" any *compatible* state that reaches exactly the same instruction 4324 * index. I.e., if we jumped to that instruction from a completely different 4325 * code path than original finalized state was derived from, it doesn't 4326 * matter, current state can be discarded because from that instruction 4327 * forward having a compatible state will ensure we will safely reach the 4328 * exit. States describe preconditions for further exploration, but completely 4329 * forget the history of how we got here. 4330 * 4331 * This also means that even if we needed precise SCALAR range to get to 4332 * finalized state, but from that point forward *that same* SCALAR register is 4333 * never used in a precise context (i.e., it's precise value is not needed for 4334 * correctness), it's correct and safe to mark such register as "imprecise" 4335 * (i.e., precise marking set to false). This is what we rely on when we do 4336 * not set precise marking in current state. If no child state requires 4337 * precision for any given SCALAR register, it's safe to dictate that it can 4338 * be imprecise. If any child state does require this register to be precise, 4339 * we'll mark it precise later retroactively during precise markings 4340 * propagation from child state to parent states. 4341 * 4342 * Skipping precise marking setting in current state is a mild version of 4343 * relying on the above observation. But we can utilize this property even 4344 * more aggressively by proactively forgetting any precise marking in the 4345 * current state (which we inherited from the parent state), right before we 4346 * checkpoint it and branch off into new child state. This is done by 4347 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 4348 * finalized states which help in short circuiting more future states. 4349 */ 4350 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno) 4351 { 4352 struct backtrack_state *bt = &env->bt; 4353 struct bpf_verifier_state *st = env->cur_state; 4354 int first_idx = st->first_insn_idx; 4355 int last_idx = env->insn_idx; 4356 int subseq_idx = -1; 4357 struct bpf_func_state *func; 4358 struct bpf_reg_state *reg; 4359 bool skip_first = true; 4360 int i, fr, err; 4361 4362 if (!env->bpf_capable) 4363 return 0; 4364 4365 /* set frame number from which we are starting to backtrack */ 4366 bt_init(bt, env->cur_state->curframe); 4367 4368 /* Do sanity checks against current state of register and/or stack 4369 * slot, but don't set precise flag in current state, as precision 4370 * tracking in the current state is unnecessary. 4371 */ 4372 func = st->frame[bt->frame]; 4373 if (regno >= 0) { 4374 reg = &func->regs[regno]; 4375 if (reg->type != SCALAR_VALUE) { 4376 WARN_ONCE(1, "backtracing misuse"); 4377 return -EFAULT; 4378 } 4379 bt_set_reg(bt, regno); 4380 } 4381 4382 if (bt_empty(bt)) 4383 return 0; 4384 4385 for (;;) { 4386 DECLARE_BITMAP(mask, 64); 4387 u32 hist_start = st->insn_hist_start; 4388 u32 hist_end = st->insn_hist_end; 4389 struct bpf_insn_hist_entry *hist; 4390 4391 if (env->log.level & BPF_LOG_LEVEL2) { 4392 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n", 4393 bt->frame, last_idx, first_idx, subseq_idx); 4394 } 4395 4396 if (last_idx < 0) { 4397 /* we are at the entry into subprog, which 4398 * is expected for global funcs, but only if 4399 * requested precise registers are R1-R5 4400 * (which are global func's input arguments) 4401 */ 4402 if (st->curframe == 0 && 4403 st->frame[0]->subprogno > 0 && 4404 st->frame[0]->callsite == BPF_MAIN_FUNC && 4405 bt_stack_mask(bt) == 0 && 4406 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) { 4407 bitmap_from_u64(mask, bt_reg_mask(bt)); 4408 for_each_set_bit(i, mask, 32) { 4409 reg = &st->frame[0]->regs[i]; 4410 bt_clear_reg(bt, i); 4411 if (reg->type == SCALAR_VALUE) 4412 reg->precise = true; 4413 } 4414 return 0; 4415 } 4416 4417 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n", 4418 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt)); 4419 WARN_ONCE(1, "verifier backtracking bug"); 4420 return -EFAULT; 4421 } 4422 4423 for (i = last_idx;;) { 4424 if (skip_first) { 4425 err = 0; 4426 skip_first = false; 4427 } else { 4428 hist = get_insn_hist_entry(env, hist_start, hist_end, i); 4429 err = backtrack_insn(env, i, subseq_idx, hist, bt); 4430 } 4431 if (err == -ENOTSUPP) { 4432 mark_all_scalars_precise(env, env->cur_state); 4433 bt_reset(bt); 4434 return 0; 4435 } else if (err) { 4436 return err; 4437 } 4438 if (bt_empty(bt)) 4439 /* Found assignment(s) into tracked register in this state. 4440 * Since this state is already marked, just return. 4441 * Nothing to be tracked further in the parent state. 4442 */ 4443 return 0; 4444 subseq_idx = i; 4445 i = get_prev_insn_idx(env, st, i, hist_start, &hist_end); 4446 if (i == -ENOENT) 4447 break; 4448 if (i >= env->prog->len) { 4449 /* This can happen if backtracking reached insn 0 4450 * and there are still reg_mask or stack_mask 4451 * to backtrack. 4452 * It means the backtracking missed the spot where 4453 * particular register was initialized with a constant. 4454 */ 4455 verbose(env, "BUG backtracking idx %d\n", i); 4456 WARN_ONCE(1, "verifier backtracking bug"); 4457 return -EFAULT; 4458 } 4459 } 4460 st = st->parent; 4461 if (!st) 4462 break; 4463 4464 for (fr = bt->frame; fr >= 0; fr--) { 4465 func = st->frame[fr]; 4466 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4467 for_each_set_bit(i, mask, 32) { 4468 reg = &func->regs[i]; 4469 if (reg->type != SCALAR_VALUE) { 4470 bt_clear_frame_reg(bt, fr, i); 4471 continue; 4472 } 4473 if (reg->precise) 4474 bt_clear_frame_reg(bt, fr, i); 4475 else 4476 reg->precise = true; 4477 } 4478 4479 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4480 for_each_set_bit(i, mask, 64) { 4481 if (i >= func->allocated_stack / BPF_REG_SIZE) { 4482 verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n", 4483 i, func->allocated_stack / BPF_REG_SIZE); 4484 WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)"); 4485 return -EFAULT; 4486 } 4487 4488 if (!is_spilled_scalar_reg(&func->stack[i])) { 4489 bt_clear_frame_slot(bt, fr, i); 4490 continue; 4491 } 4492 reg = &func->stack[i].spilled_ptr; 4493 if (reg->precise) 4494 bt_clear_frame_slot(bt, fr, i); 4495 else 4496 reg->precise = true; 4497 } 4498 if (env->log.level & BPF_LOG_LEVEL2) { 4499 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4500 bt_frame_reg_mask(bt, fr)); 4501 verbose(env, "mark_precise: frame%d: parent state regs=%s ", 4502 fr, env->tmp_str_buf); 4503 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4504 bt_frame_stack_mask(bt, fr)); 4505 verbose(env, "stack=%s: ", env->tmp_str_buf); 4506 print_verifier_state(env, func, true); 4507 } 4508 } 4509 4510 if (bt_empty(bt)) 4511 return 0; 4512 4513 subseq_idx = first_idx; 4514 last_idx = st->last_insn_idx; 4515 first_idx = st->first_insn_idx; 4516 } 4517 4518 /* if we still have requested precise regs or slots, we missed 4519 * something (e.g., stack access through non-r10 register), so 4520 * fallback to marking all precise 4521 */ 4522 if (!bt_empty(bt)) { 4523 mark_all_scalars_precise(env, env->cur_state); 4524 bt_reset(bt); 4525 } 4526 4527 return 0; 4528 } 4529 4530 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 4531 { 4532 return __mark_chain_precision(env, regno); 4533 } 4534 4535 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 4536 * desired reg and stack masks across all relevant frames 4537 */ 4538 static int mark_chain_precision_batch(struct bpf_verifier_env *env) 4539 { 4540 return __mark_chain_precision(env, -1); 4541 } 4542 4543 static bool is_spillable_regtype(enum bpf_reg_type type) 4544 { 4545 switch (base_type(type)) { 4546 case PTR_TO_MAP_VALUE: 4547 case PTR_TO_STACK: 4548 case PTR_TO_CTX: 4549 case PTR_TO_PACKET: 4550 case PTR_TO_PACKET_META: 4551 case PTR_TO_PACKET_END: 4552 case PTR_TO_FLOW_KEYS: 4553 case CONST_PTR_TO_MAP: 4554 case PTR_TO_SOCKET: 4555 case PTR_TO_SOCK_COMMON: 4556 case PTR_TO_TCP_SOCK: 4557 case PTR_TO_XDP_SOCK: 4558 case PTR_TO_BTF_ID: 4559 case PTR_TO_BUF: 4560 case PTR_TO_MEM: 4561 case PTR_TO_FUNC: 4562 case PTR_TO_MAP_KEY: 4563 case PTR_TO_ARENA: 4564 return true; 4565 default: 4566 return false; 4567 } 4568 } 4569 4570 /* Does this register contain a constant zero? */ 4571 static bool register_is_null(struct bpf_reg_state *reg) 4572 { 4573 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 4574 } 4575 4576 /* check if register is a constant scalar value */ 4577 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32) 4578 { 4579 return reg->type == SCALAR_VALUE && 4580 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off); 4581 } 4582 4583 /* assuming is_reg_const() is true, return constant value of a register */ 4584 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32) 4585 { 4586 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value; 4587 } 4588 4589 static bool __is_pointer_value(bool allow_ptr_leaks, 4590 const struct bpf_reg_state *reg) 4591 { 4592 if (allow_ptr_leaks) 4593 return false; 4594 4595 return reg->type != SCALAR_VALUE; 4596 } 4597 4598 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env, 4599 struct bpf_reg_state *src_reg) 4600 { 4601 if (src_reg->type != SCALAR_VALUE) 4602 return; 4603 4604 if (src_reg->id & BPF_ADD_CONST) { 4605 /* 4606 * The verifier is processing rX = rY insn and 4607 * rY->id has special linked register already. 4608 * Cleared it, since multiple rX += const are not supported. 4609 */ 4610 src_reg->id = 0; 4611 src_reg->off = 0; 4612 } 4613 4614 if (!src_reg->id && !tnum_is_const(src_reg->var_off)) 4615 /* Ensure that src_reg has a valid ID that will be copied to 4616 * dst_reg and then will be used by sync_linked_regs() to 4617 * propagate min/max range. 4618 */ 4619 src_reg->id = ++env->id_gen; 4620 } 4621 4622 /* Copy src state preserving dst->parent and dst->live fields */ 4623 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 4624 { 4625 struct bpf_reg_state *parent = dst->parent; 4626 enum bpf_reg_liveness live = dst->live; 4627 4628 *dst = *src; 4629 dst->parent = parent; 4630 dst->live = live; 4631 } 4632 4633 static void save_register_state(struct bpf_verifier_env *env, 4634 struct bpf_func_state *state, 4635 int spi, struct bpf_reg_state *reg, 4636 int size) 4637 { 4638 int i; 4639 4640 copy_register_state(&state->stack[spi].spilled_ptr, reg); 4641 if (size == BPF_REG_SIZE) 4642 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4643 4644 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 4645 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 4646 4647 /* size < 8 bytes spill */ 4648 for (; i; i--) 4649 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]); 4650 } 4651 4652 static bool is_bpf_st_mem(struct bpf_insn *insn) 4653 { 4654 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 4655 } 4656 4657 static int get_reg_width(struct bpf_reg_state *reg) 4658 { 4659 return fls64(reg->umax_value); 4660 } 4661 4662 /* See comment for mark_fastcall_pattern_for_call() */ 4663 static void check_fastcall_stack_contract(struct bpf_verifier_env *env, 4664 struct bpf_func_state *state, int insn_idx, int off) 4665 { 4666 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 4667 struct bpf_insn_aux_data *aux = env->insn_aux_data; 4668 int i; 4669 4670 if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern) 4671 return; 4672 /* access to the region [max_stack_depth .. fastcall_stack_off) 4673 * from something that is not a part of the fastcall pattern, 4674 * disable fastcall rewrites for current subprogram by setting 4675 * fastcall_stack_off to a value smaller than any possible offset. 4676 */ 4677 subprog->fastcall_stack_off = S16_MIN; 4678 /* reset fastcall aux flags within subprogram, 4679 * happens at most once per subprogram 4680 */ 4681 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 4682 aux[i].fastcall_spills_num = 0; 4683 aux[i].fastcall_pattern = 0; 4684 } 4685 } 4686 4687 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 4688 * stack boundary and alignment are checked in check_mem_access() 4689 */ 4690 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 4691 /* stack frame we're writing to */ 4692 struct bpf_func_state *state, 4693 int off, int size, int value_regno, 4694 int insn_idx) 4695 { 4696 struct bpf_func_state *cur; /* state of the current function */ 4697 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 4698 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4699 struct bpf_reg_state *reg = NULL; 4700 int insn_flags = insn_stack_access_flags(state->frameno, spi); 4701 4702 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 4703 * so it's aligned access and [off, off + size) are within stack limits 4704 */ 4705 if (!env->allow_ptr_leaks && 4706 is_spilled_reg(&state->stack[spi]) && 4707 !is_spilled_scalar_reg(&state->stack[spi]) && 4708 size != BPF_REG_SIZE) { 4709 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 4710 return -EACCES; 4711 } 4712 4713 cur = env->cur_state->frame[env->cur_state->curframe]; 4714 if (value_regno >= 0) 4715 reg = &cur->regs[value_regno]; 4716 if (!env->bypass_spec_v4) { 4717 bool sanitize = reg && is_spillable_regtype(reg->type); 4718 4719 for (i = 0; i < size; i++) { 4720 u8 type = state->stack[spi].slot_type[i]; 4721 4722 if (type != STACK_MISC && type != STACK_ZERO) { 4723 sanitize = true; 4724 break; 4725 } 4726 } 4727 4728 if (sanitize) 4729 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 4730 } 4731 4732 err = destroy_if_dynptr_stack_slot(env, state, spi); 4733 if (err) 4734 return err; 4735 4736 check_fastcall_stack_contract(env, state, insn_idx, off); 4737 mark_stack_slot_scratched(env, spi); 4738 if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) { 4739 bool reg_value_fits; 4740 4741 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size; 4742 /* Make sure that reg had an ID to build a relation on spill. */ 4743 if (reg_value_fits) 4744 assign_scalar_id_before_mov(env, reg); 4745 save_register_state(env, state, spi, reg, size); 4746 /* Break the relation on a narrowing spill. */ 4747 if (!reg_value_fits) 4748 state->stack[spi].spilled_ptr.id = 0; 4749 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 4750 env->bpf_capable) { 4751 struct bpf_reg_state *tmp_reg = &env->fake_reg[0]; 4752 4753 memset(tmp_reg, 0, sizeof(*tmp_reg)); 4754 __mark_reg_known(tmp_reg, insn->imm); 4755 tmp_reg->type = SCALAR_VALUE; 4756 save_register_state(env, state, spi, tmp_reg, size); 4757 } else if (reg && is_spillable_regtype(reg->type)) { 4758 /* register containing pointer is being spilled into stack */ 4759 if (size != BPF_REG_SIZE) { 4760 verbose_linfo(env, insn_idx, "; "); 4761 verbose(env, "invalid size of register spill\n"); 4762 return -EACCES; 4763 } 4764 if (state != cur && reg->type == PTR_TO_STACK) { 4765 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4766 return -EINVAL; 4767 } 4768 save_register_state(env, state, spi, reg, size); 4769 } else { 4770 u8 type = STACK_MISC; 4771 4772 /* regular write of data into stack destroys any spilled ptr */ 4773 state->stack[spi].spilled_ptr.type = NOT_INIT; 4774 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 4775 if (is_stack_slot_special(&state->stack[spi])) 4776 for (i = 0; i < BPF_REG_SIZE; i++) 4777 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 4778 4779 /* only mark the slot as written if all 8 bytes were written 4780 * otherwise read propagation may incorrectly stop too soon 4781 * when stack slots are partially written. 4782 * This heuristic means that read propagation will be 4783 * conservative, since it will add reg_live_read marks 4784 * to stack slots all the way to first state when programs 4785 * writes+reads less than 8 bytes 4786 */ 4787 if (size == BPF_REG_SIZE) 4788 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4789 4790 /* when we zero initialize stack slots mark them as such */ 4791 if ((reg && register_is_null(reg)) || 4792 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4793 /* STACK_ZERO case happened because register spill 4794 * wasn't properly aligned at the stack slot boundary, 4795 * so it's not a register spill anymore; force 4796 * originating register to be precise to make 4797 * STACK_ZERO correct for subsequent states 4798 */ 4799 err = mark_chain_precision(env, value_regno); 4800 if (err) 4801 return err; 4802 type = STACK_ZERO; 4803 } 4804 4805 /* Mark slots affected by this stack write. */ 4806 for (i = 0; i < size; i++) 4807 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 4808 insn_flags = 0; /* not a register spill */ 4809 } 4810 4811 if (insn_flags) 4812 return push_insn_history(env, env->cur_state, insn_flags, 0); 4813 return 0; 4814 } 4815 4816 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 4817 * known to contain a variable offset. 4818 * This function checks whether the write is permitted and conservatively 4819 * tracks the effects of the write, considering that each stack slot in the 4820 * dynamic range is potentially written to. 4821 * 4822 * 'off' includes 'regno->off'. 4823 * 'value_regno' can be -1, meaning that an unknown value is being written to 4824 * the stack. 4825 * 4826 * Spilled pointers in range are not marked as written because we don't know 4827 * what's going to be actually written. This means that read propagation for 4828 * future reads cannot be terminated by this write. 4829 * 4830 * For privileged programs, uninitialized stack slots are considered 4831 * initialized by this write (even though we don't know exactly what offsets 4832 * are going to be written to). The idea is that we don't want the verifier to 4833 * reject future reads that access slots written to through variable offsets. 4834 */ 4835 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4836 /* func where register points to */ 4837 struct bpf_func_state *state, 4838 int ptr_regno, int off, int size, 4839 int value_regno, int insn_idx) 4840 { 4841 struct bpf_func_state *cur; /* state of the current function */ 4842 int min_off, max_off; 4843 int i, err; 4844 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 4845 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4846 bool writing_zero = false; 4847 /* set if the fact that we're writing a zero is used to let any 4848 * stack slots remain STACK_ZERO 4849 */ 4850 bool zero_used = false; 4851 4852 cur = env->cur_state->frame[env->cur_state->curframe]; 4853 ptr_reg = &cur->regs[ptr_regno]; 4854 min_off = ptr_reg->smin_value + off; 4855 max_off = ptr_reg->smax_value + off + size; 4856 if (value_regno >= 0) 4857 value_reg = &cur->regs[value_regno]; 4858 if ((value_reg && register_is_null(value_reg)) || 4859 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4860 writing_zero = true; 4861 4862 for (i = min_off; i < max_off; i++) { 4863 int spi; 4864 4865 spi = __get_spi(i); 4866 err = destroy_if_dynptr_stack_slot(env, state, spi); 4867 if (err) 4868 return err; 4869 } 4870 4871 check_fastcall_stack_contract(env, state, insn_idx, min_off); 4872 /* Variable offset writes destroy any spilled pointers in range. */ 4873 for (i = min_off; i < max_off; i++) { 4874 u8 new_type, *stype; 4875 int slot, spi; 4876 4877 slot = -i - 1; 4878 spi = slot / BPF_REG_SIZE; 4879 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4880 mark_stack_slot_scratched(env, spi); 4881 4882 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4883 /* Reject the write if range we may write to has not 4884 * been initialized beforehand. If we didn't reject 4885 * here, the ptr status would be erased below (even 4886 * though not all slots are actually overwritten), 4887 * possibly opening the door to leaks. 4888 * 4889 * We do however catch STACK_INVALID case below, and 4890 * only allow reading possibly uninitialized memory 4891 * later for CAP_PERFMON, as the write may not happen to 4892 * that slot. 4893 */ 4894 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4895 insn_idx, i); 4896 return -EINVAL; 4897 } 4898 4899 /* If writing_zero and the spi slot contains a spill of value 0, 4900 * maintain the spill type. 4901 */ 4902 if (writing_zero && *stype == STACK_SPILL && 4903 is_spilled_scalar_reg(&state->stack[spi])) { 4904 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr; 4905 4906 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) { 4907 zero_used = true; 4908 continue; 4909 } 4910 } 4911 4912 /* Erase all other spilled pointers. */ 4913 state->stack[spi].spilled_ptr.type = NOT_INIT; 4914 4915 /* Update the slot type. */ 4916 new_type = STACK_MISC; 4917 if (writing_zero && *stype == STACK_ZERO) { 4918 new_type = STACK_ZERO; 4919 zero_used = true; 4920 } 4921 /* If the slot is STACK_INVALID, we check whether it's OK to 4922 * pretend that it will be initialized by this write. The slot 4923 * might not actually be written to, and so if we mark it as 4924 * initialized future reads might leak uninitialized memory. 4925 * For privileged programs, we will accept such reads to slots 4926 * that may or may not be written because, if we're reject 4927 * them, the error would be too confusing. 4928 */ 4929 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4930 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4931 insn_idx, i); 4932 return -EINVAL; 4933 } 4934 *stype = new_type; 4935 } 4936 if (zero_used) { 4937 /* backtracking doesn't work for STACK_ZERO yet. */ 4938 err = mark_chain_precision(env, value_regno); 4939 if (err) 4940 return err; 4941 } 4942 return 0; 4943 } 4944 4945 /* When register 'dst_regno' is assigned some values from stack[min_off, 4946 * max_off), we set the register's type according to the types of the 4947 * respective stack slots. If all the stack values are known to be zeros, then 4948 * so is the destination reg. Otherwise, the register is considered to be 4949 * SCALAR. This function does not deal with register filling; the caller must 4950 * ensure that all spilled registers in the stack range have been marked as 4951 * read. 4952 */ 4953 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4954 /* func where src register points to */ 4955 struct bpf_func_state *ptr_state, 4956 int min_off, int max_off, int dst_regno) 4957 { 4958 struct bpf_verifier_state *vstate = env->cur_state; 4959 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4960 int i, slot, spi; 4961 u8 *stype; 4962 int zeros = 0; 4963 4964 for (i = min_off; i < max_off; i++) { 4965 slot = -i - 1; 4966 spi = slot / BPF_REG_SIZE; 4967 mark_stack_slot_scratched(env, spi); 4968 stype = ptr_state->stack[spi].slot_type; 4969 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4970 break; 4971 zeros++; 4972 } 4973 if (zeros == max_off - min_off) { 4974 /* Any access_size read into register is zero extended, 4975 * so the whole register == const_zero. 4976 */ 4977 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4978 } else { 4979 /* have read misc data from the stack */ 4980 mark_reg_unknown(env, state->regs, dst_regno); 4981 } 4982 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4983 } 4984 4985 /* Read the stack at 'off' and put the results into the register indicated by 4986 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4987 * spilled reg. 4988 * 4989 * 'dst_regno' can be -1, meaning that the read value is not going to a 4990 * register. 4991 * 4992 * The access is assumed to be within the current stack bounds. 4993 */ 4994 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4995 /* func where src register points to */ 4996 struct bpf_func_state *reg_state, 4997 int off, int size, int dst_regno) 4998 { 4999 struct bpf_verifier_state *vstate = env->cur_state; 5000 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5001 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 5002 struct bpf_reg_state *reg; 5003 u8 *stype, type; 5004 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi); 5005 5006 stype = reg_state->stack[spi].slot_type; 5007 reg = ®_state->stack[spi].spilled_ptr; 5008 5009 mark_stack_slot_scratched(env, spi); 5010 check_fastcall_stack_contract(env, state, env->insn_idx, off); 5011 5012 if (is_spilled_reg(®_state->stack[spi])) { 5013 u8 spill_size = 1; 5014 5015 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 5016 spill_size++; 5017 5018 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 5019 if (reg->type != SCALAR_VALUE) { 5020 verbose_linfo(env, env->insn_idx, "; "); 5021 verbose(env, "invalid size of register fill\n"); 5022 return -EACCES; 5023 } 5024 5025 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 5026 if (dst_regno < 0) 5027 return 0; 5028 5029 if (size <= spill_size && 5030 bpf_stack_narrow_access_ok(off, size, spill_size)) { 5031 /* The earlier check_reg_arg() has decided the 5032 * subreg_def for this insn. Save it first. 5033 */ 5034 s32 subreg_def = state->regs[dst_regno].subreg_def; 5035 5036 copy_register_state(&state->regs[dst_regno], reg); 5037 state->regs[dst_regno].subreg_def = subreg_def; 5038 5039 /* Break the relation on a narrowing fill. 5040 * coerce_reg_to_size will adjust the boundaries. 5041 */ 5042 if (get_reg_width(reg) > size * BITS_PER_BYTE) 5043 state->regs[dst_regno].id = 0; 5044 } else { 5045 int spill_cnt = 0, zero_cnt = 0; 5046 5047 for (i = 0; i < size; i++) { 5048 type = stype[(slot - i) % BPF_REG_SIZE]; 5049 if (type == STACK_SPILL) { 5050 spill_cnt++; 5051 continue; 5052 } 5053 if (type == STACK_MISC) 5054 continue; 5055 if (type == STACK_ZERO) { 5056 zero_cnt++; 5057 continue; 5058 } 5059 if (type == STACK_INVALID && env->allow_uninit_stack) 5060 continue; 5061 verbose(env, "invalid read from stack off %d+%d size %d\n", 5062 off, i, size); 5063 return -EACCES; 5064 } 5065 5066 if (spill_cnt == size && 5067 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 5068 __mark_reg_const_zero(env, &state->regs[dst_regno]); 5069 /* this IS register fill, so keep insn_flags */ 5070 } else if (zero_cnt == size) { 5071 /* similarly to mark_reg_stack_read(), preserve zeroes */ 5072 __mark_reg_const_zero(env, &state->regs[dst_regno]); 5073 insn_flags = 0; /* not restoring original register state */ 5074 } else { 5075 mark_reg_unknown(env, state->regs, dst_regno); 5076 insn_flags = 0; /* not restoring original register state */ 5077 } 5078 } 5079 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 5080 } else if (dst_regno >= 0) { 5081 /* restore register state from stack */ 5082 copy_register_state(&state->regs[dst_regno], reg); 5083 /* mark reg as written since spilled pointer state likely 5084 * has its liveness marks cleared by is_state_visited() 5085 * which resets stack/reg liveness for state transitions 5086 */ 5087 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 5088 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 5089 /* If dst_regno==-1, the caller is asking us whether 5090 * it is acceptable to use this value as a SCALAR_VALUE 5091 * (e.g. for XADD). 5092 * We must not allow unprivileged callers to do that 5093 * with spilled pointers. 5094 */ 5095 verbose(env, "leaking pointer from stack off %d\n", 5096 off); 5097 return -EACCES; 5098 } 5099 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 5100 } else { 5101 for (i = 0; i < size; i++) { 5102 type = stype[(slot - i) % BPF_REG_SIZE]; 5103 if (type == STACK_MISC) 5104 continue; 5105 if (type == STACK_ZERO) 5106 continue; 5107 if (type == STACK_INVALID && env->allow_uninit_stack) 5108 continue; 5109 verbose(env, "invalid read from stack off %d+%d size %d\n", 5110 off, i, size); 5111 return -EACCES; 5112 } 5113 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 5114 if (dst_regno >= 0) 5115 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 5116 insn_flags = 0; /* we are not restoring spilled register */ 5117 } 5118 if (insn_flags) 5119 return push_insn_history(env, env->cur_state, insn_flags, 0); 5120 return 0; 5121 } 5122 5123 enum bpf_access_src { 5124 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 5125 ACCESS_HELPER = 2, /* the access is performed by a helper */ 5126 }; 5127 5128 static int check_stack_range_initialized(struct bpf_verifier_env *env, 5129 int regno, int off, int access_size, 5130 bool zero_size_allowed, 5131 enum bpf_access_src type, 5132 struct bpf_call_arg_meta *meta); 5133 5134 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 5135 { 5136 return cur_regs(env) + regno; 5137 } 5138 5139 /* Read the stack at 'ptr_regno + off' and put the result into the register 5140 * 'dst_regno'. 5141 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 5142 * but not its variable offset. 5143 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 5144 * 5145 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 5146 * filling registers (i.e. reads of spilled register cannot be detected when 5147 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 5148 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 5149 * offset; for a fixed offset check_stack_read_fixed_off should be used 5150 * instead. 5151 */ 5152 static int check_stack_read_var_off(struct bpf_verifier_env *env, 5153 int ptr_regno, int off, int size, int dst_regno) 5154 { 5155 /* The state of the source register. */ 5156 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5157 struct bpf_func_state *ptr_state = func(env, reg); 5158 int err; 5159 int min_off, max_off; 5160 5161 /* Note that we pass a NULL meta, so raw access will not be permitted. 5162 */ 5163 err = check_stack_range_initialized(env, ptr_regno, off, size, 5164 false, ACCESS_DIRECT, NULL); 5165 if (err) 5166 return err; 5167 5168 min_off = reg->smin_value + off; 5169 max_off = reg->smax_value + off; 5170 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 5171 check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off); 5172 return 0; 5173 } 5174 5175 /* check_stack_read dispatches to check_stack_read_fixed_off or 5176 * check_stack_read_var_off. 5177 * 5178 * The caller must ensure that the offset falls within the allocated stack 5179 * bounds. 5180 * 5181 * 'dst_regno' is a register which will receive the value from the stack. It 5182 * can be -1, meaning that the read value is not going to a register. 5183 */ 5184 static int check_stack_read(struct bpf_verifier_env *env, 5185 int ptr_regno, int off, int size, 5186 int dst_regno) 5187 { 5188 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5189 struct bpf_func_state *state = func(env, reg); 5190 int err; 5191 /* Some accesses are only permitted with a static offset. */ 5192 bool var_off = !tnum_is_const(reg->var_off); 5193 5194 /* The offset is required to be static when reads don't go to a 5195 * register, in order to not leak pointers (see 5196 * check_stack_read_fixed_off). 5197 */ 5198 if (dst_regno < 0 && var_off) { 5199 char tn_buf[48]; 5200 5201 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5202 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 5203 tn_buf, off, size); 5204 return -EACCES; 5205 } 5206 /* Variable offset is prohibited for unprivileged mode for simplicity 5207 * since it requires corresponding support in Spectre masking for stack 5208 * ALU. See also retrieve_ptr_limit(). The check in 5209 * check_stack_access_for_ptr_arithmetic() called by 5210 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 5211 * with variable offsets, therefore no check is required here. Further, 5212 * just checking it here would be insufficient as speculative stack 5213 * writes could still lead to unsafe speculative behaviour. 5214 */ 5215 if (!var_off) { 5216 off += reg->var_off.value; 5217 err = check_stack_read_fixed_off(env, state, off, size, 5218 dst_regno); 5219 } else { 5220 /* Variable offset stack reads need more conservative handling 5221 * than fixed offset ones. Note that dst_regno >= 0 on this 5222 * branch. 5223 */ 5224 err = check_stack_read_var_off(env, ptr_regno, off, size, 5225 dst_regno); 5226 } 5227 return err; 5228 } 5229 5230 5231 /* check_stack_write dispatches to check_stack_write_fixed_off or 5232 * check_stack_write_var_off. 5233 * 5234 * 'ptr_regno' is the register used as a pointer into the stack. 5235 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 5236 * 'value_regno' is the register whose value we're writing to the stack. It can 5237 * be -1, meaning that we're not writing from a register. 5238 * 5239 * The caller must ensure that the offset falls within the maximum stack size. 5240 */ 5241 static int check_stack_write(struct bpf_verifier_env *env, 5242 int ptr_regno, int off, int size, 5243 int value_regno, int insn_idx) 5244 { 5245 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5246 struct bpf_func_state *state = func(env, reg); 5247 int err; 5248 5249 if (tnum_is_const(reg->var_off)) { 5250 off += reg->var_off.value; 5251 err = check_stack_write_fixed_off(env, state, off, size, 5252 value_regno, insn_idx); 5253 } else { 5254 /* Variable offset stack reads need more conservative handling 5255 * than fixed offset ones. 5256 */ 5257 err = check_stack_write_var_off(env, state, 5258 ptr_regno, off, size, 5259 value_regno, insn_idx); 5260 } 5261 return err; 5262 } 5263 5264 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 5265 int off, int size, enum bpf_access_type type) 5266 { 5267 struct bpf_reg_state *regs = cur_regs(env); 5268 struct bpf_map *map = regs[regno].map_ptr; 5269 u32 cap = bpf_map_flags_to_cap(map); 5270 5271 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 5272 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 5273 map->value_size, off, size); 5274 return -EACCES; 5275 } 5276 5277 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 5278 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 5279 map->value_size, off, size); 5280 return -EACCES; 5281 } 5282 5283 return 0; 5284 } 5285 5286 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 5287 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 5288 int off, int size, u32 mem_size, 5289 bool zero_size_allowed) 5290 { 5291 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 5292 struct bpf_reg_state *reg; 5293 5294 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 5295 return 0; 5296 5297 reg = &cur_regs(env)[regno]; 5298 switch (reg->type) { 5299 case PTR_TO_MAP_KEY: 5300 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 5301 mem_size, off, size); 5302 break; 5303 case PTR_TO_MAP_VALUE: 5304 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 5305 mem_size, off, size); 5306 break; 5307 case PTR_TO_PACKET: 5308 case PTR_TO_PACKET_META: 5309 case PTR_TO_PACKET_END: 5310 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 5311 off, size, regno, reg->id, off, mem_size); 5312 break; 5313 case PTR_TO_MEM: 5314 default: 5315 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 5316 mem_size, off, size); 5317 } 5318 5319 return -EACCES; 5320 } 5321 5322 /* check read/write into a memory region with possible variable offset */ 5323 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 5324 int off, int size, u32 mem_size, 5325 bool zero_size_allowed) 5326 { 5327 struct bpf_verifier_state *vstate = env->cur_state; 5328 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5329 struct bpf_reg_state *reg = &state->regs[regno]; 5330 int err; 5331 5332 /* We may have adjusted the register pointing to memory region, so we 5333 * need to try adding each of min_value and max_value to off 5334 * to make sure our theoretical access will be safe. 5335 * 5336 * The minimum value is only important with signed 5337 * comparisons where we can't assume the floor of a 5338 * value is 0. If we are using signed variables for our 5339 * index'es we need to make sure that whatever we use 5340 * will have a set floor within our range. 5341 */ 5342 if (reg->smin_value < 0 && 5343 (reg->smin_value == S64_MIN || 5344 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5345 reg->smin_value + off < 0)) { 5346 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5347 regno); 5348 return -EACCES; 5349 } 5350 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5351 mem_size, zero_size_allowed); 5352 if (err) { 5353 verbose(env, "R%d min value is outside of the allowed memory range\n", 5354 regno); 5355 return err; 5356 } 5357 5358 /* If we haven't set a max value then we need to bail since we can't be 5359 * sure we won't do bad things. 5360 * If reg->umax_value + off could overflow, treat that as unbounded too. 5361 */ 5362 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5363 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5364 regno); 5365 return -EACCES; 5366 } 5367 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5368 mem_size, zero_size_allowed); 5369 if (err) { 5370 verbose(env, "R%d max value is outside of the allowed memory range\n", 5371 regno); 5372 return err; 5373 } 5374 5375 return 0; 5376 } 5377 5378 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5379 const struct bpf_reg_state *reg, int regno, 5380 bool fixed_off_ok) 5381 { 5382 /* Access to this pointer-typed register or passing it to a helper 5383 * is only allowed in its original, unmodified form. 5384 */ 5385 5386 if (reg->off < 0) { 5387 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5388 reg_type_str(env, reg->type), regno, reg->off); 5389 return -EACCES; 5390 } 5391 5392 if (!fixed_off_ok && reg->off) { 5393 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5394 reg_type_str(env, reg->type), regno, reg->off); 5395 return -EACCES; 5396 } 5397 5398 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5399 char tn_buf[48]; 5400 5401 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5402 verbose(env, "variable %s access var_off=%s disallowed\n", 5403 reg_type_str(env, reg->type), tn_buf); 5404 return -EACCES; 5405 } 5406 5407 return 0; 5408 } 5409 5410 static int check_ptr_off_reg(struct bpf_verifier_env *env, 5411 const struct bpf_reg_state *reg, int regno) 5412 { 5413 return __check_ptr_off_reg(env, reg, regno, false); 5414 } 5415 5416 static int map_kptr_match_type(struct bpf_verifier_env *env, 5417 struct btf_field *kptr_field, 5418 struct bpf_reg_state *reg, u32 regno) 5419 { 5420 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5421 int perm_flags; 5422 const char *reg_name = ""; 5423 5424 if (btf_is_kernel(reg->btf)) { 5425 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5426 5427 /* Only unreferenced case accepts untrusted pointers */ 5428 if (kptr_field->type == BPF_KPTR_UNREF) 5429 perm_flags |= PTR_UNTRUSTED; 5430 } else { 5431 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5432 if (kptr_field->type == BPF_KPTR_PERCPU) 5433 perm_flags |= MEM_PERCPU; 5434 } 5435 5436 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5437 goto bad_type; 5438 5439 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5440 reg_name = btf_type_name(reg->btf, reg->btf_id); 5441 5442 /* For ref_ptr case, release function check should ensure we get one 5443 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5444 * normal store of unreferenced kptr, we must ensure var_off is zero. 5445 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5446 * reg->off and reg->ref_obj_id are not needed here. 5447 */ 5448 if (__check_ptr_off_reg(env, reg, regno, true)) 5449 return -EACCES; 5450 5451 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5452 * we also need to take into account the reg->off. 5453 * 5454 * We want to support cases like: 5455 * 5456 * struct foo { 5457 * struct bar br; 5458 * struct baz bz; 5459 * }; 5460 * 5461 * struct foo *v; 5462 * v = func(); // PTR_TO_BTF_ID 5463 * val->foo = v; // reg->off is zero, btf and btf_id match type 5464 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5465 * // first member type of struct after comparison fails 5466 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5467 * // to match type 5468 * 5469 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5470 * is zero. We must also ensure that btf_struct_ids_match does not walk 5471 * the struct to match type against first member of struct, i.e. reject 5472 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5473 * strict mode to true for type match. 5474 */ 5475 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5476 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5477 kptr_field->type != BPF_KPTR_UNREF)) 5478 goto bad_type; 5479 return 0; 5480 bad_type: 5481 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5482 reg_type_str(env, reg->type), reg_name); 5483 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5484 if (kptr_field->type == BPF_KPTR_UNREF) 5485 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5486 targ_name); 5487 else 5488 verbose(env, "\n"); 5489 return -EINVAL; 5490 } 5491 5492 static bool in_sleepable(struct bpf_verifier_env *env) 5493 { 5494 return env->prog->sleepable || 5495 (env->cur_state && env->cur_state->in_sleepable); 5496 } 5497 5498 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5499 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5500 */ 5501 static bool in_rcu_cs(struct bpf_verifier_env *env) 5502 { 5503 return env->cur_state->active_rcu_lock || 5504 cur_func(env)->active_locks || 5505 !in_sleepable(env); 5506 } 5507 5508 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5509 BTF_SET_START(rcu_protected_types) 5510 BTF_ID(struct, prog_test_ref_kfunc) 5511 #ifdef CONFIG_CGROUPS 5512 BTF_ID(struct, cgroup) 5513 #endif 5514 #ifdef CONFIG_BPF_JIT 5515 BTF_ID(struct, bpf_cpumask) 5516 #endif 5517 BTF_ID(struct, task_struct) 5518 BTF_ID(struct, bpf_crypto_ctx) 5519 BTF_SET_END(rcu_protected_types) 5520 5521 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5522 { 5523 if (!btf_is_kernel(btf)) 5524 return true; 5525 return btf_id_set_contains(&rcu_protected_types, btf_id); 5526 } 5527 5528 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 5529 { 5530 struct btf_struct_meta *meta; 5531 5532 if (btf_is_kernel(kptr_field->kptr.btf)) 5533 return NULL; 5534 5535 meta = btf_find_struct_meta(kptr_field->kptr.btf, 5536 kptr_field->kptr.btf_id); 5537 5538 return meta ? meta->record : NULL; 5539 } 5540 5541 static bool rcu_safe_kptr(const struct btf_field *field) 5542 { 5543 const struct btf_field_kptr *kptr = &field->kptr; 5544 5545 return field->type == BPF_KPTR_PERCPU || 5546 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 5547 } 5548 5549 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 5550 { 5551 struct btf_record *rec; 5552 u32 ret; 5553 5554 ret = PTR_MAYBE_NULL; 5555 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 5556 ret |= MEM_RCU; 5557 if (kptr_field->type == BPF_KPTR_PERCPU) 5558 ret |= MEM_PERCPU; 5559 else if (!btf_is_kernel(kptr_field->kptr.btf)) 5560 ret |= MEM_ALLOC; 5561 5562 rec = kptr_pointee_btf_record(kptr_field); 5563 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 5564 ret |= NON_OWN_REF; 5565 } else { 5566 ret |= PTR_UNTRUSTED; 5567 } 5568 5569 return ret; 5570 } 5571 5572 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno, 5573 struct btf_field *field) 5574 { 5575 struct bpf_reg_state *reg; 5576 const struct btf_type *t; 5577 5578 t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id); 5579 mark_reg_known_zero(env, cur_regs(env), regno); 5580 reg = reg_state(env, regno); 5581 reg->type = PTR_TO_MEM | PTR_MAYBE_NULL; 5582 reg->mem_size = t->size; 5583 reg->id = ++env->id_gen; 5584 5585 return 0; 5586 } 5587 5588 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5589 int value_regno, int insn_idx, 5590 struct btf_field *kptr_field) 5591 { 5592 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5593 int class = BPF_CLASS(insn->code); 5594 struct bpf_reg_state *val_reg; 5595 5596 /* Things we already checked for in check_map_access and caller: 5597 * - Reject cases where variable offset may touch kptr 5598 * - size of access (must be BPF_DW) 5599 * - tnum_is_const(reg->var_off) 5600 * - kptr_field->offset == off + reg->var_off.value 5601 */ 5602 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5603 if (BPF_MODE(insn->code) != BPF_MEM) { 5604 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5605 return -EACCES; 5606 } 5607 5608 /* We only allow loading referenced kptr, since it will be marked as 5609 * untrusted, similar to unreferenced kptr. 5610 */ 5611 if (class != BPF_LDX && 5612 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 5613 verbose(env, "store to referenced kptr disallowed\n"); 5614 return -EACCES; 5615 } 5616 if (class != BPF_LDX && kptr_field->type == BPF_UPTR) { 5617 verbose(env, "store to uptr disallowed\n"); 5618 return -EACCES; 5619 } 5620 5621 if (class == BPF_LDX) { 5622 if (kptr_field->type == BPF_UPTR) 5623 return mark_uptr_ld_reg(env, value_regno, kptr_field); 5624 5625 /* We can simply mark the value_regno receiving the pointer 5626 * value from map as PTR_TO_BTF_ID, with the correct type. 5627 */ 5628 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5629 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field)); 5630 } else if (class == BPF_STX) { 5631 val_reg = reg_state(env, value_regno); 5632 if (!register_is_null(val_reg) && 5633 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5634 return -EACCES; 5635 } else if (class == BPF_ST) { 5636 if (insn->imm) { 5637 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5638 kptr_field->offset); 5639 return -EACCES; 5640 } 5641 } else { 5642 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5643 return -EACCES; 5644 } 5645 return 0; 5646 } 5647 5648 /* check read/write into a map element with possible variable offset */ 5649 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5650 int off, int size, bool zero_size_allowed, 5651 enum bpf_access_src src) 5652 { 5653 struct bpf_verifier_state *vstate = env->cur_state; 5654 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5655 struct bpf_reg_state *reg = &state->regs[regno]; 5656 struct bpf_map *map = reg->map_ptr; 5657 struct btf_record *rec; 5658 int err, i; 5659 5660 err = check_mem_region_access(env, regno, off, size, map->value_size, 5661 zero_size_allowed); 5662 if (err) 5663 return err; 5664 5665 if (IS_ERR_OR_NULL(map->record)) 5666 return 0; 5667 rec = map->record; 5668 for (i = 0; i < rec->cnt; i++) { 5669 struct btf_field *field = &rec->fields[i]; 5670 u32 p = field->offset; 5671 5672 /* If any part of a field can be touched by load/store, reject 5673 * this program. To check that [x1, x2) overlaps with [y1, y2), 5674 * it is sufficient to check x1 < y2 && y1 < x2. 5675 */ 5676 if (reg->smin_value + off < p + field->size && 5677 p < reg->umax_value + off + size) { 5678 switch (field->type) { 5679 case BPF_KPTR_UNREF: 5680 case BPF_KPTR_REF: 5681 case BPF_KPTR_PERCPU: 5682 case BPF_UPTR: 5683 if (src != ACCESS_DIRECT) { 5684 verbose(env, "%s cannot be accessed indirectly by helper\n", 5685 btf_field_type_name(field->type)); 5686 return -EACCES; 5687 } 5688 if (!tnum_is_const(reg->var_off)) { 5689 verbose(env, "%s access cannot have variable offset\n", 5690 btf_field_type_name(field->type)); 5691 return -EACCES; 5692 } 5693 if (p != off + reg->var_off.value) { 5694 verbose(env, "%s access misaligned expected=%u off=%llu\n", 5695 btf_field_type_name(field->type), 5696 p, off + reg->var_off.value); 5697 return -EACCES; 5698 } 5699 if (size != bpf_size_to_bytes(BPF_DW)) { 5700 verbose(env, "%s access size must be BPF_DW\n", 5701 btf_field_type_name(field->type)); 5702 return -EACCES; 5703 } 5704 break; 5705 default: 5706 verbose(env, "%s cannot be accessed directly by load/store\n", 5707 btf_field_type_name(field->type)); 5708 return -EACCES; 5709 } 5710 } 5711 } 5712 return 0; 5713 } 5714 5715 #define MAX_PACKET_OFF 0xffff 5716 5717 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5718 const struct bpf_call_arg_meta *meta, 5719 enum bpf_access_type t) 5720 { 5721 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5722 5723 switch (prog_type) { 5724 /* Program types only with direct read access go here! */ 5725 case BPF_PROG_TYPE_LWT_IN: 5726 case BPF_PROG_TYPE_LWT_OUT: 5727 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5728 case BPF_PROG_TYPE_SK_REUSEPORT: 5729 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5730 case BPF_PROG_TYPE_CGROUP_SKB: 5731 if (t == BPF_WRITE) 5732 return false; 5733 fallthrough; 5734 5735 /* Program types with direct read + write access go here! */ 5736 case BPF_PROG_TYPE_SCHED_CLS: 5737 case BPF_PROG_TYPE_SCHED_ACT: 5738 case BPF_PROG_TYPE_XDP: 5739 case BPF_PROG_TYPE_LWT_XMIT: 5740 case BPF_PROG_TYPE_SK_SKB: 5741 case BPF_PROG_TYPE_SK_MSG: 5742 if (meta) 5743 return meta->pkt_access; 5744 5745 env->seen_direct_write = true; 5746 return true; 5747 5748 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5749 if (t == BPF_WRITE) 5750 env->seen_direct_write = true; 5751 5752 return true; 5753 5754 default: 5755 return false; 5756 } 5757 } 5758 5759 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5760 int size, bool zero_size_allowed) 5761 { 5762 struct bpf_reg_state *regs = cur_regs(env); 5763 struct bpf_reg_state *reg = ®s[regno]; 5764 int err; 5765 5766 /* We may have added a variable offset to the packet pointer; but any 5767 * reg->range we have comes after that. We are only checking the fixed 5768 * offset. 5769 */ 5770 5771 /* We don't allow negative numbers, because we aren't tracking enough 5772 * detail to prove they're safe. 5773 */ 5774 if (reg->smin_value < 0) { 5775 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5776 regno); 5777 return -EACCES; 5778 } 5779 5780 err = reg->range < 0 ? -EINVAL : 5781 __check_mem_access(env, regno, off, size, reg->range, 5782 zero_size_allowed); 5783 if (err) { 5784 verbose(env, "R%d offset is outside of the packet\n", regno); 5785 return err; 5786 } 5787 5788 /* __check_mem_access has made sure "off + size - 1" is within u16. 5789 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5790 * otherwise find_good_pkt_pointers would have refused to set range info 5791 * that __check_mem_access would have rejected this pkt access. 5792 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5793 */ 5794 env->prog->aux->max_pkt_offset = 5795 max_t(u32, env->prog->aux->max_pkt_offset, 5796 off + reg->umax_value + size - 1); 5797 5798 return err; 5799 } 5800 5801 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5802 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5803 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5804 struct btf **btf, u32 *btf_id, bool *is_retval, bool is_ldsx) 5805 { 5806 struct bpf_insn_access_aux info = { 5807 .reg_type = *reg_type, 5808 .log = &env->log, 5809 .is_retval = false, 5810 .is_ldsx = is_ldsx, 5811 }; 5812 5813 if (env->ops->is_valid_access && 5814 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5815 /* A non zero info.ctx_field_size indicates that this field is a 5816 * candidate for later verifier transformation to load the whole 5817 * field and then apply a mask when accessed with a narrower 5818 * access than actual ctx access size. A zero info.ctx_field_size 5819 * will only allow for whole field access and rejects any other 5820 * type of narrower access. 5821 */ 5822 *reg_type = info.reg_type; 5823 *is_retval = info.is_retval; 5824 5825 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5826 *btf = info.btf; 5827 *btf_id = info.btf_id; 5828 } else { 5829 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5830 } 5831 /* remember the offset of last byte accessed in ctx */ 5832 if (env->prog->aux->max_ctx_offset < off + size) 5833 env->prog->aux->max_ctx_offset = off + size; 5834 return 0; 5835 } 5836 5837 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5838 return -EACCES; 5839 } 5840 5841 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5842 int size) 5843 { 5844 if (size < 0 || off < 0 || 5845 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5846 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5847 off, size); 5848 return -EACCES; 5849 } 5850 return 0; 5851 } 5852 5853 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5854 u32 regno, int off, int size, 5855 enum bpf_access_type t) 5856 { 5857 struct bpf_reg_state *regs = cur_regs(env); 5858 struct bpf_reg_state *reg = ®s[regno]; 5859 struct bpf_insn_access_aux info = {}; 5860 bool valid; 5861 5862 if (reg->smin_value < 0) { 5863 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5864 regno); 5865 return -EACCES; 5866 } 5867 5868 switch (reg->type) { 5869 case PTR_TO_SOCK_COMMON: 5870 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5871 break; 5872 case PTR_TO_SOCKET: 5873 valid = bpf_sock_is_valid_access(off, size, t, &info); 5874 break; 5875 case PTR_TO_TCP_SOCK: 5876 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5877 break; 5878 case PTR_TO_XDP_SOCK: 5879 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5880 break; 5881 default: 5882 valid = false; 5883 } 5884 5885 5886 if (valid) { 5887 env->insn_aux_data[insn_idx].ctx_field_size = 5888 info.ctx_field_size; 5889 return 0; 5890 } 5891 5892 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5893 regno, reg_type_str(env, reg->type), off, size); 5894 5895 return -EACCES; 5896 } 5897 5898 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5899 { 5900 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5901 } 5902 5903 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5904 { 5905 const struct bpf_reg_state *reg = reg_state(env, regno); 5906 5907 return reg->type == PTR_TO_CTX; 5908 } 5909 5910 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5911 { 5912 const struct bpf_reg_state *reg = reg_state(env, regno); 5913 5914 return type_is_sk_pointer(reg->type); 5915 } 5916 5917 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5918 { 5919 const struct bpf_reg_state *reg = reg_state(env, regno); 5920 5921 return type_is_pkt_pointer(reg->type); 5922 } 5923 5924 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5925 { 5926 const struct bpf_reg_state *reg = reg_state(env, regno); 5927 5928 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5929 return reg->type == PTR_TO_FLOW_KEYS; 5930 } 5931 5932 static bool is_arena_reg(struct bpf_verifier_env *env, int regno) 5933 { 5934 const struct bpf_reg_state *reg = reg_state(env, regno); 5935 5936 return reg->type == PTR_TO_ARENA; 5937 } 5938 5939 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5940 #ifdef CONFIG_NET 5941 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5942 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5943 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5944 #endif 5945 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5946 }; 5947 5948 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5949 { 5950 /* A referenced register is always trusted. */ 5951 if (reg->ref_obj_id) 5952 return true; 5953 5954 /* Types listed in the reg2btf_ids are always trusted */ 5955 if (reg2btf_ids[base_type(reg->type)] && 5956 !bpf_type_has_unsafe_modifiers(reg->type)) 5957 return true; 5958 5959 /* If a register is not referenced, it is trusted if it has the 5960 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5961 * other type modifiers may be safe, but we elect to take an opt-in 5962 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5963 * not. 5964 * 5965 * Eventually, we should make PTR_TRUSTED the single source of truth 5966 * for whether a register is trusted. 5967 */ 5968 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5969 !bpf_type_has_unsafe_modifiers(reg->type); 5970 } 5971 5972 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5973 { 5974 return reg->type & MEM_RCU; 5975 } 5976 5977 static void clear_trusted_flags(enum bpf_type_flag *flag) 5978 { 5979 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5980 } 5981 5982 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5983 const struct bpf_reg_state *reg, 5984 int off, int size, bool strict) 5985 { 5986 struct tnum reg_off; 5987 int ip_align; 5988 5989 /* Byte size accesses are always allowed. */ 5990 if (!strict || size == 1) 5991 return 0; 5992 5993 /* For platforms that do not have a Kconfig enabling 5994 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5995 * NET_IP_ALIGN is universally set to '2'. And on platforms 5996 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5997 * to this code only in strict mode where we want to emulate 5998 * the NET_IP_ALIGN==2 checking. Therefore use an 5999 * unconditional IP align value of '2'. 6000 */ 6001 ip_align = 2; 6002 6003 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 6004 if (!tnum_is_aligned(reg_off, size)) { 6005 char tn_buf[48]; 6006 6007 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6008 verbose(env, 6009 "misaligned packet access off %d+%s+%d+%d size %d\n", 6010 ip_align, tn_buf, reg->off, off, size); 6011 return -EACCES; 6012 } 6013 6014 return 0; 6015 } 6016 6017 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 6018 const struct bpf_reg_state *reg, 6019 const char *pointer_desc, 6020 int off, int size, bool strict) 6021 { 6022 struct tnum reg_off; 6023 6024 /* Byte size accesses are always allowed. */ 6025 if (!strict || size == 1) 6026 return 0; 6027 6028 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 6029 if (!tnum_is_aligned(reg_off, size)) { 6030 char tn_buf[48]; 6031 6032 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6033 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 6034 pointer_desc, tn_buf, reg->off, off, size); 6035 return -EACCES; 6036 } 6037 6038 return 0; 6039 } 6040 6041 static int check_ptr_alignment(struct bpf_verifier_env *env, 6042 const struct bpf_reg_state *reg, int off, 6043 int size, bool strict_alignment_once) 6044 { 6045 bool strict = env->strict_alignment || strict_alignment_once; 6046 const char *pointer_desc = ""; 6047 6048 switch (reg->type) { 6049 case PTR_TO_PACKET: 6050 case PTR_TO_PACKET_META: 6051 /* Special case, because of NET_IP_ALIGN. Given metadata sits 6052 * right in front, treat it the very same way. 6053 */ 6054 return check_pkt_ptr_alignment(env, reg, off, size, strict); 6055 case PTR_TO_FLOW_KEYS: 6056 pointer_desc = "flow keys "; 6057 break; 6058 case PTR_TO_MAP_KEY: 6059 pointer_desc = "key "; 6060 break; 6061 case PTR_TO_MAP_VALUE: 6062 pointer_desc = "value "; 6063 break; 6064 case PTR_TO_CTX: 6065 pointer_desc = "context "; 6066 break; 6067 case PTR_TO_STACK: 6068 pointer_desc = "stack "; 6069 /* The stack spill tracking logic in check_stack_write_fixed_off() 6070 * and check_stack_read_fixed_off() relies on stack accesses being 6071 * aligned. 6072 */ 6073 strict = true; 6074 break; 6075 case PTR_TO_SOCKET: 6076 pointer_desc = "sock "; 6077 break; 6078 case PTR_TO_SOCK_COMMON: 6079 pointer_desc = "sock_common "; 6080 break; 6081 case PTR_TO_TCP_SOCK: 6082 pointer_desc = "tcp_sock "; 6083 break; 6084 case PTR_TO_XDP_SOCK: 6085 pointer_desc = "xdp_sock "; 6086 break; 6087 case PTR_TO_ARENA: 6088 return 0; 6089 default: 6090 break; 6091 } 6092 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 6093 strict); 6094 } 6095 6096 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog) 6097 { 6098 if (!bpf_jit_supports_private_stack()) 6099 return NO_PRIV_STACK; 6100 6101 /* bpf_prog_check_recur() checks all prog types that use bpf trampoline 6102 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked 6103 * explicitly. 6104 */ 6105 switch (prog->type) { 6106 case BPF_PROG_TYPE_KPROBE: 6107 case BPF_PROG_TYPE_TRACEPOINT: 6108 case BPF_PROG_TYPE_PERF_EVENT: 6109 case BPF_PROG_TYPE_RAW_TRACEPOINT: 6110 return PRIV_STACK_ADAPTIVE; 6111 case BPF_PROG_TYPE_TRACING: 6112 case BPF_PROG_TYPE_LSM: 6113 case BPF_PROG_TYPE_STRUCT_OPS: 6114 if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog)) 6115 return PRIV_STACK_ADAPTIVE; 6116 fallthrough; 6117 default: 6118 break; 6119 } 6120 6121 return NO_PRIV_STACK; 6122 } 6123 6124 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth) 6125 { 6126 if (env->prog->jit_requested) 6127 return round_up(stack_depth, 16); 6128 6129 /* round up to 32-bytes, since this is granularity 6130 * of interpreter stack size 6131 */ 6132 return round_up(max_t(u32, stack_depth, 1), 32); 6133 } 6134 6135 /* starting from main bpf function walk all instructions of the function 6136 * and recursively walk all callees that given function can call. 6137 * Ignore jump and exit insns. 6138 * Since recursion is prevented by check_cfg() this algorithm 6139 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 6140 */ 6141 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx, 6142 bool priv_stack_supported) 6143 { 6144 struct bpf_subprog_info *subprog = env->subprog_info; 6145 struct bpf_insn *insn = env->prog->insnsi; 6146 int depth = 0, frame = 0, i, subprog_end, subprog_depth; 6147 bool tail_call_reachable = false; 6148 int ret_insn[MAX_CALL_FRAMES]; 6149 int ret_prog[MAX_CALL_FRAMES]; 6150 int j; 6151 6152 i = subprog[idx].start; 6153 if (!priv_stack_supported) 6154 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 6155 process_func: 6156 /* protect against potential stack overflow that might happen when 6157 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 6158 * depth for such case down to 256 so that the worst case scenario 6159 * would result in 8k stack size (32 which is tailcall limit * 256 = 6160 * 8k). 6161 * 6162 * To get the idea what might happen, see an example: 6163 * func1 -> sub rsp, 128 6164 * subfunc1 -> sub rsp, 256 6165 * tailcall1 -> add rsp, 256 6166 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 6167 * subfunc2 -> sub rsp, 64 6168 * subfunc22 -> sub rsp, 128 6169 * tailcall2 -> add rsp, 128 6170 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 6171 * 6172 * tailcall will unwind the current stack frame but it will not get rid 6173 * of caller's stack as shown on the example above. 6174 */ 6175 if (idx && subprog[idx].has_tail_call && depth >= 256) { 6176 verbose(env, 6177 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 6178 depth); 6179 return -EACCES; 6180 } 6181 6182 subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth); 6183 if (priv_stack_supported) { 6184 /* Request private stack support only if the subprog stack 6185 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to 6186 * avoid jit penalty if the stack usage is small. 6187 */ 6188 if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN && 6189 subprog_depth >= BPF_PRIV_STACK_MIN_SIZE) 6190 subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE; 6191 } 6192 6193 if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 6194 if (subprog_depth > MAX_BPF_STACK) { 6195 verbose(env, "stack size of subprog %d is %d. Too large\n", 6196 idx, subprog_depth); 6197 return -EACCES; 6198 } 6199 } else { 6200 depth += subprog_depth; 6201 if (depth > MAX_BPF_STACK) { 6202 verbose(env, "combined stack size of %d calls is %d. Too large\n", 6203 frame + 1, depth); 6204 return -EACCES; 6205 } 6206 } 6207 continue_func: 6208 subprog_end = subprog[idx + 1].start; 6209 for (; i < subprog_end; i++) { 6210 int next_insn, sidx; 6211 6212 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 6213 bool err = false; 6214 6215 if (!is_bpf_throw_kfunc(insn + i)) 6216 continue; 6217 if (subprog[idx].is_cb) 6218 err = true; 6219 for (int c = 0; c < frame && !err; c++) { 6220 if (subprog[ret_prog[c]].is_cb) { 6221 err = true; 6222 break; 6223 } 6224 } 6225 if (!err) 6226 continue; 6227 verbose(env, 6228 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 6229 i, idx); 6230 return -EINVAL; 6231 } 6232 6233 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 6234 continue; 6235 /* remember insn and function to return to */ 6236 ret_insn[frame] = i + 1; 6237 ret_prog[frame] = idx; 6238 6239 /* find the callee */ 6240 next_insn = i + insn[i].imm + 1; 6241 sidx = find_subprog(env, next_insn); 6242 if (sidx < 0) { 6243 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 6244 next_insn); 6245 return -EFAULT; 6246 } 6247 if (subprog[sidx].is_async_cb) { 6248 if (subprog[sidx].has_tail_call) { 6249 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 6250 return -EFAULT; 6251 } 6252 /* async callbacks don't increase bpf prog stack size unless called directly */ 6253 if (!bpf_pseudo_call(insn + i)) 6254 continue; 6255 if (subprog[sidx].is_exception_cb) { 6256 verbose(env, "insn %d cannot call exception cb directly\n", i); 6257 return -EINVAL; 6258 } 6259 } 6260 i = next_insn; 6261 idx = sidx; 6262 if (!priv_stack_supported) 6263 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 6264 6265 if (subprog[idx].has_tail_call) 6266 tail_call_reachable = true; 6267 6268 frame++; 6269 if (frame >= MAX_CALL_FRAMES) { 6270 verbose(env, "the call stack of %d frames is too deep !\n", 6271 frame); 6272 return -E2BIG; 6273 } 6274 goto process_func; 6275 } 6276 /* if tail call got detected across bpf2bpf calls then mark each of the 6277 * currently present subprog frames as tail call reachable subprogs; 6278 * this info will be utilized by JIT so that we will be preserving the 6279 * tail call counter throughout bpf2bpf calls combined with tailcalls 6280 */ 6281 if (tail_call_reachable) 6282 for (j = 0; j < frame; j++) { 6283 if (subprog[ret_prog[j]].is_exception_cb) { 6284 verbose(env, "cannot tail call within exception cb\n"); 6285 return -EINVAL; 6286 } 6287 subprog[ret_prog[j]].tail_call_reachable = true; 6288 } 6289 if (subprog[0].tail_call_reachable) 6290 env->prog->aux->tail_call_reachable = true; 6291 6292 /* end of for() loop means the last insn of the 'subprog' 6293 * was reached. Doesn't matter whether it was JA or EXIT 6294 */ 6295 if (frame == 0) 6296 return 0; 6297 if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE) 6298 depth -= round_up_stack_depth(env, subprog[idx].stack_depth); 6299 frame--; 6300 i = ret_insn[frame]; 6301 idx = ret_prog[frame]; 6302 goto continue_func; 6303 } 6304 6305 static int check_max_stack_depth(struct bpf_verifier_env *env) 6306 { 6307 enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN; 6308 struct bpf_subprog_info *si = env->subprog_info; 6309 bool priv_stack_supported; 6310 int ret; 6311 6312 for (int i = 0; i < env->subprog_cnt; i++) { 6313 if (si[i].has_tail_call) { 6314 priv_stack_mode = NO_PRIV_STACK; 6315 break; 6316 } 6317 } 6318 6319 if (priv_stack_mode == PRIV_STACK_UNKNOWN) 6320 priv_stack_mode = bpf_enable_priv_stack(env->prog); 6321 6322 /* All async_cb subprogs use normal kernel stack. If a particular 6323 * subprog appears in both main prog and async_cb subtree, that 6324 * subprog will use normal kernel stack to avoid potential nesting. 6325 * The reverse subprog traversal ensures when main prog subtree is 6326 * checked, the subprogs appearing in async_cb subtrees are already 6327 * marked as using normal kernel stack, so stack size checking can 6328 * be done properly. 6329 */ 6330 for (int i = env->subprog_cnt - 1; i >= 0; i--) { 6331 if (!i || si[i].is_async_cb) { 6332 priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE; 6333 ret = check_max_stack_depth_subprog(env, i, priv_stack_supported); 6334 if (ret < 0) 6335 return ret; 6336 } 6337 } 6338 6339 for (int i = 0; i < env->subprog_cnt; i++) { 6340 if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 6341 env->prog->aux->jits_use_priv_stack = true; 6342 break; 6343 } 6344 } 6345 6346 return 0; 6347 } 6348 6349 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 6350 static int get_callee_stack_depth(struct bpf_verifier_env *env, 6351 const struct bpf_insn *insn, int idx) 6352 { 6353 int start = idx + insn->imm + 1, subprog; 6354 6355 subprog = find_subprog(env, start); 6356 if (subprog < 0) { 6357 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 6358 start); 6359 return -EFAULT; 6360 } 6361 return env->subprog_info[subprog].stack_depth; 6362 } 6363 #endif 6364 6365 static int __check_buffer_access(struct bpf_verifier_env *env, 6366 const char *buf_info, 6367 const struct bpf_reg_state *reg, 6368 int regno, int off, int size) 6369 { 6370 if (off < 0) { 6371 verbose(env, 6372 "R%d invalid %s buffer access: off=%d, size=%d\n", 6373 regno, buf_info, off, size); 6374 return -EACCES; 6375 } 6376 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6377 char tn_buf[48]; 6378 6379 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6380 verbose(env, 6381 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 6382 regno, off, tn_buf); 6383 return -EACCES; 6384 } 6385 6386 return 0; 6387 } 6388 6389 static int check_tp_buffer_access(struct bpf_verifier_env *env, 6390 const struct bpf_reg_state *reg, 6391 int regno, int off, int size) 6392 { 6393 int err; 6394 6395 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 6396 if (err) 6397 return err; 6398 6399 if (off + size > env->prog->aux->max_tp_access) 6400 env->prog->aux->max_tp_access = off + size; 6401 6402 return 0; 6403 } 6404 6405 static int check_buffer_access(struct bpf_verifier_env *env, 6406 const struct bpf_reg_state *reg, 6407 int regno, int off, int size, 6408 bool zero_size_allowed, 6409 u32 *max_access) 6410 { 6411 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 6412 int err; 6413 6414 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 6415 if (err) 6416 return err; 6417 6418 if (off + size > *max_access) 6419 *max_access = off + size; 6420 6421 return 0; 6422 } 6423 6424 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 6425 static void zext_32_to_64(struct bpf_reg_state *reg) 6426 { 6427 reg->var_off = tnum_subreg(reg->var_off); 6428 __reg_assign_32_into_64(reg); 6429 } 6430 6431 /* truncate register to smaller size (in bytes) 6432 * must be called with size < BPF_REG_SIZE 6433 */ 6434 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 6435 { 6436 u64 mask; 6437 6438 /* clear high bits in bit representation */ 6439 reg->var_off = tnum_cast(reg->var_off, size); 6440 6441 /* fix arithmetic bounds */ 6442 mask = ((u64)1 << (size * 8)) - 1; 6443 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 6444 reg->umin_value &= mask; 6445 reg->umax_value &= mask; 6446 } else { 6447 reg->umin_value = 0; 6448 reg->umax_value = mask; 6449 } 6450 reg->smin_value = reg->umin_value; 6451 reg->smax_value = reg->umax_value; 6452 6453 /* If size is smaller than 32bit register the 32bit register 6454 * values are also truncated so we push 64-bit bounds into 6455 * 32-bit bounds. Above were truncated < 32-bits already. 6456 */ 6457 if (size < 4) 6458 __mark_reg32_unbounded(reg); 6459 6460 reg_bounds_sync(reg); 6461 } 6462 6463 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 6464 { 6465 if (size == 1) { 6466 reg->smin_value = reg->s32_min_value = S8_MIN; 6467 reg->smax_value = reg->s32_max_value = S8_MAX; 6468 } else if (size == 2) { 6469 reg->smin_value = reg->s32_min_value = S16_MIN; 6470 reg->smax_value = reg->s32_max_value = S16_MAX; 6471 } else { 6472 /* size == 4 */ 6473 reg->smin_value = reg->s32_min_value = S32_MIN; 6474 reg->smax_value = reg->s32_max_value = S32_MAX; 6475 } 6476 reg->umin_value = reg->u32_min_value = 0; 6477 reg->umax_value = U64_MAX; 6478 reg->u32_max_value = U32_MAX; 6479 reg->var_off = tnum_unknown; 6480 } 6481 6482 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6483 { 6484 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6485 u64 top_smax_value, top_smin_value; 6486 u64 num_bits = size * 8; 6487 6488 if (tnum_is_const(reg->var_off)) { 6489 u64_cval = reg->var_off.value; 6490 if (size == 1) 6491 reg->var_off = tnum_const((s8)u64_cval); 6492 else if (size == 2) 6493 reg->var_off = tnum_const((s16)u64_cval); 6494 else 6495 /* size == 4 */ 6496 reg->var_off = tnum_const((s32)u64_cval); 6497 6498 u64_cval = reg->var_off.value; 6499 reg->smax_value = reg->smin_value = u64_cval; 6500 reg->umax_value = reg->umin_value = u64_cval; 6501 reg->s32_max_value = reg->s32_min_value = u64_cval; 6502 reg->u32_max_value = reg->u32_min_value = u64_cval; 6503 return; 6504 } 6505 6506 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6507 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6508 6509 if (top_smax_value != top_smin_value) 6510 goto out; 6511 6512 /* find the s64_min and s64_min after sign extension */ 6513 if (size == 1) { 6514 init_s64_max = (s8)reg->smax_value; 6515 init_s64_min = (s8)reg->smin_value; 6516 } else if (size == 2) { 6517 init_s64_max = (s16)reg->smax_value; 6518 init_s64_min = (s16)reg->smin_value; 6519 } else { 6520 init_s64_max = (s32)reg->smax_value; 6521 init_s64_min = (s32)reg->smin_value; 6522 } 6523 6524 s64_max = max(init_s64_max, init_s64_min); 6525 s64_min = min(init_s64_max, init_s64_min); 6526 6527 /* both of s64_max/s64_min positive or negative */ 6528 if ((s64_max >= 0) == (s64_min >= 0)) { 6529 reg->s32_min_value = reg->smin_value = s64_min; 6530 reg->s32_max_value = reg->smax_value = s64_max; 6531 reg->u32_min_value = reg->umin_value = s64_min; 6532 reg->u32_max_value = reg->umax_value = s64_max; 6533 reg->var_off = tnum_range(s64_min, s64_max); 6534 return; 6535 } 6536 6537 out: 6538 set_sext64_default_val(reg, size); 6539 } 6540 6541 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6542 { 6543 if (size == 1) { 6544 reg->s32_min_value = S8_MIN; 6545 reg->s32_max_value = S8_MAX; 6546 } else { 6547 /* size == 2 */ 6548 reg->s32_min_value = S16_MIN; 6549 reg->s32_max_value = S16_MAX; 6550 } 6551 reg->u32_min_value = 0; 6552 reg->u32_max_value = U32_MAX; 6553 reg->var_off = tnum_subreg(tnum_unknown); 6554 } 6555 6556 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6557 { 6558 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6559 u32 top_smax_value, top_smin_value; 6560 u32 num_bits = size * 8; 6561 6562 if (tnum_is_const(reg->var_off)) { 6563 u32_val = reg->var_off.value; 6564 if (size == 1) 6565 reg->var_off = tnum_const((s8)u32_val); 6566 else 6567 reg->var_off = tnum_const((s16)u32_val); 6568 6569 u32_val = reg->var_off.value; 6570 reg->s32_min_value = reg->s32_max_value = u32_val; 6571 reg->u32_min_value = reg->u32_max_value = u32_val; 6572 return; 6573 } 6574 6575 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 6576 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 6577 6578 if (top_smax_value != top_smin_value) 6579 goto out; 6580 6581 /* find the s32_min and s32_min after sign extension */ 6582 if (size == 1) { 6583 init_s32_max = (s8)reg->s32_max_value; 6584 init_s32_min = (s8)reg->s32_min_value; 6585 } else { 6586 /* size == 2 */ 6587 init_s32_max = (s16)reg->s32_max_value; 6588 init_s32_min = (s16)reg->s32_min_value; 6589 } 6590 s32_max = max(init_s32_max, init_s32_min); 6591 s32_min = min(init_s32_max, init_s32_min); 6592 6593 if ((s32_min >= 0) == (s32_max >= 0)) { 6594 reg->s32_min_value = s32_min; 6595 reg->s32_max_value = s32_max; 6596 reg->u32_min_value = (u32)s32_min; 6597 reg->u32_max_value = (u32)s32_max; 6598 reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max)); 6599 return; 6600 } 6601 6602 out: 6603 set_sext32_default_val(reg, size); 6604 } 6605 6606 static bool bpf_map_is_rdonly(const struct bpf_map *map) 6607 { 6608 /* A map is considered read-only if the following condition are true: 6609 * 6610 * 1) BPF program side cannot change any of the map content. The 6611 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6612 * and was set at map creation time. 6613 * 2) The map value(s) have been initialized from user space by a 6614 * loader and then "frozen", such that no new map update/delete 6615 * operations from syscall side are possible for the rest of 6616 * the map's lifetime from that point onwards. 6617 * 3) Any parallel/pending map update/delete operations from syscall 6618 * side have been completed. Only after that point, it's safe to 6619 * assume that map value(s) are immutable. 6620 */ 6621 return (map->map_flags & BPF_F_RDONLY_PROG) && 6622 READ_ONCE(map->frozen) && 6623 !bpf_map_write_active(map); 6624 } 6625 6626 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6627 bool is_ldsx) 6628 { 6629 void *ptr; 6630 u64 addr; 6631 int err; 6632 6633 err = map->ops->map_direct_value_addr(map, &addr, off); 6634 if (err) 6635 return err; 6636 ptr = (void *)(long)addr + off; 6637 6638 switch (size) { 6639 case sizeof(u8): 6640 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6641 break; 6642 case sizeof(u16): 6643 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6644 break; 6645 case sizeof(u32): 6646 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6647 break; 6648 case sizeof(u64): 6649 *val = *(u64 *)ptr; 6650 break; 6651 default: 6652 return -EINVAL; 6653 } 6654 return 0; 6655 } 6656 6657 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6658 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6659 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6660 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null) 6661 6662 /* 6663 * Allow list few fields as RCU trusted or full trusted. 6664 * This logic doesn't allow mix tagging and will be removed once GCC supports 6665 * btf_type_tag. 6666 */ 6667 6668 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6669 BTF_TYPE_SAFE_RCU(struct task_struct) { 6670 const cpumask_t *cpus_ptr; 6671 struct css_set __rcu *cgroups; 6672 struct task_struct __rcu *real_parent; 6673 struct task_struct *group_leader; 6674 }; 6675 6676 BTF_TYPE_SAFE_RCU(struct cgroup) { 6677 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6678 struct kernfs_node *kn; 6679 }; 6680 6681 BTF_TYPE_SAFE_RCU(struct css_set) { 6682 struct cgroup *dfl_cgrp; 6683 }; 6684 6685 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6686 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6687 struct file __rcu *exe_file; 6688 }; 6689 6690 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6691 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6692 */ 6693 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6694 struct sock *sk; 6695 }; 6696 6697 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6698 struct sock *sk; 6699 }; 6700 6701 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6702 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6703 struct seq_file *seq; 6704 }; 6705 6706 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6707 struct bpf_iter_meta *meta; 6708 struct task_struct *task; 6709 }; 6710 6711 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6712 struct file *file; 6713 }; 6714 6715 BTF_TYPE_SAFE_TRUSTED(struct file) { 6716 struct inode *f_inode; 6717 }; 6718 6719 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 6720 /* no negative dentry-s in places where bpf can see it */ 6721 struct inode *d_inode; 6722 }; 6723 6724 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) { 6725 struct sock *sk; 6726 }; 6727 6728 static bool type_is_rcu(struct bpf_verifier_env *env, 6729 struct bpf_reg_state *reg, 6730 const char *field_name, u32 btf_id) 6731 { 6732 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6733 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6734 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6735 6736 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6737 } 6738 6739 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6740 struct bpf_reg_state *reg, 6741 const char *field_name, u32 btf_id) 6742 { 6743 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6744 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6745 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6746 6747 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6748 } 6749 6750 static bool type_is_trusted(struct bpf_verifier_env *env, 6751 struct bpf_reg_state *reg, 6752 const char *field_name, u32 btf_id) 6753 { 6754 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 6755 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6756 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6757 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6758 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 6759 6760 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6761 } 6762 6763 static bool type_is_trusted_or_null(struct bpf_verifier_env *env, 6764 struct bpf_reg_state *reg, 6765 const char *field_name, u32 btf_id) 6766 { 6767 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)); 6768 6769 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, 6770 "__safe_trusted_or_null"); 6771 } 6772 6773 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6774 struct bpf_reg_state *regs, 6775 int regno, int off, int size, 6776 enum bpf_access_type atype, 6777 int value_regno) 6778 { 6779 struct bpf_reg_state *reg = regs + regno; 6780 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6781 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6782 const char *field_name = NULL; 6783 enum bpf_type_flag flag = 0; 6784 u32 btf_id = 0; 6785 int ret; 6786 6787 if (!env->allow_ptr_leaks) { 6788 verbose(env, 6789 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6790 tname); 6791 return -EPERM; 6792 } 6793 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6794 verbose(env, 6795 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6796 tname); 6797 return -EINVAL; 6798 } 6799 if (off < 0) { 6800 verbose(env, 6801 "R%d is ptr_%s invalid negative access: off=%d\n", 6802 regno, tname, off); 6803 return -EACCES; 6804 } 6805 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6806 char tn_buf[48]; 6807 6808 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6809 verbose(env, 6810 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6811 regno, tname, off, tn_buf); 6812 return -EACCES; 6813 } 6814 6815 if (reg->type & MEM_USER) { 6816 verbose(env, 6817 "R%d is ptr_%s access user memory: off=%d\n", 6818 regno, tname, off); 6819 return -EACCES; 6820 } 6821 6822 if (reg->type & MEM_PERCPU) { 6823 verbose(env, 6824 "R%d is ptr_%s access percpu memory: off=%d\n", 6825 regno, tname, off); 6826 return -EACCES; 6827 } 6828 6829 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6830 if (!btf_is_kernel(reg->btf)) { 6831 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 6832 return -EFAULT; 6833 } 6834 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6835 } else { 6836 /* Writes are permitted with default btf_struct_access for 6837 * program allocated objects (which always have ref_obj_id > 0), 6838 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6839 */ 6840 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6841 verbose(env, "only read is supported\n"); 6842 return -EACCES; 6843 } 6844 6845 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6846 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 6847 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 6848 return -EFAULT; 6849 } 6850 6851 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6852 } 6853 6854 if (ret < 0) 6855 return ret; 6856 6857 if (ret != PTR_TO_BTF_ID) { 6858 /* just mark; */ 6859 6860 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6861 /* If this is an untrusted pointer, all pointers formed by walking it 6862 * also inherit the untrusted flag. 6863 */ 6864 flag = PTR_UNTRUSTED; 6865 6866 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6867 /* By default any pointer obtained from walking a trusted pointer is no 6868 * longer trusted, unless the field being accessed has explicitly been 6869 * marked as inheriting its parent's state of trust (either full or RCU). 6870 * For example: 6871 * 'cgroups' pointer is untrusted if task->cgroups dereference 6872 * happened in a sleepable program outside of bpf_rcu_read_lock() 6873 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6874 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6875 * 6876 * A regular RCU-protected pointer with __rcu tag can also be deemed 6877 * trusted if we are in an RCU CS. Such pointer can be NULL. 6878 */ 6879 if (type_is_trusted(env, reg, field_name, btf_id)) { 6880 flag |= PTR_TRUSTED; 6881 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) { 6882 flag |= PTR_TRUSTED | PTR_MAYBE_NULL; 6883 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6884 if (type_is_rcu(env, reg, field_name, btf_id)) { 6885 /* ignore __rcu tag and mark it MEM_RCU */ 6886 flag |= MEM_RCU; 6887 } else if (flag & MEM_RCU || 6888 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6889 /* __rcu tagged pointers can be NULL */ 6890 flag |= MEM_RCU | PTR_MAYBE_NULL; 6891 6892 /* We always trust them */ 6893 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6894 flag & PTR_UNTRUSTED) 6895 flag &= ~PTR_UNTRUSTED; 6896 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6897 /* keep as-is */ 6898 } else { 6899 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6900 clear_trusted_flags(&flag); 6901 } 6902 } else { 6903 /* 6904 * If not in RCU CS or MEM_RCU pointer can be NULL then 6905 * aggressively mark as untrusted otherwise such 6906 * pointers will be plain PTR_TO_BTF_ID without flags 6907 * and will be allowed to be passed into helpers for 6908 * compat reasons. 6909 */ 6910 flag = PTR_UNTRUSTED; 6911 } 6912 } else { 6913 /* Old compat. Deprecated */ 6914 clear_trusted_flags(&flag); 6915 } 6916 6917 if (atype == BPF_READ && value_regno >= 0) 6918 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6919 6920 return 0; 6921 } 6922 6923 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6924 struct bpf_reg_state *regs, 6925 int regno, int off, int size, 6926 enum bpf_access_type atype, 6927 int value_regno) 6928 { 6929 struct bpf_reg_state *reg = regs + regno; 6930 struct bpf_map *map = reg->map_ptr; 6931 struct bpf_reg_state map_reg; 6932 enum bpf_type_flag flag = 0; 6933 const struct btf_type *t; 6934 const char *tname; 6935 u32 btf_id; 6936 int ret; 6937 6938 if (!btf_vmlinux) { 6939 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6940 return -ENOTSUPP; 6941 } 6942 6943 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6944 verbose(env, "map_ptr access not supported for map type %d\n", 6945 map->map_type); 6946 return -ENOTSUPP; 6947 } 6948 6949 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6950 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6951 6952 if (!env->allow_ptr_leaks) { 6953 verbose(env, 6954 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6955 tname); 6956 return -EPERM; 6957 } 6958 6959 if (off < 0) { 6960 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6961 regno, tname, off); 6962 return -EACCES; 6963 } 6964 6965 if (atype != BPF_READ) { 6966 verbose(env, "only read from %s is supported\n", tname); 6967 return -EACCES; 6968 } 6969 6970 /* Simulate access to a PTR_TO_BTF_ID */ 6971 memset(&map_reg, 0, sizeof(map_reg)); 6972 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6973 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6974 if (ret < 0) 6975 return ret; 6976 6977 if (value_regno >= 0) 6978 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6979 6980 return 0; 6981 } 6982 6983 /* Check that the stack access at the given offset is within bounds. The 6984 * maximum valid offset is -1. 6985 * 6986 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6987 * -state->allocated_stack for reads. 6988 */ 6989 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 6990 s64 off, 6991 struct bpf_func_state *state, 6992 enum bpf_access_type t) 6993 { 6994 int min_valid_off; 6995 6996 if (t == BPF_WRITE || env->allow_uninit_stack) 6997 min_valid_off = -MAX_BPF_STACK; 6998 else 6999 min_valid_off = -state->allocated_stack; 7000 7001 if (off < min_valid_off || off > -1) 7002 return -EACCES; 7003 return 0; 7004 } 7005 7006 /* Check that the stack access at 'regno + off' falls within the maximum stack 7007 * bounds. 7008 * 7009 * 'off' includes `regno->offset`, but not its dynamic part (if any). 7010 */ 7011 static int check_stack_access_within_bounds( 7012 struct bpf_verifier_env *env, 7013 int regno, int off, int access_size, 7014 enum bpf_access_src src, enum bpf_access_type type) 7015 { 7016 struct bpf_reg_state *regs = cur_regs(env); 7017 struct bpf_reg_state *reg = regs + regno; 7018 struct bpf_func_state *state = func(env, reg); 7019 s64 min_off, max_off; 7020 int err; 7021 char *err_extra; 7022 7023 if (src == ACCESS_HELPER) 7024 /* We don't know if helpers are reading or writing (or both). */ 7025 err_extra = " indirect access to"; 7026 else if (type == BPF_READ) 7027 err_extra = " read from"; 7028 else 7029 err_extra = " write to"; 7030 7031 if (tnum_is_const(reg->var_off)) { 7032 min_off = (s64)reg->var_off.value + off; 7033 max_off = min_off + access_size; 7034 } else { 7035 if (reg->smax_value >= BPF_MAX_VAR_OFF || 7036 reg->smin_value <= -BPF_MAX_VAR_OFF) { 7037 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 7038 err_extra, regno); 7039 return -EACCES; 7040 } 7041 min_off = reg->smin_value + off; 7042 max_off = reg->smax_value + off + access_size; 7043 } 7044 7045 err = check_stack_slot_within_bounds(env, min_off, state, type); 7046 if (!err && max_off > 0) 7047 err = -EINVAL; /* out of stack access into non-negative offsets */ 7048 if (!err && access_size < 0) 7049 /* access_size should not be negative (or overflow an int); others checks 7050 * along the way should have prevented such an access. 7051 */ 7052 err = -EFAULT; /* invalid negative access size; integer overflow? */ 7053 7054 if (err) { 7055 if (tnum_is_const(reg->var_off)) { 7056 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 7057 err_extra, regno, off, access_size); 7058 } else { 7059 char tn_buf[48]; 7060 7061 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7062 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n", 7063 err_extra, regno, tn_buf, off, access_size); 7064 } 7065 return err; 7066 } 7067 7068 /* Note that there is no stack access with offset zero, so the needed stack 7069 * size is -min_off, not -min_off+1. 7070 */ 7071 return grow_stack_state(env, state, -min_off /* size */); 7072 } 7073 7074 static bool get_func_retval_range(struct bpf_prog *prog, 7075 struct bpf_retval_range *range) 7076 { 7077 if (prog->type == BPF_PROG_TYPE_LSM && 7078 prog->expected_attach_type == BPF_LSM_MAC && 7079 !bpf_lsm_get_retval_range(prog, range)) { 7080 return true; 7081 } 7082 return false; 7083 } 7084 7085 /* check whether memory at (regno + off) is accessible for t = (read | write) 7086 * if t==write, value_regno is a register which value is stored into memory 7087 * if t==read, value_regno is a register which will receive the value from memory 7088 * if t==write && value_regno==-1, some unknown value is stored into memory 7089 * if t==read && value_regno==-1, don't care what we read from memory 7090 */ 7091 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 7092 int off, int bpf_size, enum bpf_access_type t, 7093 int value_regno, bool strict_alignment_once, bool is_ldsx) 7094 { 7095 struct bpf_reg_state *regs = cur_regs(env); 7096 struct bpf_reg_state *reg = regs + regno; 7097 int size, err = 0; 7098 7099 size = bpf_size_to_bytes(bpf_size); 7100 if (size < 0) 7101 return size; 7102 7103 /* alignment checks will add in reg->off themselves */ 7104 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 7105 if (err) 7106 return err; 7107 7108 /* for access checks, reg->off is just part of off */ 7109 off += reg->off; 7110 7111 if (reg->type == PTR_TO_MAP_KEY) { 7112 if (t == BPF_WRITE) { 7113 verbose(env, "write to change key R%d not allowed\n", regno); 7114 return -EACCES; 7115 } 7116 7117 err = check_mem_region_access(env, regno, off, size, 7118 reg->map_ptr->key_size, false); 7119 if (err) 7120 return err; 7121 if (value_regno >= 0) 7122 mark_reg_unknown(env, regs, value_regno); 7123 } else if (reg->type == PTR_TO_MAP_VALUE) { 7124 struct btf_field *kptr_field = NULL; 7125 7126 if (t == BPF_WRITE && value_regno >= 0 && 7127 is_pointer_value(env, value_regno)) { 7128 verbose(env, "R%d leaks addr into map\n", value_regno); 7129 return -EACCES; 7130 } 7131 err = check_map_access_type(env, regno, off, size, t); 7132 if (err) 7133 return err; 7134 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 7135 if (err) 7136 return err; 7137 if (tnum_is_const(reg->var_off)) 7138 kptr_field = btf_record_find(reg->map_ptr->record, 7139 off + reg->var_off.value, BPF_KPTR | BPF_UPTR); 7140 if (kptr_field) { 7141 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 7142 } else if (t == BPF_READ && value_regno >= 0) { 7143 struct bpf_map *map = reg->map_ptr; 7144 7145 /* if map is read-only, track its contents as scalars */ 7146 if (tnum_is_const(reg->var_off) && 7147 bpf_map_is_rdonly(map) && 7148 map->ops->map_direct_value_addr) { 7149 int map_off = off + reg->var_off.value; 7150 u64 val = 0; 7151 7152 err = bpf_map_direct_read(map, map_off, size, 7153 &val, is_ldsx); 7154 if (err) 7155 return err; 7156 7157 regs[value_regno].type = SCALAR_VALUE; 7158 __mark_reg_known(®s[value_regno], val); 7159 } else { 7160 mark_reg_unknown(env, regs, value_regno); 7161 } 7162 } 7163 } else if (base_type(reg->type) == PTR_TO_MEM) { 7164 bool rdonly_mem = type_is_rdonly_mem(reg->type); 7165 7166 if (type_may_be_null(reg->type)) { 7167 verbose(env, "R%d invalid mem access '%s'\n", regno, 7168 reg_type_str(env, reg->type)); 7169 return -EACCES; 7170 } 7171 7172 if (t == BPF_WRITE && rdonly_mem) { 7173 verbose(env, "R%d cannot write into %s\n", 7174 regno, reg_type_str(env, reg->type)); 7175 return -EACCES; 7176 } 7177 7178 if (t == BPF_WRITE && value_regno >= 0 && 7179 is_pointer_value(env, value_regno)) { 7180 verbose(env, "R%d leaks addr into mem\n", value_regno); 7181 return -EACCES; 7182 } 7183 7184 err = check_mem_region_access(env, regno, off, size, 7185 reg->mem_size, false); 7186 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 7187 mark_reg_unknown(env, regs, value_regno); 7188 } else if (reg->type == PTR_TO_CTX) { 7189 bool is_retval = false; 7190 struct bpf_retval_range range; 7191 enum bpf_reg_type reg_type = SCALAR_VALUE; 7192 struct btf *btf = NULL; 7193 u32 btf_id = 0; 7194 7195 if (t == BPF_WRITE && value_regno >= 0 && 7196 is_pointer_value(env, value_regno)) { 7197 verbose(env, "R%d leaks addr into ctx\n", value_regno); 7198 return -EACCES; 7199 } 7200 7201 err = check_ptr_off_reg(env, reg, regno); 7202 if (err < 0) 7203 return err; 7204 7205 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 7206 &btf_id, &is_retval, is_ldsx); 7207 if (err) 7208 verbose_linfo(env, insn_idx, "; "); 7209 if (!err && t == BPF_READ && value_regno >= 0) { 7210 /* ctx access returns either a scalar, or a 7211 * PTR_TO_PACKET[_META,_END]. In the latter 7212 * case, we know the offset is zero. 7213 */ 7214 if (reg_type == SCALAR_VALUE) { 7215 if (is_retval && get_func_retval_range(env->prog, &range)) { 7216 err = __mark_reg_s32_range(env, regs, value_regno, 7217 range.minval, range.maxval); 7218 if (err) 7219 return err; 7220 } else { 7221 mark_reg_unknown(env, regs, value_regno); 7222 } 7223 } else { 7224 mark_reg_known_zero(env, regs, 7225 value_regno); 7226 if (type_may_be_null(reg_type)) 7227 regs[value_regno].id = ++env->id_gen; 7228 /* A load of ctx field could have different 7229 * actual load size with the one encoded in the 7230 * insn. When the dst is PTR, it is for sure not 7231 * a sub-register. 7232 */ 7233 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 7234 if (base_type(reg_type) == PTR_TO_BTF_ID) { 7235 regs[value_regno].btf = btf; 7236 regs[value_regno].btf_id = btf_id; 7237 } 7238 } 7239 regs[value_regno].type = reg_type; 7240 } 7241 7242 } else if (reg->type == PTR_TO_STACK) { 7243 /* Basic bounds checks. */ 7244 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 7245 if (err) 7246 return err; 7247 7248 if (t == BPF_READ) 7249 err = check_stack_read(env, regno, off, size, 7250 value_regno); 7251 else 7252 err = check_stack_write(env, regno, off, size, 7253 value_regno, insn_idx); 7254 } else if (reg_is_pkt_pointer(reg)) { 7255 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 7256 verbose(env, "cannot write into packet\n"); 7257 return -EACCES; 7258 } 7259 if (t == BPF_WRITE && value_regno >= 0 && 7260 is_pointer_value(env, value_regno)) { 7261 verbose(env, "R%d leaks addr into packet\n", 7262 value_regno); 7263 return -EACCES; 7264 } 7265 err = check_packet_access(env, regno, off, size, false); 7266 if (!err && t == BPF_READ && value_regno >= 0) 7267 mark_reg_unknown(env, regs, value_regno); 7268 } else if (reg->type == PTR_TO_FLOW_KEYS) { 7269 if (t == BPF_WRITE && value_regno >= 0 && 7270 is_pointer_value(env, value_regno)) { 7271 verbose(env, "R%d leaks addr into flow keys\n", 7272 value_regno); 7273 return -EACCES; 7274 } 7275 7276 err = check_flow_keys_access(env, off, size); 7277 if (!err && t == BPF_READ && value_regno >= 0) 7278 mark_reg_unknown(env, regs, value_regno); 7279 } else if (type_is_sk_pointer(reg->type)) { 7280 if (t == BPF_WRITE) { 7281 verbose(env, "R%d cannot write into %s\n", 7282 regno, reg_type_str(env, reg->type)); 7283 return -EACCES; 7284 } 7285 err = check_sock_access(env, insn_idx, regno, off, size, t); 7286 if (!err && value_regno >= 0) 7287 mark_reg_unknown(env, regs, value_regno); 7288 } else if (reg->type == PTR_TO_TP_BUFFER) { 7289 err = check_tp_buffer_access(env, reg, regno, off, size); 7290 if (!err && t == BPF_READ && value_regno >= 0) 7291 mark_reg_unknown(env, regs, value_regno); 7292 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 7293 !type_may_be_null(reg->type)) { 7294 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 7295 value_regno); 7296 } else if (reg->type == CONST_PTR_TO_MAP) { 7297 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 7298 value_regno); 7299 } else if (base_type(reg->type) == PTR_TO_BUF) { 7300 bool rdonly_mem = type_is_rdonly_mem(reg->type); 7301 u32 *max_access; 7302 7303 if (rdonly_mem) { 7304 if (t == BPF_WRITE) { 7305 verbose(env, "R%d cannot write into %s\n", 7306 regno, reg_type_str(env, reg->type)); 7307 return -EACCES; 7308 } 7309 max_access = &env->prog->aux->max_rdonly_access; 7310 } else { 7311 max_access = &env->prog->aux->max_rdwr_access; 7312 } 7313 7314 err = check_buffer_access(env, reg, regno, off, size, false, 7315 max_access); 7316 7317 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 7318 mark_reg_unknown(env, regs, value_regno); 7319 } else if (reg->type == PTR_TO_ARENA) { 7320 if (t == BPF_READ && value_regno >= 0) 7321 mark_reg_unknown(env, regs, value_regno); 7322 } else { 7323 verbose(env, "R%d invalid mem access '%s'\n", regno, 7324 reg_type_str(env, reg->type)); 7325 return -EACCES; 7326 } 7327 7328 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 7329 regs[value_regno].type == SCALAR_VALUE) { 7330 if (!is_ldsx) 7331 /* b/h/w load zero-extends, mark upper bits as known 0 */ 7332 coerce_reg_to_size(®s[value_regno], size); 7333 else 7334 coerce_reg_to_size_sx(®s[value_regno], size); 7335 } 7336 return err; 7337 } 7338 7339 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 7340 bool allow_trust_mismatch); 7341 7342 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 7343 { 7344 int load_reg; 7345 int err; 7346 7347 switch (insn->imm) { 7348 case BPF_ADD: 7349 case BPF_ADD | BPF_FETCH: 7350 case BPF_AND: 7351 case BPF_AND | BPF_FETCH: 7352 case BPF_OR: 7353 case BPF_OR | BPF_FETCH: 7354 case BPF_XOR: 7355 case BPF_XOR | BPF_FETCH: 7356 case BPF_XCHG: 7357 case BPF_CMPXCHG: 7358 break; 7359 default: 7360 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 7361 return -EINVAL; 7362 } 7363 7364 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 7365 verbose(env, "invalid atomic operand size\n"); 7366 return -EINVAL; 7367 } 7368 7369 /* check src1 operand */ 7370 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7371 if (err) 7372 return err; 7373 7374 /* check src2 operand */ 7375 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 7376 if (err) 7377 return err; 7378 7379 if (insn->imm == BPF_CMPXCHG) { 7380 /* Check comparison of R0 with memory location */ 7381 const u32 aux_reg = BPF_REG_0; 7382 7383 err = check_reg_arg(env, aux_reg, SRC_OP); 7384 if (err) 7385 return err; 7386 7387 if (is_pointer_value(env, aux_reg)) { 7388 verbose(env, "R%d leaks addr into mem\n", aux_reg); 7389 return -EACCES; 7390 } 7391 } 7392 7393 if (is_pointer_value(env, insn->src_reg)) { 7394 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 7395 return -EACCES; 7396 } 7397 7398 if (is_ctx_reg(env, insn->dst_reg) || 7399 is_pkt_reg(env, insn->dst_reg) || 7400 is_flow_key_reg(env, insn->dst_reg) || 7401 is_sk_reg(env, insn->dst_reg) || 7402 (is_arena_reg(env, insn->dst_reg) && !bpf_jit_supports_insn(insn, true))) { 7403 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 7404 insn->dst_reg, 7405 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 7406 return -EACCES; 7407 } 7408 7409 if (insn->imm & BPF_FETCH) { 7410 if (insn->imm == BPF_CMPXCHG) 7411 load_reg = BPF_REG_0; 7412 else 7413 load_reg = insn->src_reg; 7414 7415 /* check and record load of old value */ 7416 err = check_reg_arg(env, load_reg, DST_OP); 7417 if (err) 7418 return err; 7419 } else { 7420 /* This instruction accesses a memory location but doesn't 7421 * actually load it into a register. 7422 */ 7423 load_reg = -1; 7424 } 7425 7426 /* Check whether we can read the memory, with second call for fetch 7427 * case to simulate the register fill. 7428 */ 7429 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7430 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 7431 if (!err && load_reg >= 0) 7432 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7433 BPF_SIZE(insn->code), BPF_READ, load_reg, 7434 true, false); 7435 if (err) 7436 return err; 7437 7438 if (is_arena_reg(env, insn->dst_reg)) { 7439 err = save_aux_ptr_type(env, PTR_TO_ARENA, false); 7440 if (err) 7441 return err; 7442 } 7443 /* Check whether we can write into the same memory. */ 7444 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7445 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 7446 if (err) 7447 return err; 7448 return 0; 7449 } 7450 7451 /* When register 'regno' is used to read the stack (either directly or through 7452 * a helper function) make sure that it's within stack boundary and, depending 7453 * on the access type and privileges, that all elements of the stack are 7454 * initialized. 7455 * 7456 * 'off' includes 'regno->off', but not its dynamic part (if any). 7457 * 7458 * All registers that have been spilled on the stack in the slots within the 7459 * read offsets are marked as read. 7460 */ 7461 static int check_stack_range_initialized( 7462 struct bpf_verifier_env *env, int regno, int off, 7463 int access_size, bool zero_size_allowed, 7464 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 7465 { 7466 struct bpf_reg_state *reg = reg_state(env, regno); 7467 struct bpf_func_state *state = func(env, reg); 7468 int err, min_off, max_off, i, j, slot, spi; 7469 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 7470 enum bpf_access_type bounds_check_type; 7471 /* Some accesses can write anything into the stack, others are 7472 * read-only. 7473 */ 7474 bool clobber = false; 7475 7476 if (access_size == 0 && !zero_size_allowed) { 7477 verbose(env, "invalid zero-sized read\n"); 7478 return -EACCES; 7479 } 7480 7481 if (type == ACCESS_HELPER) { 7482 /* The bounds checks for writes are more permissive than for 7483 * reads. However, if raw_mode is not set, we'll do extra 7484 * checks below. 7485 */ 7486 bounds_check_type = BPF_WRITE; 7487 clobber = true; 7488 } else { 7489 bounds_check_type = BPF_READ; 7490 } 7491 err = check_stack_access_within_bounds(env, regno, off, access_size, 7492 type, bounds_check_type); 7493 if (err) 7494 return err; 7495 7496 7497 if (tnum_is_const(reg->var_off)) { 7498 min_off = max_off = reg->var_off.value + off; 7499 } else { 7500 /* Variable offset is prohibited for unprivileged mode for 7501 * simplicity since it requires corresponding support in 7502 * Spectre masking for stack ALU. 7503 * See also retrieve_ptr_limit(). 7504 */ 7505 if (!env->bypass_spec_v1) { 7506 char tn_buf[48]; 7507 7508 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7509 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 7510 regno, err_extra, tn_buf); 7511 return -EACCES; 7512 } 7513 /* Only initialized buffer on stack is allowed to be accessed 7514 * with variable offset. With uninitialized buffer it's hard to 7515 * guarantee that whole memory is marked as initialized on 7516 * helper return since specific bounds are unknown what may 7517 * cause uninitialized stack leaking. 7518 */ 7519 if (meta && meta->raw_mode) 7520 meta = NULL; 7521 7522 min_off = reg->smin_value + off; 7523 max_off = reg->smax_value + off; 7524 } 7525 7526 if (meta && meta->raw_mode) { 7527 /* Ensure we won't be overwriting dynptrs when simulating byte 7528 * by byte access in check_helper_call using meta.access_size. 7529 * This would be a problem if we have a helper in the future 7530 * which takes: 7531 * 7532 * helper(uninit_mem, len, dynptr) 7533 * 7534 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 7535 * may end up writing to dynptr itself when touching memory from 7536 * arg 1. This can be relaxed on a case by case basis for known 7537 * safe cases, but reject due to the possibilitiy of aliasing by 7538 * default. 7539 */ 7540 for (i = min_off; i < max_off + access_size; i++) { 7541 int stack_off = -i - 1; 7542 7543 spi = __get_spi(i); 7544 /* raw_mode may write past allocated_stack */ 7545 if (state->allocated_stack <= stack_off) 7546 continue; 7547 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 7548 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 7549 return -EACCES; 7550 } 7551 } 7552 meta->access_size = access_size; 7553 meta->regno = regno; 7554 return 0; 7555 } 7556 7557 for (i = min_off; i < max_off + access_size; i++) { 7558 u8 *stype; 7559 7560 slot = -i - 1; 7561 spi = slot / BPF_REG_SIZE; 7562 if (state->allocated_stack <= slot) { 7563 verbose(env, "verifier bug: allocated_stack too small"); 7564 return -EFAULT; 7565 } 7566 7567 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 7568 if (*stype == STACK_MISC) 7569 goto mark; 7570 if ((*stype == STACK_ZERO) || 7571 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 7572 if (clobber) { 7573 /* helper can write anything into the stack */ 7574 *stype = STACK_MISC; 7575 } 7576 goto mark; 7577 } 7578 7579 if (is_spilled_reg(&state->stack[spi]) && 7580 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 7581 env->allow_ptr_leaks)) { 7582 if (clobber) { 7583 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 7584 for (j = 0; j < BPF_REG_SIZE; j++) 7585 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 7586 } 7587 goto mark; 7588 } 7589 7590 if (tnum_is_const(reg->var_off)) { 7591 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 7592 err_extra, regno, min_off, i - min_off, access_size); 7593 } else { 7594 char tn_buf[48]; 7595 7596 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7597 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 7598 err_extra, regno, tn_buf, i - min_off, access_size); 7599 } 7600 return -EACCES; 7601 mark: 7602 /* reading any byte out of 8-byte 'spill_slot' will cause 7603 * the whole slot to be marked as 'read' 7604 */ 7605 mark_reg_read(env, &state->stack[spi].spilled_ptr, 7606 state->stack[spi].spilled_ptr.parent, 7607 REG_LIVE_READ64); 7608 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 7609 * be sure that whether stack slot is written to or not. Hence, 7610 * we must still conservatively propagate reads upwards even if 7611 * helper may write to the entire memory range. 7612 */ 7613 } 7614 return 0; 7615 } 7616 7617 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 7618 int access_size, enum bpf_access_type access_type, 7619 bool zero_size_allowed, 7620 struct bpf_call_arg_meta *meta) 7621 { 7622 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7623 u32 *max_access; 7624 7625 switch (base_type(reg->type)) { 7626 case PTR_TO_PACKET: 7627 case PTR_TO_PACKET_META: 7628 return check_packet_access(env, regno, reg->off, access_size, 7629 zero_size_allowed); 7630 case PTR_TO_MAP_KEY: 7631 if (access_type == BPF_WRITE) { 7632 verbose(env, "R%d cannot write into %s\n", regno, 7633 reg_type_str(env, reg->type)); 7634 return -EACCES; 7635 } 7636 return check_mem_region_access(env, regno, reg->off, access_size, 7637 reg->map_ptr->key_size, false); 7638 case PTR_TO_MAP_VALUE: 7639 if (check_map_access_type(env, regno, reg->off, access_size, access_type)) 7640 return -EACCES; 7641 return check_map_access(env, regno, reg->off, access_size, 7642 zero_size_allowed, ACCESS_HELPER); 7643 case PTR_TO_MEM: 7644 if (type_is_rdonly_mem(reg->type)) { 7645 if (access_type == BPF_WRITE) { 7646 verbose(env, "R%d cannot write into %s\n", regno, 7647 reg_type_str(env, reg->type)); 7648 return -EACCES; 7649 } 7650 } 7651 return check_mem_region_access(env, regno, reg->off, 7652 access_size, reg->mem_size, 7653 zero_size_allowed); 7654 case PTR_TO_BUF: 7655 if (type_is_rdonly_mem(reg->type)) { 7656 if (access_type == BPF_WRITE) { 7657 verbose(env, "R%d cannot write into %s\n", regno, 7658 reg_type_str(env, reg->type)); 7659 return -EACCES; 7660 } 7661 7662 max_access = &env->prog->aux->max_rdonly_access; 7663 } else { 7664 max_access = &env->prog->aux->max_rdwr_access; 7665 } 7666 return check_buffer_access(env, reg, regno, reg->off, 7667 access_size, zero_size_allowed, 7668 max_access); 7669 case PTR_TO_STACK: 7670 return check_stack_range_initialized( 7671 env, 7672 regno, reg->off, access_size, 7673 zero_size_allowed, ACCESS_HELPER, meta); 7674 case PTR_TO_BTF_ID: 7675 return check_ptr_to_btf_access(env, regs, regno, reg->off, 7676 access_size, BPF_READ, -1); 7677 case PTR_TO_CTX: 7678 /* in case the function doesn't know how to access the context, 7679 * (because we are in a program of type SYSCALL for example), we 7680 * can not statically check its size. 7681 * Dynamically check it now. 7682 */ 7683 if (!env->ops->convert_ctx_access) { 7684 int offset = access_size - 1; 7685 7686 /* Allow zero-byte read from PTR_TO_CTX */ 7687 if (access_size == 0) 7688 return zero_size_allowed ? 0 : -EACCES; 7689 7690 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 7691 access_type, -1, false, false); 7692 } 7693 7694 fallthrough; 7695 default: /* scalar_value or invalid ptr */ 7696 /* Allow zero-byte read from NULL, regardless of pointer type */ 7697 if (zero_size_allowed && access_size == 0 && 7698 register_is_null(reg)) 7699 return 0; 7700 7701 verbose(env, "R%d type=%s ", regno, 7702 reg_type_str(env, reg->type)); 7703 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7704 return -EACCES; 7705 } 7706 } 7707 7708 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 7709 * size. 7710 * 7711 * @regno is the register containing the access size. regno-1 is the register 7712 * containing the pointer. 7713 */ 7714 static int check_mem_size_reg(struct bpf_verifier_env *env, 7715 struct bpf_reg_state *reg, u32 regno, 7716 enum bpf_access_type access_type, 7717 bool zero_size_allowed, 7718 struct bpf_call_arg_meta *meta) 7719 { 7720 int err; 7721 7722 /* This is used to refine r0 return value bounds for helpers 7723 * that enforce this value as an upper bound on return values. 7724 * See do_refine_retval_range() for helpers that can refine 7725 * the return value. C type of helper is u32 so we pull register 7726 * bound from umax_value however, if negative verifier errors 7727 * out. Only upper bounds can be learned because retval is an 7728 * int type and negative retvals are allowed. 7729 */ 7730 meta->msize_max_value = reg->umax_value; 7731 7732 /* The register is SCALAR_VALUE; the access check happens using 7733 * its boundaries. For unprivileged variable accesses, disable 7734 * raw mode so that the program is required to initialize all 7735 * the memory that the helper could just partially fill up. 7736 */ 7737 if (!tnum_is_const(reg->var_off)) 7738 meta = NULL; 7739 7740 if (reg->smin_value < 0) { 7741 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7742 regno); 7743 return -EACCES; 7744 } 7745 7746 if (reg->umin_value == 0 && !zero_size_allowed) { 7747 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n", 7748 regno, reg->umin_value, reg->umax_value); 7749 return -EACCES; 7750 } 7751 7752 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7753 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7754 regno); 7755 return -EACCES; 7756 } 7757 err = check_helper_mem_access(env, regno - 1, reg->umax_value, 7758 access_type, zero_size_allowed, meta); 7759 if (!err) 7760 err = mark_chain_precision(env, regno); 7761 return err; 7762 } 7763 7764 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7765 u32 regno, u32 mem_size) 7766 { 7767 bool may_be_null = type_may_be_null(reg->type); 7768 struct bpf_reg_state saved_reg; 7769 int err; 7770 7771 if (register_is_null(reg)) 7772 return 0; 7773 7774 /* Assuming that the register contains a value check if the memory 7775 * access is safe. Temporarily save and restore the register's state as 7776 * the conversion shouldn't be visible to a caller. 7777 */ 7778 if (may_be_null) { 7779 saved_reg = *reg; 7780 mark_ptr_not_null_reg(reg); 7781 } 7782 7783 err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL); 7784 err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL); 7785 7786 if (may_be_null) 7787 *reg = saved_reg; 7788 7789 return err; 7790 } 7791 7792 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7793 u32 regno) 7794 { 7795 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7796 bool may_be_null = type_may_be_null(mem_reg->type); 7797 struct bpf_reg_state saved_reg; 7798 struct bpf_call_arg_meta meta; 7799 int err; 7800 7801 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7802 7803 memset(&meta, 0, sizeof(meta)); 7804 7805 if (may_be_null) { 7806 saved_reg = *mem_reg; 7807 mark_ptr_not_null_reg(mem_reg); 7808 } 7809 7810 err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta); 7811 err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta); 7812 7813 if (may_be_null) 7814 *mem_reg = saved_reg; 7815 7816 return err; 7817 } 7818 7819 /* Implementation details: 7820 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7821 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7822 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7823 * Two separate bpf_obj_new will also have different reg->id. 7824 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7825 * clears reg->id after value_or_null->value transition, since the verifier only 7826 * cares about the range of access to valid map value pointer and doesn't care 7827 * about actual address of the map element. 7828 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7829 * reg->id > 0 after value_or_null->value transition. By doing so 7830 * two bpf_map_lookups will be considered two different pointers that 7831 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7832 * returned from bpf_obj_new. 7833 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7834 * dead-locks. 7835 * Since only one bpf_spin_lock is allowed the checks are simpler than 7836 * reg_is_refcounted() logic. The verifier needs to remember only 7837 * one spin_lock instead of array of acquired_refs. 7838 * cur_func(env)->active_locks remembers which map value element or allocated 7839 * object got locked and clears it after bpf_spin_unlock. 7840 */ 7841 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 7842 bool is_lock) 7843 { 7844 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7845 bool is_const = tnum_is_const(reg->var_off); 7846 struct bpf_func_state *cur = cur_func(env); 7847 u64 val = reg->var_off.value; 7848 struct bpf_map *map = NULL; 7849 struct btf *btf = NULL; 7850 struct btf_record *rec; 7851 int err; 7852 7853 if (!is_const) { 7854 verbose(env, 7855 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 7856 regno); 7857 return -EINVAL; 7858 } 7859 if (reg->type == PTR_TO_MAP_VALUE) { 7860 map = reg->map_ptr; 7861 if (!map->btf) { 7862 verbose(env, 7863 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 7864 map->name); 7865 return -EINVAL; 7866 } 7867 } else { 7868 btf = reg->btf; 7869 } 7870 7871 rec = reg_btf_record(reg); 7872 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 7873 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 7874 map ? map->name : "kptr"); 7875 return -EINVAL; 7876 } 7877 if (rec->spin_lock_off != val + reg->off) { 7878 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 7879 val + reg->off, rec->spin_lock_off); 7880 return -EINVAL; 7881 } 7882 if (is_lock) { 7883 void *ptr; 7884 7885 if (map) 7886 ptr = map; 7887 else 7888 ptr = btf; 7889 7890 if (cur->active_locks) { 7891 verbose(env, 7892 "Locking two bpf_spin_locks are not allowed\n"); 7893 return -EINVAL; 7894 } 7895 err = acquire_lock_state(env, env->insn_idx, REF_TYPE_LOCK, reg->id, ptr); 7896 if (err < 0) { 7897 verbose(env, "Failed to acquire lock state\n"); 7898 return err; 7899 } 7900 } else { 7901 void *ptr; 7902 7903 if (map) 7904 ptr = map; 7905 else 7906 ptr = btf; 7907 7908 if (!cur->active_locks) { 7909 verbose(env, "bpf_spin_unlock without taking a lock\n"); 7910 return -EINVAL; 7911 } 7912 7913 if (release_lock_state(cur_func(env), REF_TYPE_LOCK, reg->id, ptr)) { 7914 verbose(env, "bpf_spin_unlock of different lock\n"); 7915 return -EINVAL; 7916 } 7917 7918 invalidate_non_owning_refs(env); 7919 } 7920 return 0; 7921 } 7922 7923 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7924 struct bpf_call_arg_meta *meta) 7925 { 7926 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7927 bool is_const = tnum_is_const(reg->var_off); 7928 struct bpf_map *map = reg->map_ptr; 7929 u64 val = reg->var_off.value; 7930 7931 if (!is_const) { 7932 verbose(env, 7933 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 7934 regno); 7935 return -EINVAL; 7936 } 7937 if (!map->btf) { 7938 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 7939 map->name); 7940 return -EINVAL; 7941 } 7942 if (!btf_record_has_field(map->record, BPF_TIMER)) { 7943 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 7944 return -EINVAL; 7945 } 7946 if (map->record->timer_off != val + reg->off) { 7947 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 7948 val + reg->off, map->record->timer_off); 7949 return -EINVAL; 7950 } 7951 if (meta->map_ptr) { 7952 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 7953 return -EFAULT; 7954 } 7955 meta->map_uid = reg->map_uid; 7956 meta->map_ptr = map; 7957 return 0; 7958 } 7959 7960 static int process_wq_func(struct bpf_verifier_env *env, int regno, 7961 struct bpf_kfunc_call_arg_meta *meta) 7962 { 7963 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7964 struct bpf_map *map = reg->map_ptr; 7965 u64 val = reg->var_off.value; 7966 7967 if (map->record->wq_off != val + reg->off) { 7968 verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n", 7969 val + reg->off, map->record->wq_off); 7970 return -EINVAL; 7971 } 7972 meta->map.uid = reg->map_uid; 7973 meta->map.ptr = map; 7974 return 0; 7975 } 7976 7977 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7978 struct bpf_call_arg_meta *meta) 7979 { 7980 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7981 struct btf_field *kptr_field; 7982 struct bpf_map *map_ptr; 7983 struct btf_record *rec; 7984 u32 kptr_off; 7985 7986 if (type_is_ptr_alloc_obj(reg->type)) { 7987 rec = reg_btf_record(reg); 7988 } else { /* PTR_TO_MAP_VALUE */ 7989 map_ptr = reg->map_ptr; 7990 if (!map_ptr->btf) { 7991 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7992 map_ptr->name); 7993 return -EINVAL; 7994 } 7995 rec = map_ptr->record; 7996 meta->map_ptr = map_ptr; 7997 } 7998 7999 if (!tnum_is_const(reg->var_off)) { 8000 verbose(env, 8001 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 8002 regno); 8003 return -EINVAL; 8004 } 8005 8006 if (!btf_record_has_field(rec, BPF_KPTR)) { 8007 verbose(env, "R%d has no valid kptr\n", regno); 8008 return -EINVAL; 8009 } 8010 8011 kptr_off = reg->off + reg->var_off.value; 8012 kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR); 8013 if (!kptr_field) { 8014 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 8015 return -EACCES; 8016 } 8017 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 8018 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 8019 return -EACCES; 8020 } 8021 meta->kptr_field = kptr_field; 8022 return 0; 8023 } 8024 8025 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 8026 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 8027 * 8028 * In both cases we deal with the first 8 bytes, but need to mark the next 8 8029 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 8030 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 8031 * 8032 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 8033 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 8034 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 8035 * mutate the view of the dynptr and also possibly destroy it. In the latter 8036 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 8037 * memory that dynptr points to. 8038 * 8039 * The verifier will keep track both levels of mutation (bpf_dynptr's in 8040 * reg->type and the memory's in reg->dynptr.type), but there is no support for 8041 * readonly dynptr view yet, hence only the first case is tracked and checked. 8042 * 8043 * This is consistent with how C applies the const modifier to a struct object, 8044 * where the pointer itself inside bpf_dynptr becomes const but not what it 8045 * points to. 8046 * 8047 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 8048 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 8049 */ 8050 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 8051 enum bpf_arg_type arg_type, int clone_ref_obj_id) 8052 { 8053 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8054 int err; 8055 8056 if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) { 8057 verbose(env, 8058 "arg#%d expected pointer to stack or const struct bpf_dynptr\n", 8059 regno - 1); 8060 return -EINVAL; 8061 } 8062 8063 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 8064 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 8065 */ 8066 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 8067 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 8068 return -EFAULT; 8069 } 8070 8071 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 8072 * constructing a mutable bpf_dynptr object. 8073 * 8074 * Currently, this is only possible with PTR_TO_STACK 8075 * pointing to a region of at least 16 bytes which doesn't 8076 * contain an existing bpf_dynptr. 8077 * 8078 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 8079 * mutated or destroyed. However, the memory it points to 8080 * may be mutated. 8081 * 8082 * None - Points to a initialized dynptr that can be mutated and 8083 * destroyed, including mutation of the memory it points 8084 * to. 8085 */ 8086 if (arg_type & MEM_UNINIT) { 8087 int i; 8088 8089 if (!is_dynptr_reg_valid_uninit(env, reg)) { 8090 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 8091 return -EINVAL; 8092 } 8093 8094 /* we write BPF_DW bits (8 bytes) at a time */ 8095 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 8096 err = check_mem_access(env, insn_idx, regno, 8097 i, BPF_DW, BPF_WRITE, -1, false, false); 8098 if (err) 8099 return err; 8100 } 8101 8102 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 8103 } else /* MEM_RDONLY and None case from above */ { 8104 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 8105 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 8106 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 8107 return -EINVAL; 8108 } 8109 8110 if (!is_dynptr_reg_valid_init(env, reg)) { 8111 verbose(env, 8112 "Expected an initialized dynptr as arg #%d\n", 8113 regno - 1); 8114 return -EINVAL; 8115 } 8116 8117 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 8118 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 8119 verbose(env, 8120 "Expected a dynptr of type %s as arg #%d\n", 8121 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno - 1); 8122 return -EINVAL; 8123 } 8124 8125 err = mark_dynptr_read(env, reg); 8126 } 8127 return err; 8128 } 8129 8130 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 8131 { 8132 struct bpf_func_state *state = func(env, reg); 8133 8134 return state->stack[spi].spilled_ptr.ref_obj_id; 8135 } 8136 8137 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 8138 { 8139 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 8140 } 8141 8142 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 8143 { 8144 return meta->kfunc_flags & KF_ITER_NEW; 8145 } 8146 8147 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 8148 { 8149 return meta->kfunc_flags & KF_ITER_NEXT; 8150 } 8151 8152 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 8153 { 8154 return meta->kfunc_flags & KF_ITER_DESTROY; 8155 } 8156 8157 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx, 8158 const struct btf_param *arg) 8159 { 8160 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 8161 * kfunc is iter state pointer 8162 */ 8163 if (is_iter_kfunc(meta)) 8164 return arg_idx == 0; 8165 8166 /* iter passed as an argument to a generic kfunc */ 8167 return btf_param_match_suffix(meta->btf, arg, "__iter"); 8168 } 8169 8170 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 8171 struct bpf_kfunc_call_arg_meta *meta) 8172 { 8173 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8174 const struct btf_type *t; 8175 int spi, err, i, nr_slots, btf_id; 8176 8177 if (reg->type != PTR_TO_STACK) { 8178 verbose(env, "arg#%d expected pointer to an iterator on stack\n", regno - 1); 8179 return -EINVAL; 8180 } 8181 8182 /* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs() 8183 * ensures struct convention, so we wouldn't need to do any BTF 8184 * validation here. But given iter state can be passed as a parameter 8185 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more 8186 * conservative here. 8187 */ 8188 btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1); 8189 if (btf_id < 0) { 8190 verbose(env, "expected valid iter pointer as arg #%d\n", regno - 1); 8191 return -EINVAL; 8192 } 8193 t = btf_type_by_id(meta->btf, btf_id); 8194 nr_slots = t->size / BPF_REG_SIZE; 8195 8196 if (is_iter_new_kfunc(meta)) { 8197 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 8198 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 8199 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 8200 iter_type_str(meta->btf, btf_id), regno - 1); 8201 return -EINVAL; 8202 } 8203 8204 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 8205 err = check_mem_access(env, insn_idx, regno, 8206 i, BPF_DW, BPF_WRITE, -1, false, false); 8207 if (err) 8208 return err; 8209 } 8210 8211 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 8212 if (err) 8213 return err; 8214 } else { 8215 /* iter_next() or iter_destroy(), as well as any kfunc 8216 * accepting iter argument, expect initialized iter state 8217 */ 8218 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 8219 switch (err) { 8220 case 0: 8221 break; 8222 case -EINVAL: 8223 verbose(env, "expected an initialized iter_%s as arg #%d\n", 8224 iter_type_str(meta->btf, btf_id), regno - 1); 8225 return err; 8226 case -EPROTO: 8227 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 8228 return err; 8229 default: 8230 return err; 8231 } 8232 8233 spi = iter_get_spi(env, reg, nr_slots); 8234 if (spi < 0) 8235 return spi; 8236 8237 err = mark_iter_read(env, reg, spi, nr_slots); 8238 if (err) 8239 return err; 8240 8241 /* remember meta->iter info for process_iter_next_call() */ 8242 meta->iter.spi = spi; 8243 meta->iter.frameno = reg->frameno; 8244 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 8245 8246 if (is_iter_destroy_kfunc(meta)) { 8247 err = unmark_stack_slots_iter(env, reg, nr_slots); 8248 if (err) 8249 return err; 8250 } 8251 } 8252 8253 return 0; 8254 } 8255 8256 /* Look for a previous loop entry at insn_idx: nearest parent state 8257 * stopped at insn_idx with callsites matching those in cur->frame. 8258 */ 8259 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 8260 struct bpf_verifier_state *cur, 8261 int insn_idx) 8262 { 8263 struct bpf_verifier_state_list *sl; 8264 struct bpf_verifier_state *st; 8265 8266 /* Explored states are pushed in stack order, most recent states come first */ 8267 sl = *explored_state(env, insn_idx); 8268 for (; sl; sl = sl->next) { 8269 /* If st->branches != 0 state is a part of current DFS verification path, 8270 * hence cur & st for a loop. 8271 */ 8272 st = &sl->state; 8273 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 8274 st->dfs_depth < cur->dfs_depth) 8275 return st; 8276 } 8277 8278 return NULL; 8279 } 8280 8281 static void reset_idmap_scratch(struct bpf_verifier_env *env); 8282 static bool regs_exact(const struct bpf_reg_state *rold, 8283 const struct bpf_reg_state *rcur, 8284 struct bpf_idmap *idmap); 8285 8286 static void maybe_widen_reg(struct bpf_verifier_env *env, 8287 struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 8288 struct bpf_idmap *idmap) 8289 { 8290 if (rold->type != SCALAR_VALUE) 8291 return; 8292 if (rold->type != rcur->type) 8293 return; 8294 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap)) 8295 return; 8296 __mark_reg_unknown(env, rcur); 8297 } 8298 8299 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 8300 struct bpf_verifier_state *old, 8301 struct bpf_verifier_state *cur) 8302 { 8303 struct bpf_func_state *fold, *fcur; 8304 int i, fr; 8305 8306 reset_idmap_scratch(env); 8307 for (fr = old->curframe; fr >= 0; fr--) { 8308 fold = old->frame[fr]; 8309 fcur = cur->frame[fr]; 8310 8311 for (i = 0; i < MAX_BPF_REG; i++) 8312 maybe_widen_reg(env, 8313 &fold->regs[i], 8314 &fcur->regs[i], 8315 &env->idmap_scratch); 8316 8317 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) { 8318 if (!is_spilled_reg(&fold->stack[i]) || 8319 !is_spilled_reg(&fcur->stack[i])) 8320 continue; 8321 8322 maybe_widen_reg(env, 8323 &fold->stack[i].spilled_ptr, 8324 &fcur->stack[i].spilled_ptr, 8325 &env->idmap_scratch); 8326 } 8327 } 8328 return 0; 8329 } 8330 8331 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st, 8332 struct bpf_kfunc_call_arg_meta *meta) 8333 { 8334 int iter_frameno = meta->iter.frameno; 8335 int iter_spi = meta->iter.spi; 8336 8337 return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 8338 } 8339 8340 /* process_iter_next_call() is called when verifier gets to iterator's next 8341 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 8342 * to it as just "iter_next()" in comments below. 8343 * 8344 * BPF verifier relies on a crucial contract for any iter_next() 8345 * implementation: it should *eventually* return NULL, and once that happens 8346 * it should keep returning NULL. That is, once iterator exhausts elements to 8347 * iterate, it should never reset or spuriously return new elements. 8348 * 8349 * With the assumption of such contract, process_iter_next_call() simulates 8350 * a fork in the verifier state to validate loop logic correctness and safety 8351 * without having to simulate infinite amount of iterations. 8352 * 8353 * In current state, we first assume that iter_next() returned NULL and 8354 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 8355 * conditions we should not form an infinite loop and should eventually reach 8356 * exit. 8357 * 8358 * Besides that, we also fork current state and enqueue it for later 8359 * verification. In a forked state we keep iterator state as ACTIVE 8360 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 8361 * also bump iteration depth to prevent erroneous infinite loop detection 8362 * later on (see iter_active_depths_differ() comment for details). In this 8363 * state we assume that we'll eventually loop back to another iter_next() 8364 * calls (it could be in exactly same location or in some other instruction, 8365 * it doesn't matter, we don't make any unnecessary assumptions about this, 8366 * everything revolves around iterator state in a stack slot, not which 8367 * instruction is calling iter_next()). When that happens, we either will come 8368 * to iter_next() with equivalent state and can conclude that next iteration 8369 * will proceed in exactly the same way as we just verified, so it's safe to 8370 * assume that loop converges. If not, we'll go on another iteration 8371 * simulation with a different input state, until all possible starting states 8372 * are validated or we reach maximum number of instructions limit. 8373 * 8374 * This way, we will either exhaustively discover all possible input states 8375 * that iterator loop can start with and eventually will converge, or we'll 8376 * effectively regress into bounded loop simulation logic and either reach 8377 * maximum number of instructions if loop is not provably convergent, or there 8378 * is some statically known limit on number of iterations (e.g., if there is 8379 * an explicit `if n > 100 then break;` statement somewhere in the loop). 8380 * 8381 * Iteration convergence logic in is_state_visited() relies on exact 8382 * states comparison, which ignores read and precision marks. 8383 * This is necessary because read and precision marks are not finalized 8384 * while in the loop. Exact comparison might preclude convergence for 8385 * simple programs like below: 8386 * 8387 * i = 0; 8388 * while(iter_next(&it)) 8389 * i++; 8390 * 8391 * At each iteration step i++ would produce a new distinct state and 8392 * eventually instruction processing limit would be reached. 8393 * 8394 * To avoid such behavior speculatively forget (widen) range for 8395 * imprecise scalar registers, if those registers were not precise at the 8396 * end of the previous iteration and do not match exactly. 8397 * 8398 * This is a conservative heuristic that allows to verify wide range of programs, 8399 * however it precludes verification of programs that conjure an 8400 * imprecise value on the first loop iteration and use it as precise on a second. 8401 * For example, the following safe program would fail to verify: 8402 * 8403 * struct bpf_num_iter it; 8404 * int arr[10]; 8405 * int i = 0, a = 0; 8406 * bpf_iter_num_new(&it, 0, 10); 8407 * while (bpf_iter_num_next(&it)) { 8408 * if (a == 0) { 8409 * a = 1; 8410 * i = 7; // Because i changed verifier would forget 8411 * // it's range on second loop entry. 8412 * } else { 8413 * arr[i] = 42; // This would fail to verify. 8414 * } 8415 * } 8416 * bpf_iter_num_destroy(&it); 8417 */ 8418 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 8419 struct bpf_kfunc_call_arg_meta *meta) 8420 { 8421 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 8422 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 8423 struct bpf_reg_state *cur_iter, *queued_iter; 8424 8425 BTF_TYPE_EMIT(struct bpf_iter); 8426 8427 cur_iter = get_iter_from_state(cur_st, meta); 8428 8429 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 8430 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 8431 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 8432 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 8433 return -EFAULT; 8434 } 8435 8436 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 8437 /* Because iter_next() call is a checkpoint is_state_visitied() 8438 * should guarantee parent state with same call sites and insn_idx. 8439 */ 8440 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 8441 !same_callsites(cur_st->parent, cur_st)) { 8442 verbose(env, "bug: bad parent state for iter next call"); 8443 return -EFAULT; 8444 } 8445 /* Note cur_st->parent in the call below, it is necessary to skip 8446 * checkpoint created for cur_st by is_state_visited() 8447 * right at this instruction. 8448 */ 8449 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 8450 /* branch out active iter state */ 8451 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 8452 if (!queued_st) 8453 return -ENOMEM; 8454 8455 queued_iter = get_iter_from_state(queued_st, meta); 8456 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 8457 queued_iter->iter.depth++; 8458 if (prev_st) 8459 widen_imprecise_scalars(env, prev_st, queued_st); 8460 8461 queued_fr = queued_st->frame[queued_st->curframe]; 8462 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 8463 } 8464 8465 /* switch to DRAINED state, but keep the depth unchanged */ 8466 /* mark current iter state as drained and assume returned NULL */ 8467 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 8468 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 8469 8470 return 0; 8471 } 8472 8473 static bool arg_type_is_mem_size(enum bpf_arg_type type) 8474 { 8475 return type == ARG_CONST_SIZE || 8476 type == ARG_CONST_SIZE_OR_ZERO; 8477 } 8478 8479 static bool arg_type_is_raw_mem(enum bpf_arg_type type) 8480 { 8481 return base_type(type) == ARG_PTR_TO_MEM && 8482 type & MEM_UNINIT; 8483 } 8484 8485 static bool arg_type_is_release(enum bpf_arg_type type) 8486 { 8487 return type & OBJ_RELEASE; 8488 } 8489 8490 static bool arg_type_is_dynptr(enum bpf_arg_type type) 8491 { 8492 return base_type(type) == ARG_PTR_TO_DYNPTR; 8493 } 8494 8495 static int resolve_map_arg_type(struct bpf_verifier_env *env, 8496 const struct bpf_call_arg_meta *meta, 8497 enum bpf_arg_type *arg_type) 8498 { 8499 if (!meta->map_ptr) { 8500 /* kernel subsystem misconfigured verifier */ 8501 verbose(env, "invalid map_ptr to access map->type\n"); 8502 return -EACCES; 8503 } 8504 8505 switch (meta->map_ptr->map_type) { 8506 case BPF_MAP_TYPE_SOCKMAP: 8507 case BPF_MAP_TYPE_SOCKHASH: 8508 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 8509 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 8510 } else { 8511 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 8512 return -EINVAL; 8513 } 8514 break; 8515 case BPF_MAP_TYPE_BLOOM_FILTER: 8516 if (meta->func_id == BPF_FUNC_map_peek_elem) 8517 *arg_type = ARG_PTR_TO_MAP_VALUE; 8518 break; 8519 default: 8520 break; 8521 } 8522 return 0; 8523 } 8524 8525 struct bpf_reg_types { 8526 const enum bpf_reg_type types[10]; 8527 u32 *btf_id; 8528 }; 8529 8530 static const struct bpf_reg_types sock_types = { 8531 .types = { 8532 PTR_TO_SOCK_COMMON, 8533 PTR_TO_SOCKET, 8534 PTR_TO_TCP_SOCK, 8535 PTR_TO_XDP_SOCK, 8536 }, 8537 }; 8538 8539 #ifdef CONFIG_NET 8540 static const struct bpf_reg_types btf_id_sock_common_types = { 8541 .types = { 8542 PTR_TO_SOCK_COMMON, 8543 PTR_TO_SOCKET, 8544 PTR_TO_TCP_SOCK, 8545 PTR_TO_XDP_SOCK, 8546 PTR_TO_BTF_ID, 8547 PTR_TO_BTF_ID | PTR_TRUSTED, 8548 }, 8549 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 8550 }; 8551 #endif 8552 8553 static const struct bpf_reg_types mem_types = { 8554 .types = { 8555 PTR_TO_STACK, 8556 PTR_TO_PACKET, 8557 PTR_TO_PACKET_META, 8558 PTR_TO_MAP_KEY, 8559 PTR_TO_MAP_VALUE, 8560 PTR_TO_MEM, 8561 PTR_TO_MEM | MEM_RINGBUF, 8562 PTR_TO_BUF, 8563 PTR_TO_BTF_ID | PTR_TRUSTED, 8564 }, 8565 }; 8566 8567 static const struct bpf_reg_types spin_lock_types = { 8568 .types = { 8569 PTR_TO_MAP_VALUE, 8570 PTR_TO_BTF_ID | MEM_ALLOC, 8571 } 8572 }; 8573 8574 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 8575 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 8576 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 8577 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 8578 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 8579 static const struct bpf_reg_types btf_ptr_types = { 8580 .types = { 8581 PTR_TO_BTF_ID, 8582 PTR_TO_BTF_ID | PTR_TRUSTED, 8583 PTR_TO_BTF_ID | MEM_RCU, 8584 }, 8585 }; 8586 static const struct bpf_reg_types percpu_btf_ptr_types = { 8587 .types = { 8588 PTR_TO_BTF_ID | MEM_PERCPU, 8589 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 8590 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 8591 } 8592 }; 8593 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 8594 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 8595 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8596 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 8597 static const struct bpf_reg_types kptr_xchg_dest_types = { 8598 .types = { 8599 PTR_TO_MAP_VALUE, 8600 PTR_TO_BTF_ID | MEM_ALLOC 8601 } 8602 }; 8603 static const struct bpf_reg_types dynptr_types = { 8604 .types = { 8605 PTR_TO_STACK, 8606 CONST_PTR_TO_DYNPTR, 8607 } 8608 }; 8609 8610 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 8611 [ARG_PTR_TO_MAP_KEY] = &mem_types, 8612 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 8613 [ARG_CONST_SIZE] = &scalar_types, 8614 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 8615 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 8616 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 8617 [ARG_PTR_TO_CTX] = &context_types, 8618 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 8619 #ifdef CONFIG_NET 8620 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 8621 #endif 8622 [ARG_PTR_TO_SOCKET] = &fullsock_types, 8623 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 8624 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 8625 [ARG_PTR_TO_MEM] = &mem_types, 8626 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 8627 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 8628 [ARG_PTR_TO_FUNC] = &func_ptr_types, 8629 [ARG_PTR_TO_STACK] = &stack_ptr_types, 8630 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 8631 [ARG_PTR_TO_TIMER] = &timer_types, 8632 [ARG_KPTR_XCHG_DEST] = &kptr_xchg_dest_types, 8633 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 8634 }; 8635 8636 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 8637 enum bpf_arg_type arg_type, 8638 const u32 *arg_btf_id, 8639 struct bpf_call_arg_meta *meta) 8640 { 8641 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8642 enum bpf_reg_type expected, type = reg->type; 8643 const struct bpf_reg_types *compatible; 8644 int i, j; 8645 8646 compatible = compatible_reg_types[base_type(arg_type)]; 8647 if (!compatible) { 8648 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 8649 return -EFAULT; 8650 } 8651 8652 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 8653 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 8654 * 8655 * Same for MAYBE_NULL: 8656 * 8657 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 8658 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 8659 * 8660 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 8661 * 8662 * Therefore we fold these flags depending on the arg_type before comparison. 8663 */ 8664 if (arg_type & MEM_RDONLY) 8665 type &= ~MEM_RDONLY; 8666 if (arg_type & PTR_MAYBE_NULL) 8667 type &= ~PTR_MAYBE_NULL; 8668 if (base_type(arg_type) == ARG_PTR_TO_MEM) 8669 type &= ~DYNPTR_TYPE_FLAG_MASK; 8670 8671 /* Local kptr types are allowed as the source argument of bpf_kptr_xchg */ 8672 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) { 8673 type &= ~MEM_ALLOC; 8674 type &= ~MEM_PERCPU; 8675 } 8676 8677 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 8678 expected = compatible->types[i]; 8679 if (expected == NOT_INIT) 8680 break; 8681 8682 if (type == expected) 8683 goto found; 8684 } 8685 8686 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 8687 for (j = 0; j + 1 < i; j++) 8688 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 8689 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 8690 return -EACCES; 8691 8692 found: 8693 if (base_type(reg->type) != PTR_TO_BTF_ID) 8694 return 0; 8695 8696 if (compatible == &mem_types) { 8697 if (!(arg_type & MEM_RDONLY)) { 8698 verbose(env, 8699 "%s() may write into memory pointed by R%d type=%s\n", 8700 func_id_name(meta->func_id), 8701 regno, reg_type_str(env, reg->type)); 8702 return -EACCES; 8703 } 8704 return 0; 8705 } 8706 8707 switch ((int)reg->type) { 8708 case PTR_TO_BTF_ID: 8709 case PTR_TO_BTF_ID | PTR_TRUSTED: 8710 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL: 8711 case PTR_TO_BTF_ID | MEM_RCU: 8712 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 8713 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 8714 { 8715 /* For bpf_sk_release, it needs to match against first member 8716 * 'struct sock_common', hence make an exception for it. This 8717 * allows bpf_sk_release to work for multiple socket types. 8718 */ 8719 bool strict_type_match = arg_type_is_release(arg_type) && 8720 meta->func_id != BPF_FUNC_sk_release; 8721 8722 if (type_may_be_null(reg->type) && 8723 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 8724 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 8725 return -EACCES; 8726 } 8727 8728 if (!arg_btf_id) { 8729 if (!compatible->btf_id) { 8730 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 8731 return -EFAULT; 8732 } 8733 arg_btf_id = compatible->btf_id; 8734 } 8735 8736 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8737 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8738 return -EACCES; 8739 } else { 8740 if (arg_btf_id == BPF_PTR_POISON) { 8741 verbose(env, "verifier internal error:"); 8742 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 8743 regno); 8744 return -EACCES; 8745 } 8746 8747 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 8748 btf_vmlinux, *arg_btf_id, 8749 strict_type_match)) { 8750 verbose(env, "R%d is of type %s but %s is expected\n", 8751 regno, btf_type_name(reg->btf, reg->btf_id), 8752 btf_type_name(btf_vmlinux, *arg_btf_id)); 8753 return -EACCES; 8754 } 8755 } 8756 break; 8757 } 8758 case PTR_TO_BTF_ID | MEM_ALLOC: 8759 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 8760 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8761 meta->func_id != BPF_FUNC_kptr_xchg) { 8762 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 8763 return -EFAULT; 8764 } 8765 /* Check if local kptr in src arg matches kptr in dst arg */ 8766 if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) { 8767 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8768 return -EACCES; 8769 } 8770 break; 8771 case PTR_TO_BTF_ID | MEM_PERCPU: 8772 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 8773 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8774 /* Handled by helper specific checks */ 8775 break; 8776 default: 8777 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 8778 return -EFAULT; 8779 } 8780 return 0; 8781 } 8782 8783 static struct btf_field * 8784 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8785 { 8786 struct btf_field *field; 8787 struct btf_record *rec; 8788 8789 rec = reg_btf_record(reg); 8790 if (!rec) 8791 return NULL; 8792 8793 field = btf_record_find(rec, off, fields); 8794 if (!field) 8795 return NULL; 8796 8797 return field; 8798 } 8799 8800 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 8801 const struct bpf_reg_state *reg, int regno, 8802 enum bpf_arg_type arg_type) 8803 { 8804 u32 type = reg->type; 8805 8806 /* When referenced register is passed to release function, its fixed 8807 * offset must be 0. 8808 * 8809 * We will check arg_type_is_release reg has ref_obj_id when storing 8810 * meta->release_regno. 8811 */ 8812 if (arg_type_is_release(arg_type)) { 8813 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8814 * may not directly point to the object being released, but to 8815 * dynptr pointing to such object, which might be at some offset 8816 * on the stack. In that case, we simply to fallback to the 8817 * default handling. 8818 */ 8819 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8820 return 0; 8821 8822 /* Doing check_ptr_off_reg check for the offset will catch this 8823 * because fixed_off_ok is false, but checking here allows us 8824 * to give the user a better error message. 8825 */ 8826 if (reg->off) { 8827 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 8828 regno); 8829 return -EINVAL; 8830 } 8831 return __check_ptr_off_reg(env, reg, regno, false); 8832 } 8833 8834 switch (type) { 8835 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8836 case PTR_TO_STACK: 8837 case PTR_TO_PACKET: 8838 case PTR_TO_PACKET_META: 8839 case PTR_TO_MAP_KEY: 8840 case PTR_TO_MAP_VALUE: 8841 case PTR_TO_MEM: 8842 case PTR_TO_MEM | MEM_RDONLY: 8843 case PTR_TO_MEM | MEM_RINGBUF: 8844 case PTR_TO_BUF: 8845 case PTR_TO_BUF | MEM_RDONLY: 8846 case PTR_TO_ARENA: 8847 case SCALAR_VALUE: 8848 return 0; 8849 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8850 * fixed offset. 8851 */ 8852 case PTR_TO_BTF_ID: 8853 case PTR_TO_BTF_ID | MEM_ALLOC: 8854 case PTR_TO_BTF_ID | PTR_TRUSTED: 8855 case PTR_TO_BTF_ID | MEM_RCU: 8856 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8857 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8858 /* When referenced PTR_TO_BTF_ID is passed to release function, 8859 * its fixed offset must be 0. In the other cases, fixed offset 8860 * can be non-zero. This was already checked above. So pass 8861 * fixed_off_ok as true to allow fixed offset for all other 8862 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8863 * still need to do checks instead of returning. 8864 */ 8865 return __check_ptr_off_reg(env, reg, regno, true); 8866 default: 8867 return __check_ptr_off_reg(env, reg, regno, false); 8868 } 8869 } 8870 8871 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8872 const struct bpf_func_proto *fn, 8873 struct bpf_reg_state *regs) 8874 { 8875 struct bpf_reg_state *state = NULL; 8876 int i; 8877 8878 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8879 if (arg_type_is_dynptr(fn->arg_type[i])) { 8880 if (state) { 8881 verbose(env, "verifier internal error: multiple dynptr args\n"); 8882 return NULL; 8883 } 8884 state = ®s[BPF_REG_1 + i]; 8885 } 8886 8887 if (!state) 8888 verbose(env, "verifier internal error: no dynptr arg found\n"); 8889 8890 return state; 8891 } 8892 8893 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8894 { 8895 struct bpf_func_state *state = func(env, reg); 8896 int spi; 8897 8898 if (reg->type == CONST_PTR_TO_DYNPTR) 8899 return reg->id; 8900 spi = dynptr_get_spi(env, reg); 8901 if (spi < 0) 8902 return spi; 8903 return state->stack[spi].spilled_ptr.id; 8904 } 8905 8906 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8907 { 8908 struct bpf_func_state *state = func(env, reg); 8909 int spi; 8910 8911 if (reg->type == CONST_PTR_TO_DYNPTR) 8912 return reg->ref_obj_id; 8913 spi = dynptr_get_spi(env, reg); 8914 if (spi < 0) 8915 return spi; 8916 return state->stack[spi].spilled_ptr.ref_obj_id; 8917 } 8918 8919 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8920 struct bpf_reg_state *reg) 8921 { 8922 struct bpf_func_state *state = func(env, reg); 8923 int spi; 8924 8925 if (reg->type == CONST_PTR_TO_DYNPTR) 8926 return reg->dynptr.type; 8927 8928 spi = __get_spi(reg->off); 8929 if (spi < 0) { 8930 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8931 return BPF_DYNPTR_TYPE_INVALID; 8932 } 8933 8934 return state->stack[spi].spilled_ptr.dynptr.type; 8935 } 8936 8937 static int check_reg_const_str(struct bpf_verifier_env *env, 8938 struct bpf_reg_state *reg, u32 regno) 8939 { 8940 struct bpf_map *map = reg->map_ptr; 8941 int err; 8942 int map_off; 8943 u64 map_addr; 8944 char *str_ptr; 8945 8946 if (reg->type != PTR_TO_MAP_VALUE) 8947 return -EINVAL; 8948 8949 if (!bpf_map_is_rdonly(map)) { 8950 verbose(env, "R%d does not point to a readonly map'\n", regno); 8951 return -EACCES; 8952 } 8953 8954 if (!tnum_is_const(reg->var_off)) { 8955 verbose(env, "R%d is not a constant address'\n", regno); 8956 return -EACCES; 8957 } 8958 8959 if (!map->ops->map_direct_value_addr) { 8960 verbose(env, "no direct value access support for this map type\n"); 8961 return -EACCES; 8962 } 8963 8964 err = check_map_access(env, regno, reg->off, 8965 map->value_size - reg->off, false, 8966 ACCESS_HELPER); 8967 if (err) 8968 return err; 8969 8970 map_off = reg->off + reg->var_off.value; 8971 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8972 if (err) { 8973 verbose(env, "direct value access on string failed\n"); 8974 return err; 8975 } 8976 8977 str_ptr = (char *)(long)(map_addr); 8978 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8979 verbose(env, "string is not zero-terminated\n"); 8980 return -EINVAL; 8981 } 8982 return 0; 8983 } 8984 8985 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8986 struct bpf_call_arg_meta *meta, 8987 const struct bpf_func_proto *fn, 8988 int insn_idx) 8989 { 8990 u32 regno = BPF_REG_1 + arg; 8991 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8992 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8993 enum bpf_reg_type type = reg->type; 8994 u32 *arg_btf_id = NULL; 8995 int err = 0; 8996 8997 if (arg_type == ARG_DONTCARE) 8998 return 0; 8999 9000 err = check_reg_arg(env, regno, SRC_OP); 9001 if (err) 9002 return err; 9003 9004 if (arg_type == ARG_ANYTHING) { 9005 if (is_pointer_value(env, regno)) { 9006 verbose(env, "R%d leaks addr into helper function\n", 9007 regno); 9008 return -EACCES; 9009 } 9010 return 0; 9011 } 9012 9013 if (type_is_pkt_pointer(type) && 9014 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 9015 verbose(env, "helper access to the packet is not allowed\n"); 9016 return -EACCES; 9017 } 9018 9019 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 9020 err = resolve_map_arg_type(env, meta, &arg_type); 9021 if (err) 9022 return err; 9023 } 9024 9025 if (register_is_null(reg) && type_may_be_null(arg_type)) 9026 /* A NULL register has a SCALAR_VALUE type, so skip 9027 * type checking. 9028 */ 9029 goto skip_type_check; 9030 9031 /* arg_btf_id and arg_size are in a union. */ 9032 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 9033 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 9034 arg_btf_id = fn->arg_btf_id[arg]; 9035 9036 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 9037 if (err) 9038 return err; 9039 9040 err = check_func_arg_reg_off(env, reg, regno, arg_type); 9041 if (err) 9042 return err; 9043 9044 skip_type_check: 9045 if (arg_type_is_release(arg_type)) { 9046 if (arg_type_is_dynptr(arg_type)) { 9047 struct bpf_func_state *state = func(env, reg); 9048 int spi; 9049 9050 /* Only dynptr created on stack can be released, thus 9051 * the get_spi and stack state checks for spilled_ptr 9052 * should only be done before process_dynptr_func for 9053 * PTR_TO_STACK. 9054 */ 9055 if (reg->type == PTR_TO_STACK) { 9056 spi = dynptr_get_spi(env, reg); 9057 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 9058 verbose(env, "arg %d is an unacquired reference\n", regno); 9059 return -EINVAL; 9060 } 9061 } else { 9062 verbose(env, "cannot release unowned const bpf_dynptr\n"); 9063 return -EINVAL; 9064 } 9065 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 9066 verbose(env, "R%d must be referenced when passed to release function\n", 9067 regno); 9068 return -EINVAL; 9069 } 9070 if (meta->release_regno) { 9071 verbose(env, "verifier internal error: more than one release argument\n"); 9072 return -EFAULT; 9073 } 9074 meta->release_regno = regno; 9075 } 9076 9077 if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) { 9078 if (meta->ref_obj_id) { 9079 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 9080 regno, reg->ref_obj_id, 9081 meta->ref_obj_id); 9082 return -EFAULT; 9083 } 9084 meta->ref_obj_id = reg->ref_obj_id; 9085 } 9086 9087 switch (base_type(arg_type)) { 9088 case ARG_CONST_MAP_PTR: 9089 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 9090 if (meta->map_ptr) { 9091 /* Use map_uid (which is unique id of inner map) to reject: 9092 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 9093 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 9094 * if (inner_map1 && inner_map2) { 9095 * timer = bpf_map_lookup_elem(inner_map1); 9096 * if (timer) 9097 * // mismatch would have been allowed 9098 * bpf_timer_init(timer, inner_map2); 9099 * } 9100 * 9101 * Comparing map_ptr is enough to distinguish normal and outer maps. 9102 */ 9103 if (meta->map_ptr != reg->map_ptr || 9104 meta->map_uid != reg->map_uid) { 9105 verbose(env, 9106 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 9107 meta->map_uid, reg->map_uid); 9108 return -EINVAL; 9109 } 9110 } 9111 meta->map_ptr = reg->map_ptr; 9112 meta->map_uid = reg->map_uid; 9113 break; 9114 case ARG_PTR_TO_MAP_KEY: 9115 /* bpf_map_xxx(..., map_ptr, ..., key) call: 9116 * check that [key, key + map->key_size) are within 9117 * stack limits and initialized 9118 */ 9119 if (!meta->map_ptr) { 9120 /* in function declaration map_ptr must come before 9121 * map_key, so that it's verified and known before 9122 * we have to check map_key here. Otherwise it means 9123 * that kernel subsystem misconfigured verifier 9124 */ 9125 verbose(env, "invalid map_ptr to access map->key\n"); 9126 return -EACCES; 9127 } 9128 err = check_helper_mem_access(env, regno, meta->map_ptr->key_size, 9129 BPF_READ, false, NULL); 9130 break; 9131 case ARG_PTR_TO_MAP_VALUE: 9132 if (type_may_be_null(arg_type) && register_is_null(reg)) 9133 return 0; 9134 9135 /* bpf_map_xxx(..., map_ptr, ..., value) call: 9136 * check [value, value + map->value_size) validity 9137 */ 9138 if (!meta->map_ptr) { 9139 /* kernel subsystem misconfigured verifier */ 9140 verbose(env, "invalid map_ptr to access map->value\n"); 9141 return -EACCES; 9142 } 9143 meta->raw_mode = arg_type & MEM_UNINIT; 9144 err = check_helper_mem_access(env, regno, meta->map_ptr->value_size, 9145 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 9146 false, meta); 9147 break; 9148 case ARG_PTR_TO_PERCPU_BTF_ID: 9149 if (!reg->btf_id) { 9150 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 9151 return -EACCES; 9152 } 9153 meta->ret_btf = reg->btf; 9154 meta->ret_btf_id = reg->btf_id; 9155 break; 9156 case ARG_PTR_TO_SPIN_LOCK: 9157 if (in_rbtree_lock_required_cb(env)) { 9158 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 9159 return -EACCES; 9160 } 9161 if (meta->func_id == BPF_FUNC_spin_lock) { 9162 err = process_spin_lock(env, regno, true); 9163 if (err) 9164 return err; 9165 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 9166 err = process_spin_lock(env, regno, false); 9167 if (err) 9168 return err; 9169 } else { 9170 verbose(env, "verifier internal error\n"); 9171 return -EFAULT; 9172 } 9173 break; 9174 case ARG_PTR_TO_TIMER: 9175 err = process_timer_func(env, regno, meta); 9176 if (err) 9177 return err; 9178 break; 9179 case ARG_PTR_TO_FUNC: 9180 meta->subprogno = reg->subprogno; 9181 break; 9182 case ARG_PTR_TO_MEM: 9183 /* The access to this pointer is only checked when we hit the 9184 * next is_mem_size argument below. 9185 */ 9186 meta->raw_mode = arg_type & MEM_UNINIT; 9187 if (arg_type & MEM_FIXED_SIZE) { 9188 err = check_helper_mem_access(env, regno, fn->arg_size[arg], 9189 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 9190 false, meta); 9191 if (err) 9192 return err; 9193 if (arg_type & MEM_ALIGNED) 9194 err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true); 9195 } 9196 break; 9197 case ARG_CONST_SIZE: 9198 err = check_mem_size_reg(env, reg, regno, 9199 fn->arg_type[arg - 1] & MEM_WRITE ? 9200 BPF_WRITE : BPF_READ, 9201 false, meta); 9202 break; 9203 case ARG_CONST_SIZE_OR_ZERO: 9204 err = check_mem_size_reg(env, reg, regno, 9205 fn->arg_type[arg - 1] & MEM_WRITE ? 9206 BPF_WRITE : BPF_READ, 9207 true, meta); 9208 break; 9209 case ARG_PTR_TO_DYNPTR: 9210 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 9211 if (err) 9212 return err; 9213 break; 9214 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 9215 if (!tnum_is_const(reg->var_off)) { 9216 verbose(env, "R%d is not a known constant'\n", 9217 regno); 9218 return -EACCES; 9219 } 9220 meta->mem_size = reg->var_off.value; 9221 err = mark_chain_precision(env, regno); 9222 if (err) 9223 return err; 9224 break; 9225 case ARG_PTR_TO_CONST_STR: 9226 { 9227 err = check_reg_const_str(env, reg, regno); 9228 if (err) 9229 return err; 9230 break; 9231 } 9232 case ARG_KPTR_XCHG_DEST: 9233 err = process_kptr_func(env, regno, meta); 9234 if (err) 9235 return err; 9236 break; 9237 } 9238 9239 return err; 9240 } 9241 9242 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 9243 { 9244 enum bpf_attach_type eatype = env->prog->expected_attach_type; 9245 enum bpf_prog_type type = resolve_prog_type(env->prog); 9246 9247 if (func_id != BPF_FUNC_map_update_elem && 9248 func_id != BPF_FUNC_map_delete_elem) 9249 return false; 9250 9251 /* It's not possible to get access to a locked struct sock in these 9252 * contexts, so updating is safe. 9253 */ 9254 switch (type) { 9255 case BPF_PROG_TYPE_TRACING: 9256 if (eatype == BPF_TRACE_ITER) 9257 return true; 9258 break; 9259 case BPF_PROG_TYPE_SOCK_OPS: 9260 /* map_update allowed only via dedicated helpers with event type checks */ 9261 if (func_id == BPF_FUNC_map_delete_elem) 9262 return true; 9263 break; 9264 case BPF_PROG_TYPE_SOCKET_FILTER: 9265 case BPF_PROG_TYPE_SCHED_CLS: 9266 case BPF_PROG_TYPE_SCHED_ACT: 9267 case BPF_PROG_TYPE_XDP: 9268 case BPF_PROG_TYPE_SK_REUSEPORT: 9269 case BPF_PROG_TYPE_FLOW_DISSECTOR: 9270 case BPF_PROG_TYPE_SK_LOOKUP: 9271 return true; 9272 default: 9273 break; 9274 } 9275 9276 verbose(env, "cannot update sockmap in this context\n"); 9277 return false; 9278 } 9279 9280 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 9281 { 9282 return env->prog->jit_requested && 9283 bpf_jit_supports_subprog_tailcalls(); 9284 } 9285 9286 static int check_map_func_compatibility(struct bpf_verifier_env *env, 9287 struct bpf_map *map, int func_id) 9288 { 9289 if (!map) 9290 return 0; 9291 9292 /* We need a two way check, first is from map perspective ... */ 9293 switch (map->map_type) { 9294 case BPF_MAP_TYPE_PROG_ARRAY: 9295 if (func_id != BPF_FUNC_tail_call) 9296 goto error; 9297 break; 9298 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 9299 if (func_id != BPF_FUNC_perf_event_read && 9300 func_id != BPF_FUNC_perf_event_output && 9301 func_id != BPF_FUNC_skb_output && 9302 func_id != BPF_FUNC_perf_event_read_value && 9303 func_id != BPF_FUNC_xdp_output) 9304 goto error; 9305 break; 9306 case BPF_MAP_TYPE_RINGBUF: 9307 if (func_id != BPF_FUNC_ringbuf_output && 9308 func_id != BPF_FUNC_ringbuf_reserve && 9309 func_id != BPF_FUNC_ringbuf_query && 9310 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 9311 func_id != BPF_FUNC_ringbuf_submit_dynptr && 9312 func_id != BPF_FUNC_ringbuf_discard_dynptr) 9313 goto error; 9314 break; 9315 case BPF_MAP_TYPE_USER_RINGBUF: 9316 if (func_id != BPF_FUNC_user_ringbuf_drain) 9317 goto error; 9318 break; 9319 case BPF_MAP_TYPE_STACK_TRACE: 9320 if (func_id != BPF_FUNC_get_stackid) 9321 goto error; 9322 break; 9323 case BPF_MAP_TYPE_CGROUP_ARRAY: 9324 if (func_id != BPF_FUNC_skb_under_cgroup && 9325 func_id != BPF_FUNC_current_task_under_cgroup) 9326 goto error; 9327 break; 9328 case BPF_MAP_TYPE_CGROUP_STORAGE: 9329 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 9330 if (func_id != BPF_FUNC_get_local_storage) 9331 goto error; 9332 break; 9333 case BPF_MAP_TYPE_DEVMAP: 9334 case BPF_MAP_TYPE_DEVMAP_HASH: 9335 if (func_id != BPF_FUNC_redirect_map && 9336 func_id != BPF_FUNC_map_lookup_elem) 9337 goto error; 9338 break; 9339 /* Restrict bpf side of cpumap and xskmap, open when use-cases 9340 * appear. 9341 */ 9342 case BPF_MAP_TYPE_CPUMAP: 9343 if (func_id != BPF_FUNC_redirect_map) 9344 goto error; 9345 break; 9346 case BPF_MAP_TYPE_XSKMAP: 9347 if (func_id != BPF_FUNC_redirect_map && 9348 func_id != BPF_FUNC_map_lookup_elem) 9349 goto error; 9350 break; 9351 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 9352 case BPF_MAP_TYPE_HASH_OF_MAPS: 9353 if (func_id != BPF_FUNC_map_lookup_elem) 9354 goto error; 9355 break; 9356 case BPF_MAP_TYPE_SOCKMAP: 9357 if (func_id != BPF_FUNC_sk_redirect_map && 9358 func_id != BPF_FUNC_sock_map_update && 9359 func_id != BPF_FUNC_msg_redirect_map && 9360 func_id != BPF_FUNC_sk_select_reuseport && 9361 func_id != BPF_FUNC_map_lookup_elem && 9362 !may_update_sockmap(env, func_id)) 9363 goto error; 9364 break; 9365 case BPF_MAP_TYPE_SOCKHASH: 9366 if (func_id != BPF_FUNC_sk_redirect_hash && 9367 func_id != BPF_FUNC_sock_hash_update && 9368 func_id != BPF_FUNC_msg_redirect_hash && 9369 func_id != BPF_FUNC_sk_select_reuseport && 9370 func_id != BPF_FUNC_map_lookup_elem && 9371 !may_update_sockmap(env, func_id)) 9372 goto error; 9373 break; 9374 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 9375 if (func_id != BPF_FUNC_sk_select_reuseport) 9376 goto error; 9377 break; 9378 case BPF_MAP_TYPE_QUEUE: 9379 case BPF_MAP_TYPE_STACK: 9380 if (func_id != BPF_FUNC_map_peek_elem && 9381 func_id != BPF_FUNC_map_pop_elem && 9382 func_id != BPF_FUNC_map_push_elem) 9383 goto error; 9384 break; 9385 case BPF_MAP_TYPE_SK_STORAGE: 9386 if (func_id != BPF_FUNC_sk_storage_get && 9387 func_id != BPF_FUNC_sk_storage_delete && 9388 func_id != BPF_FUNC_kptr_xchg) 9389 goto error; 9390 break; 9391 case BPF_MAP_TYPE_INODE_STORAGE: 9392 if (func_id != BPF_FUNC_inode_storage_get && 9393 func_id != BPF_FUNC_inode_storage_delete && 9394 func_id != BPF_FUNC_kptr_xchg) 9395 goto error; 9396 break; 9397 case BPF_MAP_TYPE_TASK_STORAGE: 9398 if (func_id != BPF_FUNC_task_storage_get && 9399 func_id != BPF_FUNC_task_storage_delete && 9400 func_id != BPF_FUNC_kptr_xchg) 9401 goto error; 9402 break; 9403 case BPF_MAP_TYPE_CGRP_STORAGE: 9404 if (func_id != BPF_FUNC_cgrp_storage_get && 9405 func_id != BPF_FUNC_cgrp_storage_delete && 9406 func_id != BPF_FUNC_kptr_xchg) 9407 goto error; 9408 break; 9409 case BPF_MAP_TYPE_BLOOM_FILTER: 9410 if (func_id != BPF_FUNC_map_peek_elem && 9411 func_id != BPF_FUNC_map_push_elem) 9412 goto error; 9413 break; 9414 default: 9415 break; 9416 } 9417 9418 /* ... and second from the function itself. */ 9419 switch (func_id) { 9420 case BPF_FUNC_tail_call: 9421 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 9422 goto error; 9423 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 9424 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 9425 return -EINVAL; 9426 } 9427 break; 9428 case BPF_FUNC_perf_event_read: 9429 case BPF_FUNC_perf_event_output: 9430 case BPF_FUNC_perf_event_read_value: 9431 case BPF_FUNC_skb_output: 9432 case BPF_FUNC_xdp_output: 9433 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 9434 goto error; 9435 break; 9436 case BPF_FUNC_ringbuf_output: 9437 case BPF_FUNC_ringbuf_reserve: 9438 case BPF_FUNC_ringbuf_query: 9439 case BPF_FUNC_ringbuf_reserve_dynptr: 9440 case BPF_FUNC_ringbuf_submit_dynptr: 9441 case BPF_FUNC_ringbuf_discard_dynptr: 9442 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 9443 goto error; 9444 break; 9445 case BPF_FUNC_user_ringbuf_drain: 9446 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 9447 goto error; 9448 break; 9449 case BPF_FUNC_get_stackid: 9450 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 9451 goto error; 9452 break; 9453 case BPF_FUNC_current_task_under_cgroup: 9454 case BPF_FUNC_skb_under_cgroup: 9455 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 9456 goto error; 9457 break; 9458 case BPF_FUNC_redirect_map: 9459 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 9460 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 9461 map->map_type != BPF_MAP_TYPE_CPUMAP && 9462 map->map_type != BPF_MAP_TYPE_XSKMAP) 9463 goto error; 9464 break; 9465 case BPF_FUNC_sk_redirect_map: 9466 case BPF_FUNC_msg_redirect_map: 9467 case BPF_FUNC_sock_map_update: 9468 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 9469 goto error; 9470 break; 9471 case BPF_FUNC_sk_redirect_hash: 9472 case BPF_FUNC_msg_redirect_hash: 9473 case BPF_FUNC_sock_hash_update: 9474 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 9475 goto error; 9476 break; 9477 case BPF_FUNC_get_local_storage: 9478 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 9479 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 9480 goto error; 9481 break; 9482 case BPF_FUNC_sk_select_reuseport: 9483 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 9484 map->map_type != BPF_MAP_TYPE_SOCKMAP && 9485 map->map_type != BPF_MAP_TYPE_SOCKHASH) 9486 goto error; 9487 break; 9488 case BPF_FUNC_map_pop_elem: 9489 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9490 map->map_type != BPF_MAP_TYPE_STACK) 9491 goto error; 9492 break; 9493 case BPF_FUNC_map_peek_elem: 9494 case BPF_FUNC_map_push_elem: 9495 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9496 map->map_type != BPF_MAP_TYPE_STACK && 9497 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 9498 goto error; 9499 break; 9500 case BPF_FUNC_map_lookup_percpu_elem: 9501 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 9502 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 9503 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 9504 goto error; 9505 break; 9506 case BPF_FUNC_sk_storage_get: 9507 case BPF_FUNC_sk_storage_delete: 9508 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 9509 goto error; 9510 break; 9511 case BPF_FUNC_inode_storage_get: 9512 case BPF_FUNC_inode_storage_delete: 9513 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 9514 goto error; 9515 break; 9516 case BPF_FUNC_task_storage_get: 9517 case BPF_FUNC_task_storage_delete: 9518 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 9519 goto error; 9520 break; 9521 case BPF_FUNC_cgrp_storage_get: 9522 case BPF_FUNC_cgrp_storage_delete: 9523 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 9524 goto error; 9525 break; 9526 default: 9527 break; 9528 } 9529 9530 return 0; 9531 error: 9532 verbose(env, "cannot pass map_type %d into func %s#%d\n", 9533 map->map_type, func_id_name(func_id), func_id); 9534 return -EINVAL; 9535 } 9536 9537 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 9538 { 9539 int count = 0; 9540 9541 if (arg_type_is_raw_mem(fn->arg1_type)) 9542 count++; 9543 if (arg_type_is_raw_mem(fn->arg2_type)) 9544 count++; 9545 if (arg_type_is_raw_mem(fn->arg3_type)) 9546 count++; 9547 if (arg_type_is_raw_mem(fn->arg4_type)) 9548 count++; 9549 if (arg_type_is_raw_mem(fn->arg5_type)) 9550 count++; 9551 9552 /* We only support one arg being in raw mode at the moment, 9553 * which is sufficient for the helper functions we have 9554 * right now. 9555 */ 9556 return count <= 1; 9557 } 9558 9559 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 9560 { 9561 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 9562 bool has_size = fn->arg_size[arg] != 0; 9563 bool is_next_size = false; 9564 9565 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 9566 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 9567 9568 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 9569 return is_next_size; 9570 9571 return has_size == is_next_size || is_next_size == is_fixed; 9572 } 9573 9574 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 9575 { 9576 /* bpf_xxx(..., buf, len) call will access 'len' 9577 * bytes from memory 'buf'. Both arg types need 9578 * to be paired, so make sure there's no buggy 9579 * helper function specification. 9580 */ 9581 if (arg_type_is_mem_size(fn->arg1_type) || 9582 check_args_pair_invalid(fn, 0) || 9583 check_args_pair_invalid(fn, 1) || 9584 check_args_pair_invalid(fn, 2) || 9585 check_args_pair_invalid(fn, 3) || 9586 check_args_pair_invalid(fn, 4)) 9587 return false; 9588 9589 return true; 9590 } 9591 9592 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 9593 { 9594 int i; 9595 9596 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 9597 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 9598 return !!fn->arg_btf_id[i]; 9599 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 9600 return fn->arg_btf_id[i] == BPF_PTR_POISON; 9601 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 9602 /* arg_btf_id and arg_size are in a union. */ 9603 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 9604 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 9605 return false; 9606 } 9607 9608 return true; 9609 } 9610 9611 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 9612 { 9613 return check_raw_mode_ok(fn) && 9614 check_arg_pair_ok(fn) && 9615 check_btf_id_ok(fn) ? 0 : -EINVAL; 9616 } 9617 9618 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 9619 * are now invalid, so turn them into unknown SCALAR_VALUE. 9620 * 9621 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 9622 * since these slices point to packet data. 9623 */ 9624 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 9625 { 9626 struct bpf_func_state *state; 9627 struct bpf_reg_state *reg; 9628 9629 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9630 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 9631 mark_reg_invalid(env, reg); 9632 })); 9633 } 9634 9635 enum { 9636 AT_PKT_END = -1, 9637 BEYOND_PKT_END = -2, 9638 }; 9639 9640 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 9641 { 9642 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9643 struct bpf_reg_state *reg = &state->regs[regn]; 9644 9645 if (reg->type != PTR_TO_PACKET) 9646 /* PTR_TO_PACKET_META is not supported yet */ 9647 return; 9648 9649 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 9650 * How far beyond pkt_end it goes is unknown. 9651 * if (!range_open) it's the case of pkt >= pkt_end 9652 * if (range_open) it's the case of pkt > pkt_end 9653 * hence this pointer is at least 1 byte bigger than pkt_end 9654 */ 9655 if (range_open) 9656 reg->range = BEYOND_PKT_END; 9657 else 9658 reg->range = AT_PKT_END; 9659 } 9660 9661 /* The pointer with the specified id has released its reference to kernel 9662 * resources. Identify all copies of the same pointer and clear the reference. 9663 */ 9664 static int release_reference(struct bpf_verifier_env *env, 9665 int ref_obj_id) 9666 { 9667 struct bpf_func_state *state; 9668 struct bpf_reg_state *reg; 9669 int err; 9670 9671 err = release_reference_state(cur_func(env), ref_obj_id); 9672 if (err) 9673 return err; 9674 9675 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9676 if (reg->ref_obj_id == ref_obj_id) 9677 mark_reg_invalid(env, reg); 9678 })); 9679 9680 return 0; 9681 } 9682 9683 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9684 { 9685 struct bpf_func_state *unused; 9686 struct bpf_reg_state *reg; 9687 9688 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9689 if (type_is_non_owning_ref(reg->type)) 9690 mark_reg_invalid(env, reg); 9691 })); 9692 } 9693 9694 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9695 struct bpf_reg_state *regs) 9696 { 9697 int i; 9698 9699 /* after the call registers r0 - r5 were scratched */ 9700 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9701 mark_reg_not_init(env, regs, caller_saved[i]); 9702 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9703 } 9704 } 9705 9706 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9707 struct bpf_func_state *caller, 9708 struct bpf_func_state *callee, 9709 int insn_idx); 9710 9711 static int set_callee_state(struct bpf_verifier_env *env, 9712 struct bpf_func_state *caller, 9713 struct bpf_func_state *callee, int insn_idx); 9714 9715 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9716 set_callee_state_fn set_callee_state_cb, 9717 struct bpf_verifier_state *state) 9718 { 9719 struct bpf_func_state *caller, *callee; 9720 int err; 9721 9722 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9723 verbose(env, "the call stack of %d frames is too deep\n", 9724 state->curframe + 2); 9725 return -E2BIG; 9726 } 9727 9728 if (state->frame[state->curframe + 1]) { 9729 verbose(env, "verifier bug. Frame %d already allocated\n", 9730 state->curframe + 1); 9731 return -EFAULT; 9732 } 9733 9734 caller = state->frame[state->curframe]; 9735 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 9736 if (!callee) 9737 return -ENOMEM; 9738 state->frame[state->curframe + 1] = callee; 9739 9740 /* callee cannot access r0, r6 - r9 for reading and has to write 9741 * into its own stack before reading from it. 9742 * callee can read/write into caller's stack 9743 */ 9744 init_func_state(env, callee, 9745 /* remember the callsite, it will be used by bpf_exit */ 9746 callsite, 9747 state->curframe + 1 /* frameno within this callchain */, 9748 subprog /* subprog number within this prog */); 9749 /* Transfer references to the callee */ 9750 err = copy_reference_state(callee, caller); 9751 err = err ?: set_callee_state_cb(env, caller, callee, callsite); 9752 if (err) 9753 goto err_out; 9754 9755 /* only increment it after check_reg_arg() finished */ 9756 state->curframe++; 9757 9758 return 0; 9759 9760 err_out: 9761 free_func_state(callee); 9762 state->frame[state->curframe + 1] = NULL; 9763 return err; 9764 } 9765 9766 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, 9767 const struct btf *btf, 9768 struct bpf_reg_state *regs) 9769 { 9770 struct bpf_subprog_info *sub = subprog_info(env, subprog); 9771 struct bpf_verifier_log *log = &env->log; 9772 u32 i; 9773 int ret; 9774 9775 ret = btf_prepare_func_args(env, subprog); 9776 if (ret) 9777 return ret; 9778 9779 /* check that BTF function arguments match actual types that the 9780 * verifier sees. 9781 */ 9782 for (i = 0; i < sub->arg_cnt; i++) { 9783 u32 regno = i + 1; 9784 struct bpf_reg_state *reg = ®s[regno]; 9785 struct bpf_subprog_arg_info *arg = &sub->args[i]; 9786 9787 if (arg->arg_type == ARG_ANYTHING) { 9788 if (reg->type != SCALAR_VALUE) { 9789 bpf_log(log, "R%d is not a scalar\n", regno); 9790 return -EINVAL; 9791 } 9792 } else if (arg->arg_type == ARG_PTR_TO_CTX) { 9793 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9794 if (ret < 0) 9795 return ret; 9796 /* If function expects ctx type in BTF check that caller 9797 * is passing PTR_TO_CTX. 9798 */ 9799 if (reg->type != PTR_TO_CTX) { 9800 bpf_log(log, "arg#%d expects pointer to ctx\n", i); 9801 return -EINVAL; 9802 } 9803 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 9804 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9805 if (ret < 0) 9806 return ret; 9807 if (check_mem_reg(env, reg, regno, arg->mem_size)) 9808 return -EINVAL; 9809 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) { 9810 bpf_log(log, "arg#%d is expected to be non-NULL\n", i); 9811 return -EINVAL; 9812 } 9813 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 9814 /* 9815 * Can pass any value and the kernel won't crash, but 9816 * only PTR_TO_ARENA or SCALAR make sense. Everything 9817 * else is a bug in the bpf program. Point it out to 9818 * the user at the verification time instead of 9819 * run-time debug nightmare. 9820 */ 9821 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) { 9822 bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno); 9823 return -EINVAL; 9824 } 9825 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 9826 ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR); 9827 if (ret) 9828 return ret; 9829 9830 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0); 9831 if (ret) 9832 return ret; 9833 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 9834 struct bpf_call_arg_meta meta; 9835 int err; 9836 9837 if (register_is_null(reg) && type_may_be_null(arg->arg_type)) 9838 continue; 9839 9840 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */ 9841 err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta); 9842 err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type); 9843 if (err) 9844 return err; 9845 } else { 9846 bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n", 9847 i, arg->arg_type); 9848 return -EFAULT; 9849 } 9850 } 9851 9852 return 0; 9853 } 9854 9855 /* Compare BTF of a function call with given bpf_reg_state. 9856 * Returns: 9857 * EFAULT - there is a verifier bug. Abort verification. 9858 * EINVAL - there is a type mismatch or BTF is not available. 9859 * 0 - BTF matches with what bpf_reg_state expects. 9860 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized. 9861 */ 9862 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog, 9863 struct bpf_reg_state *regs) 9864 { 9865 struct bpf_prog *prog = env->prog; 9866 struct btf *btf = prog->aux->btf; 9867 u32 btf_id; 9868 int err; 9869 9870 if (!prog->aux->func_info) 9871 return -EINVAL; 9872 9873 btf_id = prog->aux->func_info[subprog].type_id; 9874 if (!btf_id) 9875 return -EFAULT; 9876 9877 if (prog->aux->func_info_aux[subprog].unreliable) 9878 return -EINVAL; 9879 9880 err = btf_check_func_arg_match(env, subprog, btf, regs); 9881 /* Compiler optimizations can remove arguments from static functions 9882 * or mismatched type can be passed into a global function. 9883 * In such cases mark the function as unreliable from BTF point of view. 9884 */ 9885 if (err) 9886 prog->aux->func_info_aux[subprog].unreliable = true; 9887 return err; 9888 } 9889 9890 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9891 int insn_idx, int subprog, 9892 set_callee_state_fn set_callee_state_cb) 9893 { 9894 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9895 struct bpf_func_state *caller, *callee; 9896 int err; 9897 9898 caller = state->frame[state->curframe]; 9899 err = btf_check_subprog_call(env, subprog, caller->regs); 9900 if (err == -EFAULT) 9901 return err; 9902 9903 /* set_callee_state is used for direct subprog calls, but we are 9904 * interested in validating only BPF helpers that can call subprogs as 9905 * callbacks 9906 */ 9907 env->subprog_info[subprog].is_cb = true; 9908 if (bpf_pseudo_kfunc_call(insn) && 9909 !is_callback_calling_kfunc(insn->imm)) { 9910 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 9911 func_id_name(insn->imm), insn->imm); 9912 return -EFAULT; 9913 } else if (!bpf_pseudo_kfunc_call(insn) && 9914 !is_callback_calling_function(insn->imm)) { /* helper */ 9915 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 9916 func_id_name(insn->imm), insn->imm); 9917 return -EFAULT; 9918 } 9919 9920 if (is_async_callback_calling_insn(insn)) { 9921 struct bpf_verifier_state *async_cb; 9922 9923 /* there is no real recursion here. timer and workqueue callbacks are async */ 9924 env->subprog_info[subprog].is_async_cb = true; 9925 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9926 insn_idx, subprog, 9927 is_bpf_wq_set_callback_impl_kfunc(insn->imm)); 9928 if (!async_cb) 9929 return -EFAULT; 9930 callee = async_cb->frame[0]; 9931 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9932 9933 /* Convert bpf_timer_set_callback() args into timer callback args */ 9934 err = set_callee_state_cb(env, caller, callee, insn_idx); 9935 if (err) 9936 return err; 9937 9938 return 0; 9939 } 9940 9941 /* for callback functions enqueue entry to callback and 9942 * proceed with next instruction within current frame. 9943 */ 9944 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9945 if (!callback_state) 9946 return -ENOMEM; 9947 9948 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9949 callback_state); 9950 if (err) 9951 return err; 9952 9953 callback_state->callback_unroll_depth++; 9954 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9955 caller->callback_depth = 0; 9956 return 0; 9957 } 9958 9959 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9960 int *insn_idx) 9961 { 9962 struct bpf_verifier_state *state = env->cur_state; 9963 struct bpf_func_state *caller; 9964 int err, subprog, target_insn; 9965 9966 target_insn = *insn_idx + insn->imm + 1; 9967 subprog = find_subprog(env, target_insn); 9968 if (subprog < 0) { 9969 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn); 9970 return -EFAULT; 9971 } 9972 9973 caller = state->frame[state->curframe]; 9974 err = btf_check_subprog_call(env, subprog, caller->regs); 9975 if (err == -EFAULT) 9976 return err; 9977 if (subprog_is_global(env, subprog)) { 9978 const char *sub_name = subprog_name(env, subprog); 9979 9980 /* Only global subprogs cannot be called with a lock held. */ 9981 if (cur_func(env)->active_locks) { 9982 verbose(env, "global function calls are not allowed while holding a lock,\n" 9983 "use static function instead\n"); 9984 return -EINVAL; 9985 } 9986 9987 /* Only global subprogs cannot be called with preemption disabled. */ 9988 if (env->cur_state->active_preempt_lock) { 9989 verbose(env, "global function calls are not allowed with preemption disabled,\n" 9990 "use static function instead\n"); 9991 return -EINVAL; 9992 } 9993 9994 if (err) { 9995 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 9996 subprog, sub_name); 9997 return err; 9998 } 9999 10000 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 10001 subprog, sub_name); 10002 if (env->subprog_info[subprog].changes_pkt_data) 10003 clear_all_pkt_pointers(env); 10004 /* mark global subprog for verifying after main prog */ 10005 subprog_aux(env, subprog)->called = true; 10006 clear_caller_saved_regs(env, caller->regs); 10007 10008 /* All global functions return a 64-bit SCALAR_VALUE */ 10009 mark_reg_unknown(env, caller->regs, BPF_REG_0); 10010 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10011 10012 /* continue with next insn after call */ 10013 return 0; 10014 } 10015 10016 /* for regular function entry setup new frame and continue 10017 * from that frame. 10018 */ 10019 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 10020 if (err) 10021 return err; 10022 10023 clear_caller_saved_regs(env, caller->regs); 10024 10025 /* and go analyze first insn of the callee */ 10026 *insn_idx = env->subprog_info[subprog].start - 1; 10027 10028 if (env->log.level & BPF_LOG_LEVEL) { 10029 verbose(env, "caller:\n"); 10030 print_verifier_state(env, caller, true); 10031 verbose(env, "callee:\n"); 10032 print_verifier_state(env, state->frame[state->curframe], true); 10033 } 10034 10035 return 0; 10036 } 10037 10038 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 10039 struct bpf_func_state *caller, 10040 struct bpf_func_state *callee) 10041 { 10042 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 10043 * void *callback_ctx, u64 flags); 10044 * callback_fn(struct bpf_map *map, void *key, void *value, 10045 * void *callback_ctx); 10046 */ 10047 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 10048 10049 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 10050 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 10051 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 10052 10053 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 10054 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 10055 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 10056 10057 /* pointer to stack or null */ 10058 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 10059 10060 /* unused */ 10061 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10062 return 0; 10063 } 10064 10065 static int set_callee_state(struct bpf_verifier_env *env, 10066 struct bpf_func_state *caller, 10067 struct bpf_func_state *callee, int insn_idx) 10068 { 10069 int i; 10070 10071 /* copy r1 - r5 args that callee can access. The copy includes parent 10072 * pointers, which connects us up to the liveness chain 10073 */ 10074 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 10075 callee->regs[i] = caller->regs[i]; 10076 return 0; 10077 } 10078 10079 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 10080 struct bpf_func_state *caller, 10081 struct bpf_func_state *callee, 10082 int insn_idx) 10083 { 10084 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 10085 struct bpf_map *map; 10086 int err; 10087 10088 /* valid map_ptr and poison value does not matter */ 10089 map = insn_aux->map_ptr_state.map_ptr; 10090 if (!map->ops->map_set_for_each_callback_args || 10091 !map->ops->map_for_each_callback) { 10092 verbose(env, "callback function not allowed for map\n"); 10093 return -ENOTSUPP; 10094 } 10095 10096 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 10097 if (err) 10098 return err; 10099 10100 callee->in_callback_fn = true; 10101 callee->callback_ret_range = retval_range(0, 1); 10102 return 0; 10103 } 10104 10105 static int set_loop_callback_state(struct bpf_verifier_env *env, 10106 struct bpf_func_state *caller, 10107 struct bpf_func_state *callee, 10108 int insn_idx) 10109 { 10110 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 10111 * u64 flags); 10112 * callback_fn(u64 index, void *callback_ctx); 10113 */ 10114 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 10115 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 10116 10117 /* unused */ 10118 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 10119 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10120 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10121 10122 callee->in_callback_fn = true; 10123 callee->callback_ret_range = retval_range(0, 1); 10124 return 0; 10125 } 10126 10127 static int set_timer_callback_state(struct bpf_verifier_env *env, 10128 struct bpf_func_state *caller, 10129 struct bpf_func_state *callee, 10130 int insn_idx) 10131 { 10132 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 10133 10134 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 10135 * callback_fn(struct bpf_map *map, void *key, void *value); 10136 */ 10137 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 10138 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 10139 callee->regs[BPF_REG_1].map_ptr = map_ptr; 10140 10141 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 10142 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 10143 callee->regs[BPF_REG_2].map_ptr = map_ptr; 10144 10145 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 10146 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 10147 callee->regs[BPF_REG_3].map_ptr = map_ptr; 10148 10149 /* unused */ 10150 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10151 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10152 callee->in_async_callback_fn = true; 10153 callee->callback_ret_range = retval_range(0, 1); 10154 return 0; 10155 } 10156 10157 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 10158 struct bpf_func_state *caller, 10159 struct bpf_func_state *callee, 10160 int insn_idx) 10161 { 10162 /* bpf_find_vma(struct task_struct *task, u64 addr, 10163 * void *callback_fn, void *callback_ctx, u64 flags) 10164 * (callback_fn)(struct task_struct *task, 10165 * struct vm_area_struct *vma, void *callback_ctx); 10166 */ 10167 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 10168 10169 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 10170 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 10171 callee->regs[BPF_REG_2].btf = btf_vmlinux; 10172 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 10173 10174 /* pointer to stack or null */ 10175 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 10176 10177 /* unused */ 10178 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10179 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10180 callee->in_callback_fn = true; 10181 callee->callback_ret_range = retval_range(0, 1); 10182 return 0; 10183 } 10184 10185 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 10186 struct bpf_func_state *caller, 10187 struct bpf_func_state *callee, 10188 int insn_idx) 10189 { 10190 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 10191 * callback_ctx, u64 flags); 10192 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 10193 */ 10194 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 10195 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 10196 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 10197 10198 /* unused */ 10199 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 10200 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10201 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10202 10203 callee->in_callback_fn = true; 10204 callee->callback_ret_range = retval_range(0, 1); 10205 return 0; 10206 } 10207 10208 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 10209 struct bpf_func_state *caller, 10210 struct bpf_func_state *callee, 10211 int insn_idx) 10212 { 10213 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 10214 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 10215 * 10216 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 10217 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 10218 * by this point, so look at 'root' 10219 */ 10220 struct btf_field *field; 10221 10222 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 10223 BPF_RB_ROOT); 10224 if (!field || !field->graph_root.value_btf_id) 10225 return -EFAULT; 10226 10227 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 10228 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 10229 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 10230 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 10231 10232 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 10233 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10234 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10235 callee->in_callback_fn = true; 10236 callee->callback_ret_range = retval_range(0, 1); 10237 return 0; 10238 } 10239 10240 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 10241 10242 /* Are we currently verifying the callback for a rbtree helper that must 10243 * be called with lock held? If so, no need to complain about unreleased 10244 * lock 10245 */ 10246 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 10247 { 10248 struct bpf_verifier_state *state = env->cur_state; 10249 struct bpf_insn *insn = env->prog->insnsi; 10250 struct bpf_func_state *callee; 10251 int kfunc_btf_id; 10252 10253 if (!state->curframe) 10254 return false; 10255 10256 callee = state->frame[state->curframe]; 10257 10258 if (!callee->in_callback_fn) 10259 return false; 10260 10261 kfunc_btf_id = insn[callee->callsite].imm; 10262 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 10263 } 10264 10265 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg, 10266 bool return_32bit) 10267 { 10268 if (return_32bit) 10269 return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval; 10270 else 10271 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval; 10272 } 10273 10274 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 10275 { 10276 struct bpf_verifier_state *state = env->cur_state, *prev_st; 10277 struct bpf_func_state *caller, *callee; 10278 struct bpf_reg_state *r0; 10279 bool in_callback_fn; 10280 int err; 10281 10282 callee = state->frame[state->curframe]; 10283 r0 = &callee->regs[BPF_REG_0]; 10284 if (r0->type == PTR_TO_STACK) { 10285 /* technically it's ok to return caller's stack pointer 10286 * (or caller's caller's pointer) back to the caller, 10287 * since these pointers are valid. Only current stack 10288 * pointer will be invalid as soon as function exits, 10289 * but let's be conservative 10290 */ 10291 verbose(env, "cannot return stack pointer to the caller\n"); 10292 return -EINVAL; 10293 } 10294 10295 caller = state->frame[state->curframe - 1]; 10296 if (callee->in_callback_fn) { 10297 if (r0->type != SCALAR_VALUE) { 10298 verbose(env, "R0 not a scalar value\n"); 10299 return -EACCES; 10300 } 10301 10302 /* we are going to rely on register's precise value */ 10303 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64); 10304 err = err ?: mark_chain_precision(env, BPF_REG_0); 10305 if (err) 10306 return err; 10307 10308 /* enforce R0 return value range, and bpf_callback_t returns 64bit */ 10309 if (!retval_range_within(callee->callback_ret_range, r0, false)) { 10310 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 10311 "At callback return", "R0"); 10312 return -EINVAL; 10313 } 10314 if (!calls_callback(env, callee->callsite)) { 10315 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n", 10316 *insn_idx, callee->callsite); 10317 return -EFAULT; 10318 } 10319 } else { 10320 /* return to the caller whatever r0 had in the callee */ 10321 caller->regs[BPF_REG_0] = *r0; 10322 } 10323 10324 /* Transfer references to the caller */ 10325 err = copy_reference_state(caller, callee); 10326 if (err) 10327 return err; 10328 10329 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 10330 * there function call logic would reschedule callback visit. If iteration 10331 * converges is_state_visited() would prune that visit eventually. 10332 */ 10333 in_callback_fn = callee->in_callback_fn; 10334 if (in_callback_fn) 10335 *insn_idx = callee->callsite; 10336 else 10337 *insn_idx = callee->callsite + 1; 10338 10339 if (env->log.level & BPF_LOG_LEVEL) { 10340 verbose(env, "returning from callee:\n"); 10341 print_verifier_state(env, callee, true); 10342 verbose(env, "to caller at %d:\n", *insn_idx); 10343 print_verifier_state(env, caller, true); 10344 } 10345 /* clear everything in the callee. In case of exceptional exits using 10346 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 10347 free_func_state(callee); 10348 state->frame[state->curframe--] = NULL; 10349 10350 /* for callbacks widen imprecise scalars to make programs like below verify: 10351 * 10352 * struct ctx { int i; } 10353 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 10354 * ... 10355 * struct ctx = { .i = 0; } 10356 * bpf_loop(100, cb, &ctx, 0); 10357 * 10358 * This is similar to what is done in process_iter_next_call() for open 10359 * coded iterators. 10360 */ 10361 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 10362 if (prev_st) { 10363 err = widen_imprecise_scalars(env, prev_st, state); 10364 if (err) 10365 return err; 10366 } 10367 return 0; 10368 } 10369 10370 static int do_refine_retval_range(struct bpf_verifier_env *env, 10371 struct bpf_reg_state *regs, int ret_type, 10372 int func_id, 10373 struct bpf_call_arg_meta *meta) 10374 { 10375 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 10376 10377 if (ret_type != RET_INTEGER) 10378 return 0; 10379 10380 switch (func_id) { 10381 case BPF_FUNC_get_stack: 10382 case BPF_FUNC_get_task_stack: 10383 case BPF_FUNC_probe_read_str: 10384 case BPF_FUNC_probe_read_kernel_str: 10385 case BPF_FUNC_probe_read_user_str: 10386 ret_reg->smax_value = meta->msize_max_value; 10387 ret_reg->s32_max_value = meta->msize_max_value; 10388 ret_reg->smin_value = -MAX_ERRNO; 10389 ret_reg->s32_min_value = -MAX_ERRNO; 10390 reg_bounds_sync(ret_reg); 10391 break; 10392 case BPF_FUNC_get_smp_processor_id: 10393 ret_reg->umax_value = nr_cpu_ids - 1; 10394 ret_reg->u32_max_value = nr_cpu_ids - 1; 10395 ret_reg->smax_value = nr_cpu_ids - 1; 10396 ret_reg->s32_max_value = nr_cpu_ids - 1; 10397 ret_reg->umin_value = 0; 10398 ret_reg->u32_min_value = 0; 10399 ret_reg->smin_value = 0; 10400 ret_reg->s32_min_value = 0; 10401 reg_bounds_sync(ret_reg); 10402 break; 10403 } 10404 10405 return reg_bounds_sanity_check(env, ret_reg, "retval"); 10406 } 10407 10408 static int 10409 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 10410 int func_id, int insn_idx) 10411 { 10412 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 10413 struct bpf_map *map = meta->map_ptr; 10414 10415 if (func_id != BPF_FUNC_tail_call && 10416 func_id != BPF_FUNC_map_lookup_elem && 10417 func_id != BPF_FUNC_map_update_elem && 10418 func_id != BPF_FUNC_map_delete_elem && 10419 func_id != BPF_FUNC_map_push_elem && 10420 func_id != BPF_FUNC_map_pop_elem && 10421 func_id != BPF_FUNC_map_peek_elem && 10422 func_id != BPF_FUNC_for_each_map_elem && 10423 func_id != BPF_FUNC_redirect_map && 10424 func_id != BPF_FUNC_map_lookup_percpu_elem) 10425 return 0; 10426 10427 if (map == NULL) { 10428 verbose(env, "kernel subsystem misconfigured verifier\n"); 10429 return -EINVAL; 10430 } 10431 10432 /* In case of read-only, some additional restrictions 10433 * need to be applied in order to prevent altering the 10434 * state of the map from program side. 10435 */ 10436 if ((map->map_flags & BPF_F_RDONLY_PROG) && 10437 (func_id == BPF_FUNC_map_delete_elem || 10438 func_id == BPF_FUNC_map_update_elem || 10439 func_id == BPF_FUNC_map_push_elem || 10440 func_id == BPF_FUNC_map_pop_elem)) { 10441 verbose(env, "write into map forbidden\n"); 10442 return -EACCES; 10443 } 10444 10445 if (!aux->map_ptr_state.map_ptr) 10446 bpf_map_ptr_store(aux, meta->map_ptr, 10447 !meta->map_ptr->bypass_spec_v1, false); 10448 else if (aux->map_ptr_state.map_ptr != meta->map_ptr) 10449 bpf_map_ptr_store(aux, meta->map_ptr, 10450 !meta->map_ptr->bypass_spec_v1, true); 10451 return 0; 10452 } 10453 10454 static int 10455 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 10456 int func_id, int insn_idx) 10457 { 10458 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 10459 struct bpf_reg_state *regs = cur_regs(env), *reg; 10460 struct bpf_map *map = meta->map_ptr; 10461 u64 val, max; 10462 int err; 10463 10464 if (func_id != BPF_FUNC_tail_call) 10465 return 0; 10466 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 10467 verbose(env, "kernel subsystem misconfigured verifier\n"); 10468 return -EINVAL; 10469 } 10470 10471 reg = ®s[BPF_REG_3]; 10472 val = reg->var_off.value; 10473 max = map->max_entries; 10474 10475 if (!(is_reg_const(reg, false) && val < max)) { 10476 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 10477 return 0; 10478 } 10479 10480 err = mark_chain_precision(env, BPF_REG_3); 10481 if (err) 10482 return err; 10483 if (bpf_map_key_unseen(aux)) 10484 bpf_map_key_store(aux, val); 10485 else if (!bpf_map_key_poisoned(aux) && 10486 bpf_map_key_immediate(aux) != val) 10487 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 10488 return 0; 10489 } 10490 10491 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 10492 { 10493 struct bpf_func_state *state = cur_func(env); 10494 bool refs_lingering = false; 10495 int i; 10496 10497 if (!exception_exit && state->frameno) 10498 return 0; 10499 10500 for (i = 0; i < state->acquired_refs; i++) { 10501 if (state->refs[i].type != REF_TYPE_PTR) 10502 continue; 10503 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 10504 state->refs[i].id, state->refs[i].insn_idx); 10505 refs_lingering = true; 10506 } 10507 return refs_lingering ? -EINVAL : 0; 10508 } 10509 10510 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix) 10511 { 10512 int err; 10513 10514 if (check_lock && cur_func(env)->active_locks) { 10515 verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix); 10516 return -EINVAL; 10517 } 10518 10519 err = check_reference_leak(env, exception_exit); 10520 if (err) { 10521 verbose(env, "%s would lead to reference leak\n", prefix); 10522 return err; 10523 } 10524 10525 if (check_lock && env->cur_state->active_rcu_lock) { 10526 verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix); 10527 return -EINVAL; 10528 } 10529 10530 if (check_lock && env->cur_state->active_preempt_lock) { 10531 verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix); 10532 return -EINVAL; 10533 } 10534 10535 return 0; 10536 } 10537 10538 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 10539 struct bpf_reg_state *regs) 10540 { 10541 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 10542 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 10543 struct bpf_map *fmt_map = fmt_reg->map_ptr; 10544 struct bpf_bprintf_data data = {}; 10545 int err, fmt_map_off, num_args; 10546 u64 fmt_addr; 10547 char *fmt; 10548 10549 /* data must be an array of u64 */ 10550 if (data_len_reg->var_off.value % 8) 10551 return -EINVAL; 10552 num_args = data_len_reg->var_off.value / 8; 10553 10554 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 10555 * and map_direct_value_addr is set. 10556 */ 10557 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 10558 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 10559 fmt_map_off); 10560 if (err) { 10561 verbose(env, "verifier bug\n"); 10562 return -EFAULT; 10563 } 10564 fmt = (char *)(long)fmt_addr + fmt_map_off; 10565 10566 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 10567 * can focus on validating the format specifiers. 10568 */ 10569 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 10570 if (err < 0) 10571 verbose(env, "Invalid format string\n"); 10572 10573 return err; 10574 } 10575 10576 static int check_get_func_ip(struct bpf_verifier_env *env) 10577 { 10578 enum bpf_prog_type type = resolve_prog_type(env->prog); 10579 int func_id = BPF_FUNC_get_func_ip; 10580 10581 if (type == BPF_PROG_TYPE_TRACING) { 10582 if (!bpf_prog_has_trampoline(env->prog)) { 10583 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 10584 func_id_name(func_id), func_id); 10585 return -ENOTSUPP; 10586 } 10587 return 0; 10588 } else if (type == BPF_PROG_TYPE_KPROBE) { 10589 return 0; 10590 } 10591 10592 verbose(env, "func %s#%d not supported for program type %d\n", 10593 func_id_name(func_id), func_id, type); 10594 return -ENOTSUPP; 10595 } 10596 10597 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 10598 { 10599 return &env->insn_aux_data[env->insn_idx]; 10600 } 10601 10602 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 10603 { 10604 struct bpf_reg_state *regs = cur_regs(env); 10605 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 10606 bool reg_is_null = register_is_null(reg); 10607 10608 if (reg_is_null) 10609 mark_chain_precision(env, BPF_REG_4); 10610 10611 return reg_is_null; 10612 } 10613 10614 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 10615 { 10616 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 10617 10618 if (!state->initialized) { 10619 state->initialized = 1; 10620 state->fit_for_inline = loop_flag_is_zero(env); 10621 state->callback_subprogno = subprogno; 10622 return; 10623 } 10624 10625 if (!state->fit_for_inline) 10626 return; 10627 10628 state->fit_for_inline = (loop_flag_is_zero(env) && 10629 state->callback_subprogno == subprogno); 10630 } 10631 10632 static int get_helper_proto(struct bpf_verifier_env *env, int func_id, 10633 const struct bpf_func_proto **ptr) 10634 { 10635 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) 10636 return -ERANGE; 10637 10638 if (!env->ops->get_func_proto) 10639 return -EINVAL; 10640 10641 *ptr = env->ops->get_func_proto(func_id, env->prog); 10642 return *ptr ? 0 : -EINVAL; 10643 } 10644 10645 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10646 int *insn_idx_p) 10647 { 10648 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 10649 bool returns_cpu_specific_alloc_ptr = false; 10650 const struct bpf_func_proto *fn = NULL; 10651 enum bpf_return_type ret_type; 10652 enum bpf_type_flag ret_flag; 10653 struct bpf_reg_state *regs; 10654 struct bpf_call_arg_meta meta; 10655 int insn_idx = *insn_idx_p; 10656 bool changes_data; 10657 int i, err, func_id; 10658 10659 /* find function prototype */ 10660 func_id = insn->imm; 10661 err = get_helper_proto(env, insn->imm, &fn); 10662 if (err == -ERANGE) { 10663 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id); 10664 return -EINVAL; 10665 } 10666 10667 if (err) { 10668 verbose(env, "program of this type cannot use helper %s#%d\n", 10669 func_id_name(func_id), func_id); 10670 return err; 10671 } 10672 10673 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 10674 if (!env->prog->gpl_compatible && fn->gpl_only) { 10675 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10676 return -EINVAL; 10677 } 10678 10679 if (fn->allowed && !fn->allowed(env->prog)) { 10680 verbose(env, "helper call is not allowed in probe\n"); 10681 return -EINVAL; 10682 } 10683 10684 if (!in_sleepable(env) && fn->might_sleep) { 10685 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 10686 return -EINVAL; 10687 } 10688 10689 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10690 changes_data = bpf_helper_changes_pkt_data(func_id); 10691 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10692 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 10693 func_id_name(func_id), func_id); 10694 return -EINVAL; 10695 } 10696 10697 memset(&meta, 0, sizeof(meta)); 10698 meta.pkt_access = fn->pkt_access; 10699 10700 err = check_func_proto(fn, func_id); 10701 if (err) { 10702 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 10703 func_id_name(func_id), func_id); 10704 return err; 10705 } 10706 10707 if (env->cur_state->active_rcu_lock) { 10708 if (fn->might_sleep) { 10709 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 10710 func_id_name(func_id), func_id); 10711 return -EINVAL; 10712 } 10713 10714 if (in_sleepable(env) && is_storage_get_function(func_id)) 10715 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10716 } 10717 10718 if (env->cur_state->active_preempt_lock) { 10719 if (fn->might_sleep) { 10720 verbose(env, "sleepable helper %s#%d in non-preemptible region\n", 10721 func_id_name(func_id), func_id); 10722 return -EINVAL; 10723 } 10724 10725 if (in_sleepable(env) && is_storage_get_function(func_id)) 10726 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10727 } 10728 10729 meta.func_id = func_id; 10730 /* check args */ 10731 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10732 err = check_func_arg(env, i, &meta, fn, insn_idx); 10733 if (err) 10734 return err; 10735 } 10736 10737 err = record_func_map(env, &meta, func_id, insn_idx); 10738 if (err) 10739 return err; 10740 10741 err = record_func_key(env, &meta, func_id, insn_idx); 10742 if (err) 10743 return err; 10744 10745 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10746 * is inferred from register state. 10747 */ 10748 for (i = 0; i < meta.access_size; i++) { 10749 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 10750 BPF_WRITE, -1, false, false); 10751 if (err) 10752 return err; 10753 } 10754 10755 regs = cur_regs(env); 10756 10757 if (meta.release_regno) { 10758 err = -EINVAL; 10759 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 10760 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 10761 * is safe to do directly. 10762 */ 10763 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 10764 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 10765 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 10766 return -EFAULT; 10767 } 10768 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 10769 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 10770 u32 ref_obj_id = meta.ref_obj_id; 10771 bool in_rcu = in_rcu_cs(env); 10772 struct bpf_func_state *state; 10773 struct bpf_reg_state *reg; 10774 10775 err = release_reference_state(cur_func(env), ref_obj_id); 10776 if (!err) { 10777 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10778 if (reg->ref_obj_id == ref_obj_id) { 10779 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 10780 reg->ref_obj_id = 0; 10781 reg->type &= ~MEM_ALLOC; 10782 reg->type |= MEM_RCU; 10783 } else { 10784 mark_reg_invalid(env, reg); 10785 } 10786 } 10787 })); 10788 } 10789 } else if (meta.ref_obj_id) { 10790 err = release_reference(env, meta.ref_obj_id); 10791 } else if (register_is_null(®s[meta.release_regno])) { 10792 /* meta.ref_obj_id can only be 0 if register that is meant to be 10793 * released is NULL, which must be > R0. 10794 */ 10795 err = 0; 10796 } 10797 if (err) { 10798 verbose(env, "func %s#%d reference has not been acquired before\n", 10799 func_id_name(func_id), func_id); 10800 return err; 10801 } 10802 } 10803 10804 switch (func_id) { 10805 case BPF_FUNC_tail_call: 10806 err = check_resource_leak(env, false, true, "tail_call"); 10807 if (err) 10808 return err; 10809 break; 10810 case BPF_FUNC_get_local_storage: 10811 /* check that flags argument in get_local_storage(map, flags) is 0, 10812 * this is required because get_local_storage() can't return an error. 10813 */ 10814 if (!register_is_null(®s[BPF_REG_2])) { 10815 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10816 return -EINVAL; 10817 } 10818 break; 10819 case BPF_FUNC_for_each_map_elem: 10820 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10821 set_map_elem_callback_state); 10822 break; 10823 case BPF_FUNC_timer_set_callback: 10824 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10825 set_timer_callback_state); 10826 break; 10827 case BPF_FUNC_find_vma: 10828 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10829 set_find_vma_callback_state); 10830 break; 10831 case BPF_FUNC_snprintf: 10832 err = check_bpf_snprintf_call(env, regs); 10833 break; 10834 case BPF_FUNC_loop: 10835 update_loop_inline_state(env, meta.subprogno); 10836 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10837 * is finished, thus mark it precise. 10838 */ 10839 err = mark_chain_precision(env, BPF_REG_1); 10840 if (err) 10841 return err; 10842 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) { 10843 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10844 set_loop_callback_state); 10845 } else { 10846 cur_func(env)->callback_depth = 0; 10847 if (env->log.level & BPF_LOG_LEVEL2) 10848 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10849 env->cur_state->curframe); 10850 } 10851 break; 10852 case BPF_FUNC_dynptr_from_mem: 10853 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10854 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10855 reg_type_str(env, regs[BPF_REG_1].type)); 10856 return -EACCES; 10857 } 10858 break; 10859 case BPF_FUNC_set_retval: 10860 if (prog_type == BPF_PROG_TYPE_LSM && 10861 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10862 if (!env->prog->aux->attach_func_proto->type) { 10863 /* Make sure programs that attach to void 10864 * hooks don't try to modify return value. 10865 */ 10866 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10867 return -EINVAL; 10868 } 10869 } 10870 break; 10871 case BPF_FUNC_dynptr_data: 10872 { 10873 struct bpf_reg_state *reg; 10874 int id, ref_obj_id; 10875 10876 reg = get_dynptr_arg_reg(env, fn, regs); 10877 if (!reg) 10878 return -EFAULT; 10879 10880 10881 if (meta.dynptr_id) { 10882 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 10883 return -EFAULT; 10884 } 10885 if (meta.ref_obj_id) { 10886 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 10887 return -EFAULT; 10888 } 10889 10890 id = dynptr_id(env, reg); 10891 if (id < 0) { 10892 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 10893 return id; 10894 } 10895 10896 ref_obj_id = dynptr_ref_obj_id(env, reg); 10897 if (ref_obj_id < 0) { 10898 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 10899 return ref_obj_id; 10900 } 10901 10902 meta.dynptr_id = id; 10903 meta.ref_obj_id = ref_obj_id; 10904 10905 break; 10906 } 10907 case BPF_FUNC_dynptr_write: 10908 { 10909 enum bpf_dynptr_type dynptr_type; 10910 struct bpf_reg_state *reg; 10911 10912 reg = get_dynptr_arg_reg(env, fn, regs); 10913 if (!reg) 10914 return -EFAULT; 10915 10916 dynptr_type = dynptr_get_type(env, reg); 10917 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10918 return -EFAULT; 10919 10920 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 10921 /* this will trigger clear_all_pkt_pointers(), which will 10922 * invalidate all dynptr slices associated with the skb 10923 */ 10924 changes_data = true; 10925 10926 break; 10927 } 10928 case BPF_FUNC_per_cpu_ptr: 10929 case BPF_FUNC_this_cpu_ptr: 10930 { 10931 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 10932 const struct btf_type *type; 10933 10934 if (reg->type & MEM_RCU) { 10935 type = btf_type_by_id(reg->btf, reg->btf_id); 10936 if (!type || !btf_type_is_struct(type)) { 10937 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 10938 return -EFAULT; 10939 } 10940 returns_cpu_specific_alloc_ptr = true; 10941 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 10942 } 10943 break; 10944 } 10945 case BPF_FUNC_user_ringbuf_drain: 10946 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10947 set_user_ringbuf_callback_state); 10948 break; 10949 } 10950 10951 if (err) 10952 return err; 10953 10954 /* reset caller saved regs */ 10955 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10956 mark_reg_not_init(env, regs, caller_saved[i]); 10957 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10958 } 10959 10960 /* helper call returns 64-bit value. */ 10961 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10962 10963 /* update return register (already marked as written above) */ 10964 ret_type = fn->ret_type; 10965 ret_flag = type_flag(ret_type); 10966 10967 switch (base_type(ret_type)) { 10968 case RET_INTEGER: 10969 /* sets type to SCALAR_VALUE */ 10970 mark_reg_unknown(env, regs, BPF_REG_0); 10971 break; 10972 case RET_VOID: 10973 regs[BPF_REG_0].type = NOT_INIT; 10974 break; 10975 case RET_PTR_TO_MAP_VALUE: 10976 /* There is no offset yet applied, variable or fixed */ 10977 mark_reg_known_zero(env, regs, BPF_REG_0); 10978 /* remember map_ptr, so that check_map_access() 10979 * can check 'value_size' boundary of memory access 10980 * to map element returned from bpf_map_lookup_elem() 10981 */ 10982 if (meta.map_ptr == NULL) { 10983 verbose(env, 10984 "kernel subsystem misconfigured verifier\n"); 10985 return -EINVAL; 10986 } 10987 regs[BPF_REG_0].map_ptr = meta.map_ptr; 10988 regs[BPF_REG_0].map_uid = meta.map_uid; 10989 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10990 if (!type_may_be_null(ret_type) && 10991 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 10992 regs[BPF_REG_0].id = ++env->id_gen; 10993 } 10994 break; 10995 case RET_PTR_TO_SOCKET: 10996 mark_reg_known_zero(env, regs, BPF_REG_0); 10997 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10998 break; 10999 case RET_PTR_TO_SOCK_COMMON: 11000 mark_reg_known_zero(env, regs, BPF_REG_0); 11001 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 11002 break; 11003 case RET_PTR_TO_TCP_SOCK: 11004 mark_reg_known_zero(env, regs, BPF_REG_0); 11005 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 11006 break; 11007 case RET_PTR_TO_MEM: 11008 mark_reg_known_zero(env, regs, BPF_REG_0); 11009 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 11010 regs[BPF_REG_0].mem_size = meta.mem_size; 11011 break; 11012 case RET_PTR_TO_MEM_OR_BTF_ID: 11013 { 11014 const struct btf_type *t; 11015 11016 mark_reg_known_zero(env, regs, BPF_REG_0); 11017 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 11018 if (!btf_type_is_struct(t)) { 11019 u32 tsize; 11020 const struct btf_type *ret; 11021 const char *tname; 11022 11023 /* resolve the type size of ksym. */ 11024 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 11025 if (IS_ERR(ret)) { 11026 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 11027 verbose(env, "unable to resolve the size of type '%s': %ld\n", 11028 tname, PTR_ERR(ret)); 11029 return -EINVAL; 11030 } 11031 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 11032 regs[BPF_REG_0].mem_size = tsize; 11033 } else { 11034 if (returns_cpu_specific_alloc_ptr) { 11035 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 11036 } else { 11037 /* MEM_RDONLY may be carried from ret_flag, but it 11038 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 11039 * it will confuse the check of PTR_TO_BTF_ID in 11040 * check_mem_access(). 11041 */ 11042 ret_flag &= ~MEM_RDONLY; 11043 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 11044 } 11045 11046 regs[BPF_REG_0].btf = meta.ret_btf; 11047 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 11048 } 11049 break; 11050 } 11051 case RET_PTR_TO_BTF_ID: 11052 { 11053 struct btf *ret_btf; 11054 int ret_btf_id; 11055 11056 mark_reg_known_zero(env, regs, BPF_REG_0); 11057 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 11058 if (func_id == BPF_FUNC_kptr_xchg) { 11059 ret_btf = meta.kptr_field->kptr.btf; 11060 ret_btf_id = meta.kptr_field->kptr.btf_id; 11061 if (!btf_is_kernel(ret_btf)) { 11062 regs[BPF_REG_0].type |= MEM_ALLOC; 11063 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 11064 regs[BPF_REG_0].type |= MEM_PERCPU; 11065 } 11066 } else { 11067 if (fn->ret_btf_id == BPF_PTR_POISON) { 11068 verbose(env, "verifier internal error:"); 11069 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 11070 func_id_name(func_id)); 11071 return -EINVAL; 11072 } 11073 ret_btf = btf_vmlinux; 11074 ret_btf_id = *fn->ret_btf_id; 11075 } 11076 if (ret_btf_id == 0) { 11077 verbose(env, "invalid return type %u of func %s#%d\n", 11078 base_type(ret_type), func_id_name(func_id), 11079 func_id); 11080 return -EINVAL; 11081 } 11082 regs[BPF_REG_0].btf = ret_btf; 11083 regs[BPF_REG_0].btf_id = ret_btf_id; 11084 break; 11085 } 11086 default: 11087 verbose(env, "unknown return type %u of func %s#%d\n", 11088 base_type(ret_type), func_id_name(func_id), func_id); 11089 return -EINVAL; 11090 } 11091 11092 if (type_may_be_null(regs[BPF_REG_0].type)) 11093 regs[BPF_REG_0].id = ++env->id_gen; 11094 11095 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 11096 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 11097 func_id_name(func_id), func_id); 11098 return -EFAULT; 11099 } 11100 11101 if (is_dynptr_ref_function(func_id)) 11102 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 11103 11104 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 11105 /* For release_reference() */ 11106 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 11107 } else if (is_acquire_function(func_id, meta.map_ptr)) { 11108 int id = acquire_reference_state(env, insn_idx); 11109 11110 if (id < 0) 11111 return id; 11112 /* For mark_ptr_or_null_reg() */ 11113 regs[BPF_REG_0].id = id; 11114 /* For release_reference() */ 11115 regs[BPF_REG_0].ref_obj_id = id; 11116 } 11117 11118 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 11119 if (err) 11120 return err; 11121 11122 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 11123 if (err) 11124 return err; 11125 11126 if ((func_id == BPF_FUNC_get_stack || 11127 func_id == BPF_FUNC_get_task_stack) && 11128 !env->prog->has_callchain_buf) { 11129 const char *err_str; 11130 11131 #ifdef CONFIG_PERF_EVENTS 11132 err = get_callchain_buffers(sysctl_perf_event_max_stack); 11133 err_str = "cannot get callchain buffer for func %s#%d\n"; 11134 #else 11135 err = -ENOTSUPP; 11136 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 11137 #endif 11138 if (err) { 11139 verbose(env, err_str, func_id_name(func_id), func_id); 11140 return err; 11141 } 11142 11143 env->prog->has_callchain_buf = true; 11144 } 11145 11146 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 11147 env->prog->call_get_stack = true; 11148 11149 if (func_id == BPF_FUNC_get_func_ip) { 11150 if (check_get_func_ip(env)) 11151 return -ENOTSUPP; 11152 env->prog->call_get_func_ip = true; 11153 } 11154 11155 if (changes_data) 11156 clear_all_pkt_pointers(env); 11157 return 0; 11158 } 11159 11160 /* mark_btf_func_reg_size() is used when the reg size is determined by 11161 * the BTF func_proto's return value size and argument. 11162 */ 11163 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 11164 size_t reg_size) 11165 { 11166 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 11167 11168 if (regno == BPF_REG_0) { 11169 /* Function return value */ 11170 reg->live |= REG_LIVE_WRITTEN; 11171 reg->subreg_def = reg_size == sizeof(u64) ? 11172 DEF_NOT_SUBREG : env->insn_idx + 1; 11173 } else { 11174 /* Function argument */ 11175 if (reg_size == sizeof(u64)) { 11176 mark_insn_zext(env, reg); 11177 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 11178 } else { 11179 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 11180 } 11181 } 11182 } 11183 11184 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 11185 { 11186 return meta->kfunc_flags & KF_ACQUIRE; 11187 } 11188 11189 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 11190 { 11191 return meta->kfunc_flags & KF_RELEASE; 11192 } 11193 11194 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 11195 { 11196 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 11197 } 11198 11199 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 11200 { 11201 return meta->kfunc_flags & KF_SLEEPABLE; 11202 } 11203 11204 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 11205 { 11206 return meta->kfunc_flags & KF_DESTRUCTIVE; 11207 } 11208 11209 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 11210 { 11211 return meta->kfunc_flags & KF_RCU; 11212 } 11213 11214 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 11215 { 11216 return meta->kfunc_flags & KF_RCU_PROTECTED; 11217 } 11218 11219 static bool is_kfunc_arg_mem_size(const struct btf *btf, 11220 const struct btf_param *arg, 11221 const struct bpf_reg_state *reg) 11222 { 11223 const struct btf_type *t; 11224 11225 t = btf_type_skip_modifiers(btf, arg->type, NULL); 11226 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 11227 return false; 11228 11229 return btf_param_match_suffix(btf, arg, "__sz"); 11230 } 11231 11232 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 11233 const struct btf_param *arg, 11234 const struct bpf_reg_state *reg) 11235 { 11236 const struct btf_type *t; 11237 11238 t = btf_type_skip_modifiers(btf, arg->type, NULL); 11239 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 11240 return false; 11241 11242 return btf_param_match_suffix(btf, arg, "__szk"); 11243 } 11244 11245 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 11246 { 11247 return btf_param_match_suffix(btf, arg, "__opt"); 11248 } 11249 11250 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 11251 { 11252 return btf_param_match_suffix(btf, arg, "__k"); 11253 } 11254 11255 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 11256 { 11257 return btf_param_match_suffix(btf, arg, "__ign"); 11258 } 11259 11260 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg) 11261 { 11262 return btf_param_match_suffix(btf, arg, "__map"); 11263 } 11264 11265 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 11266 { 11267 return btf_param_match_suffix(btf, arg, "__alloc"); 11268 } 11269 11270 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 11271 { 11272 return btf_param_match_suffix(btf, arg, "__uninit"); 11273 } 11274 11275 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 11276 { 11277 return btf_param_match_suffix(btf, arg, "__refcounted_kptr"); 11278 } 11279 11280 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 11281 { 11282 return btf_param_match_suffix(btf, arg, "__nullable"); 11283 } 11284 11285 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 11286 { 11287 return btf_param_match_suffix(btf, arg, "__str"); 11288 } 11289 11290 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 11291 const struct btf_param *arg, 11292 const char *name) 11293 { 11294 int len, target_len = strlen(name); 11295 const char *param_name; 11296 11297 param_name = btf_name_by_offset(btf, arg->name_off); 11298 if (str_is_empty(param_name)) 11299 return false; 11300 len = strlen(param_name); 11301 if (len != target_len) 11302 return false; 11303 if (strcmp(param_name, name)) 11304 return false; 11305 11306 return true; 11307 } 11308 11309 enum { 11310 KF_ARG_DYNPTR_ID, 11311 KF_ARG_LIST_HEAD_ID, 11312 KF_ARG_LIST_NODE_ID, 11313 KF_ARG_RB_ROOT_ID, 11314 KF_ARG_RB_NODE_ID, 11315 KF_ARG_WORKQUEUE_ID, 11316 }; 11317 11318 BTF_ID_LIST(kf_arg_btf_ids) 11319 BTF_ID(struct, bpf_dynptr) 11320 BTF_ID(struct, bpf_list_head) 11321 BTF_ID(struct, bpf_list_node) 11322 BTF_ID(struct, bpf_rb_root) 11323 BTF_ID(struct, bpf_rb_node) 11324 BTF_ID(struct, bpf_wq) 11325 11326 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 11327 const struct btf_param *arg, int type) 11328 { 11329 const struct btf_type *t; 11330 u32 res_id; 11331 11332 t = btf_type_skip_modifiers(btf, arg->type, NULL); 11333 if (!t) 11334 return false; 11335 if (!btf_type_is_ptr(t)) 11336 return false; 11337 t = btf_type_skip_modifiers(btf, t->type, &res_id); 11338 if (!t) 11339 return false; 11340 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 11341 } 11342 11343 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 11344 { 11345 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 11346 } 11347 11348 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 11349 { 11350 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 11351 } 11352 11353 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 11354 { 11355 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 11356 } 11357 11358 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 11359 { 11360 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 11361 } 11362 11363 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 11364 { 11365 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 11366 } 11367 11368 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg) 11369 { 11370 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID); 11371 } 11372 11373 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 11374 const struct btf_param *arg) 11375 { 11376 const struct btf_type *t; 11377 11378 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 11379 if (!t) 11380 return false; 11381 11382 return true; 11383 } 11384 11385 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 11386 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 11387 const struct btf *btf, 11388 const struct btf_type *t, int rec) 11389 { 11390 const struct btf_type *member_type; 11391 const struct btf_member *member; 11392 u32 i; 11393 11394 if (!btf_type_is_struct(t)) 11395 return false; 11396 11397 for_each_member(i, t, member) { 11398 const struct btf_array *array; 11399 11400 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 11401 if (btf_type_is_struct(member_type)) { 11402 if (rec >= 3) { 11403 verbose(env, "max struct nesting depth exceeded\n"); 11404 return false; 11405 } 11406 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 11407 return false; 11408 continue; 11409 } 11410 if (btf_type_is_array(member_type)) { 11411 array = btf_array(member_type); 11412 if (!array->nelems) 11413 return false; 11414 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 11415 if (!btf_type_is_scalar(member_type)) 11416 return false; 11417 continue; 11418 } 11419 if (!btf_type_is_scalar(member_type)) 11420 return false; 11421 } 11422 return true; 11423 } 11424 11425 enum kfunc_ptr_arg_type { 11426 KF_ARG_PTR_TO_CTX, 11427 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 11428 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 11429 KF_ARG_PTR_TO_DYNPTR, 11430 KF_ARG_PTR_TO_ITER, 11431 KF_ARG_PTR_TO_LIST_HEAD, 11432 KF_ARG_PTR_TO_LIST_NODE, 11433 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 11434 KF_ARG_PTR_TO_MEM, 11435 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 11436 KF_ARG_PTR_TO_CALLBACK, 11437 KF_ARG_PTR_TO_RB_ROOT, 11438 KF_ARG_PTR_TO_RB_NODE, 11439 KF_ARG_PTR_TO_NULL, 11440 KF_ARG_PTR_TO_CONST_STR, 11441 KF_ARG_PTR_TO_MAP, 11442 KF_ARG_PTR_TO_WORKQUEUE, 11443 }; 11444 11445 enum special_kfunc_type { 11446 KF_bpf_obj_new_impl, 11447 KF_bpf_obj_drop_impl, 11448 KF_bpf_refcount_acquire_impl, 11449 KF_bpf_list_push_front_impl, 11450 KF_bpf_list_push_back_impl, 11451 KF_bpf_list_pop_front, 11452 KF_bpf_list_pop_back, 11453 KF_bpf_cast_to_kern_ctx, 11454 KF_bpf_rdonly_cast, 11455 KF_bpf_rcu_read_lock, 11456 KF_bpf_rcu_read_unlock, 11457 KF_bpf_rbtree_remove, 11458 KF_bpf_rbtree_add_impl, 11459 KF_bpf_rbtree_first, 11460 KF_bpf_dynptr_from_skb, 11461 KF_bpf_dynptr_from_xdp, 11462 KF_bpf_dynptr_slice, 11463 KF_bpf_dynptr_slice_rdwr, 11464 KF_bpf_dynptr_clone, 11465 KF_bpf_percpu_obj_new_impl, 11466 KF_bpf_percpu_obj_drop_impl, 11467 KF_bpf_throw, 11468 KF_bpf_wq_set_callback_impl, 11469 KF_bpf_preempt_disable, 11470 KF_bpf_preempt_enable, 11471 KF_bpf_iter_css_task_new, 11472 KF_bpf_session_cookie, 11473 KF_bpf_get_kmem_cache, 11474 }; 11475 11476 BTF_SET_START(special_kfunc_set) 11477 BTF_ID(func, bpf_obj_new_impl) 11478 BTF_ID(func, bpf_obj_drop_impl) 11479 BTF_ID(func, bpf_refcount_acquire_impl) 11480 BTF_ID(func, bpf_list_push_front_impl) 11481 BTF_ID(func, bpf_list_push_back_impl) 11482 BTF_ID(func, bpf_list_pop_front) 11483 BTF_ID(func, bpf_list_pop_back) 11484 BTF_ID(func, bpf_cast_to_kern_ctx) 11485 BTF_ID(func, bpf_rdonly_cast) 11486 BTF_ID(func, bpf_rbtree_remove) 11487 BTF_ID(func, bpf_rbtree_add_impl) 11488 BTF_ID(func, bpf_rbtree_first) 11489 BTF_ID(func, bpf_dynptr_from_skb) 11490 BTF_ID(func, bpf_dynptr_from_xdp) 11491 BTF_ID(func, bpf_dynptr_slice) 11492 BTF_ID(func, bpf_dynptr_slice_rdwr) 11493 BTF_ID(func, bpf_dynptr_clone) 11494 BTF_ID(func, bpf_percpu_obj_new_impl) 11495 BTF_ID(func, bpf_percpu_obj_drop_impl) 11496 BTF_ID(func, bpf_throw) 11497 BTF_ID(func, bpf_wq_set_callback_impl) 11498 #ifdef CONFIG_CGROUPS 11499 BTF_ID(func, bpf_iter_css_task_new) 11500 #endif 11501 BTF_SET_END(special_kfunc_set) 11502 11503 BTF_ID_LIST(special_kfunc_list) 11504 BTF_ID(func, bpf_obj_new_impl) 11505 BTF_ID(func, bpf_obj_drop_impl) 11506 BTF_ID(func, bpf_refcount_acquire_impl) 11507 BTF_ID(func, bpf_list_push_front_impl) 11508 BTF_ID(func, bpf_list_push_back_impl) 11509 BTF_ID(func, bpf_list_pop_front) 11510 BTF_ID(func, bpf_list_pop_back) 11511 BTF_ID(func, bpf_cast_to_kern_ctx) 11512 BTF_ID(func, bpf_rdonly_cast) 11513 BTF_ID(func, bpf_rcu_read_lock) 11514 BTF_ID(func, bpf_rcu_read_unlock) 11515 BTF_ID(func, bpf_rbtree_remove) 11516 BTF_ID(func, bpf_rbtree_add_impl) 11517 BTF_ID(func, bpf_rbtree_first) 11518 BTF_ID(func, bpf_dynptr_from_skb) 11519 BTF_ID(func, bpf_dynptr_from_xdp) 11520 BTF_ID(func, bpf_dynptr_slice) 11521 BTF_ID(func, bpf_dynptr_slice_rdwr) 11522 BTF_ID(func, bpf_dynptr_clone) 11523 BTF_ID(func, bpf_percpu_obj_new_impl) 11524 BTF_ID(func, bpf_percpu_obj_drop_impl) 11525 BTF_ID(func, bpf_throw) 11526 BTF_ID(func, bpf_wq_set_callback_impl) 11527 BTF_ID(func, bpf_preempt_disable) 11528 BTF_ID(func, bpf_preempt_enable) 11529 #ifdef CONFIG_CGROUPS 11530 BTF_ID(func, bpf_iter_css_task_new) 11531 #else 11532 BTF_ID_UNUSED 11533 #endif 11534 #ifdef CONFIG_BPF_EVENTS 11535 BTF_ID(func, bpf_session_cookie) 11536 #else 11537 BTF_ID_UNUSED 11538 #endif 11539 BTF_ID(func, bpf_get_kmem_cache) 11540 11541 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 11542 { 11543 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 11544 meta->arg_owning_ref) { 11545 return false; 11546 } 11547 11548 return meta->kfunc_flags & KF_RET_NULL; 11549 } 11550 11551 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 11552 { 11553 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 11554 } 11555 11556 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 11557 { 11558 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 11559 } 11560 11561 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta) 11562 { 11563 return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable]; 11564 } 11565 11566 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta) 11567 { 11568 return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable]; 11569 } 11570 11571 static enum kfunc_ptr_arg_type 11572 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 11573 struct bpf_kfunc_call_arg_meta *meta, 11574 const struct btf_type *t, const struct btf_type *ref_t, 11575 const char *ref_tname, const struct btf_param *args, 11576 int argno, int nargs) 11577 { 11578 u32 regno = argno + 1; 11579 struct bpf_reg_state *regs = cur_regs(env); 11580 struct bpf_reg_state *reg = ®s[regno]; 11581 bool arg_mem_size = false; 11582 11583 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 11584 return KF_ARG_PTR_TO_CTX; 11585 11586 /* In this function, we verify the kfunc's BTF as per the argument type, 11587 * leaving the rest of the verification with respect to the register 11588 * type to our caller. When a set of conditions hold in the BTF type of 11589 * arguments, we resolve it to a known kfunc_ptr_arg_type. 11590 */ 11591 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 11592 return KF_ARG_PTR_TO_CTX; 11593 11594 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg)) 11595 return KF_ARG_PTR_TO_NULL; 11596 11597 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 11598 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 11599 11600 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 11601 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 11602 11603 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 11604 return KF_ARG_PTR_TO_DYNPTR; 11605 11606 if (is_kfunc_arg_iter(meta, argno, &args[argno])) 11607 return KF_ARG_PTR_TO_ITER; 11608 11609 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 11610 return KF_ARG_PTR_TO_LIST_HEAD; 11611 11612 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 11613 return KF_ARG_PTR_TO_LIST_NODE; 11614 11615 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 11616 return KF_ARG_PTR_TO_RB_ROOT; 11617 11618 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 11619 return KF_ARG_PTR_TO_RB_NODE; 11620 11621 if (is_kfunc_arg_const_str(meta->btf, &args[argno])) 11622 return KF_ARG_PTR_TO_CONST_STR; 11623 11624 if (is_kfunc_arg_map(meta->btf, &args[argno])) 11625 return KF_ARG_PTR_TO_MAP; 11626 11627 if (is_kfunc_arg_wq(meta->btf, &args[argno])) 11628 return KF_ARG_PTR_TO_WORKQUEUE; 11629 11630 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 11631 if (!btf_type_is_struct(ref_t)) { 11632 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 11633 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 11634 return -EINVAL; 11635 } 11636 return KF_ARG_PTR_TO_BTF_ID; 11637 } 11638 11639 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 11640 return KF_ARG_PTR_TO_CALLBACK; 11641 11642 if (argno + 1 < nargs && 11643 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 11644 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 11645 arg_mem_size = true; 11646 11647 /* This is the catch all argument type of register types supported by 11648 * check_helper_mem_access. However, we only allow when argument type is 11649 * pointer to scalar, or struct composed (recursively) of scalars. When 11650 * arg_mem_size is true, the pointer can be void *. 11651 */ 11652 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 11653 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 11654 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 11655 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 11656 return -EINVAL; 11657 } 11658 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 11659 } 11660 11661 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 11662 struct bpf_reg_state *reg, 11663 const struct btf_type *ref_t, 11664 const char *ref_tname, u32 ref_id, 11665 struct bpf_kfunc_call_arg_meta *meta, 11666 int argno) 11667 { 11668 const struct btf_type *reg_ref_t; 11669 bool strict_type_match = false; 11670 const struct btf *reg_btf; 11671 const char *reg_ref_tname; 11672 bool taking_projection; 11673 bool struct_same; 11674 u32 reg_ref_id; 11675 11676 if (base_type(reg->type) == PTR_TO_BTF_ID) { 11677 reg_btf = reg->btf; 11678 reg_ref_id = reg->btf_id; 11679 } else { 11680 reg_btf = btf_vmlinux; 11681 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 11682 } 11683 11684 /* Enforce strict type matching for calls to kfuncs that are acquiring 11685 * or releasing a reference, or are no-cast aliases. We do _not_ 11686 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 11687 * as we want to enable BPF programs to pass types that are bitwise 11688 * equivalent without forcing them to explicitly cast with something 11689 * like bpf_cast_to_kern_ctx(). 11690 * 11691 * For example, say we had a type like the following: 11692 * 11693 * struct bpf_cpumask { 11694 * cpumask_t cpumask; 11695 * refcount_t usage; 11696 * }; 11697 * 11698 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 11699 * to a struct cpumask, so it would be safe to pass a struct 11700 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 11701 * 11702 * The philosophy here is similar to how we allow scalars of different 11703 * types to be passed to kfuncs as long as the size is the same. The 11704 * only difference here is that we're simply allowing 11705 * btf_struct_ids_match() to walk the struct at the 0th offset, and 11706 * resolve types. 11707 */ 11708 if ((is_kfunc_release(meta) && reg->ref_obj_id) || 11709 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 11710 strict_type_match = true; 11711 11712 WARN_ON_ONCE(is_kfunc_release(meta) && 11713 (reg->off || !tnum_is_const(reg->var_off) || 11714 reg->var_off.value)); 11715 11716 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 11717 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 11718 struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match); 11719 /* If kfunc is accepting a projection type (ie. __sk_buff), it cannot 11720 * actually use it -- it must cast to the underlying type. So we allow 11721 * caller to pass in the underlying type. 11722 */ 11723 taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname); 11724 if (!taking_projection && !struct_same) { 11725 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 11726 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 11727 btf_type_str(reg_ref_t), reg_ref_tname); 11728 return -EINVAL; 11729 } 11730 return 0; 11731 } 11732 11733 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11734 { 11735 struct btf_record *rec = reg_btf_record(reg); 11736 11737 if (!cur_func(env)->active_locks) { 11738 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 11739 return -EFAULT; 11740 } 11741 11742 if (type_flag(reg->type) & NON_OWN_REF) { 11743 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 11744 return -EFAULT; 11745 } 11746 11747 reg->type |= NON_OWN_REF; 11748 if (rec->refcount_off >= 0) 11749 reg->type |= MEM_RCU; 11750 11751 return 0; 11752 } 11753 11754 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 11755 { 11756 struct bpf_func_state *state, *unused; 11757 struct bpf_reg_state *reg; 11758 int i; 11759 11760 state = cur_func(env); 11761 11762 if (!ref_obj_id) { 11763 verbose(env, "verifier internal error: ref_obj_id is zero for " 11764 "owning -> non-owning conversion\n"); 11765 return -EFAULT; 11766 } 11767 11768 for (i = 0; i < state->acquired_refs; i++) { 11769 if (state->refs[i].id != ref_obj_id) 11770 continue; 11771 11772 /* Clear ref_obj_id here so release_reference doesn't clobber 11773 * the whole reg 11774 */ 11775 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11776 if (reg->ref_obj_id == ref_obj_id) { 11777 reg->ref_obj_id = 0; 11778 ref_set_non_owning(env, reg); 11779 } 11780 })); 11781 return 0; 11782 } 11783 11784 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 11785 return -EFAULT; 11786 } 11787 11788 /* Implementation details: 11789 * 11790 * Each register points to some region of memory, which we define as an 11791 * allocation. Each allocation may embed a bpf_spin_lock which protects any 11792 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 11793 * allocation. The lock and the data it protects are colocated in the same 11794 * memory region. 11795 * 11796 * Hence, everytime a register holds a pointer value pointing to such 11797 * allocation, the verifier preserves a unique reg->id for it. 11798 * 11799 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 11800 * bpf_spin_lock is called. 11801 * 11802 * To enable this, lock state in the verifier captures two values: 11803 * active_lock.ptr = Register's type specific pointer 11804 * active_lock.id = A unique ID for each register pointer value 11805 * 11806 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11807 * supported register types. 11808 * 11809 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11810 * allocated objects is the reg->btf pointer. 11811 * 11812 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11813 * can establish the provenance of the map value statically for each distinct 11814 * lookup into such maps. They always contain a single map value hence unique 11815 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11816 * 11817 * So, in case of global variables, they use array maps with max_entries = 1, 11818 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11819 * into the same map value as max_entries is 1, as described above). 11820 * 11821 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11822 * outer map pointer (in verifier context), but each lookup into an inner map 11823 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11824 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11825 * will get different reg->id assigned to each lookup, hence different 11826 * active_lock.id. 11827 * 11828 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11829 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11830 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11831 */ 11832 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11833 { 11834 struct bpf_reference_state *s; 11835 void *ptr; 11836 u32 id; 11837 11838 switch ((int)reg->type) { 11839 case PTR_TO_MAP_VALUE: 11840 ptr = reg->map_ptr; 11841 break; 11842 case PTR_TO_BTF_ID | MEM_ALLOC: 11843 ptr = reg->btf; 11844 break; 11845 default: 11846 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 11847 return -EFAULT; 11848 } 11849 id = reg->id; 11850 11851 if (!cur_func(env)->active_locks) 11852 return -EINVAL; 11853 s = find_lock_state(env, REF_TYPE_LOCK, id, ptr); 11854 if (!s) { 11855 verbose(env, "held lock and object are not in the same allocation\n"); 11856 return -EINVAL; 11857 } 11858 return 0; 11859 } 11860 11861 static bool is_bpf_list_api_kfunc(u32 btf_id) 11862 { 11863 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11864 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11865 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11866 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 11867 } 11868 11869 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11870 { 11871 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 11872 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11873 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 11874 } 11875 11876 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11877 { 11878 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 11879 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11880 } 11881 11882 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11883 { 11884 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11885 } 11886 11887 static bool is_async_callback_calling_kfunc(u32 btf_id) 11888 { 11889 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl]; 11890 } 11891 11892 static bool is_bpf_throw_kfunc(struct bpf_insn *insn) 11893 { 11894 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 11895 insn->imm == special_kfunc_list[KF_bpf_throw]; 11896 } 11897 11898 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id) 11899 { 11900 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl]; 11901 } 11902 11903 static bool is_callback_calling_kfunc(u32 btf_id) 11904 { 11905 return is_sync_callback_calling_kfunc(btf_id) || 11906 is_async_callback_calling_kfunc(btf_id); 11907 } 11908 11909 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11910 { 11911 return is_bpf_rbtree_api_kfunc(btf_id); 11912 } 11913 11914 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11915 enum btf_field_type head_field_type, 11916 u32 kfunc_btf_id) 11917 { 11918 bool ret; 11919 11920 switch (head_field_type) { 11921 case BPF_LIST_HEAD: 11922 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11923 break; 11924 case BPF_RB_ROOT: 11925 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11926 break; 11927 default: 11928 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11929 btf_field_type_name(head_field_type)); 11930 return false; 11931 } 11932 11933 if (!ret) 11934 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11935 btf_field_type_name(head_field_type)); 11936 return ret; 11937 } 11938 11939 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11940 enum btf_field_type node_field_type, 11941 u32 kfunc_btf_id) 11942 { 11943 bool ret; 11944 11945 switch (node_field_type) { 11946 case BPF_LIST_NODE: 11947 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11948 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 11949 break; 11950 case BPF_RB_NODE: 11951 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11952 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 11953 break; 11954 default: 11955 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11956 btf_field_type_name(node_field_type)); 11957 return false; 11958 } 11959 11960 if (!ret) 11961 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11962 btf_field_type_name(node_field_type)); 11963 return ret; 11964 } 11965 11966 static int 11967 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11968 struct bpf_reg_state *reg, u32 regno, 11969 struct bpf_kfunc_call_arg_meta *meta, 11970 enum btf_field_type head_field_type, 11971 struct btf_field **head_field) 11972 { 11973 const char *head_type_name; 11974 struct btf_field *field; 11975 struct btf_record *rec; 11976 u32 head_off; 11977 11978 if (meta->btf != btf_vmlinux) { 11979 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11980 return -EFAULT; 11981 } 11982 11983 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11984 return -EFAULT; 11985 11986 head_type_name = btf_field_type_name(head_field_type); 11987 if (!tnum_is_const(reg->var_off)) { 11988 verbose(env, 11989 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11990 regno, head_type_name); 11991 return -EINVAL; 11992 } 11993 11994 rec = reg_btf_record(reg); 11995 head_off = reg->off + reg->var_off.value; 11996 field = btf_record_find(rec, head_off, head_field_type); 11997 if (!field) { 11998 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11999 return -EINVAL; 12000 } 12001 12002 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 12003 if (check_reg_allocation_locked(env, reg)) { 12004 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 12005 rec->spin_lock_off, head_type_name); 12006 return -EINVAL; 12007 } 12008 12009 if (*head_field) { 12010 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 12011 return -EFAULT; 12012 } 12013 *head_field = field; 12014 return 0; 12015 } 12016 12017 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 12018 struct bpf_reg_state *reg, u32 regno, 12019 struct bpf_kfunc_call_arg_meta *meta) 12020 { 12021 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 12022 &meta->arg_list_head.field); 12023 } 12024 12025 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 12026 struct bpf_reg_state *reg, u32 regno, 12027 struct bpf_kfunc_call_arg_meta *meta) 12028 { 12029 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 12030 &meta->arg_rbtree_root.field); 12031 } 12032 12033 static int 12034 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 12035 struct bpf_reg_state *reg, u32 regno, 12036 struct bpf_kfunc_call_arg_meta *meta, 12037 enum btf_field_type head_field_type, 12038 enum btf_field_type node_field_type, 12039 struct btf_field **node_field) 12040 { 12041 const char *node_type_name; 12042 const struct btf_type *et, *t; 12043 struct btf_field *field; 12044 u32 node_off; 12045 12046 if (meta->btf != btf_vmlinux) { 12047 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 12048 return -EFAULT; 12049 } 12050 12051 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 12052 return -EFAULT; 12053 12054 node_type_name = btf_field_type_name(node_field_type); 12055 if (!tnum_is_const(reg->var_off)) { 12056 verbose(env, 12057 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 12058 regno, node_type_name); 12059 return -EINVAL; 12060 } 12061 12062 node_off = reg->off + reg->var_off.value; 12063 field = reg_find_field_offset(reg, node_off, node_field_type); 12064 if (!field) { 12065 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 12066 return -EINVAL; 12067 } 12068 12069 field = *node_field; 12070 12071 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 12072 t = btf_type_by_id(reg->btf, reg->btf_id); 12073 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 12074 field->graph_root.value_btf_id, true)) { 12075 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 12076 "in struct %s, but arg is at offset=%d in struct %s\n", 12077 btf_field_type_name(head_field_type), 12078 btf_field_type_name(node_field_type), 12079 field->graph_root.node_offset, 12080 btf_name_by_offset(field->graph_root.btf, et->name_off), 12081 node_off, btf_name_by_offset(reg->btf, t->name_off)); 12082 return -EINVAL; 12083 } 12084 meta->arg_btf = reg->btf; 12085 meta->arg_btf_id = reg->btf_id; 12086 12087 if (node_off != field->graph_root.node_offset) { 12088 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 12089 node_off, btf_field_type_name(node_field_type), 12090 field->graph_root.node_offset, 12091 btf_name_by_offset(field->graph_root.btf, et->name_off)); 12092 return -EINVAL; 12093 } 12094 12095 return 0; 12096 } 12097 12098 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 12099 struct bpf_reg_state *reg, u32 regno, 12100 struct bpf_kfunc_call_arg_meta *meta) 12101 { 12102 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 12103 BPF_LIST_HEAD, BPF_LIST_NODE, 12104 &meta->arg_list_head.field); 12105 } 12106 12107 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 12108 struct bpf_reg_state *reg, u32 regno, 12109 struct bpf_kfunc_call_arg_meta *meta) 12110 { 12111 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 12112 BPF_RB_ROOT, BPF_RB_NODE, 12113 &meta->arg_rbtree_root.field); 12114 } 12115 12116 /* 12117 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 12118 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 12119 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 12120 * them can only be attached to some specific hook points. 12121 */ 12122 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 12123 { 12124 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 12125 12126 switch (prog_type) { 12127 case BPF_PROG_TYPE_LSM: 12128 return true; 12129 case BPF_PROG_TYPE_TRACING: 12130 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 12131 return true; 12132 fallthrough; 12133 default: 12134 return in_sleepable(env); 12135 } 12136 } 12137 12138 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 12139 int insn_idx) 12140 { 12141 const char *func_name = meta->func_name, *ref_tname; 12142 const struct btf *btf = meta->btf; 12143 const struct btf_param *args; 12144 struct btf_record *rec; 12145 u32 i, nargs; 12146 int ret; 12147 12148 args = (const struct btf_param *)(meta->func_proto + 1); 12149 nargs = btf_type_vlen(meta->func_proto); 12150 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 12151 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 12152 MAX_BPF_FUNC_REG_ARGS); 12153 return -EINVAL; 12154 } 12155 12156 /* Check that BTF function arguments match actual types that the 12157 * verifier sees. 12158 */ 12159 for (i = 0; i < nargs; i++) { 12160 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 12161 const struct btf_type *t, *ref_t, *resolve_ret; 12162 enum bpf_arg_type arg_type = ARG_DONTCARE; 12163 u32 regno = i + 1, ref_id, type_size; 12164 bool is_ret_buf_sz = false; 12165 int kf_arg_type; 12166 12167 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 12168 12169 if (is_kfunc_arg_ignore(btf, &args[i])) 12170 continue; 12171 12172 if (btf_type_is_scalar(t)) { 12173 if (reg->type != SCALAR_VALUE) { 12174 verbose(env, "R%d is not a scalar\n", regno); 12175 return -EINVAL; 12176 } 12177 12178 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 12179 if (meta->arg_constant.found) { 12180 verbose(env, "verifier internal error: only one constant argument permitted\n"); 12181 return -EFAULT; 12182 } 12183 if (!tnum_is_const(reg->var_off)) { 12184 verbose(env, "R%d must be a known constant\n", regno); 12185 return -EINVAL; 12186 } 12187 ret = mark_chain_precision(env, regno); 12188 if (ret < 0) 12189 return ret; 12190 meta->arg_constant.found = true; 12191 meta->arg_constant.value = reg->var_off.value; 12192 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 12193 meta->r0_rdonly = true; 12194 is_ret_buf_sz = true; 12195 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 12196 is_ret_buf_sz = true; 12197 } 12198 12199 if (is_ret_buf_sz) { 12200 if (meta->r0_size) { 12201 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 12202 return -EINVAL; 12203 } 12204 12205 if (!tnum_is_const(reg->var_off)) { 12206 verbose(env, "R%d is not a const\n", regno); 12207 return -EINVAL; 12208 } 12209 12210 meta->r0_size = reg->var_off.value; 12211 ret = mark_chain_precision(env, regno); 12212 if (ret) 12213 return ret; 12214 } 12215 continue; 12216 } 12217 12218 if (!btf_type_is_ptr(t)) { 12219 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 12220 return -EINVAL; 12221 } 12222 12223 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 12224 (register_is_null(reg) || type_may_be_null(reg->type)) && 12225 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 12226 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 12227 return -EACCES; 12228 } 12229 12230 if (reg->ref_obj_id) { 12231 if (is_kfunc_release(meta) && meta->ref_obj_id) { 12232 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 12233 regno, reg->ref_obj_id, 12234 meta->ref_obj_id); 12235 return -EFAULT; 12236 } 12237 meta->ref_obj_id = reg->ref_obj_id; 12238 if (is_kfunc_release(meta)) 12239 meta->release_regno = regno; 12240 } 12241 12242 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 12243 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12244 12245 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 12246 if (kf_arg_type < 0) 12247 return kf_arg_type; 12248 12249 switch (kf_arg_type) { 12250 case KF_ARG_PTR_TO_NULL: 12251 continue; 12252 case KF_ARG_PTR_TO_MAP: 12253 if (!reg->map_ptr) { 12254 verbose(env, "pointer in R%d isn't map pointer\n", regno); 12255 return -EINVAL; 12256 } 12257 if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) { 12258 /* Use map_uid (which is unique id of inner map) to reject: 12259 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 12260 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 12261 * if (inner_map1 && inner_map2) { 12262 * wq = bpf_map_lookup_elem(inner_map1); 12263 * if (wq) 12264 * // mismatch would have been allowed 12265 * bpf_wq_init(wq, inner_map2); 12266 * } 12267 * 12268 * Comparing map_ptr is enough to distinguish normal and outer maps. 12269 */ 12270 if (meta->map.ptr != reg->map_ptr || 12271 meta->map.uid != reg->map_uid) { 12272 verbose(env, 12273 "workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 12274 meta->map.uid, reg->map_uid); 12275 return -EINVAL; 12276 } 12277 } 12278 meta->map.ptr = reg->map_ptr; 12279 meta->map.uid = reg->map_uid; 12280 fallthrough; 12281 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 12282 case KF_ARG_PTR_TO_BTF_ID: 12283 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 12284 break; 12285 12286 if (!is_trusted_reg(reg)) { 12287 if (!is_kfunc_rcu(meta)) { 12288 verbose(env, "R%d must be referenced or trusted\n", regno); 12289 return -EINVAL; 12290 } 12291 if (!is_rcu_reg(reg)) { 12292 verbose(env, "R%d must be a rcu pointer\n", regno); 12293 return -EINVAL; 12294 } 12295 } 12296 fallthrough; 12297 case KF_ARG_PTR_TO_CTX: 12298 case KF_ARG_PTR_TO_DYNPTR: 12299 case KF_ARG_PTR_TO_ITER: 12300 case KF_ARG_PTR_TO_LIST_HEAD: 12301 case KF_ARG_PTR_TO_LIST_NODE: 12302 case KF_ARG_PTR_TO_RB_ROOT: 12303 case KF_ARG_PTR_TO_RB_NODE: 12304 case KF_ARG_PTR_TO_MEM: 12305 case KF_ARG_PTR_TO_MEM_SIZE: 12306 case KF_ARG_PTR_TO_CALLBACK: 12307 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12308 case KF_ARG_PTR_TO_CONST_STR: 12309 case KF_ARG_PTR_TO_WORKQUEUE: 12310 break; 12311 default: 12312 WARN_ON_ONCE(1); 12313 return -EFAULT; 12314 } 12315 12316 if (is_kfunc_release(meta) && reg->ref_obj_id) 12317 arg_type |= OBJ_RELEASE; 12318 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 12319 if (ret < 0) 12320 return ret; 12321 12322 switch (kf_arg_type) { 12323 case KF_ARG_PTR_TO_CTX: 12324 if (reg->type != PTR_TO_CTX) { 12325 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", 12326 i, reg_type_str(env, reg->type)); 12327 return -EINVAL; 12328 } 12329 12330 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12331 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 12332 if (ret < 0) 12333 return -EINVAL; 12334 meta->ret_btf_id = ret; 12335 } 12336 break; 12337 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 12338 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 12339 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) { 12340 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i); 12341 return -EINVAL; 12342 } 12343 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 12344 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 12345 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i); 12346 return -EINVAL; 12347 } 12348 } else { 12349 verbose(env, "arg#%d expected pointer to allocated object\n", i); 12350 return -EINVAL; 12351 } 12352 if (!reg->ref_obj_id) { 12353 verbose(env, "allocated object must be referenced\n"); 12354 return -EINVAL; 12355 } 12356 if (meta->btf == btf_vmlinux) { 12357 meta->arg_btf = reg->btf; 12358 meta->arg_btf_id = reg->btf_id; 12359 } 12360 break; 12361 case KF_ARG_PTR_TO_DYNPTR: 12362 { 12363 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 12364 int clone_ref_obj_id = 0; 12365 12366 if (reg->type == CONST_PTR_TO_DYNPTR) 12367 dynptr_arg_type |= MEM_RDONLY; 12368 12369 if (is_kfunc_arg_uninit(btf, &args[i])) 12370 dynptr_arg_type |= MEM_UNINIT; 12371 12372 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 12373 dynptr_arg_type |= DYNPTR_TYPE_SKB; 12374 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 12375 dynptr_arg_type |= DYNPTR_TYPE_XDP; 12376 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 12377 (dynptr_arg_type & MEM_UNINIT)) { 12378 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 12379 12380 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 12381 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 12382 return -EFAULT; 12383 } 12384 12385 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 12386 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 12387 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 12388 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 12389 return -EFAULT; 12390 } 12391 } 12392 12393 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 12394 if (ret < 0) 12395 return ret; 12396 12397 if (!(dynptr_arg_type & MEM_UNINIT)) { 12398 int id = dynptr_id(env, reg); 12399 12400 if (id < 0) { 12401 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 12402 return id; 12403 } 12404 meta->initialized_dynptr.id = id; 12405 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 12406 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 12407 } 12408 12409 break; 12410 } 12411 case KF_ARG_PTR_TO_ITER: 12412 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 12413 if (!check_css_task_iter_allowlist(env)) { 12414 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 12415 return -EINVAL; 12416 } 12417 } 12418 ret = process_iter_arg(env, regno, insn_idx, meta); 12419 if (ret < 0) 12420 return ret; 12421 break; 12422 case KF_ARG_PTR_TO_LIST_HEAD: 12423 if (reg->type != PTR_TO_MAP_VALUE && 12424 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12425 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 12426 return -EINVAL; 12427 } 12428 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 12429 verbose(env, "allocated object must be referenced\n"); 12430 return -EINVAL; 12431 } 12432 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 12433 if (ret < 0) 12434 return ret; 12435 break; 12436 case KF_ARG_PTR_TO_RB_ROOT: 12437 if (reg->type != PTR_TO_MAP_VALUE && 12438 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12439 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 12440 return -EINVAL; 12441 } 12442 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 12443 verbose(env, "allocated object must be referenced\n"); 12444 return -EINVAL; 12445 } 12446 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 12447 if (ret < 0) 12448 return ret; 12449 break; 12450 case KF_ARG_PTR_TO_LIST_NODE: 12451 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12452 verbose(env, "arg#%d expected pointer to allocated object\n", i); 12453 return -EINVAL; 12454 } 12455 if (!reg->ref_obj_id) { 12456 verbose(env, "allocated object must be referenced\n"); 12457 return -EINVAL; 12458 } 12459 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 12460 if (ret < 0) 12461 return ret; 12462 break; 12463 case KF_ARG_PTR_TO_RB_NODE: 12464 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 12465 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 12466 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 12467 return -EINVAL; 12468 } 12469 if (in_rbtree_lock_required_cb(env)) { 12470 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 12471 return -EINVAL; 12472 } 12473 } else { 12474 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12475 verbose(env, "arg#%d expected pointer to allocated object\n", i); 12476 return -EINVAL; 12477 } 12478 if (!reg->ref_obj_id) { 12479 verbose(env, "allocated object must be referenced\n"); 12480 return -EINVAL; 12481 } 12482 } 12483 12484 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 12485 if (ret < 0) 12486 return ret; 12487 break; 12488 case KF_ARG_PTR_TO_MAP: 12489 /* If argument has '__map' suffix expect 'struct bpf_map *' */ 12490 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP]; 12491 ref_t = btf_type_by_id(btf_vmlinux, ref_id); 12492 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12493 fallthrough; 12494 case KF_ARG_PTR_TO_BTF_ID: 12495 /* Only base_type is checked, further checks are done here */ 12496 if ((base_type(reg->type) != PTR_TO_BTF_ID || 12497 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 12498 !reg2btf_ids[base_type(reg->type)]) { 12499 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 12500 verbose(env, "expected %s or socket\n", 12501 reg_type_str(env, base_type(reg->type) | 12502 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 12503 return -EINVAL; 12504 } 12505 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 12506 if (ret < 0) 12507 return ret; 12508 break; 12509 case KF_ARG_PTR_TO_MEM: 12510 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 12511 if (IS_ERR(resolve_ret)) { 12512 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 12513 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 12514 return -EINVAL; 12515 } 12516 ret = check_mem_reg(env, reg, regno, type_size); 12517 if (ret < 0) 12518 return ret; 12519 break; 12520 case KF_ARG_PTR_TO_MEM_SIZE: 12521 { 12522 struct bpf_reg_state *buff_reg = ®s[regno]; 12523 const struct btf_param *buff_arg = &args[i]; 12524 struct bpf_reg_state *size_reg = ®s[regno + 1]; 12525 const struct btf_param *size_arg = &args[i + 1]; 12526 12527 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 12528 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 12529 if (ret < 0) { 12530 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 12531 return ret; 12532 } 12533 } 12534 12535 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 12536 if (meta->arg_constant.found) { 12537 verbose(env, "verifier internal error: only one constant argument permitted\n"); 12538 return -EFAULT; 12539 } 12540 if (!tnum_is_const(size_reg->var_off)) { 12541 verbose(env, "R%d must be a known constant\n", regno + 1); 12542 return -EINVAL; 12543 } 12544 meta->arg_constant.found = true; 12545 meta->arg_constant.value = size_reg->var_off.value; 12546 } 12547 12548 /* Skip next '__sz' or '__szk' argument */ 12549 i++; 12550 break; 12551 } 12552 case KF_ARG_PTR_TO_CALLBACK: 12553 if (reg->type != PTR_TO_FUNC) { 12554 verbose(env, "arg%d expected pointer to func\n", i); 12555 return -EINVAL; 12556 } 12557 meta->subprogno = reg->subprogno; 12558 break; 12559 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12560 if (!type_is_ptr_alloc_obj(reg->type)) { 12561 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 12562 return -EINVAL; 12563 } 12564 if (!type_is_non_owning_ref(reg->type)) 12565 meta->arg_owning_ref = true; 12566 12567 rec = reg_btf_record(reg); 12568 if (!rec) { 12569 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 12570 return -EFAULT; 12571 } 12572 12573 if (rec->refcount_off < 0) { 12574 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 12575 return -EINVAL; 12576 } 12577 12578 meta->arg_btf = reg->btf; 12579 meta->arg_btf_id = reg->btf_id; 12580 break; 12581 case KF_ARG_PTR_TO_CONST_STR: 12582 if (reg->type != PTR_TO_MAP_VALUE) { 12583 verbose(env, "arg#%d doesn't point to a const string\n", i); 12584 return -EINVAL; 12585 } 12586 ret = check_reg_const_str(env, reg, regno); 12587 if (ret) 12588 return ret; 12589 break; 12590 case KF_ARG_PTR_TO_WORKQUEUE: 12591 if (reg->type != PTR_TO_MAP_VALUE) { 12592 verbose(env, "arg#%d doesn't point to a map value\n", i); 12593 return -EINVAL; 12594 } 12595 ret = process_wq_func(env, regno, meta); 12596 if (ret < 0) 12597 return ret; 12598 break; 12599 } 12600 } 12601 12602 if (is_kfunc_release(meta) && !meta->release_regno) { 12603 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 12604 func_name); 12605 return -EINVAL; 12606 } 12607 12608 return 0; 12609 } 12610 12611 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 12612 struct bpf_insn *insn, 12613 struct bpf_kfunc_call_arg_meta *meta, 12614 const char **kfunc_name) 12615 { 12616 const struct btf_type *func, *func_proto; 12617 u32 func_id, *kfunc_flags; 12618 const char *func_name; 12619 struct btf *desc_btf; 12620 12621 if (kfunc_name) 12622 *kfunc_name = NULL; 12623 12624 if (!insn->imm) 12625 return -EINVAL; 12626 12627 desc_btf = find_kfunc_desc_btf(env, insn->off); 12628 if (IS_ERR(desc_btf)) 12629 return PTR_ERR(desc_btf); 12630 12631 func_id = insn->imm; 12632 func = btf_type_by_id(desc_btf, func_id); 12633 func_name = btf_name_by_offset(desc_btf, func->name_off); 12634 if (kfunc_name) 12635 *kfunc_name = func_name; 12636 func_proto = btf_type_by_id(desc_btf, func->type); 12637 12638 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 12639 if (!kfunc_flags) { 12640 return -EACCES; 12641 } 12642 12643 memset(meta, 0, sizeof(*meta)); 12644 meta->btf = desc_btf; 12645 meta->func_id = func_id; 12646 meta->kfunc_flags = *kfunc_flags; 12647 meta->func_proto = func_proto; 12648 meta->func_name = func_name; 12649 12650 return 0; 12651 } 12652 12653 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 12654 12655 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 12656 int *insn_idx_p) 12657 { 12658 bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable; 12659 u32 i, nargs, ptr_type_id, release_ref_obj_id; 12660 struct bpf_reg_state *regs = cur_regs(env); 12661 const char *func_name, *ptr_type_name; 12662 const struct btf_type *t, *ptr_type; 12663 struct bpf_kfunc_call_arg_meta meta; 12664 struct bpf_insn_aux_data *insn_aux; 12665 int err, insn_idx = *insn_idx_p; 12666 const struct btf_param *args; 12667 const struct btf_type *ret_t; 12668 struct btf *desc_btf; 12669 12670 /* skip for now, but return error when we find this in fixup_kfunc_call */ 12671 if (!insn->imm) 12672 return 0; 12673 12674 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 12675 if (err == -EACCES && func_name) 12676 verbose(env, "calling kernel function %s is not allowed\n", func_name); 12677 if (err) 12678 return err; 12679 desc_btf = meta.btf; 12680 insn_aux = &env->insn_aux_data[insn_idx]; 12681 12682 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 12683 12684 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 12685 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 12686 return -EACCES; 12687 } 12688 12689 sleepable = is_kfunc_sleepable(&meta); 12690 if (sleepable && !in_sleepable(env)) { 12691 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 12692 return -EACCES; 12693 } 12694 12695 /* Check the arguments */ 12696 err = check_kfunc_args(env, &meta, insn_idx); 12697 if (err < 0) 12698 return err; 12699 12700 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12701 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12702 set_rbtree_add_callback_state); 12703 if (err) { 12704 verbose(env, "kfunc %s#%d failed callback verification\n", 12705 func_name, meta.func_id); 12706 return err; 12707 } 12708 } 12709 12710 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) { 12711 meta.r0_size = sizeof(u64); 12712 meta.r0_rdonly = false; 12713 } 12714 12715 if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) { 12716 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12717 set_timer_callback_state); 12718 if (err) { 12719 verbose(env, "kfunc %s#%d failed callback verification\n", 12720 func_name, meta.func_id); 12721 return err; 12722 } 12723 } 12724 12725 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 12726 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 12727 12728 preempt_disable = is_kfunc_bpf_preempt_disable(&meta); 12729 preempt_enable = is_kfunc_bpf_preempt_enable(&meta); 12730 12731 if (env->cur_state->active_rcu_lock) { 12732 struct bpf_func_state *state; 12733 struct bpf_reg_state *reg; 12734 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 12735 12736 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 12737 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 12738 return -EACCES; 12739 } 12740 12741 if (rcu_lock) { 12742 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 12743 return -EINVAL; 12744 } else if (rcu_unlock) { 12745 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({ 12746 if (reg->type & MEM_RCU) { 12747 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 12748 reg->type |= PTR_UNTRUSTED; 12749 } 12750 })); 12751 env->cur_state->active_rcu_lock = false; 12752 } else if (sleepable) { 12753 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 12754 return -EACCES; 12755 } 12756 } else if (rcu_lock) { 12757 env->cur_state->active_rcu_lock = true; 12758 } else if (rcu_unlock) { 12759 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 12760 return -EINVAL; 12761 } 12762 12763 if (env->cur_state->active_preempt_lock) { 12764 if (preempt_disable) { 12765 env->cur_state->active_preempt_lock++; 12766 } else if (preempt_enable) { 12767 env->cur_state->active_preempt_lock--; 12768 } else if (sleepable) { 12769 verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name); 12770 return -EACCES; 12771 } 12772 } else if (preempt_disable) { 12773 env->cur_state->active_preempt_lock++; 12774 } else if (preempt_enable) { 12775 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name); 12776 return -EINVAL; 12777 } 12778 12779 /* In case of release function, we get register number of refcounted 12780 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 12781 */ 12782 if (meta.release_regno) { 12783 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 12784 if (err) { 12785 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12786 func_name, meta.func_id); 12787 return err; 12788 } 12789 } 12790 12791 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 12792 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 12793 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12794 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 12795 insn_aux->insert_off = regs[BPF_REG_2].off; 12796 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 12797 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 12798 if (err) { 12799 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 12800 func_name, meta.func_id); 12801 return err; 12802 } 12803 12804 err = release_reference(env, release_ref_obj_id); 12805 if (err) { 12806 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12807 func_name, meta.func_id); 12808 return err; 12809 } 12810 } 12811 12812 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 12813 if (!bpf_jit_supports_exceptions()) { 12814 verbose(env, "JIT does not support calling kfunc %s#%d\n", 12815 func_name, meta.func_id); 12816 return -ENOTSUPP; 12817 } 12818 env->seen_exception = true; 12819 12820 /* In the case of the default callback, the cookie value passed 12821 * to bpf_throw becomes the return value of the program. 12822 */ 12823 if (!env->exception_callback_subprog) { 12824 err = check_return_code(env, BPF_REG_1, "R1"); 12825 if (err < 0) 12826 return err; 12827 } 12828 } 12829 12830 for (i = 0; i < CALLER_SAVED_REGS; i++) 12831 mark_reg_not_init(env, regs, caller_saved[i]); 12832 12833 /* Check return type */ 12834 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 12835 12836 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 12837 /* Only exception is bpf_obj_new_impl */ 12838 if (meta.btf != btf_vmlinux || 12839 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 12840 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] && 12841 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 12842 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 12843 return -EINVAL; 12844 } 12845 } 12846 12847 if (btf_type_is_scalar(t)) { 12848 mark_reg_unknown(env, regs, BPF_REG_0); 12849 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 12850 } else if (btf_type_is_ptr(t)) { 12851 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 12852 12853 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12854 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 12855 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12856 struct btf_struct_meta *struct_meta; 12857 struct btf *ret_btf; 12858 u32 ret_btf_id; 12859 12860 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set) 12861 return -ENOMEM; 12862 12863 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 12864 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 12865 return -EINVAL; 12866 } 12867 12868 ret_btf = env->prog->aux->btf; 12869 ret_btf_id = meta.arg_constant.value; 12870 12871 /* This may be NULL due to user not supplying a BTF */ 12872 if (!ret_btf) { 12873 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 12874 return -EINVAL; 12875 } 12876 12877 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 12878 if (!ret_t || !__btf_type_is_struct(ret_t)) { 12879 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 12880 return -EINVAL; 12881 } 12882 12883 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12884 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 12885 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 12886 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 12887 return -EINVAL; 12888 } 12889 12890 if (!bpf_global_percpu_ma_set) { 12891 mutex_lock(&bpf_percpu_ma_lock); 12892 if (!bpf_global_percpu_ma_set) { 12893 /* Charge memory allocated with bpf_global_percpu_ma to 12894 * root memcg. The obj_cgroup for root memcg is NULL. 12895 */ 12896 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 12897 if (!err) 12898 bpf_global_percpu_ma_set = true; 12899 } 12900 mutex_unlock(&bpf_percpu_ma_lock); 12901 if (err) 12902 return err; 12903 } 12904 12905 mutex_lock(&bpf_percpu_ma_lock); 12906 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 12907 mutex_unlock(&bpf_percpu_ma_lock); 12908 if (err) 12909 return err; 12910 } 12911 12912 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 12913 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12914 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 12915 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 12916 return -EINVAL; 12917 } 12918 12919 if (struct_meta) { 12920 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 12921 return -EINVAL; 12922 } 12923 } 12924 12925 mark_reg_known_zero(env, regs, BPF_REG_0); 12926 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12927 regs[BPF_REG_0].btf = ret_btf; 12928 regs[BPF_REG_0].btf_id = ret_btf_id; 12929 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) 12930 regs[BPF_REG_0].type |= MEM_PERCPU; 12931 12932 insn_aux->obj_new_size = ret_t->size; 12933 insn_aux->kptr_struct_meta = struct_meta; 12934 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 12935 mark_reg_known_zero(env, regs, BPF_REG_0); 12936 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12937 regs[BPF_REG_0].btf = meta.arg_btf; 12938 regs[BPF_REG_0].btf_id = meta.arg_btf_id; 12939 12940 insn_aux->kptr_struct_meta = 12941 btf_find_struct_meta(meta.arg_btf, 12942 meta.arg_btf_id); 12943 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 12944 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 12945 struct btf_field *field = meta.arg_list_head.field; 12946 12947 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12948 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12949 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12950 struct btf_field *field = meta.arg_rbtree_root.field; 12951 12952 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12953 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12954 mark_reg_known_zero(env, regs, BPF_REG_0); 12955 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 12956 regs[BPF_REG_0].btf = desc_btf; 12957 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 12958 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 12959 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 12960 if (!ret_t || !btf_type_is_struct(ret_t)) { 12961 verbose(env, 12962 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 12963 return -EINVAL; 12964 } 12965 12966 mark_reg_known_zero(env, regs, BPF_REG_0); 12967 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 12968 regs[BPF_REG_0].btf = desc_btf; 12969 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 12970 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 12971 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 12972 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 12973 12974 mark_reg_known_zero(env, regs, BPF_REG_0); 12975 12976 if (!meta.arg_constant.found) { 12977 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 12978 return -EFAULT; 12979 } 12980 12981 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 12982 12983 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 12984 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 12985 12986 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 12987 regs[BPF_REG_0].type |= MEM_RDONLY; 12988 } else { 12989 /* this will set env->seen_direct_write to true */ 12990 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 12991 verbose(env, "the prog does not allow writes to packet data\n"); 12992 return -EINVAL; 12993 } 12994 } 12995 12996 if (!meta.initialized_dynptr.id) { 12997 verbose(env, "verifier internal error: no dynptr id\n"); 12998 return -EFAULT; 12999 } 13000 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 13001 13002 /* we don't need to set BPF_REG_0's ref obj id 13003 * because packet slices are not refcounted (see 13004 * dynptr_type_refcounted) 13005 */ 13006 } else { 13007 verbose(env, "kernel function %s unhandled dynamic return type\n", 13008 meta.func_name); 13009 return -EFAULT; 13010 } 13011 } else if (btf_type_is_void(ptr_type)) { 13012 /* kfunc returning 'void *' is equivalent to returning scalar */ 13013 mark_reg_unknown(env, regs, BPF_REG_0); 13014 } else if (!__btf_type_is_struct(ptr_type)) { 13015 if (!meta.r0_size) { 13016 __u32 sz; 13017 13018 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 13019 meta.r0_size = sz; 13020 meta.r0_rdonly = true; 13021 } 13022 } 13023 if (!meta.r0_size) { 13024 ptr_type_name = btf_name_by_offset(desc_btf, 13025 ptr_type->name_off); 13026 verbose(env, 13027 "kernel function %s returns pointer type %s %s is not supported\n", 13028 func_name, 13029 btf_type_str(ptr_type), 13030 ptr_type_name); 13031 return -EINVAL; 13032 } 13033 13034 mark_reg_known_zero(env, regs, BPF_REG_0); 13035 regs[BPF_REG_0].type = PTR_TO_MEM; 13036 regs[BPF_REG_0].mem_size = meta.r0_size; 13037 13038 if (meta.r0_rdonly) 13039 regs[BPF_REG_0].type |= MEM_RDONLY; 13040 13041 /* Ensures we don't access the memory after a release_reference() */ 13042 if (meta.ref_obj_id) 13043 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 13044 } else { 13045 mark_reg_known_zero(env, regs, BPF_REG_0); 13046 regs[BPF_REG_0].btf = desc_btf; 13047 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 13048 regs[BPF_REG_0].btf_id = ptr_type_id; 13049 13050 if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache]) 13051 regs[BPF_REG_0].type |= PTR_UNTRUSTED; 13052 13053 if (is_iter_next_kfunc(&meta)) { 13054 struct bpf_reg_state *cur_iter; 13055 13056 cur_iter = get_iter_from_state(env->cur_state, &meta); 13057 13058 if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */ 13059 regs[BPF_REG_0].type |= MEM_RCU; 13060 else 13061 regs[BPF_REG_0].type |= PTR_TRUSTED; 13062 } 13063 } 13064 13065 if (is_kfunc_ret_null(&meta)) { 13066 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 13067 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 13068 regs[BPF_REG_0].id = ++env->id_gen; 13069 } 13070 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 13071 if (is_kfunc_acquire(&meta)) { 13072 int id = acquire_reference_state(env, insn_idx); 13073 13074 if (id < 0) 13075 return id; 13076 if (is_kfunc_ret_null(&meta)) 13077 regs[BPF_REG_0].id = id; 13078 regs[BPF_REG_0].ref_obj_id = id; 13079 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 13080 ref_set_non_owning(env, ®s[BPF_REG_0]); 13081 } 13082 13083 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 13084 regs[BPF_REG_0].id = ++env->id_gen; 13085 } else if (btf_type_is_void(t)) { 13086 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 13087 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 13088 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 13089 insn_aux->kptr_struct_meta = 13090 btf_find_struct_meta(meta.arg_btf, 13091 meta.arg_btf_id); 13092 } 13093 } 13094 } 13095 13096 nargs = btf_type_vlen(meta.func_proto); 13097 args = (const struct btf_param *)(meta.func_proto + 1); 13098 for (i = 0; i < nargs; i++) { 13099 u32 regno = i + 1; 13100 13101 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 13102 if (btf_type_is_ptr(t)) 13103 mark_btf_func_reg_size(env, regno, sizeof(void *)); 13104 else 13105 /* scalar. ensured by btf_check_kfunc_arg_match() */ 13106 mark_btf_func_reg_size(env, regno, t->size); 13107 } 13108 13109 if (is_iter_next_kfunc(&meta)) { 13110 err = process_iter_next_call(env, insn_idx, &meta); 13111 if (err) 13112 return err; 13113 } 13114 13115 return 0; 13116 } 13117 13118 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 13119 const struct bpf_reg_state *reg, 13120 enum bpf_reg_type type) 13121 { 13122 bool known = tnum_is_const(reg->var_off); 13123 s64 val = reg->var_off.value; 13124 s64 smin = reg->smin_value; 13125 13126 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 13127 verbose(env, "math between %s pointer and %lld is not allowed\n", 13128 reg_type_str(env, type), val); 13129 return false; 13130 } 13131 13132 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 13133 verbose(env, "%s pointer offset %d is not allowed\n", 13134 reg_type_str(env, type), reg->off); 13135 return false; 13136 } 13137 13138 if (smin == S64_MIN) { 13139 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 13140 reg_type_str(env, type)); 13141 return false; 13142 } 13143 13144 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 13145 verbose(env, "value %lld makes %s pointer be out of bounds\n", 13146 smin, reg_type_str(env, type)); 13147 return false; 13148 } 13149 13150 return true; 13151 } 13152 13153 enum { 13154 REASON_BOUNDS = -1, 13155 REASON_TYPE = -2, 13156 REASON_PATHS = -3, 13157 REASON_LIMIT = -4, 13158 REASON_STACK = -5, 13159 }; 13160 13161 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 13162 u32 *alu_limit, bool mask_to_left) 13163 { 13164 u32 max = 0, ptr_limit = 0; 13165 13166 switch (ptr_reg->type) { 13167 case PTR_TO_STACK: 13168 /* Offset 0 is out-of-bounds, but acceptable start for the 13169 * left direction, see BPF_REG_FP. Also, unknown scalar 13170 * offset where we would need to deal with min/max bounds is 13171 * currently prohibited for unprivileged. 13172 */ 13173 max = MAX_BPF_STACK + mask_to_left; 13174 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 13175 break; 13176 case PTR_TO_MAP_VALUE: 13177 max = ptr_reg->map_ptr->value_size; 13178 ptr_limit = (mask_to_left ? 13179 ptr_reg->smin_value : 13180 ptr_reg->umax_value) + ptr_reg->off; 13181 break; 13182 default: 13183 return REASON_TYPE; 13184 } 13185 13186 if (ptr_limit >= max) 13187 return REASON_LIMIT; 13188 *alu_limit = ptr_limit; 13189 return 0; 13190 } 13191 13192 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 13193 const struct bpf_insn *insn) 13194 { 13195 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 13196 } 13197 13198 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 13199 u32 alu_state, u32 alu_limit) 13200 { 13201 /* If we arrived here from different branches with different 13202 * state or limits to sanitize, then this won't work. 13203 */ 13204 if (aux->alu_state && 13205 (aux->alu_state != alu_state || 13206 aux->alu_limit != alu_limit)) 13207 return REASON_PATHS; 13208 13209 /* Corresponding fixup done in do_misc_fixups(). */ 13210 aux->alu_state = alu_state; 13211 aux->alu_limit = alu_limit; 13212 return 0; 13213 } 13214 13215 static int sanitize_val_alu(struct bpf_verifier_env *env, 13216 struct bpf_insn *insn) 13217 { 13218 struct bpf_insn_aux_data *aux = cur_aux(env); 13219 13220 if (can_skip_alu_sanitation(env, insn)) 13221 return 0; 13222 13223 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 13224 } 13225 13226 static bool sanitize_needed(u8 opcode) 13227 { 13228 return opcode == BPF_ADD || opcode == BPF_SUB; 13229 } 13230 13231 struct bpf_sanitize_info { 13232 struct bpf_insn_aux_data aux; 13233 bool mask_to_left; 13234 }; 13235 13236 static struct bpf_verifier_state * 13237 sanitize_speculative_path(struct bpf_verifier_env *env, 13238 const struct bpf_insn *insn, 13239 u32 next_idx, u32 curr_idx) 13240 { 13241 struct bpf_verifier_state *branch; 13242 struct bpf_reg_state *regs; 13243 13244 branch = push_stack(env, next_idx, curr_idx, true); 13245 if (branch && insn) { 13246 regs = branch->frame[branch->curframe]->regs; 13247 if (BPF_SRC(insn->code) == BPF_K) { 13248 mark_reg_unknown(env, regs, insn->dst_reg); 13249 } else if (BPF_SRC(insn->code) == BPF_X) { 13250 mark_reg_unknown(env, regs, insn->dst_reg); 13251 mark_reg_unknown(env, regs, insn->src_reg); 13252 } 13253 } 13254 return branch; 13255 } 13256 13257 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 13258 struct bpf_insn *insn, 13259 const struct bpf_reg_state *ptr_reg, 13260 const struct bpf_reg_state *off_reg, 13261 struct bpf_reg_state *dst_reg, 13262 struct bpf_sanitize_info *info, 13263 const bool commit_window) 13264 { 13265 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 13266 struct bpf_verifier_state *vstate = env->cur_state; 13267 bool off_is_imm = tnum_is_const(off_reg->var_off); 13268 bool off_is_neg = off_reg->smin_value < 0; 13269 bool ptr_is_dst_reg = ptr_reg == dst_reg; 13270 u8 opcode = BPF_OP(insn->code); 13271 u32 alu_state, alu_limit; 13272 struct bpf_reg_state tmp; 13273 bool ret; 13274 int err; 13275 13276 if (can_skip_alu_sanitation(env, insn)) 13277 return 0; 13278 13279 /* We already marked aux for masking from non-speculative 13280 * paths, thus we got here in the first place. We only care 13281 * to explore bad access from here. 13282 */ 13283 if (vstate->speculative) 13284 goto do_sim; 13285 13286 if (!commit_window) { 13287 if (!tnum_is_const(off_reg->var_off) && 13288 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 13289 return REASON_BOUNDS; 13290 13291 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 13292 (opcode == BPF_SUB && !off_is_neg); 13293 } 13294 13295 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 13296 if (err < 0) 13297 return err; 13298 13299 if (commit_window) { 13300 /* In commit phase we narrow the masking window based on 13301 * the observed pointer move after the simulated operation. 13302 */ 13303 alu_state = info->aux.alu_state; 13304 alu_limit = abs(info->aux.alu_limit - alu_limit); 13305 } else { 13306 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 13307 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 13308 alu_state |= ptr_is_dst_reg ? 13309 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 13310 13311 /* Limit pruning on unknown scalars to enable deep search for 13312 * potential masking differences from other program paths. 13313 */ 13314 if (!off_is_imm) 13315 env->explore_alu_limits = true; 13316 } 13317 13318 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 13319 if (err < 0) 13320 return err; 13321 do_sim: 13322 /* If we're in commit phase, we're done here given we already 13323 * pushed the truncated dst_reg into the speculative verification 13324 * stack. 13325 * 13326 * Also, when register is a known constant, we rewrite register-based 13327 * operation to immediate-based, and thus do not need masking (and as 13328 * a consequence, do not need to simulate the zero-truncation either). 13329 */ 13330 if (commit_window || off_is_imm) 13331 return 0; 13332 13333 /* Simulate and find potential out-of-bounds access under 13334 * speculative execution from truncation as a result of 13335 * masking when off was not within expected range. If off 13336 * sits in dst, then we temporarily need to move ptr there 13337 * to simulate dst (== 0) +/-= ptr. Needed, for example, 13338 * for cases where we use K-based arithmetic in one direction 13339 * and truncated reg-based in the other in order to explore 13340 * bad access. 13341 */ 13342 if (!ptr_is_dst_reg) { 13343 tmp = *dst_reg; 13344 copy_register_state(dst_reg, ptr_reg); 13345 } 13346 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 13347 env->insn_idx); 13348 if (!ptr_is_dst_reg && ret) 13349 *dst_reg = tmp; 13350 return !ret ? REASON_STACK : 0; 13351 } 13352 13353 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 13354 { 13355 struct bpf_verifier_state *vstate = env->cur_state; 13356 13357 /* If we simulate paths under speculation, we don't update the 13358 * insn as 'seen' such that when we verify unreachable paths in 13359 * the non-speculative domain, sanitize_dead_code() can still 13360 * rewrite/sanitize them. 13361 */ 13362 if (!vstate->speculative) 13363 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 13364 } 13365 13366 static int sanitize_err(struct bpf_verifier_env *env, 13367 const struct bpf_insn *insn, int reason, 13368 const struct bpf_reg_state *off_reg, 13369 const struct bpf_reg_state *dst_reg) 13370 { 13371 static const char *err = "pointer arithmetic with it prohibited for !root"; 13372 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 13373 u32 dst = insn->dst_reg, src = insn->src_reg; 13374 13375 switch (reason) { 13376 case REASON_BOUNDS: 13377 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 13378 off_reg == dst_reg ? dst : src, err); 13379 break; 13380 case REASON_TYPE: 13381 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 13382 off_reg == dst_reg ? src : dst, err); 13383 break; 13384 case REASON_PATHS: 13385 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 13386 dst, op, err); 13387 break; 13388 case REASON_LIMIT: 13389 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 13390 dst, op, err); 13391 break; 13392 case REASON_STACK: 13393 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 13394 dst, err); 13395 break; 13396 default: 13397 verbose(env, "verifier internal error: unknown reason (%d)\n", 13398 reason); 13399 break; 13400 } 13401 13402 return -EACCES; 13403 } 13404 13405 /* check that stack access falls within stack limits and that 'reg' doesn't 13406 * have a variable offset. 13407 * 13408 * Variable offset is prohibited for unprivileged mode for simplicity since it 13409 * requires corresponding support in Spectre masking for stack ALU. See also 13410 * retrieve_ptr_limit(). 13411 * 13412 * 13413 * 'off' includes 'reg->off'. 13414 */ 13415 static int check_stack_access_for_ptr_arithmetic( 13416 struct bpf_verifier_env *env, 13417 int regno, 13418 const struct bpf_reg_state *reg, 13419 int off) 13420 { 13421 if (!tnum_is_const(reg->var_off)) { 13422 char tn_buf[48]; 13423 13424 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 13425 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 13426 regno, tn_buf, off); 13427 return -EACCES; 13428 } 13429 13430 if (off >= 0 || off < -MAX_BPF_STACK) { 13431 verbose(env, "R%d stack pointer arithmetic goes out of range, " 13432 "prohibited for !root; off=%d\n", regno, off); 13433 return -EACCES; 13434 } 13435 13436 return 0; 13437 } 13438 13439 static int sanitize_check_bounds(struct bpf_verifier_env *env, 13440 const struct bpf_insn *insn, 13441 const struct bpf_reg_state *dst_reg) 13442 { 13443 u32 dst = insn->dst_reg; 13444 13445 /* For unprivileged we require that resulting offset must be in bounds 13446 * in order to be able to sanitize access later on. 13447 */ 13448 if (env->bypass_spec_v1) 13449 return 0; 13450 13451 switch (dst_reg->type) { 13452 case PTR_TO_STACK: 13453 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 13454 dst_reg->off + dst_reg->var_off.value)) 13455 return -EACCES; 13456 break; 13457 case PTR_TO_MAP_VALUE: 13458 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 13459 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 13460 "prohibited for !root\n", dst); 13461 return -EACCES; 13462 } 13463 break; 13464 default: 13465 break; 13466 } 13467 13468 return 0; 13469 } 13470 13471 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 13472 * Caller should also handle BPF_MOV case separately. 13473 * If we return -EACCES, caller may want to try again treating pointer as a 13474 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 13475 */ 13476 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 13477 struct bpf_insn *insn, 13478 const struct bpf_reg_state *ptr_reg, 13479 const struct bpf_reg_state *off_reg) 13480 { 13481 struct bpf_verifier_state *vstate = env->cur_state; 13482 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13483 struct bpf_reg_state *regs = state->regs, *dst_reg; 13484 bool known = tnum_is_const(off_reg->var_off); 13485 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 13486 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 13487 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 13488 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 13489 struct bpf_sanitize_info info = {}; 13490 u8 opcode = BPF_OP(insn->code); 13491 u32 dst = insn->dst_reg; 13492 int ret; 13493 13494 dst_reg = ®s[dst]; 13495 13496 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 13497 smin_val > smax_val || umin_val > umax_val) { 13498 /* Taint dst register if offset had invalid bounds derived from 13499 * e.g. dead branches. 13500 */ 13501 __mark_reg_unknown(env, dst_reg); 13502 return 0; 13503 } 13504 13505 if (BPF_CLASS(insn->code) != BPF_ALU64) { 13506 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 13507 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13508 __mark_reg_unknown(env, dst_reg); 13509 return 0; 13510 } 13511 13512 verbose(env, 13513 "R%d 32-bit pointer arithmetic prohibited\n", 13514 dst); 13515 return -EACCES; 13516 } 13517 13518 if (ptr_reg->type & PTR_MAYBE_NULL) { 13519 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 13520 dst, reg_type_str(env, ptr_reg->type)); 13521 return -EACCES; 13522 } 13523 13524 switch (base_type(ptr_reg->type)) { 13525 case PTR_TO_CTX: 13526 case PTR_TO_MAP_VALUE: 13527 case PTR_TO_MAP_KEY: 13528 case PTR_TO_STACK: 13529 case PTR_TO_PACKET_META: 13530 case PTR_TO_PACKET: 13531 case PTR_TO_TP_BUFFER: 13532 case PTR_TO_BTF_ID: 13533 case PTR_TO_MEM: 13534 case PTR_TO_BUF: 13535 case PTR_TO_FUNC: 13536 case CONST_PTR_TO_DYNPTR: 13537 break; 13538 case PTR_TO_FLOW_KEYS: 13539 if (known) 13540 break; 13541 fallthrough; 13542 case CONST_PTR_TO_MAP: 13543 /* smin_val represents the known value */ 13544 if (known && smin_val == 0 && opcode == BPF_ADD) 13545 break; 13546 fallthrough; 13547 default: 13548 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 13549 dst, reg_type_str(env, ptr_reg->type)); 13550 return -EACCES; 13551 } 13552 13553 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 13554 * The id may be overwritten later if we create a new variable offset. 13555 */ 13556 dst_reg->type = ptr_reg->type; 13557 dst_reg->id = ptr_reg->id; 13558 13559 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 13560 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 13561 return -EINVAL; 13562 13563 /* pointer types do not carry 32-bit bounds at the moment. */ 13564 __mark_reg32_unbounded(dst_reg); 13565 13566 if (sanitize_needed(opcode)) { 13567 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 13568 &info, false); 13569 if (ret < 0) 13570 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13571 } 13572 13573 switch (opcode) { 13574 case BPF_ADD: 13575 /* We can take a fixed offset as long as it doesn't overflow 13576 * the s32 'off' field 13577 */ 13578 if (known && (ptr_reg->off + smin_val == 13579 (s64)(s32)(ptr_reg->off + smin_val))) { 13580 /* pointer += K. Accumulate it into fixed offset */ 13581 dst_reg->smin_value = smin_ptr; 13582 dst_reg->smax_value = smax_ptr; 13583 dst_reg->umin_value = umin_ptr; 13584 dst_reg->umax_value = umax_ptr; 13585 dst_reg->var_off = ptr_reg->var_off; 13586 dst_reg->off = ptr_reg->off + smin_val; 13587 dst_reg->raw = ptr_reg->raw; 13588 break; 13589 } 13590 /* A new variable offset is created. Note that off_reg->off 13591 * == 0, since it's a scalar. 13592 * dst_reg gets the pointer type and since some positive 13593 * integer value was added to the pointer, give it a new 'id' 13594 * if it's a PTR_TO_PACKET. 13595 * this creates a new 'base' pointer, off_reg (variable) gets 13596 * added into the variable offset, and we copy the fixed offset 13597 * from ptr_reg. 13598 */ 13599 if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) || 13600 check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) { 13601 dst_reg->smin_value = S64_MIN; 13602 dst_reg->smax_value = S64_MAX; 13603 } 13604 if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) || 13605 check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) { 13606 dst_reg->umin_value = 0; 13607 dst_reg->umax_value = U64_MAX; 13608 } 13609 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 13610 dst_reg->off = ptr_reg->off; 13611 dst_reg->raw = ptr_reg->raw; 13612 if (reg_is_pkt_pointer(ptr_reg)) { 13613 dst_reg->id = ++env->id_gen; 13614 /* something was added to pkt_ptr, set range to zero */ 13615 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13616 } 13617 break; 13618 case BPF_SUB: 13619 if (dst_reg == off_reg) { 13620 /* scalar -= pointer. Creates an unknown scalar */ 13621 verbose(env, "R%d tried to subtract pointer from scalar\n", 13622 dst); 13623 return -EACCES; 13624 } 13625 /* We don't allow subtraction from FP, because (according to 13626 * test_verifier.c test "invalid fp arithmetic", JITs might not 13627 * be able to deal with it. 13628 */ 13629 if (ptr_reg->type == PTR_TO_STACK) { 13630 verbose(env, "R%d subtraction from stack pointer prohibited\n", 13631 dst); 13632 return -EACCES; 13633 } 13634 if (known && (ptr_reg->off - smin_val == 13635 (s64)(s32)(ptr_reg->off - smin_val))) { 13636 /* pointer -= K. Subtract it from fixed offset */ 13637 dst_reg->smin_value = smin_ptr; 13638 dst_reg->smax_value = smax_ptr; 13639 dst_reg->umin_value = umin_ptr; 13640 dst_reg->umax_value = umax_ptr; 13641 dst_reg->var_off = ptr_reg->var_off; 13642 dst_reg->id = ptr_reg->id; 13643 dst_reg->off = ptr_reg->off - smin_val; 13644 dst_reg->raw = ptr_reg->raw; 13645 break; 13646 } 13647 /* A new variable offset is created. If the subtrahend is known 13648 * nonnegative, then any reg->range we had before is still good. 13649 */ 13650 if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) || 13651 check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) { 13652 /* Overflow possible, we know nothing */ 13653 dst_reg->smin_value = S64_MIN; 13654 dst_reg->smax_value = S64_MAX; 13655 } 13656 if (umin_ptr < umax_val) { 13657 /* Overflow possible, we know nothing */ 13658 dst_reg->umin_value = 0; 13659 dst_reg->umax_value = U64_MAX; 13660 } else { 13661 /* Cannot overflow (as long as bounds are consistent) */ 13662 dst_reg->umin_value = umin_ptr - umax_val; 13663 dst_reg->umax_value = umax_ptr - umin_val; 13664 } 13665 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 13666 dst_reg->off = ptr_reg->off; 13667 dst_reg->raw = ptr_reg->raw; 13668 if (reg_is_pkt_pointer(ptr_reg)) { 13669 dst_reg->id = ++env->id_gen; 13670 /* something was added to pkt_ptr, set range to zero */ 13671 if (smin_val < 0) 13672 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13673 } 13674 break; 13675 case BPF_AND: 13676 case BPF_OR: 13677 case BPF_XOR: 13678 /* bitwise ops on pointers are troublesome, prohibit. */ 13679 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 13680 dst, bpf_alu_string[opcode >> 4]); 13681 return -EACCES; 13682 default: 13683 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 13684 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 13685 dst, bpf_alu_string[opcode >> 4]); 13686 return -EACCES; 13687 } 13688 13689 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 13690 return -EINVAL; 13691 reg_bounds_sync(dst_reg); 13692 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 13693 return -EACCES; 13694 if (sanitize_needed(opcode)) { 13695 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 13696 &info, true); 13697 if (ret < 0) 13698 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13699 } 13700 13701 return 0; 13702 } 13703 13704 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 13705 struct bpf_reg_state *src_reg) 13706 { 13707 s32 *dst_smin = &dst_reg->s32_min_value; 13708 s32 *dst_smax = &dst_reg->s32_max_value; 13709 u32 *dst_umin = &dst_reg->u32_min_value; 13710 u32 *dst_umax = &dst_reg->u32_max_value; 13711 13712 if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) || 13713 check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) { 13714 *dst_smin = S32_MIN; 13715 *dst_smax = S32_MAX; 13716 } 13717 if (check_add_overflow(*dst_umin, src_reg->u32_min_value, dst_umin) || 13718 check_add_overflow(*dst_umax, src_reg->u32_max_value, dst_umax)) { 13719 *dst_umin = 0; 13720 *dst_umax = U32_MAX; 13721 } 13722 } 13723 13724 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 13725 struct bpf_reg_state *src_reg) 13726 { 13727 s64 *dst_smin = &dst_reg->smin_value; 13728 s64 *dst_smax = &dst_reg->smax_value; 13729 u64 *dst_umin = &dst_reg->umin_value; 13730 u64 *dst_umax = &dst_reg->umax_value; 13731 13732 if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) || 13733 check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) { 13734 *dst_smin = S64_MIN; 13735 *dst_smax = S64_MAX; 13736 } 13737 if (check_add_overflow(*dst_umin, src_reg->umin_value, dst_umin) || 13738 check_add_overflow(*dst_umax, src_reg->umax_value, dst_umax)) { 13739 *dst_umin = 0; 13740 *dst_umax = U64_MAX; 13741 } 13742 } 13743 13744 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 13745 struct bpf_reg_state *src_reg) 13746 { 13747 s32 *dst_smin = &dst_reg->s32_min_value; 13748 s32 *dst_smax = &dst_reg->s32_max_value; 13749 u32 umin_val = src_reg->u32_min_value; 13750 u32 umax_val = src_reg->u32_max_value; 13751 13752 if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) || 13753 check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) { 13754 /* Overflow possible, we know nothing */ 13755 *dst_smin = S32_MIN; 13756 *dst_smax = S32_MAX; 13757 } 13758 if (dst_reg->u32_min_value < umax_val) { 13759 /* Overflow possible, we know nothing */ 13760 dst_reg->u32_min_value = 0; 13761 dst_reg->u32_max_value = U32_MAX; 13762 } else { 13763 /* Cannot overflow (as long as bounds are consistent) */ 13764 dst_reg->u32_min_value -= umax_val; 13765 dst_reg->u32_max_value -= umin_val; 13766 } 13767 } 13768 13769 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 13770 struct bpf_reg_state *src_reg) 13771 { 13772 s64 *dst_smin = &dst_reg->smin_value; 13773 s64 *dst_smax = &dst_reg->smax_value; 13774 u64 umin_val = src_reg->umin_value; 13775 u64 umax_val = src_reg->umax_value; 13776 13777 if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) || 13778 check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) { 13779 /* Overflow possible, we know nothing */ 13780 *dst_smin = S64_MIN; 13781 *dst_smax = S64_MAX; 13782 } 13783 if (dst_reg->umin_value < umax_val) { 13784 /* Overflow possible, we know nothing */ 13785 dst_reg->umin_value = 0; 13786 dst_reg->umax_value = U64_MAX; 13787 } else { 13788 /* Cannot overflow (as long as bounds are consistent) */ 13789 dst_reg->umin_value -= umax_val; 13790 dst_reg->umax_value -= umin_val; 13791 } 13792 } 13793 13794 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 13795 struct bpf_reg_state *src_reg) 13796 { 13797 s32 smin_val = src_reg->s32_min_value; 13798 u32 umin_val = src_reg->u32_min_value; 13799 u32 umax_val = src_reg->u32_max_value; 13800 13801 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 13802 /* Ain't nobody got time to multiply that sign */ 13803 __mark_reg32_unbounded(dst_reg); 13804 return; 13805 } 13806 /* Both values are positive, so we can work with unsigned and 13807 * copy the result to signed (unless it exceeds S32_MAX). 13808 */ 13809 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 13810 /* Potential overflow, we know nothing */ 13811 __mark_reg32_unbounded(dst_reg); 13812 return; 13813 } 13814 dst_reg->u32_min_value *= umin_val; 13815 dst_reg->u32_max_value *= umax_val; 13816 if (dst_reg->u32_max_value > S32_MAX) { 13817 /* Overflow possible, we know nothing */ 13818 dst_reg->s32_min_value = S32_MIN; 13819 dst_reg->s32_max_value = S32_MAX; 13820 } else { 13821 dst_reg->s32_min_value = dst_reg->u32_min_value; 13822 dst_reg->s32_max_value = dst_reg->u32_max_value; 13823 } 13824 } 13825 13826 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 13827 struct bpf_reg_state *src_reg) 13828 { 13829 s64 smin_val = src_reg->smin_value; 13830 u64 umin_val = src_reg->umin_value; 13831 u64 umax_val = src_reg->umax_value; 13832 13833 if (smin_val < 0 || dst_reg->smin_value < 0) { 13834 /* Ain't nobody got time to multiply that sign */ 13835 __mark_reg64_unbounded(dst_reg); 13836 return; 13837 } 13838 /* Both values are positive, so we can work with unsigned and 13839 * copy the result to signed (unless it exceeds S64_MAX). 13840 */ 13841 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 13842 /* Potential overflow, we know nothing */ 13843 __mark_reg64_unbounded(dst_reg); 13844 return; 13845 } 13846 dst_reg->umin_value *= umin_val; 13847 dst_reg->umax_value *= umax_val; 13848 if (dst_reg->umax_value > S64_MAX) { 13849 /* Overflow possible, we know nothing */ 13850 dst_reg->smin_value = S64_MIN; 13851 dst_reg->smax_value = S64_MAX; 13852 } else { 13853 dst_reg->smin_value = dst_reg->umin_value; 13854 dst_reg->smax_value = dst_reg->umax_value; 13855 } 13856 } 13857 13858 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 13859 struct bpf_reg_state *src_reg) 13860 { 13861 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13862 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13863 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13864 u32 umax_val = src_reg->u32_max_value; 13865 13866 if (src_known && dst_known) { 13867 __mark_reg32_known(dst_reg, var32_off.value); 13868 return; 13869 } 13870 13871 /* We get our minimum from the var_off, since that's inherently 13872 * bitwise. Our maximum is the minimum of the operands' maxima. 13873 */ 13874 dst_reg->u32_min_value = var32_off.value; 13875 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 13876 13877 /* Safe to set s32 bounds by casting u32 result into s32 when u32 13878 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 13879 */ 13880 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 13881 dst_reg->s32_min_value = dst_reg->u32_min_value; 13882 dst_reg->s32_max_value = dst_reg->u32_max_value; 13883 } else { 13884 dst_reg->s32_min_value = S32_MIN; 13885 dst_reg->s32_max_value = S32_MAX; 13886 } 13887 } 13888 13889 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 13890 struct bpf_reg_state *src_reg) 13891 { 13892 bool src_known = tnum_is_const(src_reg->var_off); 13893 bool dst_known = tnum_is_const(dst_reg->var_off); 13894 u64 umax_val = src_reg->umax_value; 13895 13896 if (src_known && dst_known) { 13897 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13898 return; 13899 } 13900 13901 /* We get our minimum from the var_off, since that's inherently 13902 * bitwise. Our maximum is the minimum of the operands' maxima. 13903 */ 13904 dst_reg->umin_value = dst_reg->var_off.value; 13905 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 13906 13907 /* Safe to set s64 bounds by casting u64 result into s64 when u64 13908 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 13909 */ 13910 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 13911 dst_reg->smin_value = dst_reg->umin_value; 13912 dst_reg->smax_value = dst_reg->umax_value; 13913 } else { 13914 dst_reg->smin_value = S64_MIN; 13915 dst_reg->smax_value = S64_MAX; 13916 } 13917 /* We may learn something more from the var_off */ 13918 __update_reg_bounds(dst_reg); 13919 } 13920 13921 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 13922 struct bpf_reg_state *src_reg) 13923 { 13924 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13925 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13926 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13927 u32 umin_val = src_reg->u32_min_value; 13928 13929 if (src_known && dst_known) { 13930 __mark_reg32_known(dst_reg, var32_off.value); 13931 return; 13932 } 13933 13934 /* We get our maximum from the var_off, and our minimum is the 13935 * maximum of the operands' minima 13936 */ 13937 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 13938 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13939 13940 /* Safe to set s32 bounds by casting u32 result into s32 when u32 13941 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 13942 */ 13943 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 13944 dst_reg->s32_min_value = dst_reg->u32_min_value; 13945 dst_reg->s32_max_value = dst_reg->u32_max_value; 13946 } else { 13947 dst_reg->s32_min_value = S32_MIN; 13948 dst_reg->s32_max_value = S32_MAX; 13949 } 13950 } 13951 13952 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 13953 struct bpf_reg_state *src_reg) 13954 { 13955 bool src_known = tnum_is_const(src_reg->var_off); 13956 bool dst_known = tnum_is_const(dst_reg->var_off); 13957 u64 umin_val = src_reg->umin_value; 13958 13959 if (src_known && dst_known) { 13960 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13961 return; 13962 } 13963 13964 /* We get our maximum from the var_off, and our minimum is the 13965 * maximum of the operands' minima 13966 */ 13967 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 13968 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13969 13970 /* Safe to set s64 bounds by casting u64 result into s64 when u64 13971 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 13972 */ 13973 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 13974 dst_reg->smin_value = dst_reg->umin_value; 13975 dst_reg->smax_value = dst_reg->umax_value; 13976 } else { 13977 dst_reg->smin_value = S64_MIN; 13978 dst_reg->smax_value = S64_MAX; 13979 } 13980 /* We may learn something more from the var_off */ 13981 __update_reg_bounds(dst_reg); 13982 } 13983 13984 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 13985 struct bpf_reg_state *src_reg) 13986 { 13987 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13988 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13989 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13990 13991 if (src_known && dst_known) { 13992 __mark_reg32_known(dst_reg, var32_off.value); 13993 return; 13994 } 13995 13996 /* We get both minimum and maximum from the var32_off. */ 13997 dst_reg->u32_min_value = var32_off.value; 13998 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13999 14000 /* Safe to set s32 bounds by casting u32 result into s32 when u32 14001 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 14002 */ 14003 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 14004 dst_reg->s32_min_value = dst_reg->u32_min_value; 14005 dst_reg->s32_max_value = dst_reg->u32_max_value; 14006 } else { 14007 dst_reg->s32_min_value = S32_MIN; 14008 dst_reg->s32_max_value = S32_MAX; 14009 } 14010 } 14011 14012 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 14013 struct bpf_reg_state *src_reg) 14014 { 14015 bool src_known = tnum_is_const(src_reg->var_off); 14016 bool dst_known = tnum_is_const(dst_reg->var_off); 14017 14018 if (src_known && dst_known) { 14019 /* dst_reg->var_off.value has been updated earlier */ 14020 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14021 return; 14022 } 14023 14024 /* We get both minimum and maximum from the var_off. */ 14025 dst_reg->umin_value = dst_reg->var_off.value; 14026 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 14027 14028 /* Safe to set s64 bounds by casting u64 result into s64 when u64 14029 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 14030 */ 14031 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 14032 dst_reg->smin_value = dst_reg->umin_value; 14033 dst_reg->smax_value = dst_reg->umax_value; 14034 } else { 14035 dst_reg->smin_value = S64_MIN; 14036 dst_reg->smax_value = S64_MAX; 14037 } 14038 14039 __update_reg_bounds(dst_reg); 14040 } 14041 14042 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 14043 u64 umin_val, u64 umax_val) 14044 { 14045 /* We lose all sign bit information (except what we can pick 14046 * up from var_off) 14047 */ 14048 dst_reg->s32_min_value = S32_MIN; 14049 dst_reg->s32_max_value = S32_MAX; 14050 /* If we might shift our top bit out, then we know nothing */ 14051 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 14052 dst_reg->u32_min_value = 0; 14053 dst_reg->u32_max_value = U32_MAX; 14054 } else { 14055 dst_reg->u32_min_value <<= umin_val; 14056 dst_reg->u32_max_value <<= umax_val; 14057 } 14058 } 14059 14060 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 14061 struct bpf_reg_state *src_reg) 14062 { 14063 u32 umax_val = src_reg->u32_max_value; 14064 u32 umin_val = src_reg->u32_min_value; 14065 /* u32 alu operation will zext upper bits */ 14066 struct tnum subreg = tnum_subreg(dst_reg->var_off); 14067 14068 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 14069 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 14070 /* Not required but being careful mark reg64 bounds as unknown so 14071 * that we are forced to pick them up from tnum and zext later and 14072 * if some path skips this step we are still safe. 14073 */ 14074 __mark_reg64_unbounded(dst_reg); 14075 __update_reg32_bounds(dst_reg); 14076 } 14077 14078 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 14079 u64 umin_val, u64 umax_val) 14080 { 14081 /* Special case <<32 because it is a common compiler pattern to sign 14082 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 14083 * positive we know this shift will also be positive so we can track 14084 * bounds correctly. Otherwise we lose all sign bit information except 14085 * what we can pick up from var_off. Perhaps we can generalize this 14086 * later to shifts of any length. 14087 */ 14088 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 14089 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 14090 else 14091 dst_reg->smax_value = S64_MAX; 14092 14093 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 14094 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 14095 else 14096 dst_reg->smin_value = S64_MIN; 14097 14098 /* If we might shift our top bit out, then we know nothing */ 14099 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 14100 dst_reg->umin_value = 0; 14101 dst_reg->umax_value = U64_MAX; 14102 } else { 14103 dst_reg->umin_value <<= umin_val; 14104 dst_reg->umax_value <<= umax_val; 14105 } 14106 } 14107 14108 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 14109 struct bpf_reg_state *src_reg) 14110 { 14111 u64 umax_val = src_reg->umax_value; 14112 u64 umin_val = src_reg->umin_value; 14113 14114 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 14115 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 14116 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 14117 14118 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 14119 /* We may learn something more from the var_off */ 14120 __update_reg_bounds(dst_reg); 14121 } 14122 14123 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 14124 struct bpf_reg_state *src_reg) 14125 { 14126 struct tnum subreg = tnum_subreg(dst_reg->var_off); 14127 u32 umax_val = src_reg->u32_max_value; 14128 u32 umin_val = src_reg->u32_min_value; 14129 14130 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 14131 * be negative, then either: 14132 * 1) src_reg might be zero, so the sign bit of the result is 14133 * unknown, so we lose our signed bounds 14134 * 2) it's known negative, thus the unsigned bounds capture the 14135 * signed bounds 14136 * 3) the signed bounds cross zero, so they tell us nothing 14137 * about the result 14138 * If the value in dst_reg is known nonnegative, then again the 14139 * unsigned bounds capture the signed bounds. 14140 * Thus, in all cases it suffices to blow away our signed bounds 14141 * and rely on inferring new ones from the unsigned bounds and 14142 * var_off of the result. 14143 */ 14144 dst_reg->s32_min_value = S32_MIN; 14145 dst_reg->s32_max_value = S32_MAX; 14146 14147 dst_reg->var_off = tnum_rshift(subreg, umin_val); 14148 dst_reg->u32_min_value >>= umax_val; 14149 dst_reg->u32_max_value >>= umin_val; 14150 14151 __mark_reg64_unbounded(dst_reg); 14152 __update_reg32_bounds(dst_reg); 14153 } 14154 14155 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 14156 struct bpf_reg_state *src_reg) 14157 { 14158 u64 umax_val = src_reg->umax_value; 14159 u64 umin_val = src_reg->umin_value; 14160 14161 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 14162 * be negative, then either: 14163 * 1) src_reg might be zero, so the sign bit of the result is 14164 * unknown, so we lose our signed bounds 14165 * 2) it's known negative, thus the unsigned bounds capture the 14166 * signed bounds 14167 * 3) the signed bounds cross zero, so they tell us nothing 14168 * about the result 14169 * If the value in dst_reg is known nonnegative, then again the 14170 * unsigned bounds capture the signed bounds. 14171 * Thus, in all cases it suffices to blow away our signed bounds 14172 * and rely on inferring new ones from the unsigned bounds and 14173 * var_off of the result. 14174 */ 14175 dst_reg->smin_value = S64_MIN; 14176 dst_reg->smax_value = S64_MAX; 14177 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 14178 dst_reg->umin_value >>= umax_val; 14179 dst_reg->umax_value >>= umin_val; 14180 14181 /* Its not easy to operate on alu32 bounds here because it depends 14182 * on bits being shifted in. Take easy way out and mark unbounded 14183 * so we can recalculate later from tnum. 14184 */ 14185 __mark_reg32_unbounded(dst_reg); 14186 __update_reg_bounds(dst_reg); 14187 } 14188 14189 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 14190 struct bpf_reg_state *src_reg) 14191 { 14192 u64 umin_val = src_reg->u32_min_value; 14193 14194 /* Upon reaching here, src_known is true and 14195 * umax_val is equal to umin_val. 14196 */ 14197 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 14198 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 14199 14200 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 14201 14202 /* blow away the dst_reg umin_value/umax_value and rely on 14203 * dst_reg var_off to refine the result. 14204 */ 14205 dst_reg->u32_min_value = 0; 14206 dst_reg->u32_max_value = U32_MAX; 14207 14208 __mark_reg64_unbounded(dst_reg); 14209 __update_reg32_bounds(dst_reg); 14210 } 14211 14212 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 14213 struct bpf_reg_state *src_reg) 14214 { 14215 u64 umin_val = src_reg->umin_value; 14216 14217 /* Upon reaching here, src_known is true and umax_val is equal 14218 * to umin_val. 14219 */ 14220 dst_reg->smin_value >>= umin_val; 14221 dst_reg->smax_value >>= umin_val; 14222 14223 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 14224 14225 /* blow away the dst_reg umin_value/umax_value and rely on 14226 * dst_reg var_off to refine the result. 14227 */ 14228 dst_reg->umin_value = 0; 14229 dst_reg->umax_value = U64_MAX; 14230 14231 /* Its not easy to operate on alu32 bounds here because it depends 14232 * on bits being shifted in from upper 32-bits. Take easy way out 14233 * and mark unbounded so we can recalculate later from tnum. 14234 */ 14235 __mark_reg32_unbounded(dst_reg); 14236 __update_reg_bounds(dst_reg); 14237 } 14238 14239 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn, 14240 const struct bpf_reg_state *src_reg) 14241 { 14242 bool src_is_const = false; 14243 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 14244 14245 if (insn_bitness == 32) { 14246 if (tnum_subreg_is_const(src_reg->var_off) 14247 && src_reg->s32_min_value == src_reg->s32_max_value 14248 && src_reg->u32_min_value == src_reg->u32_max_value) 14249 src_is_const = true; 14250 } else { 14251 if (tnum_is_const(src_reg->var_off) 14252 && src_reg->smin_value == src_reg->smax_value 14253 && src_reg->umin_value == src_reg->umax_value) 14254 src_is_const = true; 14255 } 14256 14257 switch (BPF_OP(insn->code)) { 14258 case BPF_ADD: 14259 case BPF_SUB: 14260 case BPF_AND: 14261 case BPF_XOR: 14262 case BPF_OR: 14263 case BPF_MUL: 14264 return true; 14265 14266 /* Shift operators range is only computable if shift dimension operand 14267 * is a constant. Shifts greater than 31 or 63 are undefined. This 14268 * includes shifts by a negative number. 14269 */ 14270 case BPF_LSH: 14271 case BPF_RSH: 14272 case BPF_ARSH: 14273 return (src_is_const && src_reg->umax_value < insn_bitness); 14274 default: 14275 return false; 14276 } 14277 } 14278 14279 /* WARNING: This function does calculations on 64-bit values, but the actual 14280 * execution may occur on 32-bit values. Therefore, things like bitshifts 14281 * need extra checks in the 32-bit case. 14282 */ 14283 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 14284 struct bpf_insn *insn, 14285 struct bpf_reg_state *dst_reg, 14286 struct bpf_reg_state src_reg) 14287 { 14288 u8 opcode = BPF_OP(insn->code); 14289 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14290 int ret; 14291 14292 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) { 14293 __mark_reg_unknown(env, dst_reg); 14294 return 0; 14295 } 14296 14297 if (sanitize_needed(opcode)) { 14298 ret = sanitize_val_alu(env, insn); 14299 if (ret < 0) 14300 return sanitize_err(env, insn, ret, NULL, NULL); 14301 } 14302 14303 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 14304 * There are two classes of instructions: The first class we track both 14305 * alu32 and alu64 sign/unsigned bounds independently this provides the 14306 * greatest amount of precision when alu operations are mixed with jmp32 14307 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 14308 * and BPF_OR. This is possible because these ops have fairly easy to 14309 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 14310 * See alu32 verifier tests for examples. The second class of 14311 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 14312 * with regards to tracking sign/unsigned bounds because the bits may 14313 * cross subreg boundaries in the alu64 case. When this happens we mark 14314 * the reg unbounded in the subreg bound space and use the resulting 14315 * tnum to calculate an approximation of the sign/unsigned bounds. 14316 */ 14317 switch (opcode) { 14318 case BPF_ADD: 14319 scalar32_min_max_add(dst_reg, &src_reg); 14320 scalar_min_max_add(dst_reg, &src_reg); 14321 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 14322 break; 14323 case BPF_SUB: 14324 scalar32_min_max_sub(dst_reg, &src_reg); 14325 scalar_min_max_sub(dst_reg, &src_reg); 14326 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 14327 break; 14328 case BPF_MUL: 14329 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 14330 scalar32_min_max_mul(dst_reg, &src_reg); 14331 scalar_min_max_mul(dst_reg, &src_reg); 14332 break; 14333 case BPF_AND: 14334 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 14335 scalar32_min_max_and(dst_reg, &src_reg); 14336 scalar_min_max_and(dst_reg, &src_reg); 14337 break; 14338 case BPF_OR: 14339 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 14340 scalar32_min_max_or(dst_reg, &src_reg); 14341 scalar_min_max_or(dst_reg, &src_reg); 14342 break; 14343 case BPF_XOR: 14344 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 14345 scalar32_min_max_xor(dst_reg, &src_reg); 14346 scalar_min_max_xor(dst_reg, &src_reg); 14347 break; 14348 case BPF_LSH: 14349 if (alu32) 14350 scalar32_min_max_lsh(dst_reg, &src_reg); 14351 else 14352 scalar_min_max_lsh(dst_reg, &src_reg); 14353 break; 14354 case BPF_RSH: 14355 if (alu32) 14356 scalar32_min_max_rsh(dst_reg, &src_reg); 14357 else 14358 scalar_min_max_rsh(dst_reg, &src_reg); 14359 break; 14360 case BPF_ARSH: 14361 if (alu32) 14362 scalar32_min_max_arsh(dst_reg, &src_reg); 14363 else 14364 scalar_min_max_arsh(dst_reg, &src_reg); 14365 break; 14366 default: 14367 break; 14368 } 14369 14370 /* ALU32 ops are zero extended into 64bit register */ 14371 if (alu32) 14372 zext_32_to_64(dst_reg); 14373 reg_bounds_sync(dst_reg); 14374 return 0; 14375 } 14376 14377 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 14378 * and var_off. 14379 */ 14380 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 14381 struct bpf_insn *insn) 14382 { 14383 struct bpf_verifier_state *vstate = env->cur_state; 14384 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14385 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 14386 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 14387 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14388 u8 opcode = BPF_OP(insn->code); 14389 int err; 14390 14391 dst_reg = ®s[insn->dst_reg]; 14392 src_reg = NULL; 14393 14394 if (dst_reg->type == PTR_TO_ARENA) { 14395 struct bpf_insn_aux_data *aux = cur_aux(env); 14396 14397 if (BPF_CLASS(insn->code) == BPF_ALU64) 14398 /* 14399 * 32-bit operations zero upper bits automatically. 14400 * 64-bit operations need to be converted to 32. 14401 */ 14402 aux->needs_zext = true; 14403 14404 /* Any arithmetic operations are allowed on arena pointers */ 14405 return 0; 14406 } 14407 14408 if (dst_reg->type != SCALAR_VALUE) 14409 ptr_reg = dst_reg; 14410 14411 if (BPF_SRC(insn->code) == BPF_X) { 14412 src_reg = ®s[insn->src_reg]; 14413 if (src_reg->type != SCALAR_VALUE) { 14414 if (dst_reg->type != SCALAR_VALUE) { 14415 /* Combining two pointers by any ALU op yields 14416 * an arbitrary scalar. Disallow all math except 14417 * pointer subtraction 14418 */ 14419 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 14420 mark_reg_unknown(env, regs, insn->dst_reg); 14421 return 0; 14422 } 14423 verbose(env, "R%d pointer %s pointer prohibited\n", 14424 insn->dst_reg, 14425 bpf_alu_string[opcode >> 4]); 14426 return -EACCES; 14427 } else { 14428 /* scalar += pointer 14429 * This is legal, but we have to reverse our 14430 * src/dest handling in computing the range 14431 */ 14432 err = mark_chain_precision(env, insn->dst_reg); 14433 if (err) 14434 return err; 14435 return adjust_ptr_min_max_vals(env, insn, 14436 src_reg, dst_reg); 14437 } 14438 } else if (ptr_reg) { 14439 /* pointer += scalar */ 14440 err = mark_chain_precision(env, insn->src_reg); 14441 if (err) 14442 return err; 14443 return adjust_ptr_min_max_vals(env, insn, 14444 dst_reg, src_reg); 14445 } else if (dst_reg->precise) { 14446 /* if dst_reg is precise, src_reg should be precise as well */ 14447 err = mark_chain_precision(env, insn->src_reg); 14448 if (err) 14449 return err; 14450 } 14451 } else { 14452 /* Pretend the src is a reg with a known value, since we only 14453 * need to be able to read from this state. 14454 */ 14455 off_reg.type = SCALAR_VALUE; 14456 __mark_reg_known(&off_reg, insn->imm); 14457 src_reg = &off_reg; 14458 if (ptr_reg) /* pointer += K */ 14459 return adjust_ptr_min_max_vals(env, insn, 14460 ptr_reg, src_reg); 14461 } 14462 14463 /* Got here implies adding two SCALAR_VALUEs */ 14464 if (WARN_ON_ONCE(ptr_reg)) { 14465 print_verifier_state(env, state, true); 14466 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 14467 return -EINVAL; 14468 } 14469 if (WARN_ON(!src_reg)) { 14470 print_verifier_state(env, state, true); 14471 verbose(env, "verifier internal error: no src_reg\n"); 14472 return -EINVAL; 14473 } 14474 err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 14475 if (err) 14476 return err; 14477 /* 14478 * Compilers can generate the code 14479 * r1 = r2 14480 * r1 += 0x1 14481 * if r2 < 1000 goto ... 14482 * use r1 in memory access 14483 * So for 64-bit alu remember constant delta between r2 and r1 and 14484 * update r1 after 'if' condition. 14485 */ 14486 if (env->bpf_capable && 14487 BPF_OP(insn->code) == BPF_ADD && !alu32 && 14488 dst_reg->id && is_reg_const(src_reg, false)) { 14489 u64 val = reg_const_value(src_reg, false); 14490 14491 if ((dst_reg->id & BPF_ADD_CONST) || 14492 /* prevent overflow in sync_linked_regs() later */ 14493 val > (u32)S32_MAX) { 14494 /* 14495 * If the register already went through rX += val 14496 * we cannot accumulate another val into rx->off. 14497 */ 14498 dst_reg->off = 0; 14499 dst_reg->id = 0; 14500 } else { 14501 dst_reg->id |= BPF_ADD_CONST; 14502 dst_reg->off = val; 14503 } 14504 } else { 14505 /* 14506 * Make sure ID is cleared otherwise dst_reg min/max could be 14507 * incorrectly propagated into other registers by sync_linked_regs() 14508 */ 14509 dst_reg->id = 0; 14510 } 14511 return 0; 14512 } 14513 14514 /* check validity of 32-bit and 64-bit arithmetic operations */ 14515 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 14516 { 14517 struct bpf_reg_state *regs = cur_regs(env); 14518 u8 opcode = BPF_OP(insn->code); 14519 int err; 14520 14521 if (opcode == BPF_END || opcode == BPF_NEG) { 14522 if (opcode == BPF_NEG) { 14523 if (BPF_SRC(insn->code) != BPF_K || 14524 insn->src_reg != BPF_REG_0 || 14525 insn->off != 0 || insn->imm != 0) { 14526 verbose(env, "BPF_NEG uses reserved fields\n"); 14527 return -EINVAL; 14528 } 14529 } else { 14530 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 14531 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 14532 (BPF_CLASS(insn->code) == BPF_ALU64 && 14533 BPF_SRC(insn->code) != BPF_TO_LE)) { 14534 verbose(env, "BPF_END uses reserved fields\n"); 14535 return -EINVAL; 14536 } 14537 } 14538 14539 /* check src operand */ 14540 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14541 if (err) 14542 return err; 14543 14544 if (is_pointer_value(env, insn->dst_reg)) { 14545 verbose(env, "R%d pointer arithmetic prohibited\n", 14546 insn->dst_reg); 14547 return -EACCES; 14548 } 14549 14550 /* check dest operand */ 14551 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14552 if (err) 14553 return err; 14554 14555 } else if (opcode == BPF_MOV) { 14556 14557 if (BPF_SRC(insn->code) == BPF_X) { 14558 if (BPF_CLASS(insn->code) == BPF_ALU) { 14559 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) || 14560 insn->imm) { 14561 verbose(env, "BPF_MOV uses reserved fields\n"); 14562 return -EINVAL; 14563 } 14564 } else if (insn->off == BPF_ADDR_SPACE_CAST) { 14565 if (insn->imm != 1 && insn->imm != 1u << 16) { 14566 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n"); 14567 return -EINVAL; 14568 } 14569 if (!env->prog->aux->arena) { 14570 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n"); 14571 return -EINVAL; 14572 } 14573 } else { 14574 if ((insn->off != 0 && insn->off != 8 && insn->off != 16 && 14575 insn->off != 32) || insn->imm) { 14576 verbose(env, "BPF_MOV uses reserved fields\n"); 14577 return -EINVAL; 14578 } 14579 } 14580 14581 /* check src operand */ 14582 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14583 if (err) 14584 return err; 14585 } else { 14586 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 14587 verbose(env, "BPF_MOV uses reserved fields\n"); 14588 return -EINVAL; 14589 } 14590 } 14591 14592 /* check dest operand, mark as required later */ 14593 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14594 if (err) 14595 return err; 14596 14597 if (BPF_SRC(insn->code) == BPF_X) { 14598 struct bpf_reg_state *src_reg = regs + insn->src_reg; 14599 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 14600 14601 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14602 if (insn->imm) { 14603 /* off == BPF_ADDR_SPACE_CAST */ 14604 mark_reg_unknown(env, regs, insn->dst_reg); 14605 if (insn->imm == 1) { /* cast from as(1) to as(0) */ 14606 dst_reg->type = PTR_TO_ARENA; 14607 /* PTR_TO_ARENA is 32-bit */ 14608 dst_reg->subreg_def = env->insn_idx + 1; 14609 } 14610 } else if (insn->off == 0) { 14611 /* case: R1 = R2 14612 * copy register state to dest reg 14613 */ 14614 assign_scalar_id_before_mov(env, src_reg); 14615 copy_register_state(dst_reg, src_reg); 14616 dst_reg->live |= REG_LIVE_WRITTEN; 14617 dst_reg->subreg_def = DEF_NOT_SUBREG; 14618 } else { 14619 /* case: R1 = (s8, s16 s32)R2 */ 14620 if (is_pointer_value(env, insn->src_reg)) { 14621 verbose(env, 14622 "R%d sign-extension part of pointer\n", 14623 insn->src_reg); 14624 return -EACCES; 14625 } else if (src_reg->type == SCALAR_VALUE) { 14626 bool no_sext; 14627 14628 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 14629 if (no_sext) 14630 assign_scalar_id_before_mov(env, src_reg); 14631 copy_register_state(dst_reg, src_reg); 14632 if (!no_sext) 14633 dst_reg->id = 0; 14634 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 14635 dst_reg->live |= REG_LIVE_WRITTEN; 14636 dst_reg->subreg_def = DEF_NOT_SUBREG; 14637 } else { 14638 mark_reg_unknown(env, regs, insn->dst_reg); 14639 } 14640 } 14641 } else { 14642 /* R1 = (u32) R2 */ 14643 if (is_pointer_value(env, insn->src_reg)) { 14644 verbose(env, 14645 "R%d partial copy of pointer\n", 14646 insn->src_reg); 14647 return -EACCES; 14648 } else if (src_reg->type == SCALAR_VALUE) { 14649 if (insn->off == 0) { 14650 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 14651 14652 if (is_src_reg_u32) 14653 assign_scalar_id_before_mov(env, src_reg); 14654 copy_register_state(dst_reg, src_reg); 14655 /* Make sure ID is cleared if src_reg is not in u32 14656 * range otherwise dst_reg min/max could be incorrectly 14657 * propagated into src_reg by sync_linked_regs() 14658 */ 14659 if (!is_src_reg_u32) 14660 dst_reg->id = 0; 14661 dst_reg->live |= REG_LIVE_WRITTEN; 14662 dst_reg->subreg_def = env->insn_idx + 1; 14663 } else { 14664 /* case: W1 = (s8, s16)W2 */ 14665 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 14666 14667 if (no_sext) 14668 assign_scalar_id_before_mov(env, src_reg); 14669 copy_register_state(dst_reg, src_reg); 14670 if (!no_sext) 14671 dst_reg->id = 0; 14672 dst_reg->live |= REG_LIVE_WRITTEN; 14673 dst_reg->subreg_def = env->insn_idx + 1; 14674 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 14675 } 14676 } else { 14677 mark_reg_unknown(env, regs, 14678 insn->dst_reg); 14679 } 14680 zext_32_to_64(dst_reg); 14681 reg_bounds_sync(dst_reg); 14682 } 14683 } else { 14684 /* case: R = imm 14685 * remember the value we stored into this reg 14686 */ 14687 /* clear any state __mark_reg_known doesn't set */ 14688 mark_reg_unknown(env, regs, insn->dst_reg); 14689 regs[insn->dst_reg].type = SCALAR_VALUE; 14690 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14691 __mark_reg_known(regs + insn->dst_reg, 14692 insn->imm); 14693 } else { 14694 __mark_reg_known(regs + insn->dst_reg, 14695 (u32)insn->imm); 14696 } 14697 } 14698 14699 } else if (opcode > BPF_END) { 14700 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 14701 return -EINVAL; 14702 14703 } else { /* all other ALU ops: and, sub, xor, add, ... */ 14704 14705 if (BPF_SRC(insn->code) == BPF_X) { 14706 if (insn->imm != 0 || insn->off > 1 || 14707 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14708 verbose(env, "BPF_ALU uses reserved fields\n"); 14709 return -EINVAL; 14710 } 14711 /* check src1 operand */ 14712 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14713 if (err) 14714 return err; 14715 } else { 14716 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 14717 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14718 verbose(env, "BPF_ALU uses reserved fields\n"); 14719 return -EINVAL; 14720 } 14721 } 14722 14723 /* check src2 operand */ 14724 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14725 if (err) 14726 return err; 14727 14728 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 14729 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 14730 verbose(env, "div by zero\n"); 14731 return -EINVAL; 14732 } 14733 14734 if ((opcode == BPF_LSH || opcode == BPF_RSH || 14735 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 14736 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 14737 14738 if (insn->imm < 0 || insn->imm >= size) { 14739 verbose(env, "invalid shift %d\n", insn->imm); 14740 return -EINVAL; 14741 } 14742 } 14743 14744 /* check dest operand */ 14745 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14746 err = err ?: adjust_reg_min_max_vals(env, insn); 14747 if (err) 14748 return err; 14749 } 14750 14751 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 14752 } 14753 14754 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 14755 struct bpf_reg_state *dst_reg, 14756 enum bpf_reg_type type, 14757 bool range_right_open) 14758 { 14759 struct bpf_func_state *state; 14760 struct bpf_reg_state *reg; 14761 int new_range; 14762 14763 if (dst_reg->off < 0 || 14764 (dst_reg->off == 0 && range_right_open)) 14765 /* This doesn't give us any range */ 14766 return; 14767 14768 if (dst_reg->umax_value > MAX_PACKET_OFF || 14769 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 14770 /* Risk of overflow. For instance, ptr + (1<<63) may be less 14771 * than pkt_end, but that's because it's also less than pkt. 14772 */ 14773 return; 14774 14775 new_range = dst_reg->off; 14776 if (range_right_open) 14777 new_range++; 14778 14779 /* Examples for register markings: 14780 * 14781 * pkt_data in dst register: 14782 * 14783 * r2 = r3; 14784 * r2 += 8; 14785 * if (r2 > pkt_end) goto <handle exception> 14786 * <access okay> 14787 * 14788 * r2 = r3; 14789 * r2 += 8; 14790 * if (r2 < pkt_end) goto <access okay> 14791 * <handle exception> 14792 * 14793 * Where: 14794 * r2 == dst_reg, pkt_end == src_reg 14795 * r2=pkt(id=n,off=8,r=0) 14796 * r3=pkt(id=n,off=0,r=0) 14797 * 14798 * pkt_data in src register: 14799 * 14800 * r2 = r3; 14801 * r2 += 8; 14802 * if (pkt_end >= r2) goto <access okay> 14803 * <handle exception> 14804 * 14805 * r2 = r3; 14806 * r2 += 8; 14807 * if (pkt_end <= r2) goto <handle exception> 14808 * <access okay> 14809 * 14810 * Where: 14811 * pkt_end == dst_reg, r2 == src_reg 14812 * r2=pkt(id=n,off=8,r=0) 14813 * r3=pkt(id=n,off=0,r=0) 14814 * 14815 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 14816 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 14817 * and [r3, r3 + 8-1) respectively is safe to access depending on 14818 * the check. 14819 */ 14820 14821 /* If our ids match, then we must have the same max_value. And we 14822 * don't care about the other reg's fixed offset, since if it's too big 14823 * the range won't allow anything. 14824 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 14825 */ 14826 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14827 if (reg->type == type && reg->id == dst_reg->id) 14828 /* keep the maximum range already checked */ 14829 reg->range = max(reg->range, new_range); 14830 })); 14831 } 14832 14833 /* 14834 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 14835 */ 14836 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14837 u8 opcode, bool is_jmp32) 14838 { 14839 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 14840 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 14841 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value; 14842 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value; 14843 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value; 14844 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value; 14845 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value; 14846 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value; 14847 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value; 14848 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value; 14849 14850 switch (opcode) { 14851 case BPF_JEQ: 14852 /* constants, umin/umax and smin/smax checks would be 14853 * redundant in this case because they all should match 14854 */ 14855 if (tnum_is_const(t1) && tnum_is_const(t2)) 14856 return t1.value == t2.value; 14857 /* non-overlapping ranges */ 14858 if (umin1 > umax2 || umax1 < umin2) 14859 return 0; 14860 if (smin1 > smax2 || smax1 < smin2) 14861 return 0; 14862 if (!is_jmp32) { 14863 /* if 64-bit ranges are inconclusive, see if we can 14864 * utilize 32-bit subrange knowledge to eliminate 14865 * branches that can't be taken a priori 14866 */ 14867 if (reg1->u32_min_value > reg2->u32_max_value || 14868 reg1->u32_max_value < reg2->u32_min_value) 14869 return 0; 14870 if (reg1->s32_min_value > reg2->s32_max_value || 14871 reg1->s32_max_value < reg2->s32_min_value) 14872 return 0; 14873 } 14874 break; 14875 case BPF_JNE: 14876 /* constants, umin/umax and smin/smax checks would be 14877 * redundant in this case because they all should match 14878 */ 14879 if (tnum_is_const(t1) && tnum_is_const(t2)) 14880 return t1.value != t2.value; 14881 /* non-overlapping ranges */ 14882 if (umin1 > umax2 || umax1 < umin2) 14883 return 1; 14884 if (smin1 > smax2 || smax1 < smin2) 14885 return 1; 14886 if (!is_jmp32) { 14887 /* if 64-bit ranges are inconclusive, see if we can 14888 * utilize 32-bit subrange knowledge to eliminate 14889 * branches that can't be taken a priori 14890 */ 14891 if (reg1->u32_min_value > reg2->u32_max_value || 14892 reg1->u32_max_value < reg2->u32_min_value) 14893 return 1; 14894 if (reg1->s32_min_value > reg2->s32_max_value || 14895 reg1->s32_max_value < reg2->s32_min_value) 14896 return 1; 14897 } 14898 break; 14899 case BPF_JSET: 14900 if (!is_reg_const(reg2, is_jmp32)) { 14901 swap(reg1, reg2); 14902 swap(t1, t2); 14903 } 14904 if (!is_reg_const(reg2, is_jmp32)) 14905 return -1; 14906 if ((~t1.mask & t1.value) & t2.value) 14907 return 1; 14908 if (!((t1.mask | t1.value) & t2.value)) 14909 return 0; 14910 break; 14911 case BPF_JGT: 14912 if (umin1 > umax2) 14913 return 1; 14914 else if (umax1 <= umin2) 14915 return 0; 14916 break; 14917 case BPF_JSGT: 14918 if (smin1 > smax2) 14919 return 1; 14920 else if (smax1 <= smin2) 14921 return 0; 14922 break; 14923 case BPF_JLT: 14924 if (umax1 < umin2) 14925 return 1; 14926 else if (umin1 >= umax2) 14927 return 0; 14928 break; 14929 case BPF_JSLT: 14930 if (smax1 < smin2) 14931 return 1; 14932 else if (smin1 >= smax2) 14933 return 0; 14934 break; 14935 case BPF_JGE: 14936 if (umin1 >= umax2) 14937 return 1; 14938 else if (umax1 < umin2) 14939 return 0; 14940 break; 14941 case BPF_JSGE: 14942 if (smin1 >= smax2) 14943 return 1; 14944 else if (smax1 < smin2) 14945 return 0; 14946 break; 14947 case BPF_JLE: 14948 if (umax1 <= umin2) 14949 return 1; 14950 else if (umin1 > umax2) 14951 return 0; 14952 break; 14953 case BPF_JSLE: 14954 if (smax1 <= smin2) 14955 return 1; 14956 else if (smin1 > smax2) 14957 return 0; 14958 break; 14959 } 14960 14961 return -1; 14962 } 14963 14964 static int flip_opcode(u32 opcode) 14965 { 14966 /* How can we transform "a <op> b" into "b <op> a"? */ 14967 static const u8 opcode_flip[16] = { 14968 /* these stay the same */ 14969 [BPF_JEQ >> 4] = BPF_JEQ, 14970 [BPF_JNE >> 4] = BPF_JNE, 14971 [BPF_JSET >> 4] = BPF_JSET, 14972 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 14973 [BPF_JGE >> 4] = BPF_JLE, 14974 [BPF_JGT >> 4] = BPF_JLT, 14975 [BPF_JLE >> 4] = BPF_JGE, 14976 [BPF_JLT >> 4] = BPF_JGT, 14977 [BPF_JSGE >> 4] = BPF_JSLE, 14978 [BPF_JSGT >> 4] = BPF_JSLT, 14979 [BPF_JSLE >> 4] = BPF_JSGE, 14980 [BPF_JSLT >> 4] = BPF_JSGT 14981 }; 14982 return opcode_flip[opcode >> 4]; 14983 } 14984 14985 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 14986 struct bpf_reg_state *src_reg, 14987 u8 opcode) 14988 { 14989 struct bpf_reg_state *pkt; 14990 14991 if (src_reg->type == PTR_TO_PACKET_END) { 14992 pkt = dst_reg; 14993 } else if (dst_reg->type == PTR_TO_PACKET_END) { 14994 pkt = src_reg; 14995 opcode = flip_opcode(opcode); 14996 } else { 14997 return -1; 14998 } 14999 15000 if (pkt->range >= 0) 15001 return -1; 15002 15003 switch (opcode) { 15004 case BPF_JLE: 15005 /* pkt <= pkt_end */ 15006 fallthrough; 15007 case BPF_JGT: 15008 /* pkt > pkt_end */ 15009 if (pkt->range == BEYOND_PKT_END) 15010 /* pkt has at last one extra byte beyond pkt_end */ 15011 return opcode == BPF_JGT; 15012 break; 15013 case BPF_JLT: 15014 /* pkt < pkt_end */ 15015 fallthrough; 15016 case BPF_JGE: 15017 /* pkt >= pkt_end */ 15018 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 15019 return opcode == BPF_JGE; 15020 break; 15021 } 15022 return -1; 15023 } 15024 15025 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 15026 * and return: 15027 * 1 - branch will be taken and "goto target" will be executed 15028 * 0 - branch will not be taken and fall-through to next insn 15029 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 15030 * range [0,10] 15031 */ 15032 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15033 u8 opcode, bool is_jmp32) 15034 { 15035 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 15036 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 15037 15038 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 15039 u64 val; 15040 15041 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 15042 if (!is_reg_const(reg2, is_jmp32)) { 15043 opcode = flip_opcode(opcode); 15044 swap(reg1, reg2); 15045 } 15046 /* and ensure that reg2 is a constant */ 15047 if (!is_reg_const(reg2, is_jmp32)) 15048 return -1; 15049 15050 if (!reg_not_null(reg1)) 15051 return -1; 15052 15053 /* If pointer is valid tests against zero will fail so we can 15054 * use this to direct branch taken. 15055 */ 15056 val = reg_const_value(reg2, is_jmp32); 15057 if (val != 0) 15058 return -1; 15059 15060 switch (opcode) { 15061 case BPF_JEQ: 15062 return 0; 15063 case BPF_JNE: 15064 return 1; 15065 default: 15066 return -1; 15067 } 15068 } 15069 15070 /* now deal with two scalars, but not necessarily constants */ 15071 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32); 15072 } 15073 15074 /* Opcode that corresponds to a *false* branch condition. 15075 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 15076 */ 15077 static u8 rev_opcode(u8 opcode) 15078 { 15079 switch (opcode) { 15080 case BPF_JEQ: return BPF_JNE; 15081 case BPF_JNE: return BPF_JEQ; 15082 /* JSET doesn't have it's reverse opcode in BPF, so add 15083 * BPF_X flag to denote the reverse of that operation 15084 */ 15085 case BPF_JSET: return BPF_JSET | BPF_X; 15086 case BPF_JSET | BPF_X: return BPF_JSET; 15087 case BPF_JGE: return BPF_JLT; 15088 case BPF_JGT: return BPF_JLE; 15089 case BPF_JLE: return BPF_JGT; 15090 case BPF_JLT: return BPF_JGE; 15091 case BPF_JSGE: return BPF_JSLT; 15092 case BPF_JSGT: return BPF_JSLE; 15093 case BPF_JSLE: return BPF_JSGT; 15094 case BPF_JSLT: return BPF_JSGE; 15095 default: return 0; 15096 } 15097 } 15098 15099 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 15100 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15101 u8 opcode, bool is_jmp32) 15102 { 15103 struct tnum t; 15104 u64 val; 15105 15106 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */ 15107 switch (opcode) { 15108 case BPF_JGE: 15109 case BPF_JGT: 15110 case BPF_JSGE: 15111 case BPF_JSGT: 15112 opcode = flip_opcode(opcode); 15113 swap(reg1, reg2); 15114 break; 15115 default: 15116 break; 15117 } 15118 15119 switch (opcode) { 15120 case BPF_JEQ: 15121 if (is_jmp32) { 15122 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 15123 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 15124 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 15125 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 15126 reg2->u32_min_value = reg1->u32_min_value; 15127 reg2->u32_max_value = reg1->u32_max_value; 15128 reg2->s32_min_value = reg1->s32_min_value; 15129 reg2->s32_max_value = reg1->s32_max_value; 15130 15131 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 15132 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15133 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 15134 } else { 15135 reg1->umin_value = max(reg1->umin_value, reg2->umin_value); 15136 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 15137 reg1->smin_value = max(reg1->smin_value, reg2->smin_value); 15138 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 15139 reg2->umin_value = reg1->umin_value; 15140 reg2->umax_value = reg1->umax_value; 15141 reg2->smin_value = reg1->smin_value; 15142 reg2->smax_value = reg1->smax_value; 15143 15144 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 15145 reg2->var_off = reg1->var_off; 15146 } 15147 break; 15148 case BPF_JNE: 15149 if (!is_reg_const(reg2, is_jmp32)) 15150 swap(reg1, reg2); 15151 if (!is_reg_const(reg2, is_jmp32)) 15152 break; 15153 15154 /* try to recompute the bound of reg1 if reg2 is a const and 15155 * is exactly the edge of reg1. 15156 */ 15157 val = reg_const_value(reg2, is_jmp32); 15158 if (is_jmp32) { 15159 /* u32_min_value is not equal to 0xffffffff at this point, 15160 * because otherwise u32_max_value is 0xffffffff as well, 15161 * in such a case both reg1 and reg2 would be constants, 15162 * jump would be predicted and reg_set_min_max() won't 15163 * be called. 15164 * 15165 * Same reasoning works for all {u,s}{min,max}{32,64} cases 15166 * below. 15167 */ 15168 if (reg1->u32_min_value == (u32)val) 15169 reg1->u32_min_value++; 15170 if (reg1->u32_max_value == (u32)val) 15171 reg1->u32_max_value--; 15172 if (reg1->s32_min_value == (s32)val) 15173 reg1->s32_min_value++; 15174 if (reg1->s32_max_value == (s32)val) 15175 reg1->s32_max_value--; 15176 } else { 15177 if (reg1->umin_value == (u64)val) 15178 reg1->umin_value++; 15179 if (reg1->umax_value == (u64)val) 15180 reg1->umax_value--; 15181 if (reg1->smin_value == (s64)val) 15182 reg1->smin_value++; 15183 if (reg1->smax_value == (s64)val) 15184 reg1->smax_value--; 15185 } 15186 break; 15187 case BPF_JSET: 15188 if (!is_reg_const(reg2, is_jmp32)) 15189 swap(reg1, reg2); 15190 if (!is_reg_const(reg2, is_jmp32)) 15191 break; 15192 val = reg_const_value(reg2, is_jmp32); 15193 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 15194 * requires single bit to learn something useful. E.g., if we 15195 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 15196 * are actually set? We can learn something definite only if 15197 * it's a single-bit value to begin with. 15198 * 15199 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 15200 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 15201 * bit 1 is set, which we can readily use in adjustments. 15202 */ 15203 if (!is_power_of_2(val)) 15204 break; 15205 if (is_jmp32) { 15206 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 15207 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15208 } else { 15209 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 15210 } 15211 break; 15212 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 15213 if (!is_reg_const(reg2, is_jmp32)) 15214 swap(reg1, reg2); 15215 if (!is_reg_const(reg2, is_jmp32)) 15216 break; 15217 val = reg_const_value(reg2, is_jmp32); 15218 if (is_jmp32) { 15219 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 15220 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15221 } else { 15222 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 15223 } 15224 break; 15225 case BPF_JLE: 15226 if (is_jmp32) { 15227 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 15228 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 15229 } else { 15230 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 15231 reg2->umin_value = max(reg1->umin_value, reg2->umin_value); 15232 } 15233 break; 15234 case BPF_JLT: 15235 if (is_jmp32) { 15236 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1); 15237 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value); 15238 } else { 15239 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1); 15240 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value); 15241 } 15242 break; 15243 case BPF_JSLE: 15244 if (is_jmp32) { 15245 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 15246 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 15247 } else { 15248 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 15249 reg2->smin_value = max(reg1->smin_value, reg2->smin_value); 15250 } 15251 break; 15252 case BPF_JSLT: 15253 if (is_jmp32) { 15254 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1); 15255 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value); 15256 } else { 15257 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1); 15258 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value); 15259 } 15260 break; 15261 default: 15262 return; 15263 } 15264 } 15265 15266 /* Adjusts the register min/max values in the case that the dst_reg and 15267 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K 15268 * check, in which case we have a fake SCALAR_VALUE representing insn->imm). 15269 * Technically we can do similar adjustments for pointers to the same object, 15270 * but we don't support that right now. 15271 */ 15272 static int reg_set_min_max(struct bpf_verifier_env *env, 15273 struct bpf_reg_state *true_reg1, 15274 struct bpf_reg_state *true_reg2, 15275 struct bpf_reg_state *false_reg1, 15276 struct bpf_reg_state *false_reg2, 15277 u8 opcode, bool is_jmp32) 15278 { 15279 int err; 15280 15281 /* If either register is a pointer, we can't learn anything about its 15282 * variable offset from the compare (unless they were a pointer into 15283 * the same object, but we don't bother with that). 15284 */ 15285 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE) 15286 return 0; 15287 15288 /* fallthrough (FALSE) branch */ 15289 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32); 15290 reg_bounds_sync(false_reg1); 15291 reg_bounds_sync(false_reg2); 15292 15293 /* jump (TRUE) branch */ 15294 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32); 15295 reg_bounds_sync(true_reg1); 15296 reg_bounds_sync(true_reg2); 15297 15298 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1"); 15299 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2"); 15300 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1"); 15301 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2"); 15302 return err; 15303 } 15304 15305 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 15306 struct bpf_reg_state *reg, u32 id, 15307 bool is_null) 15308 { 15309 if (type_may_be_null(reg->type) && reg->id == id && 15310 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 15311 /* Old offset (both fixed and variable parts) should have been 15312 * known-zero, because we don't allow pointer arithmetic on 15313 * pointers that might be NULL. If we see this happening, don't 15314 * convert the register. 15315 * 15316 * But in some cases, some helpers that return local kptrs 15317 * advance offset for the returned pointer. In those cases, it 15318 * is fine to expect to see reg->off. 15319 */ 15320 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 15321 return; 15322 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 15323 WARN_ON_ONCE(reg->off)) 15324 return; 15325 15326 if (is_null) { 15327 reg->type = SCALAR_VALUE; 15328 /* We don't need id and ref_obj_id from this point 15329 * onwards anymore, thus we should better reset it, 15330 * so that state pruning has chances to take effect. 15331 */ 15332 reg->id = 0; 15333 reg->ref_obj_id = 0; 15334 15335 return; 15336 } 15337 15338 mark_ptr_not_null_reg(reg); 15339 15340 if (!reg_may_point_to_spin_lock(reg)) { 15341 /* For not-NULL ptr, reg->ref_obj_id will be reset 15342 * in release_reference(). 15343 * 15344 * reg->id is still used by spin_lock ptr. Other 15345 * than spin_lock ptr type, reg->id can be reset. 15346 */ 15347 reg->id = 0; 15348 } 15349 } 15350 } 15351 15352 /* The logic is similar to find_good_pkt_pointers(), both could eventually 15353 * be folded together at some point. 15354 */ 15355 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 15356 bool is_null) 15357 { 15358 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 15359 struct bpf_reg_state *regs = state->regs, *reg; 15360 u32 ref_obj_id = regs[regno].ref_obj_id; 15361 u32 id = regs[regno].id; 15362 15363 if (ref_obj_id && ref_obj_id == id && is_null) 15364 /* regs[regno] is in the " == NULL" branch. 15365 * No one could have freed the reference state before 15366 * doing the NULL check. 15367 */ 15368 WARN_ON_ONCE(release_reference_state(state, id)); 15369 15370 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15371 mark_ptr_or_null_reg(state, reg, id, is_null); 15372 })); 15373 } 15374 15375 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 15376 struct bpf_reg_state *dst_reg, 15377 struct bpf_reg_state *src_reg, 15378 struct bpf_verifier_state *this_branch, 15379 struct bpf_verifier_state *other_branch) 15380 { 15381 if (BPF_SRC(insn->code) != BPF_X) 15382 return false; 15383 15384 /* Pointers are always 64-bit. */ 15385 if (BPF_CLASS(insn->code) == BPF_JMP32) 15386 return false; 15387 15388 switch (BPF_OP(insn->code)) { 15389 case BPF_JGT: 15390 if ((dst_reg->type == PTR_TO_PACKET && 15391 src_reg->type == PTR_TO_PACKET_END) || 15392 (dst_reg->type == PTR_TO_PACKET_META && 15393 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15394 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 15395 find_good_pkt_pointers(this_branch, dst_reg, 15396 dst_reg->type, false); 15397 mark_pkt_end(other_branch, insn->dst_reg, true); 15398 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15399 src_reg->type == PTR_TO_PACKET) || 15400 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15401 src_reg->type == PTR_TO_PACKET_META)) { 15402 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 15403 find_good_pkt_pointers(other_branch, src_reg, 15404 src_reg->type, true); 15405 mark_pkt_end(this_branch, insn->src_reg, false); 15406 } else { 15407 return false; 15408 } 15409 break; 15410 case BPF_JLT: 15411 if ((dst_reg->type == PTR_TO_PACKET && 15412 src_reg->type == PTR_TO_PACKET_END) || 15413 (dst_reg->type == PTR_TO_PACKET_META && 15414 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15415 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 15416 find_good_pkt_pointers(other_branch, dst_reg, 15417 dst_reg->type, true); 15418 mark_pkt_end(this_branch, insn->dst_reg, false); 15419 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15420 src_reg->type == PTR_TO_PACKET) || 15421 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15422 src_reg->type == PTR_TO_PACKET_META)) { 15423 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 15424 find_good_pkt_pointers(this_branch, src_reg, 15425 src_reg->type, false); 15426 mark_pkt_end(other_branch, insn->src_reg, true); 15427 } else { 15428 return false; 15429 } 15430 break; 15431 case BPF_JGE: 15432 if ((dst_reg->type == PTR_TO_PACKET && 15433 src_reg->type == PTR_TO_PACKET_END) || 15434 (dst_reg->type == PTR_TO_PACKET_META && 15435 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15436 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 15437 find_good_pkt_pointers(this_branch, dst_reg, 15438 dst_reg->type, true); 15439 mark_pkt_end(other_branch, insn->dst_reg, false); 15440 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15441 src_reg->type == PTR_TO_PACKET) || 15442 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15443 src_reg->type == PTR_TO_PACKET_META)) { 15444 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 15445 find_good_pkt_pointers(other_branch, src_reg, 15446 src_reg->type, false); 15447 mark_pkt_end(this_branch, insn->src_reg, true); 15448 } else { 15449 return false; 15450 } 15451 break; 15452 case BPF_JLE: 15453 if ((dst_reg->type == PTR_TO_PACKET && 15454 src_reg->type == PTR_TO_PACKET_END) || 15455 (dst_reg->type == PTR_TO_PACKET_META && 15456 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15457 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 15458 find_good_pkt_pointers(other_branch, dst_reg, 15459 dst_reg->type, false); 15460 mark_pkt_end(this_branch, insn->dst_reg, true); 15461 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15462 src_reg->type == PTR_TO_PACKET) || 15463 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15464 src_reg->type == PTR_TO_PACKET_META)) { 15465 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 15466 find_good_pkt_pointers(this_branch, src_reg, 15467 src_reg->type, true); 15468 mark_pkt_end(other_branch, insn->src_reg, false); 15469 } else { 15470 return false; 15471 } 15472 break; 15473 default: 15474 return false; 15475 } 15476 15477 return true; 15478 } 15479 15480 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg, 15481 u32 id, u32 frameno, u32 spi_or_reg, bool is_reg) 15482 { 15483 struct linked_reg *e; 15484 15485 if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id) 15486 return; 15487 15488 e = linked_regs_push(reg_set); 15489 if (e) { 15490 e->frameno = frameno; 15491 e->is_reg = is_reg; 15492 e->regno = spi_or_reg; 15493 } else { 15494 reg->id = 0; 15495 } 15496 } 15497 15498 /* For all R being scalar registers or spilled scalar registers 15499 * in verifier state, save R in linked_regs if R->id == id. 15500 * If there are too many Rs sharing same id, reset id for leftover Rs. 15501 */ 15502 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id, 15503 struct linked_regs *linked_regs) 15504 { 15505 struct bpf_func_state *func; 15506 struct bpf_reg_state *reg; 15507 int i, j; 15508 15509 id = id & ~BPF_ADD_CONST; 15510 for (i = vstate->curframe; i >= 0; i--) { 15511 func = vstate->frame[i]; 15512 for (j = 0; j < BPF_REG_FP; j++) { 15513 reg = &func->regs[j]; 15514 __collect_linked_regs(linked_regs, reg, id, i, j, true); 15515 } 15516 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 15517 if (!is_spilled_reg(&func->stack[j])) 15518 continue; 15519 reg = &func->stack[j].spilled_ptr; 15520 __collect_linked_regs(linked_regs, reg, id, i, j, false); 15521 } 15522 } 15523 } 15524 15525 /* For all R in linked_regs, copy known_reg range into R 15526 * if R->id == known_reg->id. 15527 */ 15528 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg, 15529 struct linked_regs *linked_regs) 15530 { 15531 struct bpf_reg_state fake_reg; 15532 struct bpf_reg_state *reg; 15533 struct linked_reg *e; 15534 int i; 15535 15536 for (i = 0; i < linked_regs->cnt; ++i) { 15537 e = &linked_regs->entries[i]; 15538 reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno] 15539 : &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr; 15540 if (reg->type != SCALAR_VALUE || reg == known_reg) 15541 continue; 15542 if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST)) 15543 continue; 15544 if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) || 15545 reg->off == known_reg->off) { 15546 s32 saved_subreg_def = reg->subreg_def; 15547 15548 copy_register_state(reg, known_reg); 15549 reg->subreg_def = saved_subreg_def; 15550 } else { 15551 s32 saved_subreg_def = reg->subreg_def; 15552 s32 saved_off = reg->off; 15553 15554 fake_reg.type = SCALAR_VALUE; 15555 __mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off); 15556 15557 /* reg = known_reg; reg += delta */ 15558 copy_register_state(reg, known_reg); 15559 /* 15560 * Must preserve off, id and add_const flag, 15561 * otherwise another sync_linked_regs() will be incorrect. 15562 */ 15563 reg->off = saved_off; 15564 reg->subreg_def = saved_subreg_def; 15565 15566 scalar32_min_max_add(reg, &fake_reg); 15567 scalar_min_max_add(reg, &fake_reg); 15568 reg->var_off = tnum_add(reg->var_off, fake_reg.var_off); 15569 } 15570 } 15571 } 15572 15573 static int check_cond_jmp_op(struct bpf_verifier_env *env, 15574 struct bpf_insn *insn, int *insn_idx) 15575 { 15576 struct bpf_verifier_state *this_branch = env->cur_state; 15577 struct bpf_verifier_state *other_branch; 15578 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 15579 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 15580 struct bpf_reg_state *eq_branch_regs; 15581 struct linked_regs linked_regs = {}; 15582 u8 opcode = BPF_OP(insn->code); 15583 bool is_jmp32; 15584 int pred = -1; 15585 int err; 15586 15587 /* Only conditional jumps are expected to reach here. */ 15588 if (opcode == BPF_JA || opcode > BPF_JCOND) { 15589 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 15590 return -EINVAL; 15591 } 15592 15593 if (opcode == BPF_JCOND) { 15594 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 15595 int idx = *insn_idx; 15596 15597 if (insn->code != (BPF_JMP | BPF_JCOND) || 15598 insn->src_reg != BPF_MAY_GOTO || 15599 insn->dst_reg || insn->imm || insn->off == 0) { 15600 verbose(env, "invalid may_goto off %d imm %d\n", 15601 insn->off, insn->imm); 15602 return -EINVAL; 15603 } 15604 prev_st = find_prev_entry(env, cur_st->parent, idx); 15605 15606 /* branch out 'fallthrough' insn as a new state to explore */ 15607 queued_st = push_stack(env, idx + 1, idx, false); 15608 if (!queued_st) 15609 return -ENOMEM; 15610 15611 queued_st->may_goto_depth++; 15612 if (prev_st) 15613 widen_imprecise_scalars(env, prev_st, queued_st); 15614 *insn_idx += insn->off; 15615 return 0; 15616 } 15617 15618 /* check src2 operand */ 15619 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15620 if (err) 15621 return err; 15622 15623 dst_reg = ®s[insn->dst_reg]; 15624 if (BPF_SRC(insn->code) == BPF_X) { 15625 if (insn->imm != 0) { 15626 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 15627 return -EINVAL; 15628 } 15629 15630 /* check src1 operand */ 15631 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15632 if (err) 15633 return err; 15634 15635 src_reg = ®s[insn->src_reg]; 15636 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 15637 is_pointer_value(env, insn->src_reg)) { 15638 verbose(env, "R%d pointer comparison prohibited\n", 15639 insn->src_reg); 15640 return -EACCES; 15641 } 15642 } else { 15643 if (insn->src_reg != BPF_REG_0) { 15644 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 15645 return -EINVAL; 15646 } 15647 src_reg = &env->fake_reg[0]; 15648 memset(src_reg, 0, sizeof(*src_reg)); 15649 src_reg->type = SCALAR_VALUE; 15650 __mark_reg_known(src_reg, insn->imm); 15651 } 15652 15653 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 15654 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32); 15655 if (pred >= 0) { 15656 /* If we get here with a dst_reg pointer type it is because 15657 * above is_branch_taken() special cased the 0 comparison. 15658 */ 15659 if (!__is_pointer_value(false, dst_reg)) 15660 err = mark_chain_precision(env, insn->dst_reg); 15661 if (BPF_SRC(insn->code) == BPF_X && !err && 15662 !__is_pointer_value(false, src_reg)) 15663 err = mark_chain_precision(env, insn->src_reg); 15664 if (err) 15665 return err; 15666 } 15667 15668 if (pred == 1) { 15669 /* Only follow the goto, ignore fall-through. If needed, push 15670 * the fall-through branch for simulation under speculative 15671 * execution. 15672 */ 15673 if (!env->bypass_spec_v1 && 15674 !sanitize_speculative_path(env, insn, *insn_idx + 1, 15675 *insn_idx)) 15676 return -EFAULT; 15677 if (env->log.level & BPF_LOG_LEVEL) 15678 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15679 *insn_idx += insn->off; 15680 return 0; 15681 } else if (pred == 0) { 15682 /* Only follow the fall-through branch, since that's where the 15683 * program will go. If needed, push the goto branch for 15684 * simulation under speculative execution. 15685 */ 15686 if (!env->bypass_spec_v1 && 15687 !sanitize_speculative_path(env, insn, 15688 *insn_idx + insn->off + 1, 15689 *insn_idx)) 15690 return -EFAULT; 15691 if (env->log.level & BPF_LOG_LEVEL) 15692 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15693 return 0; 15694 } 15695 15696 /* Push scalar registers sharing same ID to jump history, 15697 * do this before creating 'other_branch', so that both 15698 * 'this_branch' and 'other_branch' share this history 15699 * if parent state is created. 15700 */ 15701 if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id) 15702 collect_linked_regs(this_branch, src_reg->id, &linked_regs); 15703 if (dst_reg->type == SCALAR_VALUE && dst_reg->id) 15704 collect_linked_regs(this_branch, dst_reg->id, &linked_regs); 15705 if (linked_regs.cnt > 1) { 15706 err = push_insn_history(env, this_branch, 0, linked_regs_pack(&linked_regs)); 15707 if (err) 15708 return err; 15709 } 15710 15711 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 15712 false); 15713 if (!other_branch) 15714 return -EFAULT; 15715 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 15716 15717 if (BPF_SRC(insn->code) == BPF_X) { 15718 err = reg_set_min_max(env, 15719 &other_branch_regs[insn->dst_reg], 15720 &other_branch_regs[insn->src_reg], 15721 dst_reg, src_reg, opcode, is_jmp32); 15722 } else /* BPF_SRC(insn->code) == BPF_K */ { 15723 /* reg_set_min_max() can mangle the fake_reg. Make a copy 15724 * so that these are two different memory locations. The 15725 * src_reg is not used beyond here in context of K. 15726 */ 15727 memcpy(&env->fake_reg[1], &env->fake_reg[0], 15728 sizeof(env->fake_reg[0])); 15729 err = reg_set_min_max(env, 15730 &other_branch_regs[insn->dst_reg], 15731 &env->fake_reg[0], 15732 dst_reg, &env->fake_reg[1], 15733 opcode, is_jmp32); 15734 } 15735 if (err) 15736 return err; 15737 15738 if (BPF_SRC(insn->code) == BPF_X && 15739 src_reg->type == SCALAR_VALUE && src_reg->id && 15740 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 15741 sync_linked_regs(this_branch, src_reg, &linked_regs); 15742 sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs); 15743 } 15744 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 15745 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 15746 sync_linked_regs(this_branch, dst_reg, &linked_regs); 15747 sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs); 15748 } 15749 15750 /* if one pointer register is compared to another pointer 15751 * register check if PTR_MAYBE_NULL could be lifted. 15752 * E.g. register A - maybe null 15753 * register B - not null 15754 * for JNE A, B, ... - A is not null in the false branch; 15755 * for JEQ A, B, ... - A is not null in the true branch. 15756 * 15757 * Since PTR_TO_BTF_ID points to a kernel struct that does 15758 * not need to be null checked by the BPF program, i.e., 15759 * could be null even without PTR_MAYBE_NULL marking, so 15760 * only propagate nullness when neither reg is that type. 15761 */ 15762 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 15763 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 15764 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 15765 base_type(src_reg->type) != PTR_TO_BTF_ID && 15766 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 15767 eq_branch_regs = NULL; 15768 switch (opcode) { 15769 case BPF_JEQ: 15770 eq_branch_regs = other_branch_regs; 15771 break; 15772 case BPF_JNE: 15773 eq_branch_regs = regs; 15774 break; 15775 default: 15776 /* do nothing */ 15777 break; 15778 } 15779 if (eq_branch_regs) { 15780 if (type_may_be_null(src_reg->type)) 15781 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 15782 else 15783 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 15784 } 15785 } 15786 15787 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 15788 * NOTE: these optimizations below are related with pointer comparison 15789 * which will never be JMP32. 15790 */ 15791 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 15792 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 15793 type_may_be_null(dst_reg->type)) { 15794 /* Mark all identical registers in each branch as either 15795 * safe or unknown depending R == 0 or R != 0 conditional. 15796 */ 15797 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 15798 opcode == BPF_JNE); 15799 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 15800 opcode == BPF_JEQ); 15801 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 15802 this_branch, other_branch) && 15803 is_pointer_value(env, insn->dst_reg)) { 15804 verbose(env, "R%d pointer comparison prohibited\n", 15805 insn->dst_reg); 15806 return -EACCES; 15807 } 15808 if (env->log.level & BPF_LOG_LEVEL) 15809 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15810 return 0; 15811 } 15812 15813 /* verify BPF_LD_IMM64 instruction */ 15814 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 15815 { 15816 struct bpf_insn_aux_data *aux = cur_aux(env); 15817 struct bpf_reg_state *regs = cur_regs(env); 15818 struct bpf_reg_state *dst_reg; 15819 struct bpf_map *map; 15820 int err; 15821 15822 if (BPF_SIZE(insn->code) != BPF_DW) { 15823 verbose(env, "invalid BPF_LD_IMM insn\n"); 15824 return -EINVAL; 15825 } 15826 if (insn->off != 0) { 15827 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 15828 return -EINVAL; 15829 } 15830 15831 err = check_reg_arg(env, insn->dst_reg, DST_OP); 15832 if (err) 15833 return err; 15834 15835 dst_reg = ®s[insn->dst_reg]; 15836 if (insn->src_reg == 0) { 15837 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 15838 15839 dst_reg->type = SCALAR_VALUE; 15840 __mark_reg_known(®s[insn->dst_reg], imm); 15841 return 0; 15842 } 15843 15844 /* All special src_reg cases are listed below. From this point onwards 15845 * we either succeed and assign a corresponding dst_reg->type after 15846 * zeroing the offset, or fail and reject the program. 15847 */ 15848 mark_reg_known_zero(env, regs, insn->dst_reg); 15849 15850 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 15851 dst_reg->type = aux->btf_var.reg_type; 15852 switch (base_type(dst_reg->type)) { 15853 case PTR_TO_MEM: 15854 dst_reg->mem_size = aux->btf_var.mem_size; 15855 break; 15856 case PTR_TO_BTF_ID: 15857 dst_reg->btf = aux->btf_var.btf; 15858 dst_reg->btf_id = aux->btf_var.btf_id; 15859 break; 15860 default: 15861 verbose(env, "bpf verifier is misconfigured\n"); 15862 return -EFAULT; 15863 } 15864 return 0; 15865 } 15866 15867 if (insn->src_reg == BPF_PSEUDO_FUNC) { 15868 struct bpf_prog_aux *aux = env->prog->aux; 15869 u32 subprogno = find_subprog(env, 15870 env->insn_idx + insn->imm + 1); 15871 15872 if (!aux->func_info) { 15873 verbose(env, "missing btf func_info\n"); 15874 return -EINVAL; 15875 } 15876 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 15877 verbose(env, "callback function not static\n"); 15878 return -EINVAL; 15879 } 15880 15881 dst_reg->type = PTR_TO_FUNC; 15882 dst_reg->subprogno = subprogno; 15883 return 0; 15884 } 15885 15886 map = env->used_maps[aux->map_index]; 15887 dst_reg->map_ptr = map; 15888 15889 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 15890 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 15891 if (map->map_type == BPF_MAP_TYPE_ARENA) { 15892 __mark_reg_unknown(env, dst_reg); 15893 return 0; 15894 } 15895 dst_reg->type = PTR_TO_MAP_VALUE; 15896 dst_reg->off = aux->map_off; 15897 WARN_ON_ONCE(map->max_entries != 1); 15898 /* We want reg->id to be same (0) as map_value is not distinct */ 15899 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 15900 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 15901 dst_reg->type = CONST_PTR_TO_MAP; 15902 } else { 15903 verbose(env, "bpf verifier is misconfigured\n"); 15904 return -EINVAL; 15905 } 15906 15907 return 0; 15908 } 15909 15910 static bool may_access_skb(enum bpf_prog_type type) 15911 { 15912 switch (type) { 15913 case BPF_PROG_TYPE_SOCKET_FILTER: 15914 case BPF_PROG_TYPE_SCHED_CLS: 15915 case BPF_PROG_TYPE_SCHED_ACT: 15916 return true; 15917 default: 15918 return false; 15919 } 15920 } 15921 15922 /* verify safety of LD_ABS|LD_IND instructions: 15923 * - they can only appear in the programs where ctx == skb 15924 * - since they are wrappers of function calls, they scratch R1-R5 registers, 15925 * preserve R6-R9, and store return value into R0 15926 * 15927 * Implicit input: 15928 * ctx == skb == R6 == CTX 15929 * 15930 * Explicit input: 15931 * SRC == any register 15932 * IMM == 32-bit immediate 15933 * 15934 * Output: 15935 * R0 - 8/16/32-bit skb data converted to cpu endianness 15936 */ 15937 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 15938 { 15939 struct bpf_reg_state *regs = cur_regs(env); 15940 static const int ctx_reg = BPF_REG_6; 15941 u8 mode = BPF_MODE(insn->code); 15942 int i, err; 15943 15944 if (!may_access_skb(resolve_prog_type(env->prog))) { 15945 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 15946 return -EINVAL; 15947 } 15948 15949 if (!env->ops->gen_ld_abs) { 15950 verbose(env, "bpf verifier is misconfigured\n"); 15951 return -EINVAL; 15952 } 15953 15954 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 15955 BPF_SIZE(insn->code) == BPF_DW || 15956 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 15957 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 15958 return -EINVAL; 15959 } 15960 15961 /* check whether implicit source operand (register R6) is readable */ 15962 err = check_reg_arg(env, ctx_reg, SRC_OP); 15963 if (err) 15964 return err; 15965 15966 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 15967 * gen_ld_abs() may terminate the program at runtime, leading to 15968 * reference leak. 15969 */ 15970 err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]"); 15971 if (err) 15972 return err; 15973 15974 if (regs[ctx_reg].type != PTR_TO_CTX) { 15975 verbose(env, 15976 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 15977 return -EINVAL; 15978 } 15979 15980 if (mode == BPF_IND) { 15981 /* check explicit source operand */ 15982 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15983 if (err) 15984 return err; 15985 } 15986 15987 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 15988 if (err < 0) 15989 return err; 15990 15991 /* reset caller saved regs to unreadable */ 15992 for (i = 0; i < CALLER_SAVED_REGS; i++) { 15993 mark_reg_not_init(env, regs, caller_saved[i]); 15994 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 15995 } 15996 15997 /* mark destination R0 register as readable, since it contains 15998 * the value fetched from the packet. 15999 * Already marked as written above. 16000 */ 16001 mark_reg_unknown(env, regs, BPF_REG_0); 16002 /* ld_abs load up to 32-bit skb data. */ 16003 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 16004 return 0; 16005 } 16006 16007 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 16008 { 16009 const char *exit_ctx = "At program exit"; 16010 struct tnum enforce_attach_type_range = tnum_unknown; 16011 const struct bpf_prog *prog = env->prog; 16012 struct bpf_reg_state *reg; 16013 struct bpf_retval_range range = retval_range(0, 1); 16014 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 16015 int err; 16016 struct bpf_func_state *frame = env->cur_state->frame[0]; 16017 const bool is_subprog = frame->subprogno; 16018 bool return_32bit = false; 16019 16020 /* LSM and struct_ops func-ptr's return type could be "void" */ 16021 if (!is_subprog || frame->in_exception_callback_fn) { 16022 switch (prog_type) { 16023 case BPF_PROG_TYPE_LSM: 16024 if (prog->expected_attach_type == BPF_LSM_CGROUP) 16025 /* See below, can be 0 or 0-1 depending on hook. */ 16026 break; 16027 fallthrough; 16028 case BPF_PROG_TYPE_STRUCT_OPS: 16029 if (!prog->aux->attach_func_proto->type) 16030 return 0; 16031 break; 16032 default: 16033 break; 16034 } 16035 } 16036 16037 /* eBPF calling convention is such that R0 is used 16038 * to return the value from eBPF program. 16039 * Make sure that it's readable at this time 16040 * of bpf_exit, which means that program wrote 16041 * something into it earlier 16042 */ 16043 err = check_reg_arg(env, regno, SRC_OP); 16044 if (err) 16045 return err; 16046 16047 if (is_pointer_value(env, regno)) { 16048 verbose(env, "R%d leaks addr as return value\n", regno); 16049 return -EACCES; 16050 } 16051 16052 reg = cur_regs(env) + regno; 16053 16054 if (frame->in_async_callback_fn) { 16055 /* enforce return zero from async callbacks like timer */ 16056 exit_ctx = "At async callback return"; 16057 range = retval_range(0, 0); 16058 goto enforce_retval; 16059 } 16060 16061 if (is_subprog && !frame->in_exception_callback_fn) { 16062 if (reg->type != SCALAR_VALUE) { 16063 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 16064 regno, reg_type_str(env, reg->type)); 16065 return -EINVAL; 16066 } 16067 return 0; 16068 } 16069 16070 switch (prog_type) { 16071 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 16072 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 16073 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 16074 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG || 16075 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 16076 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 16077 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME || 16078 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 16079 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME || 16080 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME) 16081 range = retval_range(1, 1); 16082 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 16083 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 16084 range = retval_range(0, 3); 16085 break; 16086 case BPF_PROG_TYPE_CGROUP_SKB: 16087 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 16088 range = retval_range(0, 3); 16089 enforce_attach_type_range = tnum_range(2, 3); 16090 } 16091 break; 16092 case BPF_PROG_TYPE_CGROUP_SOCK: 16093 case BPF_PROG_TYPE_SOCK_OPS: 16094 case BPF_PROG_TYPE_CGROUP_DEVICE: 16095 case BPF_PROG_TYPE_CGROUP_SYSCTL: 16096 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 16097 break; 16098 case BPF_PROG_TYPE_RAW_TRACEPOINT: 16099 if (!env->prog->aux->attach_btf_id) 16100 return 0; 16101 range = retval_range(0, 0); 16102 break; 16103 case BPF_PROG_TYPE_TRACING: 16104 switch (env->prog->expected_attach_type) { 16105 case BPF_TRACE_FENTRY: 16106 case BPF_TRACE_FEXIT: 16107 range = retval_range(0, 0); 16108 break; 16109 case BPF_TRACE_RAW_TP: 16110 case BPF_MODIFY_RETURN: 16111 return 0; 16112 case BPF_TRACE_ITER: 16113 break; 16114 default: 16115 return -ENOTSUPP; 16116 } 16117 break; 16118 case BPF_PROG_TYPE_KPROBE: 16119 switch (env->prog->expected_attach_type) { 16120 case BPF_TRACE_KPROBE_SESSION: 16121 case BPF_TRACE_UPROBE_SESSION: 16122 range = retval_range(0, 1); 16123 break; 16124 default: 16125 return 0; 16126 } 16127 break; 16128 case BPF_PROG_TYPE_SK_LOOKUP: 16129 range = retval_range(SK_DROP, SK_PASS); 16130 break; 16131 16132 case BPF_PROG_TYPE_LSM: 16133 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 16134 /* no range found, any return value is allowed */ 16135 if (!get_func_retval_range(env->prog, &range)) 16136 return 0; 16137 /* no restricted range, any return value is allowed */ 16138 if (range.minval == S32_MIN && range.maxval == S32_MAX) 16139 return 0; 16140 return_32bit = true; 16141 } else if (!env->prog->aux->attach_func_proto->type) { 16142 /* Make sure programs that attach to void 16143 * hooks don't try to modify return value. 16144 */ 16145 range = retval_range(1, 1); 16146 } 16147 break; 16148 16149 case BPF_PROG_TYPE_NETFILTER: 16150 range = retval_range(NF_DROP, NF_ACCEPT); 16151 break; 16152 case BPF_PROG_TYPE_EXT: 16153 /* freplace program can return anything as its return value 16154 * depends on the to-be-replaced kernel func or bpf program. 16155 */ 16156 default: 16157 return 0; 16158 } 16159 16160 enforce_retval: 16161 if (reg->type != SCALAR_VALUE) { 16162 verbose(env, "%s the register R%d is not a known value (%s)\n", 16163 exit_ctx, regno, reg_type_str(env, reg->type)); 16164 return -EINVAL; 16165 } 16166 16167 err = mark_chain_precision(env, regno); 16168 if (err) 16169 return err; 16170 16171 if (!retval_range_within(range, reg, return_32bit)) { 16172 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 16173 if (!is_subprog && 16174 prog->expected_attach_type == BPF_LSM_CGROUP && 16175 prog_type == BPF_PROG_TYPE_LSM && 16176 !prog->aux->attach_func_proto->type) 16177 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 16178 return -EINVAL; 16179 } 16180 16181 if (!tnum_is_unknown(enforce_attach_type_range) && 16182 tnum_in(enforce_attach_type_range, reg->var_off)) 16183 env->prog->enforce_expected_attach_type = 1; 16184 return 0; 16185 } 16186 16187 static void mark_subprog_changes_pkt_data(struct bpf_verifier_env *env, int off) 16188 { 16189 struct bpf_subprog_info *subprog; 16190 16191 subprog = find_containing_subprog(env, off); 16192 subprog->changes_pkt_data = true; 16193 } 16194 16195 /* 't' is an index of a call-site. 16196 * 'w' is a callee entry point. 16197 * Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED. 16198 * Rely on DFS traversal order and absence of recursive calls to guarantee that 16199 * callee's change_pkt_data marks would be correct at that moment. 16200 */ 16201 static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w) 16202 { 16203 struct bpf_subprog_info *caller, *callee; 16204 16205 caller = find_containing_subprog(env, t); 16206 callee = find_containing_subprog(env, w); 16207 caller->changes_pkt_data |= callee->changes_pkt_data; 16208 } 16209 16210 /* non-recursive DFS pseudo code 16211 * 1 procedure DFS-iterative(G,v): 16212 * 2 label v as discovered 16213 * 3 let S be a stack 16214 * 4 S.push(v) 16215 * 5 while S is not empty 16216 * 6 t <- S.peek() 16217 * 7 if t is what we're looking for: 16218 * 8 return t 16219 * 9 for all edges e in G.adjacentEdges(t) do 16220 * 10 if edge e is already labelled 16221 * 11 continue with the next edge 16222 * 12 w <- G.adjacentVertex(t,e) 16223 * 13 if vertex w is not discovered and not explored 16224 * 14 label e as tree-edge 16225 * 15 label w as discovered 16226 * 16 S.push(w) 16227 * 17 continue at 5 16228 * 18 else if vertex w is discovered 16229 * 19 label e as back-edge 16230 * 20 else 16231 * 21 // vertex w is explored 16232 * 22 label e as forward- or cross-edge 16233 * 23 label t as explored 16234 * 24 S.pop() 16235 * 16236 * convention: 16237 * 0x10 - discovered 16238 * 0x11 - discovered and fall-through edge labelled 16239 * 0x12 - discovered and fall-through and branch edges labelled 16240 * 0x20 - explored 16241 */ 16242 16243 enum { 16244 DISCOVERED = 0x10, 16245 EXPLORED = 0x20, 16246 FALLTHROUGH = 1, 16247 BRANCH = 2, 16248 }; 16249 16250 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 16251 { 16252 env->insn_aux_data[idx].prune_point = true; 16253 } 16254 16255 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 16256 { 16257 return env->insn_aux_data[insn_idx].prune_point; 16258 } 16259 16260 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 16261 { 16262 env->insn_aux_data[idx].force_checkpoint = true; 16263 } 16264 16265 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 16266 { 16267 return env->insn_aux_data[insn_idx].force_checkpoint; 16268 } 16269 16270 static void mark_calls_callback(struct bpf_verifier_env *env, int idx) 16271 { 16272 env->insn_aux_data[idx].calls_callback = true; 16273 } 16274 16275 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx) 16276 { 16277 return env->insn_aux_data[insn_idx].calls_callback; 16278 } 16279 16280 enum { 16281 DONE_EXPLORING = 0, 16282 KEEP_EXPLORING = 1, 16283 }; 16284 16285 /* t, w, e - match pseudo-code above: 16286 * t - index of current instruction 16287 * w - next instruction 16288 * e - edge 16289 */ 16290 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 16291 { 16292 int *insn_stack = env->cfg.insn_stack; 16293 int *insn_state = env->cfg.insn_state; 16294 16295 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 16296 return DONE_EXPLORING; 16297 16298 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 16299 return DONE_EXPLORING; 16300 16301 if (w < 0 || w >= env->prog->len) { 16302 verbose_linfo(env, t, "%d: ", t); 16303 verbose(env, "jump out of range from insn %d to %d\n", t, w); 16304 return -EINVAL; 16305 } 16306 16307 if (e == BRANCH) { 16308 /* mark branch target for state pruning */ 16309 mark_prune_point(env, w); 16310 mark_jmp_point(env, w); 16311 } 16312 16313 if (insn_state[w] == 0) { 16314 /* tree-edge */ 16315 insn_state[t] = DISCOVERED | e; 16316 insn_state[w] = DISCOVERED; 16317 if (env->cfg.cur_stack >= env->prog->len) 16318 return -E2BIG; 16319 insn_stack[env->cfg.cur_stack++] = w; 16320 return KEEP_EXPLORING; 16321 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 16322 if (env->bpf_capable) 16323 return DONE_EXPLORING; 16324 verbose_linfo(env, t, "%d: ", t); 16325 verbose_linfo(env, w, "%d: ", w); 16326 verbose(env, "back-edge from insn %d to %d\n", t, w); 16327 return -EINVAL; 16328 } else if (insn_state[w] == EXPLORED) { 16329 /* forward- or cross-edge */ 16330 insn_state[t] = DISCOVERED | e; 16331 } else { 16332 verbose(env, "insn state internal bug\n"); 16333 return -EFAULT; 16334 } 16335 return DONE_EXPLORING; 16336 } 16337 16338 static int visit_func_call_insn(int t, struct bpf_insn *insns, 16339 struct bpf_verifier_env *env, 16340 bool visit_callee) 16341 { 16342 int ret, insn_sz; 16343 int w; 16344 16345 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 16346 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 16347 if (ret) 16348 return ret; 16349 16350 mark_prune_point(env, t + insn_sz); 16351 /* when we exit from subprog, we need to record non-linear history */ 16352 mark_jmp_point(env, t + insn_sz); 16353 16354 if (visit_callee) { 16355 w = t + insns[t].imm + 1; 16356 mark_prune_point(env, t); 16357 merge_callee_effects(env, t, w); 16358 ret = push_insn(t, w, BRANCH, env); 16359 } 16360 return ret; 16361 } 16362 16363 /* Bitmask with 1s for all caller saved registers */ 16364 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 16365 16366 /* Return a bitmask specifying which caller saved registers are 16367 * clobbered by a call to a helper *as if* this helper follows 16368 * bpf_fastcall contract: 16369 * - includes R0 if function is non-void; 16370 * - includes R1-R5 if corresponding parameter has is described 16371 * in the function prototype. 16372 */ 16373 static u32 helper_fastcall_clobber_mask(const struct bpf_func_proto *fn) 16374 { 16375 u32 mask; 16376 int i; 16377 16378 mask = 0; 16379 if (fn->ret_type != RET_VOID) 16380 mask |= BIT(BPF_REG_0); 16381 for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) 16382 if (fn->arg_type[i] != ARG_DONTCARE) 16383 mask |= BIT(BPF_REG_1 + i); 16384 return mask; 16385 } 16386 16387 /* True if do_misc_fixups() replaces calls to helper number 'imm', 16388 * replacement patch is presumed to follow bpf_fastcall contract 16389 * (see mark_fastcall_pattern_for_call() below). 16390 */ 16391 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm) 16392 { 16393 switch (imm) { 16394 #ifdef CONFIG_X86_64 16395 case BPF_FUNC_get_smp_processor_id: 16396 return env->prog->jit_requested && bpf_jit_supports_percpu_insn(); 16397 #endif 16398 default: 16399 return false; 16400 } 16401 } 16402 16403 /* Same as helper_fastcall_clobber_mask() but for kfuncs, see comment above */ 16404 static u32 kfunc_fastcall_clobber_mask(struct bpf_kfunc_call_arg_meta *meta) 16405 { 16406 u32 vlen, i, mask; 16407 16408 vlen = btf_type_vlen(meta->func_proto); 16409 mask = 0; 16410 if (!btf_type_is_void(btf_type_by_id(meta->btf, meta->func_proto->type))) 16411 mask |= BIT(BPF_REG_0); 16412 for (i = 0; i < vlen; ++i) 16413 mask |= BIT(BPF_REG_1 + i); 16414 return mask; 16415 } 16416 16417 /* Same as verifier_inlines_helper_call() but for kfuncs, see comment above */ 16418 static bool is_fastcall_kfunc_call(struct bpf_kfunc_call_arg_meta *meta) 16419 { 16420 return meta->kfunc_flags & KF_FASTCALL; 16421 } 16422 16423 /* LLVM define a bpf_fastcall function attribute. 16424 * This attribute means that function scratches only some of 16425 * the caller saved registers defined by ABI. 16426 * For BPF the set of such registers could be defined as follows: 16427 * - R0 is scratched only if function is non-void; 16428 * - R1-R5 are scratched only if corresponding parameter type is defined 16429 * in the function prototype. 16430 * 16431 * The contract between kernel and clang allows to simultaneously use 16432 * such functions and maintain backwards compatibility with old 16433 * kernels that don't understand bpf_fastcall calls: 16434 * 16435 * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5 16436 * registers are not scratched by the call; 16437 * 16438 * - as a post-processing step, clang visits each bpf_fastcall call and adds 16439 * spill/fill for every live r0-r5; 16440 * 16441 * - stack offsets used for the spill/fill are allocated as lowest 16442 * stack offsets in whole function and are not used for any other 16443 * purposes; 16444 * 16445 * - when kernel loads a program, it looks for such patterns 16446 * (bpf_fastcall function surrounded by spills/fills) and checks if 16447 * spill/fill stack offsets are used exclusively in fastcall patterns; 16448 * 16449 * - if so, and if verifier or current JIT inlines the call to the 16450 * bpf_fastcall function (e.g. a helper call), kernel removes unnecessary 16451 * spill/fill pairs; 16452 * 16453 * - when old kernel loads a program, presence of spill/fill pairs 16454 * keeps BPF program valid, albeit slightly less efficient. 16455 * 16456 * For example: 16457 * 16458 * r1 = 1; 16459 * r2 = 2; 16460 * *(u64 *)(r10 - 8) = r1; r1 = 1; 16461 * *(u64 *)(r10 - 16) = r2; r2 = 2; 16462 * call %[to_be_inlined] --> call %[to_be_inlined] 16463 * r2 = *(u64 *)(r10 - 16); r0 = r1; 16464 * r1 = *(u64 *)(r10 - 8); r0 += r2; 16465 * r0 = r1; exit; 16466 * r0 += r2; 16467 * exit; 16468 * 16469 * The purpose of mark_fastcall_pattern_for_call is to: 16470 * - look for such patterns; 16471 * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern; 16472 * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction; 16473 * - update env->subprog_info[*]->fastcall_stack_off to find an offset 16474 * at which bpf_fastcall spill/fill stack slots start; 16475 * - update env->subprog_info[*]->keep_fastcall_stack. 16476 * 16477 * The .fastcall_pattern and .fastcall_stack_off are used by 16478 * check_fastcall_stack_contract() to check if every stack access to 16479 * fastcall spill/fill stack slot originates from spill/fill 16480 * instructions, members of fastcall patterns. 16481 * 16482 * If such condition holds true for a subprogram, fastcall patterns could 16483 * be rewritten by remove_fastcall_spills_fills(). 16484 * Otherwise bpf_fastcall patterns are not changed in the subprogram 16485 * (code, presumably, generated by an older clang version). 16486 * 16487 * For example, it is *not* safe to remove spill/fill below: 16488 * 16489 * r1 = 1; 16490 * *(u64 *)(r10 - 8) = r1; r1 = 1; 16491 * call %[to_be_inlined] --> call %[to_be_inlined] 16492 * r1 = *(u64 *)(r10 - 8); r0 = *(u64 *)(r10 - 8); <---- wrong !!! 16493 * r0 = *(u64 *)(r10 - 8); r0 += r1; 16494 * r0 += r1; exit; 16495 * exit; 16496 */ 16497 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env, 16498 struct bpf_subprog_info *subprog, 16499 int insn_idx, s16 lowest_off) 16500 { 16501 struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx; 16502 struct bpf_insn *call = &env->prog->insnsi[insn_idx]; 16503 const struct bpf_func_proto *fn; 16504 u32 clobbered_regs_mask = ALL_CALLER_SAVED_REGS; 16505 u32 expected_regs_mask; 16506 bool can_be_inlined = false; 16507 s16 off; 16508 int i; 16509 16510 if (bpf_helper_call(call)) { 16511 if (get_helper_proto(env, call->imm, &fn) < 0) 16512 /* error would be reported later */ 16513 return; 16514 clobbered_regs_mask = helper_fastcall_clobber_mask(fn); 16515 can_be_inlined = fn->allow_fastcall && 16516 (verifier_inlines_helper_call(env, call->imm) || 16517 bpf_jit_inlines_helper_call(call->imm)); 16518 } 16519 16520 if (bpf_pseudo_kfunc_call(call)) { 16521 struct bpf_kfunc_call_arg_meta meta; 16522 int err; 16523 16524 err = fetch_kfunc_meta(env, call, &meta, NULL); 16525 if (err < 0) 16526 /* error would be reported later */ 16527 return; 16528 16529 clobbered_regs_mask = kfunc_fastcall_clobber_mask(&meta); 16530 can_be_inlined = is_fastcall_kfunc_call(&meta); 16531 } 16532 16533 if (clobbered_regs_mask == ALL_CALLER_SAVED_REGS) 16534 return; 16535 16536 /* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */ 16537 expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS; 16538 16539 /* match pairs of form: 16540 * 16541 * *(u64 *)(r10 - Y) = rX (where Y % 8 == 0) 16542 * ... 16543 * call %[to_be_inlined] 16544 * ... 16545 * rX = *(u64 *)(r10 - Y) 16546 */ 16547 for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) { 16548 if (insn_idx - i < 0 || insn_idx + i >= env->prog->len) 16549 break; 16550 stx = &insns[insn_idx - i]; 16551 ldx = &insns[insn_idx + i]; 16552 /* must be a stack spill/fill pair */ 16553 if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) || 16554 ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) || 16555 stx->dst_reg != BPF_REG_10 || 16556 ldx->src_reg != BPF_REG_10) 16557 break; 16558 /* must be a spill/fill for the same reg */ 16559 if (stx->src_reg != ldx->dst_reg) 16560 break; 16561 /* must be one of the previously unseen registers */ 16562 if ((BIT(stx->src_reg) & expected_regs_mask) == 0) 16563 break; 16564 /* must be a spill/fill for the same expected offset, 16565 * no need to check offset alignment, BPF_DW stack access 16566 * is always 8-byte aligned. 16567 */ 16568 if (stx->off != off || ldx->off != off) 16569 break; 16570 expected_regs_mask &= ~BIT(stx->src_reg); 16571 env->insn_aux_data[insn_idx - i].fastcall_pattern = 1; 16572 env->insn_aux_data[insn_idx + i].fastcall_pattern = 1; 16573 } 16574 if (i == 1) 16575 return; 16576 16577 /* Conditionally set 'fastcall_spills_num' to allow forward 16578 * compatibility when more helper functions are marked as 16579 * bpf_fastcall at compile time than current kernel supports, e.g: 16580 * 16581 * 1: *(u64 *)(r10 - 8) = r1 16582 * 2: call A ;; assume A is bpf_fastcall for current kernel 16583 * 3: r1 = *(u64 *)(r10 - 8) 16584 * 4: *(u64 *)(r10 - 8) = r1 16585 * 5: call B ;; assume B is not bpf_fastcall for current kernel 16586 * 6: r1 = *(u64 *)(r10 - 8) 16587 * 16588 * There is no need to block bpf_fastcall rewrite for such program. 16589 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy, 16590 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills() 16591 * does not remove spill/fill pair {4,6}. 16592 */ 16593 if (can_be_inlined) 16594 env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1; 16595 else 16596 subprog->keep_fastcall_stack = 1; 16597 subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off); 16598 } 16599 16600 static int mark_fastcall_patterns(struct bpf_verifier_env *env) 16601 { 16602 struct bpf_subprog_info *subprog = env->subprog_info; 16603 struct bpf_insn *insn; 16604 s16 lowest_off; 16605 int s, i; 16606 16607 for (s = 0; s < env->subprog_cnt; ++s, ++subprog) { 16608 /* find lowest stack spill offset used in this subprog */ 16609 lowest_off = 0; 16610 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 16611 insn = env->prog->insnsi + i; 16612 if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) || 16613 insn->dst_reg != BPF_REG_10) 16614 continue; 16615 lowest_off = min(lowest_off, insn->off); 16616 } 16617 /* use this offset to find fastcall patterns */ 16618 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 16619 insn = env->prog->insnsi + i; 16620 if (insn->code != (BPF_JMP | BPF_CALL)) 16621 continue; 16622 mark_fastcall_pattern_for_call(env, subprog, i, lowest_off); 16623 } 16624 } 16625 return 0; 16626 } 16627 16628 /* Visits the instruction at index t and returns one of the following: 16629 * < 0 - an error occurred 16630 * DONE_EXPLORING - the instruction was fully explored 16631 * KEEP_EXPLORING - there is still work to be done before it is fully explored 16632 */ 16633 static int visit_insn(int t, struct bpf_verifier_env *env) 16634 { 16635 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 16636 int ret, off, insn_sz; 16637 16638 if (bpf_pseudo_func(insn)) 16639 return visit_func_call_insn(t, insns, env, true); 16640 16641 /* All non-branch instructions have a single fall-through edge. */ 16642 if (BPF_CLASS(insn->code) != BPF_JMP && 16643 BPF_CLASS(insn->code) != BPF_JMP32) { 16644 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 16645 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 16646 } 16647 16648 switch (BPF_OP(insn->code)) { 16649 case BPF_EXIT: 16650 return DONE_EXPLORING; 16651 16652 case BPF_CALL: 16653 if (is_async_callback_calling_insn(insn)) 16654 /* Mark this call insn as a prune point to trigger 16655 * is_state_visited() check before call itself is 16656 * processed by __check_func_call(). Otherwise new 16657 * async state will be pushed for further exploration. 16658 */ 16659 mark_prune_point(env, t); 16660 /* For functions that invoke callbacks it is not known how many times 16661 * callback would be called. Verifier models callback calling functions 16662 * by repeatedly visiting callback bodies and returning to origin call 16663 * instruction. 16664 * In order to stop such iteration verifier needs to identify when a 16665 * state identical some state from a previous iteration is reached. 16666 * Check below forces creation of checkpoint before callback calling 16667 * instruction to allow search for such identical states. 16668 */ 16669 if (is_sync_callback_calling_insn(insn)) { 16670 mark_calls_callback(env, t); 16671 mark_force_checkpoint(env, t); 16672 mark_prune_point(env, t); 16673 mark_jmp_point(env, t); 16674 } 16675 if (bpf_helper_call(insn) && bpf_helper_changes_pkt_data(insn->imm)) 16676 mark_subprog_changes_pkt_data(env, t); 16677 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 16678 struct bpf_kfunc_call_arg_meta meta; 16679 16680 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 16681 if (ret == 0 && is_iter_next_kfunc(&meta)) { 16682 mark_prune_point(env, t); 16683 /* Checking and saving state checkpoints at iter_next() call 16684 * is crucial for fast convergence of open-coded iterator loop 16685 * logic, so we need to force it. If we don't do that, 16686 * is_state_visited() might skip saving a checkpoint, causing 16687 * unnecessarily long sequence of not checkpointed 16688 * instructions and jumps, leading to exhaustion of jump 16689 * history buffer, and potentially other undesired outcomes. 16690 * It is expected that with correct open-coded iterators 16691 * convergence will happen quickly, so we don't run a risk of 16692 * exhausting memory. 16693 */ 16694 mark_force_checkpoint(env, t); 16695 } 16696 } 16697 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 16698 16699 case BPF_JA: 16700 if (BPF_SRC(insn->code) != BPF_K) 16701 return -EINVAL; 16702 16703 if (BPF_CLASS(insn->code) == BPF_JMP) 16704 off = insn->off; 16705 else 16706 off = insn->imm; 16707 16708 /* unconditional jump with single edge */ 16709 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 16710 if (ret) 16711 return ret; 16712 16713 mark_prune_point(env, t + off + 1); 16714 mark_jmp_point(env, t + off + 1); 16715 16716 return ret; 16717 16718 default: 16719 /* conditional jump with two edges */ 16720 mark_prune_point(env, t); 16721 if (is_may_goto_insn(insn)) 16722 mark_force_checkpoint(env, t); 16723 16724 ret = push_insn(t, t + 1, FALLTHROUGH, env); 16725 if (ret) 16726 return ret; 16727 16728 return push_insn(t, t + insn->off + 1, BRANCH, env); 16729 } 16730 } 16731 16732 /* non-recursive depth-first-search to detect loops in BPF program 16733 * loop == back-edge in directed graph 16734 */ 16735 static int check_cfg(struct bpf_verifier_env *env) 16736 { 16737 int insn_cnt = env->prog->len; 16738 int *insn_stack, *insn_state; 16739 int ex_insn_beg, i, ret = 0; 16740 bool ex_done = false; 16741 16742 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 16743 if (!insn_state) 16744 return -ENOMEM; 16745 16746 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 16747 if (!insn_stack) { 16748 kvfree(insn_state); 16749 return -ENOMEM; 16750 } 16751 16752 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 16753 insn_stack[0] = 0; /* 0 is the first instruction */ 16754 env->cfg.cur_stack = 1; 16755 16756 walk_cfg: 16757 while (env->cfg.cur_stack > 0) { 16758 int t = insn_stack[env->cfg.cur_stack - 1]; 16759 16760 ret = visit_insn(t, env); 16761 switch (ret) { 16762 case DONE_EXPLORING: 16763 insn_state[t] = EXPLORED; 16764 env->cfg.cur_stack--; 16765 break; 16766 case KEEP_EXPLORING: 16767 break; 16768 default: 16769 if (ret > 0) { 16770 verbose(env, "visit_insn internal bug\n"); 16771 ret = -EFAULT; 16772 } 16773 goto err_free; 16774 } 16775 } 16776 16777 if (env->cfg.cur_stack < 0) { 16778 verbose(env, "pop stack internal bug\n"); 16779 ret = -EFAULT; 16780 goto err_free; 16781 } 16782 16783 if (env->exception_callback_subprog && !ex_done) { 16784 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start; 16785 16786 insn_state[ex_insn_beg] = DISCOVERED; 16787 insn_stack[0] = ex_insn_beg; 16788 env->cfg.cur_stack = 1; 16789 ex_done = true; 16790 goto walk_cfg; 16791 } 16792 16793 for (i = 0; i < insn_cnt; i++) { 16794 struct bpf_insn *insn = &env->prog->insnsi[i]; 16795 16796 if (insn_state[i] != EXPLORED) { 16797 verbose(env, "unreachable insn %d\n", i); 16798 ret = -EINVAL; 16799 goto err_free; 16800 } 16801 if (bpf_is_ldimm64(insn)) { 16802 if (insn_state[i + 1] != 0) { 16803 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 16804 ret = -EINVAL; 16805 goto err_free; 16806 } 16807 i++; /* skip second half of ldimm64 */ 16808 } 16809 } 16810 ret = 0; /* cfg looks good */ 16811 env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data; 16812 16813 err_free: 16814 kvfree(insn_state); 16815 kvfree(insn_stack); 16816 env->cfg.insn_state = env->cfg.insn_stack = NULL; 16817 return ret; 16818 } 16819 16820 static int check_abnormal_return(struct bpf_verifier_env *env) 16821 { 16822 int i; 16823 16824 for (i = 1; i < env->subprog_cnt; i++) { 16825 if (env->subprog_info[i].has_ld_abs) { 16826 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 16827 return -EINVAL; 16828 } 16829 if (env->subprog_info[i].has_tail_call) { 16830 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 16831 return -EINVAL; 16832 } 16833 } 16834 return 0; 16835 } 16836 16837 /* The minimum supported BTF func info size */ 16838 #define MIN_BPF_FUNCINFO_SIZE 8 16839 #define MAX_FUNCINFO_REC_SIZE 252 16840 16841 static int check_btf_func_early(struct bpf_verifier_env *env, 16842 const union bpf_attr *attr, 16843 bpfptr_t uattr) 16844 { 16845 u32 krec_size = sizeof(struct bpf_func_info); 16846 const struct btf_type *type, *func_proto; 16847 u32 i, nfuncs, urec_size, min_size; 16848 struct bpf_func_info *krecord; 16849 struct bpf_prog *prog; 16850 const struct btf *btf; 16851 u32 prev_offset = 0; 16852 bpfptr_t urecord; 16853 int ret = -ENOMEM; 16854 16855 nfuncs = attr->func_info_cnt; 16856 if (!nfuncs) { 16857 if (check_abnormal_return(env)) 16858 return -EINVAL; 16859 return 0; 16860 } 16861 16862 urec_size = attr->func_info_rec_size; 16863 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 16864 urec_size > MAX_FUNCINFO_REC_SIZE || 16865 urec_size % sizeof(u32)) { 16866 verbose(env, "invalid func info rec size %u\n", urec_size); 16867 return -EINVAL; 16868 } 16869 16870 prog = env->prog; 16871 btf = prog->aux->btf; 16872 16873 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 16874 min_size = min_t(u32, krec_size, urec_size); 16875 16876 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 16877 if (!krecord) 16878 return -ENOMEM; 16879 16880 for (i = 0; i < nfuncs; i++) { 16881 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 16882 if (ret) { 16883 if (ret == -E2BIG) { 16884 verbose(env, "nonzero tailing record in func info"); 16885 /* set the size kernel expects so loader can zero 16886 * out the rest of the record. 16887 */ 16888 if (copy_to_bpfptr_offset(uattr, 16889 offsetof(union bpf_attr, func_info_rec_size), 16890 &min_size, sizeof(min_size))) 16891 ret = -EFAULT; 16892 } 16893 goto err_free; 16894 } 16895 16896 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 16897 ret = -EFAULT; 16898 goto err_free; 16899 } 16900 16901 /* check insn_off */ 16902 ret = -EINVAL; 16903 if (i == 0) { 16904 if (krecord[i].insn_off) { 16905 verbose(env, 16906 "nonzero insn_off %u for the first func info record", 16907 krecord[i].insn_off); 16908 goto err_free; 16909 } 16910 } else if (krecord[i].insn_off <= prev_offset) { 16911 verbose(env, 16912 "same or smaller insn offset (%u) than previous func info record (%u)", 16913 krecord[i].insn_off, prev_offset); 16914 goto err_free; 16915 } 16916 16917 /* check type_id */ 16918 type = btf_type_by_id(btf, krecord[i].type_id); 16919 if (!type || !btf_type_is_func(type)) { 16920 verbose(env, "invalid type id %d in func info", 16921 krecord[i].type_id); 16922 goto err_free; 16923 } 16924 16925 func_proto = btf_type_by_id(btf, type->type); 16926 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 16927 /* btf_func_check() already verified it during BTF load */ 16928 goto err_free; 16929 16930 prev_offset = krecord[i].insn_off; 16931 bpfptr_add(&urecord, urec_size); 16932 } 16933 16934 prog->aux->func_info = krecord; 16935 prog->aux->func_info_cnt = nfuncs; 16936 return 0; 16937 16938 err_free: 16939 kvfree(krecord); 16940 return ret; 16941 } 16942 16943 static int check_btf_func(struct bpf_verifier_env *env, 16944 const union bpf_attr *attr, 16945 bpfptr_t uattr) 16946 { 16947 const struct btf_type *type, *func_proto, *ret_type; 16948 u32 i, nfuncs, urec_size; 16949 struct bpf_func_info *krecord; 16950 struct bpf_func_info_aux *info_aux = NULL; 16951 struct bpf_prog *prog; 16952 const struct btf *btf; 16953 bpfptr_t urecord; 16954 bool scalar_return; 16955 int ret = -ENOMEM; 16956 16957 nfuncs = attr->func_info_cnt; 16958 if (!nfuncs) { 16959 if (check_abnormal_return(env)) 16960 return -EINVAL; 16961 return 0; 16962 } 16963 if (nfuncs != env->subprog_cnt) { 16964 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 16965 return -EINVAL; 16966 } 16967 16968 urec_size = attr->func_info_rec_size; 16969 16970 prog = env->prog; 16971 btf = prog->aux->btf; 16972 16973 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 16974 16975 krecord = prog->aux->func_info; 16976 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 16977 if (!info_aux) 16978 return -ENOMEM; 16979 16980 for (i = 0; i < nfuncs; i++) { 16981 /* check insn_off */ 16982 ret = -EINVAL; 16983 16984 if (env->subprog_info[i].start != krecord[i].insn_off) { 16985 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 16986 goto err_free; 16987 } 16988 16989 /* Already checked type_id */ 16990 type = btf_type_by_id(btf, krecord[i].type_id); 16991 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 16992 /* Already checked func_proto */ 16993 func_proto = btf_type_by_id(btf, type->type); 16994 16995 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 16996 scalar_return = 16997 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 16998 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 16999 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 17000 goto err_free; 17001 } 17002 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 17003 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 17004 goto err_free; 17005 } 17006 17007 bpfptr_add(&urecord, urec_size); 17008 } 17009 17010 prog->aux->func_info_aux = info_aux; 17011 return 0; 17012 17013 err_free: 17014 kfree(info_aux); 17015 return ret; 17016 } 17017 17018 static void adjust_btf_func(struct bpf_verifier_env *env) 17019 { 17020 struct bpf_prog_aux *aux = env->prog->aux; 17021 int i; 17022 17023 if (!aux->func_info) 17024 return; 17025 17026 /* func_info is not available for hidden subprogs */ 17027 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 17028 aux->func_info[i].insn_off = env->subprog_info[i].start; 17029 } 17030 17031 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 17032 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 17033 17034 static int check_btf_line(struct bpf_verifier_env *env, 17035 const union bpf_attr *attr, 17036 bpfptr_t uattr) 17037 { 17038 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 17039 struct bpf_subprog_info *sub; 17040 struct bpf_line_info *linfo; 17041 struct bpf_prog *prog; 17042 const struct btf *btf; 17043 bpfptr_t ulinfo; 17044 int err; 17045 17046 nr_linfo = attr->line_info_cnt; 17047 if (!nr_linfo) 17048 return 0; 17049 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 17050 return -EINVAL; 17051 17052 rec_size = attr->line_info_rec_size; 17053 if (rec_size < MIN_BPF_LINEINFO_SIZE || 17054 rec_size > MAX_LINEINFO_REC_SIZE || 17055 rec_size & (sizeof(u32) - 1)) 17056 return -EINVAL; 17057 17058 /* Need to zero it in case the userspace may 17059 * pass in a smaller bpf_line_info object. 17060 */ 17061 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 17062 GFP_KERNEL | __GFP_NOWARN); 17063 if (!linfo) 17064 return -ENOMEM; 17065 17066 prog = env->prog; 17067 btf = prog->aux->btf; 17068 17069 s = 0; 17070 sub = env->subprog_info; 17071 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 17072 expected_size = sizeof(struct bpf_line_info); 17073 ncopy = min_t(u32, expected_size, rec_size); 17074 for (i = 0; i < nr_linfo; i++) { 17075 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 17076 if (err) { 17077 if (err == -E2BIG) { 17078 verbose(env, "nonzero tailing record in line_info"); 17079 if (copy_to_bpfptr_offset(uattr, 17080 offsetof(union bpf_attr, line_info_rec_size), 17081 &expected_size, sizeof(expected_size))) 17082 err = -EFAULT; 17083 } 17084 goto err_free; 17085 } 17086 17087 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 17088 err = -EFAULT; 17089 goto err_free; 17090 } 17091 17092 /* 17093 * Check insn_off to ensure 17094 * 1) strictly increasing AND 17095 * 2) bounded by prog->len 17096 * 17097 * The linfo[0].insn_off == 0 check logically falls into 17098 * the later "missing bpf_line_info for func..." case 17099 * because the first linfo[0].insn_off must be the 17100 * first sub also and the first sub must have 17101 * subprog_info[0].start == 0. 17102 */ 17103 if ((i && linfo[i].insn_off <= prev_offset) || 17104 linfo[i].insn_off >= prog->len) { 17105 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 17106 i, linfo[i].insn_off, prev_offset, 17107 prog->len); 17108 err = -EINVAL; 17109 goto err_free; 17110 } 17111 17112 if (!prog->insnsi[linfo[i].insn_off].code) { 17113 verbose(env, 17114 "Invalid insn code at line_info[%u].insn_off\n", 17115 i); 17116 err = -EINVAL; 17117 goto err_free; 17118 } 17119 17120 if (!btf_name_by_offset(btf, linfo[i].line_off) || 17121 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 17122 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 17123 err = -EINVAL; 17124 goto err_free; 17125 } 17126 17127 if (s != env->subprog_cnt) { 17128 if (linfo[i].insn_off == sub[s].start) { 17129 sub[s].linfo_idx = i; 17130 s++; 17131 } else if (sub[s].start < linfo[i].insn_off) { 17132 verbose(env, "missing bpf_line_info for func#%u\n", s); 17133 err = -EINVAL; 17134 goto err_free; 17135 } 17136 } 17137 17138 prev_offset = linfo[i].insn_off; 17139 bpfptr_add(&ulinfo, rec_size); 17140 } 17141 17142 if (s != env->subprog_cnt) { 17143 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 17144 env->subprog_cnt - s, s); 17145 err = -EINVAL; 17146 goto err_free; 17147 } 17148 17149 prog->aux->linfo = linfo; 17150 prog->aux->nr_linfo = nr_linfo; 17151 17152 return 0; 17153 17154 err_free: 17155 kvfree(linfo); 17156 return err; 17157 } 17158 17159 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 17160 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 17161 17162 static int check_core_relo(struct bpf_verifier_env *env, 17163 const union bpf_attr *attr, 17164 bpfptr_t uattr) 17165 { 17166 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 17167 struct bpf_core_relo core_relo = {}; 17168 struct bpf_prog *prog = env->prog; 17169 const struct btf *btf = prog->aux->btf; 17170 struct bpf_core_ctx ctx = { 17171 .log = &env->log, 17172 .btf = btf, 17173 }; 17174 bpfptr_t u_core_relo; 17175 int err; 17176 17177 nr_core_relo = attr->core_relo_cnt; 17178 if (!nr_core_relo) 17179 return 0; 17180 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 17181 return -EINVAL; 17182 17183 rec_size = attr->core_relo_rec_size; 17184 if (rec_size < MIN_CORE_RELO_SIZE || 17185 rec_size > MAX_CORE_RELO_SIZE || 17186 rec_size % sizeof(u32)) 17187 return -EINVAL; 17188 17189 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 17190 expected_size = sizeof(struct bpf_core_relo); 17191 ncopy = min_t(u32, expected_size, rec_size); 17192 17193 /* Unlike func_info and line_info, copy and apply each CO-RE 17194 * relocation record one at a time. 17195 */ 17196 for (i = 0; i < nr_core_relo; i++) { 17197 /* future proofing when sizeof(bpf_core_relo) changes */ 17198 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 17199 if (err) { 17200 if (err == -E2BIG) { 17201 verbose(env, "nonzero tailing record in core_relo"); 17202 if (copy_to_bpfptr_offset(uattr, 17203 offsetof(union bpf_attr, core_relo_rec_size), 17204 &expected_size, sizeof(expected_size))) 17205 err = -EFAULT; 17206 } 17207 break; 17208 } 17209 17210 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 17211 err = -EFAULT; 17212 break; 17213 } 17214 17215 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 17216 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 17217 i, core_relo.insn_off, prog->len); 17218 err = -EINVAL; 17219 break; 17220 } 17221 17222 err = bpf_core_apply(&ctx, &core_relo, i, 17223 &prog->insnsi[core_relo.insn_off / 8]); 17224 if (err) 17225 break; 17226 bpfptr_add(&u_core_relo, rec_size); 17227 } 17228 return err; 17229 } 17230 17231 static int check_btf_info_early(struct bpf_verifier_env *env, 17232 const union bpf_attr *attr, 17233 bpfptr_t uattr) 17234 { 17235 struct btf *btf; 17236 int err; 17237 17238 if (!attr->func_info_cnt && !attr->line_info_cnt) { 17239 if (check_abnormal_return(env)) 17240 return -EINVAL; 17241 return 0; 17242 } 17243 17244 btf = btf_get_by_fd(attr->prog_btf_fd); 17245 if (IS_ERR(btf)) 17246 return PTR_ERR(btf); 17247 if (btf_is_kernel(btf)) { 17248 btf_put(btf); 17249 return -EACCES; 17250 } 17251 env->prog->aux->btf = btf; 17252 17253 err = check_btf_func_early(env, attr, uattr); 17254 if (err) 17255 return err; 17256 return 0; 17257 } 17258 17259 static int check_btf_info(struct bpf_verifier_env *env, 17260 const union bpf_attr *attr, 17261 bpfptr_t uattr) 17262 { 17263 int err; 17264 17265 if (!attr->func_info_cnt && !attr->line_info_cnt) { 17266 if (check_abnormal_return(env)) 17267 return -EINVAL; 17268 return 0; 17269 } 17270 17271 err = check_btf_func(env, attr, uattr); 17272 if (err) 17273 return err; 17274 17275 err = check_btf_line(env, attr, uattr); 17276 if (err) 17277 return err; 17278 17279 err = check_core_relo(env, attr, uattr); 17280 if (err) 17281 return err; 17282 17283 return 0; 17284 } 17285 17286 /* check %cur's range satisfies %old's */ 17287 static bool range_within(const struct bpf_reg_state *old, 17288 const struct bpf_reg_state *cur) 17289 { 17290 return old->umin_value <= cur->umin_value && 17291 old->umax_value >= cur->umax_value && 17292 old->smin_value <= cur->smin_value && 17293 old->smax_value >= cur->smax_value && 17294 old->u32_min_value <= cur->u32_min_value && 17295 old->u32_max_value >= cur->u32_max_value && 17296 old->s32_min_value <= cur->s32_min_value && 17297 old->s32_max_value >= cur->s32_max_value; 17298 } 17299 17300 /* If in the old state two registers had the same id, then they need to have 17301 * the same id in the new state as well. But that id could be different from 17302 * the old state, so we need to track the mapping from old to new ids. 17303 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 17304 * regs with old id 5 must also have new id 9 for the new state to be safe. But 17305 * regs with a different old id could still have new id 9, we don't care about 17306 * that. 17307 * So we look through our idmap to see if this old id has been seen before. If 17308 * so, we require the new id to match; otherwise, we add the id pair to the map. 17309 */ 17310 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 17311 { 17312 struct bpf_id_pair *map = idmap->map; 17313 unsigned int i; 17314 17315 /* either both IDs should be set or both should be zero */ 17316 if (!!old_id != !!cur_id) 17317 return false; 17318 17319 if (old_id == 0) /* cur_id == 0 as well */ 17320 return true; 17321 17322 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 17323 if (!map[i].old) { 17324 /* Reached an empty slot; haven't seen this id before */ 17325 map[i].old = old_id; 17326 map[i].cur = cur_id; 17327 return true; 17328 } 17329 if (map[i].old == old_id) 17330 return map[i].cur == cur_id; 17331 if (map[i].cur == cur_id) 17332 return false; 17333 } 17334 /* We ran out of idmap slots, which should be impossible */ 17335 WARN_ON_ONCE(1); 17336 return false; 17337 } 17338 17339 /* Similar to check_ids(), but allocate a unique temporary ID 17340 * for 'old_id' or 'cur_id' of zero. 17341 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 17342 */ 17343 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 17344 { 17345 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 17346 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 17347 17348 return check_ids(old_id, cur_id, idmap); 17349 } 17350 17351 static void clean_func_state(struct bpf_verifier_env *env, 17352 struct bpf_func_state *st) 17353 { 17354 enum bpf_reg_liveness live; 17355 int i, j; 17356 17357 for (i = 0; i < BPF_REG_FP; i++) { 17358 live = st->regs[i].live; 17359 /* liveness must not touch this register anymore */ 17360 st->regs[i].live |= REG_LIVE_DONE; 17361 if (!(live & REG_LIVE_READ)) 17362 /* since the register is unused, clear its state 17363 * to make further comparison simpler 17364 */ 17365 __mark_reg_not_init(env, &st->regs[i]); 17366 } 17367 17368 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 17369 live = st->stack[i].spilled_ptr.live; 17370 /* liveness must not touch this stack slot anymore */ 17371 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 17372 if (!(live & REG_LIVE_READ)) { 17373 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 17374 for (j = 0; j < BPF_REG_SIZE; j++) 17375 st->stack[i].slot_type[j] = STACK_INVALID; 17376 } 17377 } 17378 } 17379 17380 static void clean_verifier_state(struct bpf_verifier_env *env, 17381 struct bpf_verifier_state *st) 17382 { 17383 int i; 17384 17385 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 17386 /* all regs in this state in all frames were already marked */ 17387 return; 17388 17389 for (i = 0; i <= st->curframe; i++) 17390 clean_func_state(env, st->frame[i]); 17391 } 17392 17393 /* the parentage chains form a tree. 17394 * the verifier states are added to state lists at given insn and 17395 * pushed into state stack for future exploration. 17396 * when the verifier reaches bpf_exit insn some of the verifer states 17397 * stored in the state lists have their final liveness state already, 17398 * but a lot of states will get revised from liveness point of view when 17399 * the verifier explores other branches. 17400 * Example: 17401 * 1: r0 = 1 17402 * 2: if r1 == 100 goto pc+1 17403 * 3: r0 = 2 17404 * 4: exit 17405 * when the verifier reaches exit insn the register r0 in the state list of 17406 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 17407 * of insn 2 and goes exploring further. At the insn 4 it will walk the 17408 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 17409 * 17410 * Since the verifier pushes the branch states as it sees them while exploring 17411 * the program the condition of walking the branch instruction for the second 17412 * time means that all states below this branch were already explored and 17413 * their final liveness marks are already propagated. 17414 * Hence when the verifier completes the search of state list in is_state_visited() 17415 * we can call this clean_live_states() function to mark all liveness states 17416 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 17417 * will not be used. 17418 * This function also clears the registers and stack for states that !READ 17419 * to simplify state merging. 17420 * 17421 * Important note here that walking the same branch instruction in the callee 17422 * doesn't meant that the states are DONE. The verifier has to compare 17423 * the callsites 17424 */ 17425 static void clean_live_states(struct bpf_verifier_env *env, int insn, 17426 struct bpf_verifier_state *cur) 17427 { 17428 struct bpf_verifier_state_list *sl; 17429 17430 sl = *explored_state(env, insn); 17431 while (sl) { 17432 if (sl->state.branches) 17433 goto next; 17434 if (sl->state.insn_idx != insn || 17435 !same_callsites(&sl->state, cur)) 17436 goto next; 17437 clean_verifier_state(env, &sl->state); 17438 next: 17439 sl = sl->next; 17440 } 17441 } 17442 17443 static bool regs_exact(const struct bpf_reg_state *rold, 17444 const struct bpf_reg_state *rcur, 17445 struct bpf_idmap *idmap) 17446 { 17447 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 17448 check_ids(rold->id, rcur->id, idmap) && 17449 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 17450 } 17451 17452 enum exact_level { 17453 NOT_EXACT, 17454 EXACT, 17455 RANGE_WITHIN 17456 }; 17457 17458 /* Returns true if (rold safe implies rcur safe) */ 17459 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 17460 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, 17461 enum exact_level exact) 17462 { 17463 if (exact == EXACT) 17464 return regs_exact(rold, rcur, idmap); 17465 17466 if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT) 17467 /* explored state didn't use this */ 17468 return true; 17469 if (rold->type == NOT_INIT) { 17470 if (exact == NOT_EXACT || rcur->type == NOT_INIT) 17471 /* explored state can't have used this */ 17472 return true; 17473 } 17474 17475 /* Enforce that register types have to match exactly, including their 17476 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 17477 * rule. 17478 * 17479 * One can make a point that using a pointer register as unbounded 17480 * SCALAR would be technically acceptable, but this could lead to 17481 * pointer leaks because scalars are allowed to leak while pointers 17482 * are not. We could make this safe in special cases if root is 17483 * calling us, but it's probably not worth the hassle. 17484 * 17485 * Also, register types that are *not* MAYBE_NULL could technically be 17486 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 17487 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 17488 * to the same map). 17489 * However, if the old MAYBE_NULL register then got NULL checked, 17490 * doing so could have affected others with the same id, and we can't 17491 * check for that because we lost the id when we converted to 17492 * a non-MAYBE_NULL variant. 17493 * So, as a general rule we don't allow mixing MAYBE_NULL and 17494 * non-MAYBE_NULL registers as well. 17495 */ 17496 if (rold->type != rcur->type) 17497 return false; 17498 17499 switch (base_type(rold->type)) { 17500 case SCALAR_VALUE: 17501 if (env->explore_alu_limits) { 17502 /* explore_alu_limits disables tnum_in() and range_within() 17503 * logic and requires everything to be strict 17504 */ 17505 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 17506 check_scalar_ids(rold->id, rcur->id, idmap); 17507 } 17508 if (!rold->precise && exact == NOT_EXACT) 17509 return true; 17510 if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST)) 17511 return false; 17512 if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off)) 17513 return false; 17514 /* Why check_ids() for scalar registers? 17515 * 17516 * Consider the following BPF code: 17517 * 1: r6 = ... unbound scalar, ID=a ... 17518 * 2: r7 = ... unbound scalar, ID=b ... 17519 * 3: if (r6 > r7) goto +1 17520 * 4: r6 = r7 17521 * 5: if (r6 > X) goto ... 17522 * 6: ... memory operation using r7 ... 17523 * 17524 * First verification path is [1-6]: 17525 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 17526 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark 17527 * r7 <= X, because r6 and r7 share same id. 17528 * Next verification path is [1-4, 6]. 17529 * 17530 * Instruction (6) would be reached in two states: 17531 * I. r6{.id=b}, r7{.id=b} via path 1-6; 17532 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 17533 * 17534 * Use check_ids() to distinguish these states. 17535 * --- 17536 * Also verify that new value satisfies old value range knowledge. 17537 */ 17538 return range_within(rold, rcur) && 17539 tnum_in(rold->var_off, rcur->var_off) && 17540 check_scalar_ids(rold->id, rcur->id, idmap); 17541 case PTR_TO_MAP_KEY: 17542 case PTR_TO_MAP_VALUE: 17543 case PTR_TO_MEM: 17544 case PTR_TO_BUF: 17545 case PTR_TO_TP_BUFFER: 17546 /* If the new min/max/var_off satisfy the old ones and 17547 * everything else matches, we are OK. 17548 */ 17549 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 17550 range_within(rold, rcur) && 17551 tnum_in(rold->var_off, rcur->var_off) && 17552 check_ids(rold->id, rcur->id, idmap) && 17553 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 17554 case PTR_TO_PACKET_META: 17555 case PTR_TO_PACKET: 17556 /* We must have at least as much range as the old ptr 17557 * did, so that any accesses which were safe before are 17558 * still safe. This is true even if old range < old off, 17559 * since someone could have accessed through (ptr - k), or 17560 * even done ptr -= k in a register, to get a safe access. 17561 */ 17562 if (rold->range > rcur->range) 17563 return false; 17564 /* If the offsets don't match, we can't trust our alignment; 17565 * nor can we be sure that we won't fall out of range. 17566 */ 17567 if (rold->off != rcur->off) 17568 return false; 17569 /* id relations must be preserved */ 17570 if (!check_ids(rold->id, rcur->id, idmap)) 17571 return false; 17572 /* new val must satisfy old val knowledge */ 17573 return range_within(rold, rcur) && 17574 tnum_in(rold->var_off, rcur->var_off); 17575 case PTR_TO_STACK: 17576 /* two stack pointers are equal only if they're pointing to 17577 * the same stack frame, since fp-8 in foo != fp-8 in bar 17578 */ 17579 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 17580 case PTR_TO_ARENA: 17581 return true; 17582 default: 17583 return regs_exact(rold, rcur, idmap); 17584 } 17585 } 17586 17587 static struct bpf_reg_state unbound_reg; 17588 17589 static __init int unbound_reg_init(void) 17590 { 17591 __mark_reg_unknown_imprecise(&unbound_reg); 17592 unbound_reg.live |= REG_LIVE_READ; 17593 return 0; 17594 } 17595 late_initcall(unbound_reg_init); 17596 17597 static bool is_stack_all_misc(struct bpf_verifier_env *env, 17598 struct bpf_stack_state *stack) 17599 { 17600 u32 i; 17601 17602 for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) { 17603 if ((stack->slot_type[i] == STACK_MISC) || 17604 (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack)) 17605 continue; 17606 return false; 17607 } 17608 17609 return true; 17610 } 17611 17612 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env, 17613 struct bpf_stack_state *stack) 17614 { 17615 if (is_spilled_scalar_reg64(stack)) 17616 return &stack->spilled_ptr; 17617 17618 if (is_stack_all_misc(env, stack)) 17619 return &unbound_reg; 17620 17621 return NULL; 17622 } 17623 17624 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 17625 struct bpf_func_state *cur, struct bpf_idmap *idmap, 17626 enum exact_level exact) 17627 { 17628 int i, spi; 17629 17630 /* walk slots of the explored stack and ignore any additional 17631 * slots in the current stack, since explored(safe) state 17632 * didn't use them 17633 */ 17634 for (i = 0; i < old->allocated_stack; i++) { 17635 struct bpf_reg_state *old_reg, *cur_reg; 17636 17637 spi = i / BPF_REG_SIZE; 17638 17639 if (exact != NOT_EXACT && 17640 (i >= cur->allocated_stack || 17641 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 17642 cur->stack[spi].slot_type[i % BPF_REG_SIZE])) 17643 return false; 17644 17645 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) 17646 && exact == NOT_EXACT) { 17647 i += BPF_REG_SIZE - 1; 17648 /* explored state didn't use this */ 17649 continue; 17650 } 17651 17652 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 17653 continue; 17654 17655 if (env->allow_uninit_stack && 17656 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 17657 continue; 17658 17659 /* explored stack has more populated slots than current stack 17660 * and these slots were used 17661 */ 17662 if (i >= cur->allocated_stack) 17663 return false; 17664 17665 /* 64-bit scalar spill vs all slots MISC and vice versa. 17666 * Load from all slots MISC produces unbound scalar. 17667 * Construct a fake register for such stack and call 17668 * regsafe() to ensure scalar ids are compared. 17669 */ 17670 old_reg = scalar_reg_for_stack(env, &old->stack[spi]); 17671 cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]); 17672 if (old_reg && cur_reg) { 17673 if (!regsafe(env, old_reg, cur_reg, idmap, exact)) 17674 return false; 17675 i += BPF_REG_SIZE - 1; 17676 continue; 17677 } 17678 17679 /* if old state was safe with misc data in the stack 17680 * it will be safe with zero-initialized stack. 17681 * The opposite is not true 17682 */ 17683 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 17684 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 17685 continue; 17686 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 17687 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 17688 /* Ex: old explored (safe) state has STACK_SPILL in 17689 * this stack slot, but current has STACK_MISC -> 17690 * this verifier states are not equivalent, 17691 * return false to continue verification of this path 17692 */ 17693 return false; 17694 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 17695 continue; 17696 /* Both old and cur are having same slot_type */ 17697 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 17698 case STACK_SPILL: 17699 /* when explored and current stack slot are both storing 17700 * spilled registers, check that stored pointers types 17701 * are the same as well. 17702 * Ex: explored safe path could have stored 17703 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 17704 * but current path has stored: 17705 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 17706 * such verifier states are not equivalent. 17707 * return false to continue verification of this path 17708 */ 17709 if (!regsafe(env, &old->stack[spi].spilled_ptr, 17710 &cur->stack[spi].spilled_ptr, idmap, exact)) 17711 return false; 17712 break; 17713 case STACK_DYNPTR: 17714 old_reg = &old->stack[spi].spilled_ptr; 17715 cur_reg = &cur->stack[spi].spilled_ptr; 17716 if (old_reg->dynptr.type != cur_reg->dynptr.type || 17717 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 17718 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 17719 return false; 17720 break; 17721 case STACK_ITER: 17722 old_reg = &old->stack[spi].spilled_ptr; 17723 cur_reg = &cur->stack[spi].spilled_ptr; 17724 /* iter.depth is not compared between states as it 17725 * doesn't matter for correctness and would otherwise 17726 * prevent convergence; we maintain it only to prevent 17727 * infinite loop check triggering, see 17728 * iter_active_depths_differ() 17729 */ 17730 if (old_reg->iter.btf != cur_reg->iter.btf || 17731 old_reg->iter.btf_id != cur_reg->iter.btf_id || 17732 old_reg->iter.state != cur_reg->iter.state || 17733 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 17734 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 17735 return false; 17736 break; 17737 case STACK_MISC: 17738 case STACK_ZERO: 17739 case STACK_INVALID: 17740 continue; 17741 /* Ensure that new unhandled slot types return false by default */ 17742 default: 17743 return false; 17744 } 17745 } 17746 return true; 17747 } 17748 17749 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 17750 struct bpf_idmap *idmap) 17751 { 17752 int i; 17753 17754 if (old->acquired_refs != cur->acquired_refs) 17755 return false; 17756 17757 for (i = 0; i < old->acquired_refs; i++) { 17758 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap) || 17759 old->refs[i].type != cur->refs[i].type) 17760 return false; 17761 switch (old->refs[i].type) { 17762 case REF_TYPE_PTR: 17763 break; 17764 case REF_TYPE_LOCK: 17765 if (old->refs[i].ptr != cur->refs[i].ptr) 17766 return false; 17767 break; 17768 default: 17769 WARN_ONCE(1, "Unhandled enum type for reference state: %d\n", old->refs[i].type); 17770 return false; 17771 } 17772 } 17773 17774 return true; 17775 } 17776 17777 /* compare two verifier states 17778 * 17779 * all states stored in state_list are known to be valid, since 17780 * verifier reached 'bpf_exit' instruction through them 17781 * 17782 * this function is called when verifier exploring different branches of 17783 * execution popped from the state stack. If it sees an old state that has 17784 * more strict register state and more strict stack state then this execution 17785 * branch doesn't need to be explored further, since verifier already 17786 * concluded that more strict state leads to valid finish. 17787 * 17788 * Therefore two states are equivalent if register state is more conservative 17789 * and explored stack state is more conservative than the current one. 17790 * Example: 17791 * explored current 17792 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 17793 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 17794 * 17795 * In other words if current stack state (one being explored) has more 17796 * valid slots than old one that already passed validation, it means 17797 * the verifier can stop exploring and conclude that current state is valid too 17798 * 17799 * Similarly with registers. If explored state has register type as invalid 17800 * whereas register type in current state is meaningful, it means that 17801 * the current state will reach 'bpf_exit' instruction safely 17802 */ 17803 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 17804 struct bpf_func_state *cur, enum exact_level exact) 17805 { 17806 int i; 17807 17808 if (old->callback_depth > cur->callback_depth) 17809 return false; 17810 17811 for (i = 0; i < MAX_BPF_REG; i++) 17812 if (!regsafe(env, &old->regs[i], &cur->regs[i], 17813 &env->idmap_scratch, exact)) 17814 return false; 17815 17816 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 17817 return false; 17818 17819 if (!refsafe(old, cur, &env->idmap_scratch)) 17820 return false; 17821 17822 return true; 17823 } 17824 17825 static void reset_idmap_scratch(struct bpf_verifier_env *env) 17826 { 17827 env->idmap_scratch.tmp_id_gen = env->id_gen; 17828 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 17829 } 17830 17831 static bool states_equal(struct bpf_verifier_env *env, 17832 struct bpf_verifier_state *old, 17833 struct bpf_verifier_state *cur, 17834 enum exact_level exact) 17835 { 17836 int i; 17837 17838 if (old->curframe != cur->curframe) 17839 return false; 17840 17841 reset_idmap_scratch(env); 17842 17843 /* Verification state from speculative execution simulation 17844 * must never prune a non-speculative execution one. 17845 */ 17846 if (old->speculative && !cur->speculative) 17847 return false; 17848 17849 if (old->active_rcu_lock != cur->active_rcu_lock) 17850 return false; 17851 17852 if (old->active_preempt_lock != cur->active_preempt_lock) 17853 return false; 17854 17855 if (old->in_sleepable != cur->in_sleepable) 17856 return false; 17857 17858 /* for states to be equal callsites have to be the same 17859 * and all frame states need to be equivalent 17860 */ 17861 for (i = 0; i <= old->curframe; i++) { 17862 if (old->frame[i]->callsite != cur->frame[i]->callsite) 17863 return false; 17864 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact)) 17865 return false; 17866 } 17867 return true; 17868 } 17869 17870 /* Return 0 if no propagation happened. Return negative error code if error 17871 * happened. Otherwise, return the propagated bit. 17872 */ 17873 static int propagate_liveness_reg(struct bpf_verifier_env *env, 17874 struct bpf_reg_state *reg, 17875 struct bpf_reg_state *parent_reg) 17876 { 17877 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 17878 u8 flag = reg->live & REG_LIVE_READ; 17879 int err; 17880 17881 /* When comes here, read flags of PARENT_REG or REG could be any of 17882 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 17883 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 17884 */ 17885 if (parent_flag == REG_LIVE_READ64 || 17886 /* Or if there is no read flag from REG. */ 17887 !flag || 17888 /* Or if the read flag from REG is the same as PARENT_REG. */ 17889 parent_flag == flag) 17890 return 0; 17891 17892 err = mark_reg_read(env, reg, parent_reg, flag); 17893 if (err) 17894 return err; 17895 17896 return flag; 17897 } 17898 17899 /* A write screens off any subsequent reads; but write marks come from the 17900 * straight-line code between a state and its parent. When we arrive at an 17901 * equivalent state (jump target or such) we didn't arrive by the straight-line 17902 * code, so read marks in the state must propagate to the parent regardless 17903 * of the state's write marks. That's what 'parent == state->parent' comparison 17904 * in mark_reg_read() is for. 17905 */ 17906 static int propagate_liveness(struct bpf_verifier_env *env, 17907 const struct bpf_verifier_state *vstate, 17908 struct bpf_verifier_state *vparent) 17909 { 17910 struct bpf_reg_state *state_reg, *parent_reg; 17911 struct bpf_func_state *state, *parent; 17912 int i, frame, err = 0; 17913 17914 if (vparent->curframe != vstate->curframe) { 17915 WARN(1, "propagate_live: parent frame %d current frame %d\n", 17916 vparent->curframe, vstate->curframe); 17917 return -EFAULT; 17918 } 17919 /* Propagate read liveness of registers... */ 17920 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 17921 for (frame = 0; frame <= vstate->curframe; frame++) { 17922 parent = vparent->frame[frame]; 17923 state = vstate->frame[frame]; 17924 parent_reg = parent->regs; 17925 state_reg = state->regs; 17926 /* We don't need to worry about FP liveness, it's read-only */ 17927 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 17928 err = propagate_liveness_reg(env, &state_reg[i], 17929 &parent_reg[i]); 17930 if (err < 0) 17931 return err; 17932 if (err == REG_LIVE_READ64) 17933 mark_insn_zext(env, &parent_reg[i]); 17934 } 17935 17936 /* Propagate stack slots. */ 17937 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 17938 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 17939 parent_reg = &parent->stack[i].spilled_ptr; 17940 state_reg = &state->stack[i].spilled_ptr; 17941 err = propagate_liveness_reg(env, state_reg, 17942 parent_reg); 17943 if (err < 0) 17944 return err; 17945 } 17946 } 17947 return 0; 17948 } 17949 17950 /* find precise scalars in the previous equivalent state and 17951 * propagate them into the current state 17952 */ 17953 static int propagate_precision(struct bpf_verifier_env *env, 17954 const struct bpf_verifier_state *old) 17955 { 17956 struct bpf_reg_state *state_reg; 17957 struct bpf_func_state *state; 17958 int i, err = 0, fr; 17959 bool first; 17960 17961 for (fr = old->curframe; fr >= 0; fr--) { 17962 state = old->frame[fr]; 17963 state_reg = state->regs; 17964 first = true; 17965 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 17966 if (state_reg->type != SCALAR_VALUE || 17967 !state_reg->precise || 17968 !(state_reg->live & REG_LIVE_READ)) 17969 continue; 17970 if (env->log.level & BPF_LOG_LEVEL2) { 17971 if (first) 17972 verbose(env, "frame %d: propagating r%d", fr, i); 17973 else 17974 verbose(env, ",r%d", i); 17975 } 17976 bt_set_frame_reg(&env->bt, fr, i); 17977 first = false; 17978 } 17979 17980 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 17981 if (!is_spilled_reg(&state->stack[i])) 17982 continue; 17983 state_reg = &state->stack[i].spilled_ptr; 17984 if (state_reg->type != SCALAR_VALUE || 17985 !state_reg->precise || 17986 !(state_reg->live & REG_LIVE_READ)) 17987 continue; 17988 if (env->log.level & BPF_LOG_LEVEL2) { 17989 if (first) 17990 verbose(env, "frame %d: propagating fp%d", 17991 fr, (-i - 1) * BPF_REG_SIZE); 17992 else 17993 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 17994 } 17995 bt_set_frame_slot(&env->bt, fr, i); 17996 first = false; 17997 } 17998 if (!first) 17999 verbose(env, "\n"); 18000 } 18001 18002 err = mark_chain_precision_batch(env); 18003 if (err < 0) 18004 return err; 18005 18006 return 0; 18007 } 18008 18009 static bool states_maybe_looping(struct bpf_verifier_state *old, 18010 struct bpf_verifier_state *cur) 18011 { 18012 struct bpf_func_state *fold, *fcur; 18013 int i, fr = cur->curframe; 18014 18015 if (old->curframe != fr) 18016 return false; 18017 18018 fold = old->frame[fr]; 18019 fcur = cur->frame[fr]; 18020 for (i = 0; i < MAX_BPF_REG; i++) 18021 if (memcmp(&fold->regs[i], &fcur->regs[i], 18022 offsetof(struct bpf_reg_state, parent))) 18023 return false; 18024 return true; 18025 } 18026 18027 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 18028 { 18029 return env->insn_aux_data[insn_idx].is_iter_next; 18030 } 18031 18032 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 18033 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 18034 * states to match, which otherwise would look like an infinite loop. So while 18035 * iter_next() calls are taken care of, we still need to be careful and 18036 * prevent erroneous and too eager declaration of "ininite loop", when 18037 * iterators are involved. 18038 * 18039 * Here's a situation in pseudo-BPF assembly form: 18040 * 18041 * 0: again: ; set up iter_next() call args 18042 * 1: r1 = &it ; <CHECKPOINT HERE> 18043 * 2: call bpf_iter_num_next ; this is iter_next() call 18044 * 3: if r0 == 0 goto done 18045 * 4: ... something useful here ... 18046 * 5: goto again ; another iteration 18047 * 6: done: 18048 * 7: r1 = &it 18049 * 8: call bpf_iter_num_destroy ; clean up iter state 18050 * 9: exit 18051 * 18052 * This is a typical loop. Let's assume that we have a prune point at 1:, 18053 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 18054 * again`, assuming other heuristics don't get in a way). 18055 * 18056 * When we first time come to 1:, let's say we have some state X. We proceed 18057 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 18058 * Now we come back to validate that forked ACTIVE state. We proceed through 18059 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 18060 * are converging. But the problem is that we don't know that yet, as this 18061 * convergence has to happen at iter_next() call site only. So if nothing is 18062 * done, at 1: verifier will use bounded loop logic and declare infinite 18063 * looping (and would be *technically* correct, if not for iterator's 18064 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 18065 * don't want that. So what we do in process_iter_next_call() when we go on 18066 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 18067 * a different iteration. So when we suspect an infinite loop, we additionally 18068 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 18069 * pretend we are not looping and wait for next iter_next() call. 18070 * 18071 * This only applies to ACTIVE state. In DRAINED state we don't expect to 18072 * loop, because that would actually mean infinite loop, as DRAINED state is 18073 * "sticky", and so we'll keep returning into the same instruction with the 18074 * same state (at least in one of possible code paths). 18075 * 18076 * This approach allows to keep infinite loop heuristic even in the face of 18077 * active iterator. E.g., C snippet below is and will be detected as 18078 * inifintely looping: 18079 * 18080 * struct bpf_iter_num it; 18081 * int *p, x; 18082 * 18083 * bpf_iter_num_new(&it, 0, 10); 18084 * while ((p = bpf_iter_num_next(&t))) { 18085 * x = p; 18086 * while (x--) {} // <<-- infinite loop here 18087 * } 18088 * 18089 */ 18090 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 18091 { 18092 struct bpf_reg_state *slot, *cur_slot; 18093 struct bpf_func_state *state; 18094 int i, fr; 18095 18096 for (fr = old->curframe; fr >= 0; fr--) { 18097 state = old->frame[fr]; 18098 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 18099 if (state->stack[i].slot_type[0] != STACK_ITER) 18100 continue; 18101 18102 slot = &state->stack[i].spilled_ptr; 18103 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 18104 continue; 18105 18106 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 18107 if (cur_slot->iter.depth != slot->iter.depth) 18108 return true; 18109 } 18110 } 18111 return false; 18112 } 18113 18114 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 18115 { 18116 struct bpf_verifier_state_list *new_sl; 18117 struct bpf_verifier_state_list *sl, **pprev; 18118 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry; 18119 int i, j, n, err, states_cnt = 0; 18120 bool force_new_state, add_new_state, force_exact; 18121 18122 force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) || 18123 /* Avoid accumulating infinitely long jmp history */ 18124 cur->insn_hist_end - cur->insn_hist_start > 40; 18125 18126 /* bpf progs typically have pruning point every 4 instructions 18127 * http://vger.kernel.org/bpfconf2019.html#session-1 18128 * Do not add new state for future pruning if the verifier hasn't seen 18129 * at least 2 jumps and at least 8 instructions. 18130 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 18131 * In tests that amounts to up to 50% reduction into total verifier 18132 * memory consumption and 20% verifier time speedup. 18133 */ 18134 add_new_state = force_new_state; 18135 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 18136 env->insn_processed - env->prev_insn_processed >= 8) 18137 add_new_state = true; 18138 18139 pprev = explored_state(env, insn_idx); 18140 sl = *pprev; 18141 18142 clean_live_states(env, insn_idx, cur); 18143 18144 while (sl) { 18145 states_cnt++; 18146 if (sl->state.insn_idx != insn_idx) 18147 goto next; 18148 18149 if (sl->state.branches) { 18150 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 18151 18152 if (frame->in_async_callback_fn && 18153 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 18154 /* Different async_entry_cnt means that the verifier is 18155 * processing another entry into async callback. 18156 * Seeing the same state is not an indication of infinite 18157 * loop or infinite recursion. 18158 * But finding the same state doesn't mean that it's safe 18159 * to stop processing the current state. The previous state 18160 * hasn't yet reached bpf_exit, since state.branches > 0. 18161 * Checking in_async_callback_fn alone is not enough either. 18162 * Since the verifier still needs to catch infinite loops 18163 * inside async callbacks. 18164 */ 18165 goto skip_inf_loop_check; 18166 } 18167 /* BPF open-coded iterators loop detection is special. 18168 * states_maybe_looping() logic is too simplistic in detecting 18169 * states that *might* be equivalent, because it doesn't know 18170 * about ID remapping, so don't even perform it. 18171 * See process_iter_next_call() and iter_active_depths_differ() 18172 * for overview of the logic. When current and one of parent 18173 * states are detected as equivalent, it's a good thing: we prove 18174 * convergence and can stop simulating further iterations. 18175 * It's safe to assume that iterator loop will finish, taking into 18176 * account iter_next() contract of eventually returning 18177 * sticky NULL result. 18178 * 18179 * Note, that states have to be compared exactly in this case because 18180 * read and precision marks might not be finalized inside the loop. 18181 * E.g. as in the program below: 18182 * 18183 * 1. r7 = -16 18184 * 2. r6 = bpf_get_prandom_u32() 18185 * 3. while (bpf_iter_num_next(&fp[-8])) { 18186 * 4. if (r6 != 42) { 18187 * 5. r7 = -32 18188 * 6. r6 = bpf_get_prandom_u32() 18189 * 7. continue 18190 * 8. } 18191 * 9. r0 = r10 18192 * 10. r0 += r7 18193 * 11. r8 = *(u64 *)(r0 + 0) 18194 * 12. r6 = bpf_get_prandom_u32() 18195 * 13. } 18196 * 18197 * Here verifier would first visit path 1-3, create a checkpoint at 3 18198 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 18199 * not have read or precision mark for r7 yet, thus inexact states 18200 * comparison would discard current state with r7=-32 18201 * => unsafe memory access at 11 would not be caught. 18202 */ 18203 if (is_iter_next_insn(env, insn_idx)) { 18204 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 18205 struct bpf_func_state *cur_frame; 18206 struct bpf_reg_state *iter_state, *iter_reg; 18207 int spi; 18208 18209 cur_frame = cur->frame[cur->curframe]; 18210 /* btf_check_iter_kfuncs() enforces that 18211 * iter state pointer is always the first arg 18212 */ 18213 iter_reg = &cur_frame->regs[BPF_REG_1]; 18214 /* current state is valid due to states_equal(), 18215 * so we can assume valid iter and reg state, 18216 * no need for extra (re-)validations 18217 */ 18218 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 18219 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 18220 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 18221 update_loop_entry(cur, &sl->state); 18222 goto hit; 18223 } 18224 } 18225 goto skip_inf_loop_check; 18226 } 18227 if (is_may_goto_insn_at(env, insn_idx)) { 18228 if (sl->state.may_goto_depth != cur->may_goto_depth && 18229 states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 18230 update_loop_entry(cur, &sl->state); 18231 goto hit; 18232 } 18233 } 18234 if (calls_callback(env, insn_idx)) { 18235 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) 18236 goto hit; 18237 goto skip_inf_loop_check; 18238 } 18239 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 18240 if (states_maybe_looping(&sl->state, cur) && 18241 states_equal(env, &sl->state, cur, EXACT) && 18242 !iter_active_depths_differ(&sl->state, cur) && 18243 sl->state.may_goto_depth == cur->may_goto_depth && 18244 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 18245 verbose_linfo(env, insn_idx, "; "); 18246 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 18247 verbose(env, "cur state:"); 18248 print_verifier_state(env, cur->frame[cur->curframe], true); 18249 verbose(env, "old state:"); 18250 print_verifier_state(env, sl->state.frame[cur->curframe], true); 18251 return -EINVAL; 18252 } 18253 /* if the verifier is processing a loop, avoid adding new state 18254 * too often, since different loop iterations have distinct 18255 * states and may not help future pruning. 18256 * This threshold shouldn't be too low to make sure that 18257 * a loop with large bound will be rejected quickly. 18258 * The most abusive loop will be: 18259 * r1 += 1 18260 * if r1 < 1000000 goto pc-2 18261 * 1M insn_procssed limit / 100 == 10k peak states. 18262 * This threshold shouldn't be too high either, since states 18263 * at the end of the loop are likely to be useful in pruning. 18264 */ 18265 skip_inf_loop_check: 18266 if (!force_new_state && 18267 env->jmps_processed - env->prev_jmps_processed < 20 && 18268 env->insn_processed - env->prev_insn_processed < 100) 18269 add_new_state = false; 18270 goto miss; 18271 } 18272 /* If sl->state is a part of a loop and this loop's entry is a part of 18273 * current verification path then states have to be compared exactly. 18274 * 'force_exact' is needed to catch the following case: 18275 * 18276 * initial Here state 'succ' was processed first, 18277 * | it was eventually tracked to produce a 18278 * V state identical to 'hdr'. 18279 * .---------> hdr All branches from 'succ' had been explored 18280 * | | and thus 'succ' has its .branches == 0. 18281 * | V 18282 * | .------... Suppose states 'cur' and 'succ' correspond 18283 * | | | to the same instruction + callsites. 18284 * | V V In such case it is necessary to check 18285 * | ... ... if 'succ' and 'cur' are states_equal(). 18286 * | | | If 'succ' and 'cur' are a part of the 18287 * | V V same loop exact flag has to be set. 18288 * | succ <- cur To check if that is the case, verify 18289 * | | if loop entry of 'succ' is in current 18290 * | V DFS path. 18291 * | ... 18292 * | | 18293 * '----' 18294 * 18295 * Additional details are in the comment before get_loop_entry(). 18296 */ 18297 loop_entry = get_loop_entry(&sl->state); 18298 force_exact = loop_entry && loop_entry->branches > 0; 18299 if (states_equal(env, &sl->state, cur, force_exact ? RANGE_WITHIN : NOT_EXACT)) { 18300 if (force_exact) 18301 update_loop_entry(cur, loop_entry); 18302 hit: 18303 sl->hit_cnt++; 18304 /* reached equivalent register/stack state, 18305 * prune the search. 18306 * Registers read by the continuation are read by us. 18307 * If we have any write marks in env->cur_state, they 18308 * will prevent corresponding reads in the continuation 18309 * from reaching our parent (an explored_state). Our 18310 * own state will get the read marks recorded, but 18311 * they'll be immediately forgotten as we're pruning 18312 * this state and will pop a new one. 18313 */ 18314 err = propagate_liveness(env, &sl->state, cur); 18315 18316 /* if previous state reached the exit with precision and 18317 * current state is equivalent to it (except precision marks) 18318 * the precision needs to be propagated back in 18319 * the current state. 18320 */ 18321 if (is_jmp_point(env, env->insn_idx)) 18322 err = err ? : push_insn_history(env, cur, 0, 0); 18323 err = err ? : propagate_precision(env, &sl->state); 18324 if (err) 18325 return err; 18326 return 1; 18327 } 18328 miss: 18329 /* when new state is not going to be added do not increase miss count. 18330 * Otherwise several loop iterations will remove the state 18331 * recorded earlier. The goal of these heuristics is to have 18332 * states from some iterations of the loop (some in the beginning 18333 * and some at the end) to help pruning. 18334 */ 18335 if (add_new_state) 18336 sl->miss_cnt++; 18337 /* heuristic to determine whether this state is beneficial 18338 * to keep checking from state equivalence point of view. 18339 * Higher numbers increase max_states_per_insn and verification time, 18340 * but do not meaningfully decrease insn_processed. 18341 * 'n' controls how many times state could miss before eviction. 18342 * Use bigger 'n' for checkpoints because evicting checkpoint states 18343 * too early would hinder iterator convergence. 18344 */ 18345 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 18346 if (sl->miss_cnt > sl->hit_cnt * n + n) { 18347 /* the state is unlikely to be useful. Remove it to 18348 * speed up verification 18349 */ 18350 *pprev = sl->next; 18351 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE && 18352 !sl->state.used_as_loop_entry) { 18353 u32 br = sl->state.branches; 18354 18355 WARN_ONCE(br, 18356 "BUG live_done but branches_to_explore %d\n", 18357 br); 18358 free_verifier_state(&sl->state, false); 18359 kfree(sl); 18360 env->peak_states--; 18361 } else { 18362 /* cannot free this state, since parentage chain may 18363 * walk it later. Add it for free_list instead to 18364 * be freed at the end of verification 18365 */ 18366 sl->next = env->free_list; 18367 env->free_list = sl; 18368 } 18369 sl = *pprev; 18370 continue; 18371 } 18372 next: 18373 pprev = &sl->next; 18374 sl = *pprev; 18375 } 18376 18377 if (env->max_states_per_insn < states_cnt) 18378 env->max_states_per_insn = states_cnt; 18379 18380 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 18381 return 0; 18382 18383 if (!add_new_state) 18384 return 0; 18385 18386 /* There were no equivalent states, remember the current one. 18387 * Technically the current state is not proven to be safe yet, 18388 * but it will either reach outer most bpf_exit (which means it's safe) 18389 * or it will be rejected. When there are no loops the verifier won't be 18390 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 18391 * again on the way to bpf_exit. 18392 * When looping the sl->state.branches will be > 0 and this state 18393 * will not be considered for equivalence until branches == 0. 18394 */ 18395 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 18396 if (!new_sl) 18397 return -ENOMEM; 18398 env->total_states++; 18399 env->peak_states++; 18400 env->prev_jmps_processed = env->jmps_processed; 18401 env->prev_insn_processed = env->insn_processed; 18402 18403 /* forget precise markings we inherited, see __mark_chain_precision */ 18404 if (env->bpf_capable) 18405 mark_all_scalars_imprecise(env, cur); 18406 18407 /* add new state to the head of linked list */ 18408 new = &new_sl->state; 18409 err = copy_verifier_state(new, cur); 18410 if (err) { 18411 free_verifier_state(new, false); 18412 kfree(new_sl); 18413 return err; 18414 } 18415 new->insn_idx = insn_idx; 18416 WARN_ONCE(new->branches != 1, 18417 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 18418 18419 cur->parent = new; 18420 cur->first_insn_idx = insn_idx; 18421 cur->insn_hist_start = cur->insn_hist_end; 18422 cur->dfs_depth = new->dfs_depth + 1; 18423 new_sl->next = *explored_state(env, insn_idx); 18424 *explored_state(env, insn_idx) = new_sl; 18425 /* connect new state to parentage chain. Current frame needs all 18426 * registers connected. Only r6 - r9 of the callers are alive (pushed 18427 * to the stack implicitly by JITs) so in callers' frames connect just 18428 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 18429 * the state of the call instruction (with WRITTEN set), and r0 comes 18430 * from callee with its full parentage chain, anyway. 18431 */ 18432 /* clear write marks in current state: the writes we did are not writes 18433 * our child did, so they don't screen off its reads from us. 18434 * (There are no read marks in current state, because reads always mark 18435 * their parent and current state never has children yet. Only 18436 * explored_states can get read marks.) 18437 */ 18438 for (j = 0; j <= cur->curframe; j++) { 18439 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 18440 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 18441 for (i = 0; i < BPF_REG_FP; i++) 18442 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 18443 } 18444 18445 /* all stack frames are accessible from callee, clear them all */ 18446 for (j = 0; j <= cur->curframe; j++) { 18447 struct bpf_func_state *frame = cur->frame[j]; 18448 struct bpf_func_state *newframe = new->frame[j]; 18449 18450 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 18451 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 18452 frame->stack[i].spilled_ptr.parent = 18453 &newframe->stack[i].spilled_ptr; 18454 } 18455 } 18456 return 0; 18457 } 18458 18459 /* Return true if it's OK to have the same insn return a different type. */ 18460 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 18461 { 18462 switch (base_type(type)) { 18463 case PTR_TO_CTX: 18464 case PTR_TO_SOCKET: 18465 case PTR_TO_SOCK_COMMON: 18466 case PTR_TO_TCP_SOCK: 18467 case PTR_TO_XDP_SOCK: 18468 case PTR_TO_BTF_ID: 18469 case PTR_TO_ARENA: 18470 return false; 18471 default: 18472 return true; 18473 } 18474 } 18475 18476 /* If an instruction was previously used with particular pointer types, then we 18477 * need to be careful to avoid cases such as the below, where it may be ok 18478 * for one branch accessing the pointer, but not ok for the other branch: 18479 * 18480 * R1 = sock_ptr 18481 * goto X; 18482 * ... 18483 * R1 = some_other_valid_ptr; 18484 * goto X; 18485 * ... 18486 * R2 = *(u32 *)(R1 + 0); 18487 */ 18488 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 18489 { 18490 return src != prev && (!reg_type_mismatch_ok(src) || 18491 !reg_type_mismatch_ok(prev)); 18492 } 18493 18494 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 18495 bool allow_trust_mismatch) 18496 { 18497 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 18498 18499 if (*prev_type == NOT_INIT) { 18500 /* Saw a valid insn 18501 * dst_reg = *(u32 *)(src_reg + off) 18502 * save type to validate intersecting paths 18503 */ 18504 *prev_type = type; 18505 } else if (reg_type_mismatch(type, *prev_type)) { 18506 /* Abuser program is trying to use the same insn 18507 * dst_reg = *(u32*) (src_reg + off) 18508 * with different pointer types: 18509 * src_reg == ctx in one branch and 18510 * src_reg == stack|map in some other branch. 18511 * Reject it. 18512 */ 18513 if (allow_trust_mismatch && 18514 base_type(type) == PTR_TO_BTF_ID && 18515 base_type(*prev_type) == PTR_TO_BTF_ID) { 18516 /* 18517 * Have to support a use case when one path through 18518 * the program yields TRUSTED pointer while another 18519 * is UNTRUSTED. Fallback to UNTRUSTED to generate 18520 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 18521 */ 18522 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 18523 } else { 18524 verbose(env, "same insn cannot be used with different pointers\n"); 18525 return -EINVAL; 18526 } 18527 } 18528 18529 return 0; 18530 } 18531 18532 static int do_check(struct bpf_verifier_env *env) 18533 { 18534 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 18535 struct bpf_verifier_state *state = env->cur_state; 18536 struct bpf_insn *insns = env->prog->insnsi; 18537 struct bpf_reg_state *regs; 18538 int insn_cnt = env->prog->len; 18539 bool do_print_state = false; 18540 int prev_insn_idx = -1; 18541 18542 for (;;) { 18543 bool exception_exit = false; 18544 struct bpf_insn *insn; 18545 u8 class; 18546 int err; 18547 18548 /* reset current history entry on each new instruction */ 18549 env->cur_hist_ent = NULL; 18550 18551 env->prev_insn_idx = prev_insn_idx; 18552 if (env->insn_idx >= insn_cnt) { 18553 verbose(env, "invalid insn idx %d insn_cnt %d\n", 18554 env->insn_idx, insn_cnt); 18555 return -EFAULT; 18556 } 18557 18558 insn = &insns[env->insn_idx]; 18559 class = BPF_CLASS(insn->code); 18560 18561 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 18562 verbose(env, 18563 "BPF program is too large. Processed %d insn\n", 18564 env->insn_processed); 18565 return -E2BIG; 18566 } 18567 18568 state->last_insn_idx = env->prev_insn_idx; 18569 18570 if (is_prune_point(env, env->insn_idx)) { 18571 err = is_state_visited(env, env->insn_idx); 18572 if (err < 0) 18573 return err; 18574 if (err == 1) { 18575 /* found equivalent state, can prune the search */ 18576 if (env->log.level & BPF_LOG_LEVEL) { 18577 if (do_print_state) 18578 verbose(env, "\nfrom %d to %d%s: safe\n", 18579 env->prev_insn_idx, env->insn_idx, 18580 env->cur_state->speculative ? 18581 " (speculative execution)" : ""); 18582 else 18583 verbose(env, "%d: safe\n", env->insn_idx); 18584 } 18585 goto process_bpf_exit; 18586 } 18587 } 18588 18589 if (is_jmp_point(env, env->insn_idx)) { 18590 err = push_insn_history(env, state, 0, 0); 18591 if (err) 18592 return err; 18593 } 18594 18595 if (signal_pending(current)) 18596 return -EAGAIN; 18597 18598 if (need_resched()) 18599 cond_resched(); 18600 18601 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 18602 verbose(env, "\nfrom %d to %d%s:", 18603 env->prev_insn_idx, env->insn_idx, 18604 env->cur_state->speculative ? 18605 " (speculative execution)" : ""); 18606 print_verifier_state(env, state->frame[state->curframe], true); 18607 do_print_state = false; 18608 } 18609 18610 if (env->log.level & BPF_LOG_LEVEL) { 18611 const struct bpf_insn_cbs cbs = { 18612 .cb_call = disasm_kfunc_name, 18613 .cb_print = verbose, 18614 .private_data = env, 18615 }; 18616 18617 if (verifier_state_scratched(env)) 18618 print_insn_state(env, state->frame[state->curframe]); 18619 18620 verbose_linfo(env, env->insn_idx, "; "); 18621 env->prev_log_pos = env->log.end_pos; 18622 verbose(env, "%d: ", env->insn_idx); 18623 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 18624 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 18625 env->prev_log_pos = env->log.end_pos; 18626 } 18627 18628 if (bpf_prog_is_offloaded(env->prog->aux)) { 18629 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 18630 env->prev_insn_idx); 18631 if (err) 18632 return err; 18633 } 18634 18635 regs = cur_regs(env); 18636 sanitize_mark_insn_seen(env); 18637 prev_insn_idx = env->insn_idx; 18638 18639 if (class == BPF_ALU || class == BPF_ALU64) { 18640 err = check_alu_op(env, insn); 18641 if (err) 18642 return err; 18643 18644 } else if (class == BPF_LDX) { 18645 enum bpf_reg_type src_reg_type; 18646 18647 /* check for reserved fields is already done */ 18648 18649 /* check src operand */ 18650 err = check_reg_arg(env, insn->src_reg, SRC_OP); 18651 if (err) 18652 return err; 18653 18654 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 18655 if (err) 18656 return err; 18657 18658 src_reg_type = regs[insn->src_reg].type; 18659 18660 /* check that memory (src_reg + off) is readable, 18661 * the state of dst_reg will be updated by this func 18662 */ 18663 err = check_mem_access(env, env->insn_idx, insn->src_reg, 18664 insn->off, BPF_SIZE(insn->code), 18665 BPF_READ, insn->dst_reg, false, 18666 BPF_MODE(insn->code) == BPF_MEMSX); 18667 err = err ?: save_aux_ptr_type(env, src_reg_type, true); 18668 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], "ldx"); 18669 if (err) 18670 return err; 18671 } else if (class == BPF_STX) { 18672 enum bpf_reg_type dst_reg_type; 18673 18674 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 18675 err = check_atomic(env, env->insn_idx, insn); 18676 if (err) 18677 return err; 18678 env->insn_idx++; 18679 continue; 18680 } 18681 18682 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 18683 verbose(env, "BPF_STX uses reserved fields\n"); 18684 return -EINVAL; 18685 } 18686 18687 /* check src1 operand */ 18688 err = check_reg_arg(env, insn->src_reg, SRC_OP); 18689 if (err) 18690 return err; 18691 /* check src2 operand */ 18692 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 18693 if (err) 18694 return err; 18695 18696 dst_reg_type = regs[insn->dst_reg].type; 18697 18698 /* check that memory (dst_reg + off) is writeable */ 18699 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 18700 insn->off, BPF_SIZE(insn->code), 18701 BPF_WRITE, insn->src_reg, false, false); 18702 if (err) 18703 return err; 18704 18705 err = save_aux_ptr_type(env, dst_reg_type, false); 18706 if (err) 18707 return err; 18708 } else if (class == BPF_ST) { 18709 enum bpf_reg_type dst_reg_type; 18710 18711 if (BPF_MODE(insn->code) != BPF_MEM || 18712 insn->src_reg != BPF_REG_0) { 18713 verbose(env, "BPF_ST uses reserved fields\n"); 18714 return -EINVAL; 18715 } 18716 /* check src operand */ 18717 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 18718 if (err) 18719 return err; 18720 18721 dst_reg_type = regs[insn->dst_reg].type; 18722 18723 /* check that memory (dst_reg + off) is writeable */ 18724 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 18725 insn->off, BPF_SIZE(insn->code), 18726 BPF_WRITE, -1, false, false); 18727 if (err) 18728 return err; 18729 18730 err = save_aux_ptr_type(env, dst_reg_type, false); 18731 if (err) 18732 return err; 18733 } else if (class == BPF_JMP || class == BPF_JMP32) { 18734 u8 opcode = BPF_OP(insn->code); 18735 18736 env->jmps_processed++; 18737 if (opcode == BPF_CALL) { 18738 if (BPF_SRC(insn->code) != BPF_K || 18739 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 18740 && insn->off != 0) || 18741 (insn->src_reg != BPF_REG_0 && 18742 insn->src_reg != BPF_PSEUDO_CALL && 18743 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 18744 insn->dst_reg != BPF_REG_0 || 18745 class == BPF_JMP32) { 18746 verbose(env, "BPF_CALL uses reserved fields\n"); 18747 return -EINVAL; 18748 } 18749 18750 if (cur_func(env)->active_locks) { 18751 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 18752 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 18753 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 18754 verbose(env, "function calls are not allowed while holding a lock\n"); 18755 return -EINVAL; 18756 } 18757 } 18758 if (insn->src_reg == BPF_PSEUDO_CALL) { 18759 err = check_func_call(env, insn, &env->insn_idx); 18760 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 18761 err = check_kfunc_call(env, insn, &env->insn_idx); 18762 if (!err && is_bpf_throw_kfunc(insn)) { 18763 exception_exit = true; 18764 goto process_bpf_exit_full; 18765 } 18766 } else { 18767 err = check_helper_call(env, insn, &env->insn_idx); 18768 } 18769 if (err) 18770 return err; 18771 18772 mark_reg_scratched(env, BPF_REG_0); 18773 } else if (opcode == BPF_JA) { 18774 if (BPF_SRC(insn->code) != BPF_K || 18775 insn->src_reg != BPF_REG_0 || 18776 insn->dst_reg != BPF_REG_0 || 18777 (class == BPF_JMP && insn->imm != 0) || 18778 (class == BPF_JMP32 && insn->off != 0)) { 18779 verbose(env, "BPF_JA uses reserved fields\n"); 18780 return -EINVAL; 18781 } 18782 18783 if (class == BPF_JMP) 18784 env->insn_idx += insn->off + 1; 18785 else 18786 env->insn_idx += insn->imm + 1; 18787 continue; 18788 18789 } else if (opcode == BPF_EXIT) { 18790 if (BPF_SRC(insn->code) != BPF_K || 18791 insn->imm != 0 || 18792 insn->src_reg != BPF_REG_0 || 18793 insn->dst_reg != BPF_REG_0 || 18794 class == BPF_JMP32) { 18795 verbose(env, "BPF_EXIT uses reserved fields\n"); 18796 return -EINVAL; 18797 } 18798 process_bpf_exit_full: 18799 /* We must do check_reference_leak here before 18800 * prepare_func_exit to handle the case when 18801 * state->curframe > 0, it may be a callback 18802 * function, for which reference_state must 18803 * match caller reference state when it exits. 18804 */ 18805 err = check_resource_leak(env, exception_exit, !env->cur_state->curframe, 18806 "BPF_EXIT instruction"); 18807 if (err) 18808 return err; 18809 18810 /* The side effect of the prepare_func_exit 18811 * which is being skipped is that it frees 18812 * bpf_func_state. Typically, process_bpf_exit 18813 * will only be hit with outermost exit. 18814 * copy_verifier_state in pop_stack will handle 18815 * freeing of any extra bpf_func_state left over 18816 * from not processing all nested function 18817 * exits. We also skip return code checks as 18818 * they are not needed for exceptional exits. 18819 */ 18820 if (exception_exit) 18821 goto process_bpf_exit; 18822 18823 if (state->curframe) { 18824 /* exit from nested function */ 18825 err = prepare_func_exit(env, &env->insn_idx); 18826 if (err) 18827 return err; 18828 do_print_state = true; 18829 continue; 18830 } 18831 18832 err = check_return_code(env, BPF_REG_0, "R0"); 18833 if (err) 18834 return err; 18835 process_bpf_exit: 18836 mark_verifier_state_scratched(env); 18837 update_branch_counts(env, env->cur_state); 18838 err = pop_stack(env, &prev_insn_idx, 18839 &env->insn_idx, pop_log); 18840 if (err < 0) { 18841 if (err != -ENOENT) 18842 return err; 18843 break; 18844 } else { 18845 do_print_state = true; 18846 continue; 18847 } 18848 } else { 18849 err = check_cond_jmp_op(env, insn, &env->insn_idx); 18850 if (err) 18851 return err; 18852 } 18853 } else if (class == BPF_LD) { 18854 u8 mode = BPF_MODE(insn->code); 18855 18856 if (mode == BPF_ABS || mode == BPF_IND) { 18857 err = check_ld_abs(env, insn); 18858 if (err) 18859 return err; 18860 18861 } else if (mode == BPF_IMM) { 18862 err = check_ld_imm(env, insn); 18863 if (err) 18864 return err; 18865 18866 env->insn_idx++; 18867 sanitize_mark_insn_seen(env); 18868 } else { 18869 verbose(env, "invalid BPF_LD mode\n"); 18870 return -EINVAL; 18871 } 18872 } else { 18873 verbose(env, "unknown insn class %d\n", class); 18874 return -EINVAL; 18875 } 18876 18877 env->insn_idx++; 18878 } 18879 18880 return 0; 18881 } 18882 18883 static int find_btf_percpu_datasec(struct btf *btf) 18884 { 18885 const struct btf_type *t; 18886 const char *tname; 18887 int i, n; 18888 18889 /* 18890 * Both vmlinux and module each have their own ".data..percpu" 18891 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 18892 * types to look at only module's own BTF types. 18893 */ 18894 n = btf_nr_types(btf); 18895 if (btf_is_module(btf)) 18896 i = btf_nr_types(btf_vmlinux); 18897 else 18898 i = 1; 18899 18900 for(; i < n; i++) { 18901 t = btf_type_by_id(btf, i); 18902 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 18903 continue; 18904 18905 tname = btf_name_by_offset(btf, t->name_off); 18906 if (!strcmp(tname, ".data..percpu")) 18907 return i; 18908 } 18909 18910 return -ENOENT; 18911 } 18912 18913 /* replace pseudo btf_id with kernel symbol address */ 18914 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 18915 struct bpf_insn *insn, 18916 struct bpf_insn_aux_data *aux) 18917 { 18918 const struct btf_var_secinfo *vsi; 18919 const struct btf_type *datasec; 18920 struct btf_mod_pair *btf_mod; 18921 const struct btf_type *t; 18922 const char *sym_name; 18923 bool percpu = false; 18924 u32 type, id = insn->imm; 18925 struct btf *btf; 18926 s32 datasec_id; 18927 u64 addr; 18928 int i, btf_fd, err; 18929 18930 btf_fd = insn[1].imm; 18931 if (btf_fd) { 18932 btf = btf_get_by_fd(btf_fd); 18933 if (IS_ERR(btf)) { 18934 verbose(env, "invalid module BTF object FD specified.\n"); 18935 return -EINVAL; 18936 } 18937 } else { 18938 if (!btf_vmlinux) { 18939 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 18940 return -EINVAL; 18941 } 18942 btf = btf_vmlinux; 18943 btf_get(btf); 18944 } 18945 18946 t = btf_type_by_id(btf, id); 18947 if (!t) { 18948 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 18949 err = -ENOENT; 18950 goto err_put; 18951 } 18952 18953 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 18954 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 18955 err = -EINVAL; 18956 goto err_put; 18957 } 18958 18959 sym_name = btf_name_by_offset(btf, t->name_off); 18960 addr = kallsyms_lookup_name(sym_name); 18961 if (!addr) { 18962 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 18963 sym_name); 18964 err = -ENOENT; 18965 goto err_put; 18966 } 18967 insn[0].imm = (u32)addr; 18968 insn[1].imm = addr >> 32; 18969 18970 if (btf_type_is_func(t)) { 18971 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 18972 aux->btf_var.mem_size = 0; 18973 goto check_btf; 18974 } 18975 18976 datasec_id = find_btf_percpu_datasec(btf); 18977 if (datasec_id > 0) { 18978 datasec = btf_type_by_id(btf, datasec_id); 18979 for_each_vsi(i, datasec, vsi) { 18980 if (vsi->type == id) { 18981 percpu = true; 18982 break; 18983 } 18984 } 18985 } 18986 18987 type = t->type; 18988 t = btf_type_skip_modifiers(btf, type, NULL); 18989 if (percpu) { 18990 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 18991 aux->btf_var.btf = btf; 18992 aux->btf_var.btf_id = type; 18993 } else if (!btf_type_is_struct(t)) { 18994 const struct btf_type *ret; 18995 const char *tname; 18996 u32 tsize; 18997 18998 /* resolve the type size of ksym. */ 18999 ret = btf_resolve_size(btf, t, &tsize); 19000 if (IS_ERR(ret)) { 19001 tname = btf_name_by_offset(btf, t->name_off); 19002 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 19003 tname, PTR_ERR(ret)); 19004 err = -EINVAL; 19005 goto err_put; 19006 } 19007 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 19008 aux->btf_var.mem_size = tsize; 19009 } else { 19010 aux->btf_var.reg_type = PTR_TO_BTF_ID; 19011 aux->btf_var.btf = btf; 19012 aux->btf_var.btf_id = type; 19013 } 19014 check_btf: 19015 /* check whether we recorded this BTF (and maybe module) already */ 19016 for (i = 0; i < env->used_btf_cnt; i++) { 19017 if (env->used_btfs[i].btf == btf) { 19018 btf_put(btf); 19019 return 0; 19020 } 19021 } 19022 19023 if (env->used_btf_cnt >= MAX_USED_BTFS) { 19024 err = -E2BIG; 19025 goto err_put; 19026 } 19027 19028 btf_mod = &env->used_btfs[env->used_btf_cnt]; 19029 btf_mod->btf = btf; 19030 btf_mod->module = NULL; 19031 19032 /* if we reference variables from kernel module, bump its refcount */ 19033 if (btf_is_module(btf)) { 19034 btf_mod->module = btf_try_get_module(btf); 19035 if (!btf_mod->module) { 19036 err = -ENXIO; 19037 goto err_put; 19038 } 19039 } 19040 19041 env->used_btf_cnt++; 19042 19043 return 0; 19044 err_put: 19045 btf_put(btf); 19046 return err; 19047 } 19048 19049 static bool is_tracing_prog_type(enum bpf_prog_type type) 19050 { 19051 switch (type) { 19052 case BPF_PROG_TYPE_KPROBE: 19053 case BPF_PROG_TYPE_TRACEPOINT: 19054 case BPF_PROG_TYPE_PERF_EVENT: 19055 case BPF_PROG_TYPE_RAW_TRACEPOINT: 19056 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 19057 return true; 19058 default: 19059 return false; 19060 } 19061 } 19062 19063 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 19064 struct bpf_map *map, 19065 struct bpf_prog *prog) 19066 19067 { 19068 enum bpf_prog_type prog_type = resolve_prog_type(prog); 19069 19070 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 19071 btf_record_has_field(map->record, BPF_RB_ROOT)) { 19072 if (is_tracing_prog_type(prog_type)) { 19073 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 19074 return -EINVAL; 19075 } 19076 } 19077 19078 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 19079 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 19080 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 19081 return -EINVAL; 19082 } 19083 19084 if (is_tracing_prog_type(prog_type)) { 19085 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 19086 return -EINVAL; 19087 } 19088 } 19089 19090 if (btf_record_has_field(map->record, BPF_TIMER)) { 19091 if (is_tracing_prog_type(prog_type)) { 19092 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 19093 return -EINVAL; 19094 } 19095 } 19096 19097 if (btf_record_has_field(map->record, BPF_WORKQUEUE)) { 19098 if (is_tracing_prog_type(prog_type)) { 19099 verbose(env, "tracing progs cannot use bpf_wq yet\n"); 19100 return -EINVAL; 19101 } 19102 } 19103 19104 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 19105 !bpf_offload_prog_map_match(prog, map)) { 19106 verbose(env, "offload device mismatch between prog and map\n"); 19107 return -EINVAL; 19108 } 19109 19110 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 19111 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 19112 return -EINVAL; 19113 } 19114 19115 if (prog->sleepable) 19116 switch (map->map_type) { 19117 case BPF_MAP_TYPE_HASH: 19118 case BPF_MAP_TYPE_LRU_HASH: 19119 case BPF_MAP_TYPE_ARRAY: 19120 case BPF_MAP_TYPE_PERCPU_HASH: 19121 case BPF_MAP_TYPE_PERCPU_ARRAY: 19122 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 19123 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 19124 case BPF_MAP_TYPE_HASH_OF_MAPS: 19125 case BPF_MAP_TYPE_RINGBUF: 19126 case BPF_MAP_TYPE_USER_RINGBUF: 19127 case BPF_MAP_TYPE_INODE_STORAGE: 19128 case BPF_MAP_TYPE_SK_STORAGE: 19129 case BPF_MAP_TYPE_TASK_STORAGE: 19130 case BPF_MAP_TYPE_CGRP_STORAGE: 19131 case BPF_MAP_TYPE_QUEUE: 19132 case BPF_MAP_TYPE_STACK: 19133 case BPF_MAP_TYPE_ARENA: 19134 break; 19135 default: 19136 verbose(env, 19137 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 19138 return -EINVAL; 19139 } 19140 19141 return 0; 19142 } 19143 19144 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 19145 { 19146 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 19147 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 19148 } 19149 19150 /* Add map behind fd to used maps list, if it's not already there, and return 19151 * its index. Also set *reused to true if this map was already in the list of 19152 * used maps. 19153 * Returns <0 on error, or >= 0 index, on success. 19154 */ 19155 static int add_used_map_from_fd(struct bpf_verifier_env *env, int fd, bool *reused) 19156 { 19157 CLASS(fd, f)(fd); 19158 struct bpf_map *map; 19159 int i; 19160 19161 map = __bpf_map_get(f); 19162 if (IS_ERR(map)) { 19163 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 19164 return PTR_ERR(map); 19165 } 19166 19167 /* check whether we recorded this map already */ 19168 for (i = 0; i < env->used_map_cnt; i++) { 19169 if (env->used_maps[i] == map) { 19170 *reused = true; 19171 return i; 19172 } 19173 } 19174 19175 if (env->used_map_cnt >= MAX_USED_MAPS) { 19176 verbose(env, "The total number of maps per program has reached the limit of %u\n", 19177 MAX_USED_MAPS); 19178 return -E2BIG; 19179 } 19180 19181 if (env->prog->sleepable) 19182 atomic64_inc(&map->sleepable_refcnt); 19183 19184 /* hold the map. If the program is rejected by verifier, 19185 * the map will be released by release_maps() or it 19186 * will be used by the valid program until it's unloaded 19187 * and all maps are released in bpf_free_used_maps() 19188 */ 19189 bpf_map_inc(map); 19190 19191 *reused = false; 19192 env->used_maps[env->used_map_cnt++] = map; 19193 19194 return env->used_map_cnt - 1; 19195 } 19196 19197 /* find and rewrite pseudo imm in ld_imm64 instructions: 19198 * 19199 * 1. if it accesses map FD, replace it with actual map pointer. 19200 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 19201 * 19202 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 19203 */ 19204 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 19205 { 19206 struct bpf_insn *insn = env->prog->insnsi; 19207 int insn_cnt = env->prog->len; 19208 int i, err; 19209 19210 err = bpf_prog_calc_tag(env->prog); 19211 if (err) 19212 return err; 19213 19214 for (i = 0; i < insn_cnt; i++, insn++) { 19215 if (BPF_CLASS(insn->code) == BPF_LDX && 19216 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 19217 insn->imm != 0)) { 19218 verbose(env, "BPF_LDX uses reserved fields\n"); 19219 return -EINVAL; 19220 } 19221 19222 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 19223 struct bpf_insn_aux_data *aux; 19224 struct bpf_map *map; 19225 int map_idx; 19226 u64 addr; 19227 u32 fd; 19228 bool reused; 19229 19230 if (i == insn_cnt - 1 || insn[1].code != 0 || 19231 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 19232 insn[1].off != 0) { 19233 verbose(env, "invalid bpf_ld_imm64 insn\n"); 19234 return -EINVAL; 19235 } 19236 19237 if (insn[0].src_reg == 0) 19238 /* valid generic load 64-bit imm */ 19239 goto next_insn; 19240 19241 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 19242 aux = &env->insn_aux_data[i]; 19243 err = check_pseudo_btf_id(env, insn, aux); 19244 if (err) 19245 return err; 19246 goto next_insn; 19247 } 19248 19249 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 19250 aux = &env->insn_aux_data[i]; 19251 aux->ptr_type = PTR_TO_FUNC; 19252 goto next_insn; 19253 } 19254 19255 /* In final convert_pseudo_ld_imm64() step, this is 19256 * converted into regular 64-bit imm load insn. 19257 */ 19258 switch (insn[0].src_reg) { 19259 case BPF_PSEUDO_MAP_VALUE: 19260 case BPF_PSEUDO_MAP_IDX_VALUE: 19261 break; 19262 case BPF_PSEUDO_MAP_FD: 19263 case BPF_PSEUDO_MAP_IDX: 19264 if (insn[1].imm == 0) 19265 break; 19266 fallthrough; 19267 default: 19268 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 19269 return -EINVAL; 19270 } 19271 19272 switch (insn[0].src_reg) { 19273 case BPF_PSEUDO_MAP_IDX_VALUE: 19274 case BPF_PSEUDO_MAP_IDX: 19275 if (bpfptr_is_null(env->fd_array)) { 19276 verbose(env, "fd_idx without fd_array is invalid\n"); 19277 return -EPROTO; 19278 } 19279 if (copy_from_bpfptr_offset(&fd, env->fd_array, 19280 insn[0].imm * sizeof(fd), 19281 sizeof(fd))) 19282 return -EFAULT; 19283 break; 19284 default: 19285 fd = insn[0].imm; 19286 break; 19287 } 19288 19289 map_idx = add_used_map_from_fd(env, fd, &reused); 19290 if (map_idx < 0) 19291 return map_idx; 19292 map = env->used_maps[map_idx]; 19293 19294 aux = &env->insn_aux_data[i]; 19295 aux->map_index = map_idx; 19296 19297 err = check_map_prog_compatibility(env, map, env->prog); 19298 if (err) 19299 return err; 19300 19301 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 19302 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 19303 addr = (unsigned long)map; 19304 } else { 19305 u32 off = insn[1].imm; 19306 19307 if (off >= BPF_MAX_VAR_OFF) { 19308 verbose(env, "direct value offset of %u is not allowed\n", off); 19309 return -EINVAL; 19310 } 19311 19312 if (!map->ops->map_direct_value_addr) { 19313 verbose(env, "no direct value access support for this map type\n"); 19314 return -EINVAL; 19315 } 19316 19317 err = map->ops->map_direct_value_addr(map, &addr, off); 19318 if (err) { 19319 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 19320 map->value_size, off); 19321 return err; 19322 } 19323 19324 aux->map_off = off; 19325 addr += off; 19326 } 19327 19328 insn[0].imm = (u32)addr; 19329 insn[1].imm = addr >> 32; 19330 19331 /* proceed with extra checks only if its newly added used map */ 19332 if (reused) 19333 goto next_insn; 19334 19335 if (bpf_map_is_cgroup_storage(map) && 19336 bpf_cgroup_storage_assign(env->prog->aux, map)) { 19337 verbose(env, "only one cgroup storage of each type is allowed\n"); 19338 return -EBUSY; 19339 } 19340 if (map->map_type == BPF_MAP_TYPE_ARENA) { 19341 if (env->prog->aux->arena) { 19342 verbose(env, "Only one arena per program\n"); 19343 return -EBUSY; 19344 } 19345 if (!env->allow_ptr_leaks || !env->bpf_capable) { 19346 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n"); 19347 return -EPERM; 19348 } 19349 if (!env->prog->jit_requested) { 19350 verbose(env, "JIT is required to use arena\n"); 19351 return -EOPNOTSUPP; 19352 } 19353 if (!bpf_jit_supports_arena()) { 19354 verbose(env, "JIT doesn't support arena\n"); 19355 return -EOPNOTSUPP; 19356 } 19357 env->prog->aux->arena = (void *)map; 19358 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) { 19359 verbose(env, "arena's user address must be set via map_extra or mmap()\n"); 19360 return -EINVAL; 19361 } 19362 } 19363 19364 next_insn: 19365 insn++; 19366 i++; 19367 continue; 19368 } 19369 19370 /* Basic sanity check before we invest more work here. */ 19371 if (!bpf_opcode_in_insntable(insn->code)) { 19372 verbose(env, "unknown opcode %02x\n", insn->code); 19373 return -EINVAL; 19374 } 19375 } 19376 19377 /* now all pseudo BPF_LD_IMM64 instructions load valid 19378 * 'struct bpf_map *' into a register instead of user map_fd. 19379 * These pointers will be used later by verifier to validate map access. 19380 */ 19381 return 0; 19382 } 19383 19384 /* drop refcnt of maps used by the rejected program */ 19385 static void release_maps(struct bpf_verifier_env *env) 19386 { 19387 __bpf_free_used_maps(env->prog->aux, env->used_maps, 19388 env->used_map_cnt); 19389 } 19390 19391 /* drop refcnt of maps used by the rejected program */ 19392 static void release_btfs(struct bpf_verifier_env *env) 19393 { 19394 __bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt); 19395 } 19396 19397 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 19398 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 19399 { 19400 struct bpf_insn *insn = env->prog->insnsi; 19401 int insn_cnt = env->prog->len; 19402 int i; 19403 19404 for (i = 0; i < insn_cnt; i++, insn++) { 19405 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 19406 continue; 19407 if (insn->src_reg == BPF_PSEUDO_FUNC) 19408 continue; 19409 insn->src_reg = 0; 19410 } 19411 } 19412 19413 /* single env->prog->insni[off] instruction was replaced with the range 19414 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 19415 * [0, off) and [off, end) to new locations, so the patched range stays zero 19416 */ 19417 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 19418 struct bpf_insn_aux_data *new_data, 19419 struct bpf_prog *new_prog, u32 off, u32 cnt) 19420 { 19421 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 19422 struct bpf_insn *insn = new_prog->insnsi; 19423 u32 old_seen = old_data[off].seen; 19424 u32 prog_len; 19425 int i; 19426 19427 /* aux info at OFF always needs adjustment, no matter fast path 19428 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 19429 * original insn at old prog. 19430 */ 19431 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 19432 19433 if (cnt == 1) 19434 return; 19435 prog_len = new_prog->len; 19436 19437 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 19438 memcpy(new_data + off + cnt - 1, old_data + off, 19439 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 19440 for (i = off; i < off + cnt - 1; i++) { 19441 /* Expand insni[off]'s seen count to the patched range. */ 19442 new_data[i].seen = old_seen; 19443 new_data[i].zext_dst = insn_has_def32(env, insn + i); 19444 } 19445 env->insn_aux_data = new_data; 19446 vfree(old_data); 19447 } 19448 19449 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 19450 { 19451 int i; 19452 19453 if (len == 1) 19454 return; 19455 /* NOTE: fake 'exit' subprog should be updated as well. */ 19456 for (i = 0; i <= env->subprog_cnt; i++) { 19457 if (env->subprog_info[i].start <= off) 19458 continue; 19459 env->subprog_info[i].start += len - 1; 19460 } 19461 } 19462 19463 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 19464 { 19465 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 19466 int i, sz = prog->aux->size_poke_tab; 19467 struct bpf_jit_poke_descriptor *desc; 19468 19469 for (i = 0; i < sz; i++) { 19470 desc = &tab[i]; 19471 if (desc->insn_idx <= off) 19472 continue; 19473 desc->insn_idx += len - 1; 19474 } 19475 } 19476 19477 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 19478 const struct bpf_insn *patch, u32 len) 19479 { 19480 struct bpf_prog *new_prog; 19481 struct bpf_insn_aux_data *new_data = NULL; 19482 19483 if (len > 1) { 19484 new_data = vzalloc(array_size(env->prog->len + len - 1, 19485 sizeof(struct bpf_insn_aux_data))); 19486 if (!new_data) 19487 return NULL; 19488 } 19489 19490 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 19491 if (IS_ERR(new_prog)) { 19492 if (PTR_ERR(new_prog) == -ERANGE) 19493 verbose(env, 19494 "insn %d cannot be patched due to 16-bit range\n", 19495 env->insn_aux_data[off].orig_idx); 19496 vfree(new_data); 19497 return NULL; 19498 } 19499 adjust_insn_aux_data(env, new_data, new_prog, off, len); 19500 adjust_subprog_starts(env, off, len); 19501 adjust_poke_descs(new_prog, off, len); 19502 return new_prog; 19503 } 19504 19505 /* 19506 * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the 19507 * jump offset by 'delta'. 19508 */ 19509 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta) 19510 { 19511 struct bpf_insn *insn = prog->insnsi; 19512 u32 insn_cnt = prog->len, i; 19513 s32 imm; 19514 s16 off; 19515 19516 for (i = 0; i < insn_cnt; i++, insn++) { 19517 u8 code = insn->code; 19518 19519 if (tgt_idx <= i && i < tgt_idx + delta) 19520 continue; 19521 19522 if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) || 19523 BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT) 19524 continue; 19525 19526 if (insn->code == (BPF_JMP32 | BPF_JA)) { 19527 if (i + 1 + insn->imm != tgt_idx) 19528 continue; 19529 if (check_add_overflow(insn->imm, delta, &imm)) 19530 return -ERANGE; 19531 insn->imm = imm; 19532 } else { 19533 if (i + 1 + insn->off != tgt_idx) 19534 continue; 19535 if (check_add_overflow(insn->off, delta, &off)) 19536 return -ERANGE; 19537 insn->off = off; 19538 } 19539 } 19540 return 0; 19541 } 19542 19543 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 19544 u32 off, u32 cnt) 19545 { 19546 int i, j; 19547 19548 /* find first prog starting at or after off (first to remove) */ 19549 for (i = 0; i < env->subprog_cnt; i++) 19550 if (env->subprog_info[i].start >= off) 19551 break; 19552 /* find first prog starting at or after off + cnt (first to stay) */ 19553 for (j = i; j < env->subprog_cnt; j++) 19554 if (env->subprog_info[j].start >= off + cnt) 19555 break; 19556 /* if j doesn't start exactly at off + cnt, we are just removing 19557 * the front of previous prog 19558 */ 19559 if (env->subprog_info[j].start != off + cnt) 19560 j--; 19561 19562 if (j > i) { 19563 struct bpf_prog_aux *aux = env->prog->aux; 19564 int move; 19565 19566 /* move fake 'exit' subprog as well */ 19567 move = env->subprog_cnt + 1 - j; 19568 19569 memmove(env->subprog_info + i, 19570 env->subprog_info + j, 19571 sizeof(*env->subprog_info) * move); 19572 env->subprog_cnt -= j - i; 19573 19574 /* remove func_info */ 19575 if (aux->func_info) { 19576 move = aux->func_info_cnt - j; 19577 19578 memmove(aux->func_info + i, 19579 aux->func_info + j, 19580 sizeof(*aux->func_info) * move); 19581 aux->func_info_cnt -= j - i; 19582 /* func_info->insn_off is set after all code rewrites, 19583 * in adjust_btf_func() - no need to adjust 19584 */ 19585 } 19586 } else { 19587 /* convert i from "first prog to remove" to "first to adjust" */ 19588 if (env->subprog_info[i].start == off) 19589 i++; 19590 } 19591 19592 /* update fake 'exit' subprog as well */ 19593 for (; i <= env->subprog_cnt; i++) 19594 env->subprog_info[i].start -= cnt; 19595 19596 return 0; 19597 } 19598 19599 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 19600 u32 cnt) 19601 { 19602 struct bpf_prog *prog = env->prog; 19603 u32 i, l_off, l_cnt, nr_linfo; 19604 struct bpf_line_info *linfo; 19605 19606 nr_linfo = prog->aux->nr_linfo; 19607 if (!nr_linfo) 19608 return 0; 19609 19610 linfo = prog->aux->linfo; 19611 19612 /* find first line info to remove, count lines to be removed */ 19613 for (i = 0; i < nr_linfo; i++) 19614 if (linfo[i].insn_off >= off) 19615 break; 19616 19617 l_off = i; 19618 l_cnt = 0; 19619 for (; i < nr_linfo; i++) 19620 if (linfo[i].insn_off < off + cnt) 19621 l_cnt++; 19622 else 19623 break; 19624 19625 /* First live insn doesn't match first live linfo, it needs to "inherit" 19626 * last removed linfo. prog is already modified, so prog->len == off 19627 * means no live instructions after (tail of the program was removed). 19628 */ 19629 if (prog->len != off && l_cnt && 19630 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 19631 l_cnt--; 19632 linfo[--i].insn_off = off + cnt; 19633 } 19634 19635 /* remove the line info which refer to the removed instructions */ 19636 if (l_cnt) { 19637 memmove(linfo + l_off, linfo + i, 19638 sizeof(*linfo) * (nr_linfo - i)); 19639 19640 prog->aux->nr_linfo -= l_cnt; 19641 nr_linfo = prog->aux->nr_linfo; 19642 } 19643 19644 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 19645 for (i = l_off; i < nr_linfo; i++) 19646 linfo[i].insn_off -= cnt; 19647 19648 /* fix up all subprogs (incl. 'exit') which start >= off */ 19649 for (i = 0; i <= env->subprog_cnt; i++) 19650 if (env->subprog_info[i].linfo_idx > l_off) { 19651 /* program may have started in the removed region but 19652 * may not be fully removed 19653 */ 19654 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 19655 env->subprog_info[i].linfo_idx -= l_cnt; 19656 else 19657 env->subprog_info[i].linfo_idx = l_off; 19658 } 19659 19660 return 0; 19661 } 19662 19663 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 19664 { 19665 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 19666 unsigned int orig_prog_len = env->prog->len; 19667 int err; 19668 19669 if (bpf_prog_is_offloaded(env->prog->aux)) 19670 bpf_prog_offload_remove_insns(env, off, cnt); 19671 19672 err = bpf_remove_insns(env->prog, off, cnt); 19673 if (err) 19674 return err; 19675 19676 err = adjust_subprog_starts_after_remove(env, off, cnt); 19677 if (err) 19678 return err; 19679 19680 err = bpf_adj_linfo_after_remove(env, off, cnt); 19681 if (err) 19682 return err; 19683 19684 memmove(aux_data + off, aux_data + off + cnt, 19685 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 19686 19687 return 0; 19688 } 19689 19690 /* The verifier does more data flow analysis than llvm and will not 19691 * explore branches that are dead at run time. Malicious programs can 19692 * have dead code too. Therefore replace all dead at-run-time code 19693 * with 'ja -1'. 19694 * 19695 * Just nops are not optimal, e.g. if they would sit at the end of the 19696 * program and through another bug we would manage to jump there, then 19697 * we'd execute beyond program memory otherwise. Returning exception 19698 * code also wouldn't work since we can have subprogs where the dead 19699 * code could be located. 19700 */ 19701 static void sanitize_dead_code(struct bpf_verifier_env *env) 19702 { 19703 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 19704 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 19705 struct bpf_insn *insn = env->prog->insnsi; 19706 const int insn_cnt = env->prog->len; 19707 int i; 19708 19709 for (i = 0; i < insn_cnt; i++) { 19710 if (aux_data[i].seen) 19711 continue; 19712 memcpy(insn + i, &trap, sizeof(trap)); 19713 aux_data[i].zext_dst = false; 19714 } 19715 } 19716 19717 static bool insn_is_cond_jump(u8 code) 19718 { 19719 u8 op; 19720 19721 op = BPF_OP(code); 19722 if (BPF_CLASS(code) == BPF_JMP32) 19723 return op != BPF_JA; 19724 19725 if (BPF_CLASS(code) != BPF_JMP) 19726 return false; 19727 19728 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 19729 } 19730 19731 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 19732 { 19733 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 19734 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 19735 struct bpf_insn *insn = env->prog->insnsi; 19736 const int insn_cnt = env->prog->len; 19737 int i; 19738 19739 for (i = 0; i < insn_cnt; i++, insn++) { 19740 if (!insn_is_cond_jump(insn->code)) 19741 continue; 19742 19743 if (!aux_data[i + 1].seen) 19744 ja.off = insn->off; 19745 else if (!aux_data[i + 1 + insn->off].seen) 19746 ja.off = 0; 19747 else 19748 continue; 19749 19750 if (bpf_prog_is_offloaded(env->prog->aux)) 19751 bpf_prog_offload_replace_insn(env, i, &ja); 19752 19753 memcpy(insn, &ja, sizeof(ja)); 19754 } 19755 } 19756 19757 static int opt_remove_dead_code(struct bpf_verifier_env *env) 19758 { 19759 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 19760 int insn_cnt = env->prog->len; 19761 int i, err; 19762 19763 for (i = 0; i < insn_cnt; i++) { 19764 int j; 19765 19766 j = 0; 19767 while (i + j < insn_cnt && !aux_data[i + j].seen) 19768 j++; 19769 if (!j) 19770 continue; 19771 19772 err = verifier_remove_insns(env, i, j); 19773 if (err) 19774 return err; 19775 insn_cnt = env->prog->len; 19776 } 19777 19778 return 0; 19779 } 19780 19781 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 19782 19783 static int opt_remove_nops(struct bpf_verifier_env *env) 19784 { 19785 const struct bpf_insn ja = NOP; 19786 struct bpf_insn *insn = env->prog->insnsi; 19787 int insn_cnt = env->prog->len; 19788 int i, err; 19789 19790 for (i = 0; i < insn_cnt; i++) { 19791 if (memcmp(&insn[i], &ja, sizeof(ja))) 19792 continue; 19793 19794 err = verifier_remove_insns(env, i, 1); 19795 if (err) 19796 return err; 19797 insn_cnt--; 19798 i--; 19799 } 19800 19801 return 0; 19802 } 19803 19804 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 19805 const union bpf_attr *attr) 19806 { 19807 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 19808 struct bpf_insn_aux_data *aux = env->insn_aux_data; 19809 int i, patch_len, delta = 0, len = env->prog->len; 19810 struct bpf_insn *insns = env->prog->insnsi; 19811 struct bpf_prog *new_prog; 19812 bool rnd_hi32; 19813 19814 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 19815 zext_patch[1] = BPF_ZEXT_REG(0); 19816 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 19817 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 19818 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 19819 for (i = 0; i < len; i++) { 19820 int adj_idx = i + delta; 19821 struct bpf_insn insn; 19822 int load_reg; 19823 19824 insn = insns[adj_idx]; 19825 load_reg = insn_def_regno(&insn); 19826 if (!aux[adj_idx].zext_dst) { 19827 u8 code, class; 19828 u32 imm_rnd; 19829 19830 if (!rnd_hi32) 19831 continue; 19832 19833 code = insn.code; 19834 class = BPF_CLASS(code); 19835 if (load_reg == -1) 19836 continue; 19837 19838 /* NOTE: arg "reg" (the fourth one) is only used for 19839 * BPF_STX + SRC_OP, so it is safe to pass NULL 19840 * here. 19841 */ 19842 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 19843 if (class == BPF_LD && 19844 BPF_MODE(code) == BPF_IMM) 19845 i++; 19846 continue; 19847 } 19848 19849 /* ctx load could be transformed into wider load. */ 19850 if (class == BPF_LDX && 19851 aux[adj_idx].ptr_type == PTR_TO_CTX) 19852 continue; 19853 19854 imm_rnd = get_random_u32(); 19855 rnd_hi32_patch[0] = insn; 19856 rnd_hi32_patch[1].imm = imm_rnd; 19857 rnd_hi32_patch[3].dst_reg = load_reg; 19858 patch = rnd_hi32_patch; 19859 patch_len = 4; 19860 goto apply_patch_buffer; 19861 } 19862 19863 /* Add in an zero-extend instruction if a) the JIT has requested 19864 * it or b) it's a CMPXCHG. 19865 * 19866 * The latter is because: BPF_CMPXCHG always loads a value into 19867 * R0, therefore always zero-extends. However some archs' 19868 * equivalent instruction only does this load when the 19869 * comparison is successful. This detail of CMPXCHG is 19870 * orthogonal to the general zero-extension behaviour of the 19871 * CPU, so it's treated independently of bpf_jit_needs_zext. 19872 */ 19873 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 19874 continue; 19875 19876 /* Zero-extension is done by the caller. */ 19877 if (bpf_pseudo_kfunc_call(&insn)) 19878 continue; 19879 19880 if (WARN_ON(load_reg == -1)) { 19881 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 19882 return -EFAULT; 19883 } 19884 19885 zext_patch[0] = insn; 19886 zext_patch[1].dst_reg = load_reg; 19887 zext_patch[1].src_reg = load_reg; 19888 patch = zext_patch; 19889 patch_len = 2; 19890 apply_patch_buffer: 19891 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 19892 if (!new_prog) 19893 return -ENOMEM; 19894 env->prog = new_prog; 19895 insns = new_prog->insnsi; 19896 aux = env->insn_aux_data; 19897 delta += patch_len - 1; 19898 } 19899 19900 return 0; 19901 } 19902 19903 /* convert load instructions that access fields of a context type into a 19904 * sequence of instructions that access fields of the underlying structure: 19905 * struct __sk_buff -> struct sk_buff 19906 * struct bpf_sock_ops -> struct sock 19907 */ 19908 static int convert_ctx_accesses(struct bpf_verifier_env *env) 19909 { 19910 struct bpf_subprog_info *subprogs = env->subprog_info; 19911 const struct bpf_verifier_ops *ops = env->ops; 19912 int i, cnt, size, ctx_field_size, delta = 0, epilogue_cnt = 0; 19913 const int insn_cnt = env->prog->len; 19914 struct bpf_insn *epilogue_buf = env->epilogue_buf; 19915 struct bpf_insn *insn_buf = env->insn_buf; 19916 struct bpf_insn *insn; 19917 u32 target_size, size_default, off; 19918 struct bpf_prog *new_prog; 19919 enum bpf_access_type type; 19920 bool is_narrower_load; 19921 int epilogue_idx = 0; 19922 19923 if (ops->gen_epilogue) { 19924 epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog, 19925 -(subprogs[0].stack_depth + 8)); 19926 if (epilogue_cnt >= INSN_BUF_SIZE) { 19927 verbose(env, "bpf verifier is misconfigured\n"); 19928 return -EINVAL; 19929 } else if (epilogue_cnt) { 19930 /* Save the ARG_PTR_TO_CTX for the epilogue to use */ 19931 cnt = 0; 19932 subprogs[0].stack_depth += 8; 19933 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1, 19934 -subprogs[0].stack_depth); 19935 insn_buf[cnt++] = env->prog->insnsi[0]; 19936 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 19937 if (!new_prog) 19938 return -ENOMEM; 19939 env->prog = new_prog; 19940 delta += cnt - 1; 19941 } 19942 } 19943 19944 if (ops->gen_prologue || env->seen_direct_write) { 19945 if (!ops->gen_prologue) { 19946 verbose(env, "bpf verifier is misconfigured\n"); 19947 return -EINVAL; 19948 } 19949 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 19950 env->prog); 19951 if (cnt >= INSN_BUF_SIZE) { 19952 verbose(env, "bpf verifier is misconfigured\n"); 19953 return -EINVAL; 19954 } else if (cnt) { 19955 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 19956 if (!new_prog) 19957 return -ENOMEM; 19958 19959 env->prog = new_prog; 19960 delta += cnt - 1; 19961 } 19962 } 19963 19964 if (delta) 19965 WARN_ON(adjust_jmp_off(env->prog, 0, delta)); 19966 19967 if (bpf_prog_is_offloaded(env->prog->aux)) 19968 return 0; 19969 19970 insn = env->prog->insnsi + delta; 19971 19972 for (i = 0; i < insn_cnt; i++, insn++) { 19973 bpf_convert_ctx_access_t convert_ctx_access; 19974 u8 mode; 19975 19976 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 19977 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 19978 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 19979 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 19980 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 19981 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 19982 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 19983 type = BPF_READ; 19984 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 19985 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 19986 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 19987 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 19988 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 19989 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 19990 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 19991 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 19992 type = BPF_WRITE; 19993 } else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) || 19994 insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) && 19995 env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) { 19996 insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code); 19997 env->prog->aux->num_exentries++; 19998 continue; 19999 } else if (insn->code == (BPF_JMP | BPF_EXIT) && 20000 epilogue_cnt && 20001 i + delta < subprogs[1].start) { 20002 /* Generate epilogue for the main prog */ 20003 if (epilogue_idx) { 20004 /* jump back to the earlier generated epilogue */ 20005 insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1); 20006 cnt = 1; 20007 } else { 20008 memcpy(insn_buf, epilogue_buf, 20009 epilogue_cnt * sizeof(*epilogue_buf)); 20010 cnt = epilogue_cnt; 20011 /* epilogue_idx cannot be 0. It must have at 20012 * least one ctx ptr saving insn before the 20013 * epilogue. 20014 */ 20015 epilogue_idx = i + delta; 20016 } 20017 goto patch_insn_buf; 20018 } else { 20019 continue; 20020 } 20021 20022 if (type == BPF_WRITE && 20023 env->insn_aux_data[i + delta].sanitize_stack_spill) { 20024 struct bpf_insn patch[] = { 20025 *insn, 20026 BPF_ST_NOSPEC(), 20027 }; 20028 20029 cnt = ARRAY_SIZE(patch); 20030 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 20031 if (!new_prog) 20032 return -ENOMEM; 20033 20034 delta += cnt - 1; 20035 env->prog = new_prog; 20036 insn = new_prog->insnsi + i + delta; 20037 continue; 20038 } 20039 20040 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 20041 case PTR_TO_CTX: 20042 if (!ops->convert_ctx_access) 20043 continue; 20044 convert_ctx_access = ops->convert_ctx_access; 20045 break; 20046 case PTR_TO_SOCKET: 20047 case PTR_TO_SOCK_COMMON: 20048 convert_ctx_access = bpf_sock_convert_ctx_access; 20049 break; 20050 case PTR_TO_TCP_SOCK: 20051 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 20052 break; 20053 case PTR_TO_XDP_SOCK: 20054 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 20055 break; 20056 case PTR_TO_BTF_ID: 20057 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 20058 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 20059 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 20060 * be said once it is marked PTR_UNTRUSTED, hence we must handle 20061 * any faults for loads into such types. BPF_WRITE is disallowed 20062 * for this case. 20063 */ 20064 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 20065 if (type == BPF_READ) { 20066 if (BPF_MODE(insn->code) == BPF_MEM) 20067 insn->code = BPF_LDX | BPF_PROBE_MEM | 20068 BPF_SIZE((insn)->code); 20069 else 20070 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 20071 BPF_SIZE((insn)->code); 20072 env->prog->aux->num_exentries++; 20073 } 20074 continue; 20075 case PTR_TO_ARENA: 20076 if (BPF_MODE(insn->code) == BPF_MEMSX) { 20077 verbose(env, "sign extending loads from arena are not supported yet\n"); 20078 return -EOPNOTSUPP; 20079 } 20080 insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code); 20081 env->prog->aux->num_exentries++; 20082 continue; 20083 default: 20084 continue; 20085 } 20086 20087 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 20088 size = BPF_LDST_BYTES(insn); 20089 mode = BPF_MODE(insn->code); 20090 20091 /* If the read access is a narrower load of the field, 20092 * convert to a 4/8-byte load, to minimum program type specific 20093 * convert_ctx_access changes. If conversion is successful, 20094 * we will apply proper mask to the result. 20095 */ 20096 is_narrower_load = size < ctx_field_size; 20097 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 20098 off = insn->off; 20099 if (is_narrower_load) { 20100 u8 size_code; 20101 20102 if (type == BPF_WRITE) { 20103 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 20104 return -EINVAL; 20105 } 20106 20107 size_code = BPF_H; 20108 if (ctx_field_size == 4) 20109 size_code = BPF_W; 20110 else if (ctx_field_size == 8) 20111 size_code = BPF_DW; 20112 20113 insn->off = off & ~(size_default - 1); 20114 insn->code = BPF_LDX | BPF_MEM | size_code; 20115 } 20116 20117 target_size = 0; 20118 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 20119 &target_size); 20120 if (cnt == 0 || cnt >= INSN_BUF_SIZE || 20121 (ctx_field_size && !target_size)) { 20122 verbose(env, "bpf verifier is misconfigured\n"); 20123 return -EINVAL; 20124 } 20125 20126 if (is_narrower_load && size < target_size) { 20127 u8 shift = bpf_ctx_narrow_access_offset( 20128 off, size, size_default) * 8; 20129 if (shift && cnt + 1 >= INSN_BUF_SIZE) { 20130 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 20131 return -EINVAL; 20132 } 20133 if (ctx_field_size <= 4) { 20134 if (shift) 20135 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 20136 insn->dst_reg, 20137 shift); 20138 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 20139 (1 << size * 8) - 1); 20140 } else { 20141 if (shift) 20142 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 20143 insn->dst_reg, 20144 shift); 20145 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 20146 (1ULL << size * 8) - 1); 20147 } 20148 } 20149 if (mode == BPF_MEMSX) 20150 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 20151 insn->dst_reg, insn->dst_reg, 20152 size * 8, 0); 20153 20154 patch_insn_buf: 20155 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20156 if (!new_prog) 20157 return -ENOMEM; 20158 20159 delta += cnt - 1; 20160 20161 /* keep walking new program and skip insns we just inserted */ 20162 env->prog = new_prog; 20163 insn = new_prog->insnsi + i + delta; 20164 } 20165 20166 return 0; 20167 } 20168 20169 static int jit_subprogs(struct bpf_verifier_env *env) 20170 { 20171 struct bpf_prog *prog = env->prog, **func, *tmp; 20172 int i, j, subprog_start, subprog_end = 0, len, subprog; 20173 struct bpf_map *map_ptr; 20174 struct bpf_insn *insn; 20175 void *old_bpf_func; 20176 int err, num_exentries; 20177 20178 if (env->subprog_cnt <= 1) 20179 return 0; 20180 20181 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 20182 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 20183 continue; 20184 20185 /* Upon error here we cannot fall back to interpreter but 20186 * need a hard reject of the program. Thus -EFAULT is 20187 * propagated in any case. 20188 */ 20189 subprog = find_subprog(env, i + insn->imm + 1); 20190 if (subprog < 0) { 20191 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 20192 i + insn->imm + 1); 20193 return -EFAULT; 20194 } 20195 /* temporarily remember subprog id inside insn instead of 20196 * aux_data, since next loop will split up all insns into funcs 20197 */ 20198 insn->off = subprog; 20199 /* remember original imm in case JIT fails and fallback 20200 * to interpreter will be needed 20201 */ 20202 env->insn_aux_data[i].call_imm = insn->imm; 20203 /* point imm to __bpf_call_base+1 from JITs point of view */ 20204 insn->imm = 1; 20205 if (bpf_pseudo_func(insn)) { 20206 #if defined(MODULES_VADDR) 20207 u64 addr = MODULES_VADDR; 20208 #else 20209 u64 addr = VMALLOC_START; 20210 #endif 20211 /* jit (e.g. x86_64) may emit fewer instructions 20212 * if it learns a u32 imm is the same as a u64 imm. 20213 * Set close enough to possible prog address. 20214 */ 20215 insn[0].imm = (u32)addr; 20216 insn[1].imm = addr >> 32; 20217 } 20218 } 20219 20220 err = bpf_prog_alloc_jited_linfo(prog); 20221 if (err) 20222 goto out_undo_insn; 20223 20224 err = -ENOMEM; 20225 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 20226 if (!func) 20227 goto out_undo_insn; 20228 20229 for (i = 0; i < env->subprog_cnt; i++) { 20230 subprog_start = subprog_end; 20231 subprog_end = env->subprog_info[i + 1].start; 20232 20233 len = subprog_end - subprog_start; 20234 /* bpf_prog_run() doesn't call subprogs directly, 20235 * hence main prog stats include the runtime of subprogs. 20236 * subprogs don't have IDs and not reachable via prog_get_next_id 20237 * func[i]->stats will never be accessed and stays NULL 20238 */ 20239 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 20240 if (!func[i]) 20241 goto out_free; 20242 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 20243 len * sizeof(struct bpf_insn)); 20244 func[i]->type = prog->type; 20245 func[i]->len = len; 20246 if (bpf_prog_calc_tag(func[i])) 20247 goto out_free; 20248 func[i]->is_func = 1; 20249 func[i]->sleepable = prog->sleepable; 20250 func[i]->aux->func_idx = i; 20251 /* Below members will be freed only at prog->aux */ 20252 func[i]->aux->btf = prog->aux->btf; 20253 func[i]->aux->func_info = prog->aux->func_info; 20254 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 20255 func[i]->aux->poke_tab = prog->aux->poke_tab; 20256 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 20257 20258 for (j = 0; j < prog->aux->size_poke_tab; j++) { 20259 struct bpf_jit_poke_descriptor *poke; 20260 20261 poke = &prog->aux->poke_tab[j]; 20262 if (poke->insn_idx < subprog_end && 20263 poke->insn_idx >= subprog_start) 20264 poke->aux = func[i]->aux; 20265 } 20266 20267 func[i]->aux->name[0] = 'F'; 20268 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 20269 if (env->subprog_info[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) 20270 func[i]->aux->jits_use_priv_stack = true; 20271 20272 func[i]->jit_requested = 1; 20273 func[i]->blinding_requested = prog->blinding_requested; 20274 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 20275 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 20276 func[i]->aux->linfo = prog->aux->linfo; 20277 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 20278 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 20279 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 20280 func[i]->aux->arena = prog->aux->arena; 20281 num_exentries = 0; 20282 insn = func[i]->insnsi; 20283 for (j = 0; j < func[i]->len; j++, insn++) { 20284 if (BPF_CLASS(insn->code) == BPF_LDX && 20285 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 20286 BPF_MODE(insn->code) == BPF_PROBE_MEM32 || 20287 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 20288 num_exentries++; 20289 if ((BPF_CLASS(insn->code) == BPF_STX || 20290 BPF_CLASS(insn->code) == BPF_ST) && 20291 BPF_MODE(insn->code) == BPF_PROBE_MEM32) 20292 num_exentries++; 20293 if (BPF_CLASS(insn->code) == BPF_STX && 20294 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) 20295 num_exentries++; 20296 } 20297 func[i]->aux->num_exentries = num_exentries; 20298 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 20299 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb; 20300 func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data; 20301 if (!i) 20302 func[i]->aux->exception_boundary = env->seen_exception; 20303 func[i] = bpf_int_jit_compile(func[i]); 20304 if (!func[i]->jited) { 20305 err = -ENOTSUPP; 20306 goto out_free; 20307 } 20308 cond_resched(); 20309 } 20310 20311 /* at this point all bpf functions were successfully JITed 20312 * now populate all bpf_calls with correct addresses and 20313 * run last pass of JIT 20314 */ 20315 for (i = 0; i < env->subprog_cnt; i++) { 20316 insn = func[i]->insnsi; 20317 for (j = 0; j < func[i]->len; j++, insn++) { 20318 if (bpf_pseudo_func(insn)) { 20319 subprog = insn->off; 20320 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 20321 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 20322 continue; 20323 } 20324 if (!bpf_pseudo_call(insn)) 20325 continue; 20326 subprog = insn->off; 20327 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 20328 } 20329 20330 /* we use the aux data to keep a list of the start addresses 20331 * of the JITed images for each function in the program 20332 * 20333 * for some architectures, such as powerpc64, the imm field 20334 * might not be large enough to hold the offset of the start 20335 * address of the callee's JITed image from __bpf_call_base 20336 * 20337 * in such cases, we can lookup the start address of a callee 20338 * by using its subprog id, available from the off field of 20339 * the call instruction, as an index for this list 20340 */ 20341 func[i]->aux->func = func; 20342 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 20343 func[i]->aux->real_func_cnt = env->subprog_cnt; 20344 } 20345 for (i = 0; i < env->subprog_cnt; i++) { 20346 old_bpf_func = func[i]->bpf_func; 20347 tmp = bpf_int_jit_compile(func[i]); 20348 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 20349 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 20350 err = -ENOTSUPP; 20351 goto out_free; 20352 } 20353 cond_resched(); 20354 } 20355 20356 /* finally lock prog and jit images for all functions and 20357 * populate kallsysm. Begin at the first subprogram, since 20358 * bpf_prog_load will add the kallsyms for the main program. 20359 */ 20360 for (i = 1; i < env->subprog_cnt; i++) { 20361 err = bpf_prog_lock_ro(func[i]); 20362 if (err) 20363 goto out_free; 20364 } 20365 20366 for (i = 1; i < env->subprog_cnt; i++) 20367 bpf_prog_kallsyms_add(func[i]); 20368 20369 /* Last step: make now unused interpreter insns from main 20370 * prog consistent for later dump requests, so they can 20371 * later look the same as if they were interpreted only. 20372 */ 20373 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 20374 if (bpf_pseudo_func(insn)) { 20375 insn[0].imm = env->insn_aux_data[i].call_imm; 20376 insn[1].imm = insn->off; 20377 insn->off = 0; 20378 continue; 20379 } 20380 if (!bpf_pseudo_call(insn)) 20381 continue; 20382 insn->off = env->insn_aux_data[i].call_imm; 20383 subprog = find_subprog(env, i + insn->off + 1); 20384 insn->imm = subprog; 20385 } 20386 20387 prog->jited = 1; 20388 prog->bpf_func = func[0]->bpf_func; 20389 prog->jited_len = func[0]->jited_len; 20390 prog->aux->extable = func[0]->aux->extable; 20391 prog->aux->num_exentries = func[0]->aux->num_exentries; 20392 prog->aux->func = func; 20393 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 20394 prog->aux->real_func_cnt = env->subprog_cnt; 20395 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func; 20396 prog->aux->exception_boundary = func[0]->aux->exception_boundary; 20397 bpf_prog_jit_attempt_done(prog); 20398 return 0; 20399 out_free: 20400 /* We failed JIT'ing, so at this point we need to unregister poke 20401 * descriptors from subprogs, so that kernel is not attempting to 20402 * patch it anymore as we're freeing the subprog JIT memory. 20403 */ 20404 for (i = 0; i < prog->aux->size_poke_tab; i++) { 20405 map_ptr = prog->aux->poke_tab[i].tail_call.map; 20406 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 20407 } 20408 /* At this point we're guaranteed that poke descriptors are not 20409 * live anymore. We can just unlink its descriptor table as it's 20410 * released with the main prog. 20411 */ 20412 for (i = 0; i < env->subprog_cnt; i++) { 20413 if (!func[i]) 20414 continue; 20415 func[i]->aux->poke_tab = NULL; 20416 bpf_jit_free(func[i]); 20417 } 20418 kfree(func); 20419 out_undo_insn: 20420 /* cleanup main prog to be interpreted */ 20421 prog->jit_requested = 0; 20422 prog->blinding_requested = 0; 20423 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 20424 if (!bpf_pseudo_call(insn)) 20425 continue; 20426 insn->off = 0; 20427 insn->imm = env->insn_aux_data[i].call_imm; 20428 } 20429 bpf_prog_jit_attempt_done(prog); 20430 return err; 20431 } 20432 20433 static int fixup_call_args(struct bpf_verifier_env *env) 20434 { 20435 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 20436 struct bpf_prog *prog = env->prog; 20437 struct bpf_insn *insn = prog->insnsi; 20438 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 20439 int i, depth; 20440 #endif 20441 int err = 0; 20442 20443 if (env->prog->jit_requested && 20444 !bpf_prog_is_offloaded(env->prog->aux)) { 20445 err = jit_subprogs(env); 20446 if (err == 0) 20447 return 0; 20448 if (err == -EFAULT) 20449 return err; 20450 } 20451 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 20452 if (has_kfunc_call) { 20453 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 20454 return -EINVAL; 20455 } 20456 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 20457 /* When JIT fails the progs with bpf2bpf calls and tail_calls 20458 * have to be rejected, since interpreter doesn't support them yet. 20459 */ 20460 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 20461 return -EINVAL; 20462 } 20463 for (i = 0; i < prog->len; i++, insn++) { 20464 if (bpf_pseudo_func(insn)) { 20465 /* When JIT fails the progs with callback calls 20466 * have to be rejected, since interpreter doesn't support them yet. 20467 */ 20468 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 20469 return -EINVAL; 20470 } 20471 20472 if (!bpf_pseudo_call(insn)) 20473 continue; 20474 depth = get_callee_stack_depth(env, insn, i); 20475 if (depth < 0) 20476 return depth; 20477 bpf_patch_call_args(insn, depth); 20478 } 20479 err = 0; 20480 #endif 20481 return err; 20482 } 20483 20484 /* replace a generic kfunc with a specialized version if necessary */ 20485 static void specialize_kfunc(struct bpf_verifier_env *env, 20486 u32 func_id, u16 offset, unsigned long *addr) 20487 { 20488 struct bpf_prog *prog = env->prog; 20489 bool seen_direct_write; 20490 void *xdp_kfunc; 20491 bool is_rdonly; 20492 20493 if (bpf_dev_bound_kfunc_id(func_id)) { 20494 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 20495 if (xdp_kfunc) { 20496 *addr = (unsigned long)xdp_kfunc; 20497 return; 20498 } 20499 /* fallback to default kfunc when not supported by netdev */ 20500 } 20501 20502 if (offset) 20503 return; 20504 20505 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 20506 seen_direct_write = env->seen_direct_write; 20507 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 20508 20509 if (is_rdonly) 20510 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 20511 20512 /* restore env->seen_direct_write to its original value, since 20513 * may_access_direct_pkt_data mutates it 20514 */ 20515 env->seen_direct_write = seen_direct_write; 20516 } 20517 } 20518 20519 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 20520 u16 struct_meta_reg, 20521 u16 node_offset_reg, 20522 struct bpf_insn *insn, 20523 struct bpf_insn *insn_buf, 20524 int *cnt) 20525 { 20526 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 20527 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 20528 20529 insn_buf[0] = addr[0]; 20530 insn_buf[1] = addr[1]; 20531 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 20532 insn_buf[3] = *insn; 20533 *cnt = 4; 20534 } 20535 20536 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 20537 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 20538 { 20539 const struct bpf_kfunc_desc *desc; 20540 20541 if (!insn->imm) { 20542 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 20543 return -EINVAL; 20544 } 20545 20546 *cnt = 0; 20547 20548 /* insn->imm has the btf func_id. Replace it with an offset relative to 20549 * __bpf_call_base, unless the JIT needs to call functions that are 20550 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 20551 */ 20552 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 20553 if (!desc) { 20554 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 20555 insn->imm); 20556 return -EFAULT; 20557 } 20558 20559 if (!bpf_jit_supports_far_kfunc_call()) 20560 insn->imm = BPF_CALL_IMM(desc->addr); 20561 if (insn->off) 20562 return 0; 20563 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 20564 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 20565 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 20566 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 20567 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 20568 20569 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) { 20570 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 20571 insn_idx); 20572 return -EFAULT; 20573 } 20574 20575 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 20576 insn_buf[1] = addr[0]; 20577 insn_buf[2] = addr[1]; 20578 insn_buf[3] = *insn; 20579 *cnt = 4; 20580 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 20581 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] || 20582 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 20583 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 20584 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 20585 20586 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) { 20587 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 20588 insn_idx); 20589 return -EFAULT; 20590 } 20591 20592 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 20593 !kptr_struct_meta) { 20594 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 20595 insn_idx); 20596 return -EFAULT; 20597 } 20598 20599 insn_buf[0] = addr[0]; 20600 insn_buf[1] = addr[1]; 20601 insn_buf[2] = *insn; 20602 *cnt = 3; 20603 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 20604 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 20605 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 20606 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 20607 int struct_meta_reg = BPF_REG_3; 20608 int node_offset_reg = BPF_REG_4; 20609 20610 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 20611 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 20612 struct_meta_reg = BPF_REG_4; 20613 node_offset_reg = BPF_REG_5; 20614 } 20615 20616 if (!kptr_struct_meta) { 20617 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 20618 insn_idx); 20619 return -EFAULT; 20620 } 20621 20622 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 20623 node_offset_reg, insn, insn_buf, cnt); 20624 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 20625 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 20626 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 20627 *cnt = 1; 20628 } else if (is_bpf_wq_set_callback_impl_kfunc(desc->func_id)) { 20629 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(BPF_REG_4, (long)env->prog->aux) }; 20630 20631 insn_buf[0] = ld_addrs[0]; 20632 insn_buf[1] = ld_addrs[1]; 20633 insn_buf[2] = *insn; 20634 *cnt = 3; 20635 } 20636 return 0; 20637 } 20638 20639 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */ 20640 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len) 20641 { 20642 struct bpf_subprog_info *info = env->subprog_info; 20643 int cnt = env->subprog_cnt; 20644 struct bpf_prog *prog; 20645 20646 /* We only reserve one slot for hidden subprogs in subprog_info. */ 20647 if (env->hidden_subprog_cnt) { 20648 verbose(env, "verifier internal error: only one hidden subprog supported\n"); 20649 return -EFAULT; 20650 } 20651 /* We're not patching any existing instruction, just appending the new 20652 * ones for the hidden subprog. Hence all of the adjustment operations 20653 * in bpf_patch_insn_data are no-ops. 20654 */ 20655 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len); 20656 if (!prog) 20657 return -ENOMEM; 20658 env->prog = prog; 20659 info[cnt + 1].start = info[cnt].start; 20660 info[cnt].start = prog->len - len + 1; 20661 env->subprog_cnt++; 20662 env->hidden_subprog_cnt++; 20663 return 0; 20664 } 20665 20666 /* Do various post-verification rewrites in a single program pass. 20667 * These rewrites simplify JIT and interpreter implementations. 20668 */ 20669 static int do_misc_fixups(struct bpf_verifier_env *env) 20670 { 20671 struct bpf_prog *prog = env->prog; 20672 enum bpf_attach_type eatype = prog->expected_attach_type; 20673 enum bpf_prog_type prog_type = resolve_prog_type(prog); 20674 struct bpf_insn *insn = prog->insnsi; 20675 const struct bpf_func_proto *fn; 20676 const int insn_cnt = prog->len; 20677 const struct bpf_map_ops *ops; 20678 struct bpf_insn_aux_data *aux; 20679 struct bpf_insn *insn_buf = env->insn_buf; 20680 struct bpf_prog *new_prog; 20681 struct bpf_map *map_ptr; 20682 int i, ret, cnt, delta = 0, cur_subprog = 0; 20683 struct bpf_subprog_info *subprogs = env->subprog_info; 20684 u16 stack_depth = subprogs[cur_subprog].stack_depth; 20685 u16 stack_depth_extra = 0; 20686 20687 if (env->seen_exception && !env->exception_callback_subprog) { 20688 struct bpf_insn patch[] = { 20689 env->prog->insnsi[insn_cnt - 1], 20690 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1), 20691 BPF_EXIT_INSN(), 20692 }; 20693 20694 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch)); 20695 if (ret < 0) 20696 return ret; 20697 prog = env->prog; 20698 insn = prog->insnsi; 20699 20700 env->exception_callback_subprog = env->subprog_cnt - 1; 20701 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */ 20702 mark_subprog_exc_cb(env, env->exception_callback_subprog); 20703 } 20704 20705 for (i = 0; i < insn_cnt;) { 20706 if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) { 20707 if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) || 20708 (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) { 20709 /* convert to 32-bit mov that clears upper 32-bit */ 20710 insn->code = BPF_ALU | BPF_MOV | BPF_X; 20711 /* clear off and imm, so it's a normal 'wX = wY' from JIT pov */ 20712 insn->off = 0; 20713 insn->imm = 0; 20714 } /* cast from as(0) to as(1) should be handled by JIT */ 20715 goto next_insn; 20716 } 20717 20718 if (env->insn_aux_data[i + delta].needs_zext) 20719 /* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */ 20720 insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code); 20721 20722 /* Make sdiv/smod divide-by-minus-one exceptions impossible. */ 20723 if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) || 20724 insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) || 20725 insn->code == (BPF_ALU | BPF_MOD | BPF_K) || 20726 insn->code == (BPF_ALU | BPF_DIV | BPF_K)) && 20727 insn->off == 1 && insn->imm == -1) { 20728 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 20729 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 20730 struct bpf_insn *patchlet; 20731 struct bpf_insn chk_and_sdiv[] = { 20732 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 20733 BPF_NEG | BPF_K, insn->dst_reg, 20734 0, 0, 0), 20735 }; 20736 struct bpf_insn chk_and_smod[] = { 20737 BPF_MOV32_IMM(insn->dst_reg, 0), 20738 }; 20739 20740 patchlet = isdiv ? chk_and_sdiv : chk_and_smod; 20741 cnt = isdiv ? ARRAY_SIZE(chk_and_sdiv) : ARRAY_SIZE(chk_and_smod); 20742 20743 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 20744 if (!new_prog) 20745 return -ENOMEM; 20746 20747 delta += cnt - 1; 20748 env->prog = prog = new_prog; 20749 insn = new_prog->insnsi + i + delta; 20750 goto next_insn; 20751 } 20752 20753 /* Make divide-by-zero and divide-by-minus-one exceptions impossible. */ 20754 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 20755 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 20756 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 20757 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 20758 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 20759 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 20760 bool is_sdiv = isdiv && insn->off == 1; 20761 bool is_smod = !isdiv && insn->off == 1; 20762 struct bpf_insn *patchlet; 20763 struct bpf_insn chk_and_div[] = { 20764 /* [R,W]x div 0 -> 0 */ 20765 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 20766 BPF_JNE | BPF_K, insn->src_reg, 20767 0, 2, 0), 20768 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 20769 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 20770 *insn, 20771 }; 20772 struct bpf_insn chk_and_mod[] = { 20773 /* [R,W]x mod 0 -> [R,W]x */ 20774 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 20775 BPF_JEQ | BPF_K, insn->src_reg, 20776 0, 1 + (is64 ? 0 : 1), 0), 20777 *insn, 20778 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 20779 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 20780 }; 20781 struct bpf_insn chk_and_sdiv[] = { 20782 /* [R,W]x sdiv 0 -> 0 20783 * LLONG_MIN sdiv -1 -> LLONG_MIN 20784 * INT_MIN sdiv -1 -> INT_MIN 20785 */ 20786 BPF_MOV64_REG(BPF_REG_AX, insn->src_reg), 20787 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 20788 BPF_ADD | BPF_K, BPF_REG_AX, 20789 0, 0, 1), 20790 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 20791 BPF_JGT | BPF_K, BPF_REG_AX, 20792 0, 4, 1), 20793 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 20794 BPF_JEQ | BPF_K, BPF_REG_AX, 20795 0, 1, 0), 20796 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 20797 BPF_MOV | BPF_K, insn->dst_reg, 20798 0, 0, 0), 20799 /* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */ 20800 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 20801 BPF_NEG | BPF_K, insn->dst_reg, 20802 0, 0, 0), 20803 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 20804 *insn, 20805 }; 20806 struct bpf_insn chk_and_smod[] = { 20807 /* [R,W]x mod 0 -> [R,W]x */ 20808 /* [R,W]x mod -1 -> 0 */ 20809 BPF_MOV64_REG(BPF_REG_AX, insn->src_reg), 20810 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 20811 BPF_ADD | BPF_K, BPF_REG_AX, 20812 0, 0, 1), 20813 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 20814 BPF_JGT | BPF_K, BPF_REG_AX, 20815 0, 3, 1), 20816 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 20817 BPF_JEQ | BPF_K, BPF_REG_AX, 20818 0, 3 + (is64 ? 0 : 1), 1), 20819 BPF_MOV32_IMM(insn->dst_reg, 0), 20820 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 20821 *insn, 20822 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 20823 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 20824 }; 20825 20826 if (is_sdiv) { 20827 patchlet = chk_and_sdiv; 20828 cnt = ARRAY_SIZE(chk_and_sdiv); 20829 } else if (is_smod) { 20830 patchlet = chk_and_smod; 20831 cnt = ARRAY_SIZE(chk_and_smod) - (is64 ? 2 : 0); 20832 } else { 20833 patchlet = isdiv ? chk_and_div : chk_and_mod; 20834 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 20835 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 20836 } 20837 20838 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 20839 if (!new_prog) 20840 return -ENOMEM; 20841 20842 delta += cnt - 1; 20843 env->prog = prog = new_prog; 20844 insn = new_prog->insnsi + i + delta; 20845 goto next_insn; 20846 } 20847 20848 /* Make it impossible to de-reference a userspace address */ 20849 if (BPF_CLASS(insn->code) == BPF_LDX && 20850 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 20851 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) { 20852 struct bpf_insn *patch = &insn_buf[0]; 20853 u64 uaddress_limit = bpf_arch_uaddress_limit(); 20854 20855 if (!uaddress_limit) 20856 goto next_insn; 20857 20858 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg); 20859 if (insn->off) 20860 *patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off); 20861 *patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32); 20862 *patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2); 20863 *patch++ = *insn; 20864 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 20865 *patch++ = BPF_MOV64_IMM(insn->dst_reg, 0); 20866 20867 cnt = patch - insn_buf; 20868 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20869 if (!new_prog) 20870 return -ENOMEM; 20871 20872 delta += cnt - 1; 20873 env->prog = prog = new_prog; 20874 insn = new_prog->insnsi + i + delta; 20875 goto next_insn; 20876 } 20877 20878 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 20879 if (BPF_CLASS(insn->code) == BPF_LD && 20880 (BPF_MODE(insn->code) == BPF_ABS || 20881 BPF_MODE(insn->code) == BPF_IND)) { 20882 cnt = env->ops->gen_ld_abs(insn, insn_buf); 20883 if (cnt == 0 || cnt >= INSN_BUF_SIZE) { 20884 verbose(env, "bpf verifier is misconfigured\n"); 20885 return -EINVAL; 20886 } 20887 20888 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20889 if (!new_prog) 20890 return -ENOMEM; 20891 20892 delta += cnt - 1; 20893 env->prog = prog = new_prog; 20894 insn = new_prog->insnsi + i + delta; 20895 goto next_insn; 20896 } 20897 20898 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 20899 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 20900 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 20901 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 20902 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 20903 struct bpf_insn *patch = &insn_buf[0]; 20904 bool issrc, isneg, isimm; 20905 u32 off_reg; 20906 20907 aux = &env->insn_aux_data[i + delta]; 20908 if (!aux->alu_state || 20909 aux->alu_state == BPF_ALU_NON_POINTER) 20910 goto next_insn; 20911 20912 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 20913 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 20914 BPF_ALU_SANITIZE_SRC; 20915 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 20916 20917 off_reg = issrc ? insn->src_reg : insn->dst_reg; 20918 if (isimm) { 20919 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 20920 } else { 20921 if (isneg) 20922 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 20923 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 20924 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 20925 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 20926 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 20927 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 20928 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 20929 } 20930 if (!issrc) 20931 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 20932 insn->src_reg = BPF_REG_AX; 20933 if (isneg) 20934 insn->code = insn->code == code_add ? 20935 code_sub : code_add; 20936 *patch++ = *insn; 20937 if (issrc && isneg && !isimm) 20938 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 20939 cnt = patch - insn_buf; 20940 20941 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20942 if (!new_prog) 20943 return -ENOMEM; 20944 20945 delta += cnt - 1; 20946 env->prog = prog = new_prog; 20947 insn = new_prog->insnsi + i + delta; 20948 goto next_insn; 20949 } 20950 20951 if (is_may_goto_insn(insn)) { 20952 int stack_off = -stack_depth - 8; 20953 20954 stack_depth_extra = 8; 20955 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off); 20956 if (insn->off >= 0) 20957 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2); 20958 else 20959 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1); 20960 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1); 20961 insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off); 20962 cnt = 4; 20963 20964 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20965 if (!new_prog) 20966 return -ENOMEM; 20967 20968 delta += cnt - 1; 20969 env->prog = prog = new_prog; 20970 insn = new_prog->insnsi + i + delta; 20971 goto next_insn; 20972 } 20973 20974 if (insn->code != (BPF_JMP | BPF_CALL)) 20975 goto next_insn; 20976 if (insn->src_reg == BPF_PSEUDO_CALL) 20977 goto next_insn; 20978 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 20979 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 20980 if (ret) 20981 return ret; 20982 if (cnt == 0) 20983 goto next_insn; 20984 20985 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20986 if (!new_prog) 20987 return -ENOMEM; 20988 20989 delta += cnt - 1; 20990 env->prog = prog = new_prog; 20991 insn = new_prog->insnsi + i + delta; 20992 goto next_insn; 20993 } 20994 20995 /* Skip inlining the helper call if the JIT does it. */ 20996 if (bpf_jit_inlines_helper_call(insn->imm)) 20997 goto next_insn; 20998 20999 if (insn->imm == BPF_FUNC_get_route_realm) 21000 prog->dst_needed = 1; 21001 if (insn->imm == BPF_FUNC_get_prandom_u32) 21002 bpf_user_rnd_init_once(); 21003 if (insn->imm == BPF_FUNC_override_return) 21004 prog->kprobe_override = 1; 21005 if (insn->imm == BPF_FUNC_tail_call) { 21006 /* If we tail call into other programs, we 21007 * cannot make any assumptions since they can 21008 * be replaced dynamically during runtime in 21009 * the program array. 21010 */ 21011 prog->cb_access = 1; 21012 if (!allow_tail_call_in_subprogs(env)) 21013 prog->aux->stack_depth = MAX_BPF_STACK; 21014 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 21015 21016 /* mark bpf_tail_call as different opcode to avoid 21017 * conditional branch in the interpreter for every normal 21018 * call and to prevent accidental JITing by JIT compiler 21019 * that doesn't support bpf_tail_call yet 21020 */ 21021 insn->imm = 0; 21022 insn->code = BPF_JMP | BPF_TAIL_CALL; 21023 21024 aux = &env->insn_aux_data[i + delta]; 21025 if (env->bpf_capable && !prog->blinding_requested && 21026 prog->jit_requested && 21027 !bpf_map_key_poisoned(aux) && 21028 !bpf_map_ptr_poisoned(aux) && 21029 !bpf_map_ptr_unpriv(aux)) { 21030 struct bpf_jit_poke_descriptor desc = { 21031 .reason = BPF_POKE_REASON_TAIL_CALL, 21032 .tail_call.map = aux->map_ptr_state.map_ptr, 21033 .tail_call.key = bpf_map_key_immediate(aux), 21034 .insn_idx = i + delta, 21035 }; 21036 21037 ret = bpf_jit_add_poke_descriptor(prog, &desc); 21038 if (ret < 0) { 21039 verbose(env, "adding tail call poke descriptor failed\n"); 21040 return ret; 21041 } 21042 21043 insn->imm = ret + 1; 21044 goto next_insn; 21045 } 21046 21047 if (!bpf_map_ptr_unpriv(aux)) 21048 goto next_insn; 21049 21050 /* instead of changing every JIT dealing with tail_call 21051 * emit two extra insns: 21052 * if (index >= max_entries) goto out; 21053 * index &= array->index_mask; 21054 * to avoid out-of-bounds cpu speculation 21055 */ 21056 if (bpf_map_ptr_poisoned(aux)) { 21057 verbose(env, "tail_call abusing map_ptr\n"); 21058 return -EINVAL; 21059 } 21060 21061 map_ptr = aux->map_ptr_state.map_ptr; 21062 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 21063 map_ptr->max_entries, 2); 21064 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 21065 container_of(map_ptr, 21066 struct bpf_array, 21067 map)->index_mask); 21068 insn_buf[2] = *insn; 21069 cnt = 3; 21070 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21071 if (!new_prog) 21072 return -ENOMEM; 21073 21074 delta += cnt - 1; 21075 env->prog = prog = new_prog; 21076 insn = new_prog->insnsi + i + delta; 21077 goto next_insn; 21078 } 21079 21080 if (insn->imm == BPF_FUNC_timer_set_callback) { 21081 /* The verifier will process callback_fn as many times as necessary 21082 * with different maps and the register states prepared by 21083 * set_timer_callback_state will be accurate. 21084 * 21085 * The following use case is valid: 21086 * map1 is shared by prog1, prog2, prog3. 21087 * prog1 calls bpf_timer_init for some map1 elements 21088 * prog2 calls bpf_timer_set_callback for some map1 elements. 21089 * Those that were not bpf_timer_init-ed will return -EINVAL. 21090 * prog3 calls bpf_timer_start for some map1 elements. 21091 * Those that were not both bpf_timer_init-ed and 21092 * bpf_timer_set_callback-ed will return -EINVAL. 21093 */ 21094 struct bpf_insn ld_addrs[2] = { 21095 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 21096 }; 21097 21098 insn_buf[0] = ld_addrs[0]; 21099 insn_buf[1] = ld_addrs[1]; 21100 insn_buf[2] = *insn; 21101 cnt = 3; 21102 21103 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21104 if (!new_prog) 21105 return -ENOMEM; 21106 21107 delta += cnt - 1; 21108 env->prog = prog = new_prog; 21109 insn = new_prog->insnsi + i + delta; 21110 goto patch_call_imm; 21111 } 21112 21113 if (is_storage_get_function(insn->imm)) { 21114 if (!in_sleepable(env) || 21115 env->insn_aux_data[i + delta].storage_get_func_atomic) 21116 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 21117 else 21118 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 21119 insn_buf[1] = *insn; 21120 cnt = 2; 21121 21122 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21123 if (!new_prog) 21124 return -ENOMEM; 21125 21126 delta += cnt - 1; 21127 env->prog = prog = new_prog; 21128 insn = new_prog->insnsi + i + delta; 21129 goto patch_call_imm; 21130 } 21131 21132 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */ 21133 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) { 21134 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data, 21135 * bpf_mem_alloc() returns a ptr to the percpu data ptr. 21136 */ 21137 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0); 21138 insn_buf[1] = *insn; 21139 cnt = 2; 21140 21141 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21142 if (!new_prog) 21143 return -ENOMEM; 21144 21145 delta += cnt - 1; 21146 env->prog = prog = new_prog; 21147 insn = new_prog->insnsi + i + delta; 21148 goto patch_call_imm; 21149 } 21150 21151 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 21152 * and other inlining handlers are currently limited to 64 bit 21153 * only. 21154 */ 21155 if (prog->jit_requested && BITS_PER_LONG == 64 && 21156 (insn->imm == BPF_FUNC_map_lookup_elem || 21157 insn->imm == BPF_FUNC_map_update_elem || 21158 insn->imm == BPF_FUNC_map_delete_elem || 21159 insn->imm == BPF_FUNC_map_push_elem || 21160 insn->imm == BPF_FUNC_map_pop_elem || 21161 insn->imm == BPF_FUNC_map_peek_elem || 21162 insn->imm == BPF_FUNC_redirect_map || 21163 insn->imm == BPF_FUNC_for_each_map_elem || 21164 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 21165 aux = &env->insn_aux_data[i + delta]; 21166 if (bpf_map_ptr_poisoned(aux)) 21167 goto patch_call_imm; 21168 21169 map_ptr = aux->map_ptr_state.map_ptr; 21170 ops = map_ptr->ops; 21171 if (insn->imm == BPF_FUNC_map_lookup_elem && 21172 ops->map_gen_lookup) { 21173 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 21174 if (cnt == -EOPNOTSUPP) 21175 goto patch_map_ops_generic; 21176 if (cnt <= 0 || cnt >= INSN_BUF_SIZE) { 21177 verbose(env, "bpf verifier is misconfigured\n"); 21178 return -EINVAL; 21179 } 21180 21181 new_prog = bpf_patch_insn_data(env, i + delta, 21182 insn_buf, cnt); 21183 if (!new_prog) 21184 return -ENOMEM; 21185 21186 delta += cnt - 1; 21187 env->prog = prog = new_prog; 21188 insn = new_prog->insnsi + i + delta; 21189 goto next_insn; 21190 } 21191 21192 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 21193 (void *(*)(struct bpf_map *map, void *key))NULL)); 21194 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 21195 (long (*)(struct bpf_map *map, void *key))NULL)); 21196 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 21197 (long (*)(struct bpf_map *map, void *key, void *value, 21198 u64 flags))NULL)); 21199 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 21200 (long (*)(struct bpf_map *map, void *value, 21201 u64 flags))NULL)); 21202 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 21203 (long (*)(struct bpf_map *map, void *value))NULL)); 21204 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 21205 (long (*)(struct bpf_map *map, void *value))NULL)); 21206 BUILD_BUG_ON(!__same_type(ops->map_redirect, 21207 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 21208 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 21209 (long (*)(struct bpf_map *map, 21210 bpf_callback_t callback_fn, 21211 void *callback_ctx, 21212 u64 flags))NULL)); 21213 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 21214 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 21215 21216 patch_map_ops_generic: 21217 switch (insn->imm) { 21218 case BPF_FUNC_map_lookup_elem: 21219 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 21220 goto next_insn; 21221 case BPF_FUNC_map_update_elem: 21222 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 21223 goto next_insn; 21224 case BPF_FUNC_map_delete_elem: 21225 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 21226 goto next_insn; 21227 case BPF_FUNC_map_push_elem: 21228 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 21229 goto next_insn; 21230 case BPF_FUNC_map_pop_elem: 21231 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 21232 goto next_insn; 21233 case BPF_FUNC_map_peek_elem: 21234 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 21235 goto next_insn; 21236 case BPF_FUNC_redirect_map: 21237 insn->imm = BPF_CALL_IMM(ops->map_redirect); 21238 goto next_insn; 21239 case BPF_FUNC_for_each_map_elem: 21240 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 21241 goto next_insn; 21242 case BPF_FUNC_map_lookup_percpu_elem: 21243 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 21244 goto next_insn; 21245 } 21246 21247 goto patch_call_imm; 21248 } 21249 21250 /* Implement bpf_jiffies64 inline. */ 21251 if (prog->jit_requested && BITS_PER_LONG == 64 && 21252 insn->imm == BPF_FUNC_jiffies64) { 21253 struct bpf_insn ld_jiffies_addr[2] = { 21254 BPF_LD_IMM64(BPF_REG_0, 21255 (unsigned long)&jiffies), 21256 }; 21257 21258 insn_buf[0] = ld_jiffies_addr[0]; 21259 insn_buf[1] = ld_jiffies_addr[1]; 21260 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 21261 BPF_REG_0, 0); 21262 cnt = 3; 21263 21264 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 21265 cnt); 21266 if (!new_prog) 21267 return -ENOMEM; 21268 21269 delta += cnt - 1; 21270 env->prog = prog = new_prog; 21271 insn = new_prog->insnsi + i + delta; 21272 goto next_insn; 21273 } 21274 21275 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML) 21276 /* Implement bpf_get_smp_processor_id() inline. */ 21277 if (insn->imm == BPF_FUNC_get_smp_processor_id && 21278 verifier_inlines_helper_call(env, insn->imm)) { 21279 /* BPF_FUNC_get_smp_processor_id inlining is an 21280 * optimization, so if pcpu_hot.cpu_number is ever 21281 * changed in some incompatible and hard to support 21282 * way, it's fine to back out this inlining logic 21283 */ 21284 #ifdef CONFIG_SMP 21285 insn_buf[0] = BPF_MOV32_IMM(BPF_REG_0, (u32)(unsigned long)&pcpu_hot.cpu_number); 21286 insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0); 21287 insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0); 21288 cnt = 3; 21289 #else 21290 insn_buf[0] = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0); 21291 cnt = 1; 21292 #endif 21293 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21294 if (!new_prog) 21295 return -ENOMEM; 21296 21297 delta += cnt - 1; 21298 env->prog = prog = new_prog; 21299 insn = new_prog->insnsi + i + delta; 21300 goto next_insn; 21301 } 21302 #endif 21303 /* Implement bpf_get_func_arg inline. */ 21304 if (prog_type == BPF_PROG_TYPE_TRACING && 21305 insn->imm == BPF_FUNC_get_func_arg) { 21306 /* Load nr_args from ctx - 8 */ 21307 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 21308 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 21309 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 21310 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 21311 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 21312 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 21313 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 21314 insn_buf[7] = BPF_JMP_A(1); 21315 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 21316 cnt = 9; 21317 21318 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21319 if (!new_prog) 21320 return -ENOMEM; 21321 21322 delta += cnt - 1; 21323 env->prog = prog = new_prog; 21324 insn = new_prog->insnsi + i + delta; 21325 goto next_insn; 21326 } 21327 21328 /* Implement bpf_get_func_ret inline. */ 21329 if (prog_type == BPF_PROG_TYPE_TRACING && 21330 insn->imm == BPF_FUNC_get_func_ret) { 21331 if (eatype == BPF_TRACE_FEXIT || 21332 eatype == BPF_MODIFY_RETURN) { 21333 /* Load nr_args from ctx - 8 */ 21334 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 21335 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 21336 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 21337 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 21338 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 21339 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 21340 cnt = 6; 21341 } else { 21342 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 21343 cnt = 1; 21344 } 21345 21346 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21347 if (!new_prog) 21348 return -ENOMEM; 21349 21350 delta += cnt - 1; 21351 env->prog = prog = new_prog; 21352 insn = new_prog->insnsi + i + delta; 21353 goto next_insn; 21354 } 21355 21356 /* Implement get_func_arg_cnt inline. */ 21357 if (prog_type == BPF_PROG_TYPE_TRACING && 21358 insn->imm == BPF_FUNC_get_func_arg_cnt) { 21359 /* Load nr_args from ctx - 8 */ 21360 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 21361 21362 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 21363 if (!new_prog) 21364 return -ENOMEM; 21365 21366 env->prog = prog = new_prog; 21367 insn = new_prog->insnsi + i + delta; 21368 goto next_insn; 21369 } 21370 21371 /* Implement bpf_get_func_ip inline. */ 21372 if (prog_type == BPF_PROG_TYPE_TRACING && 21373 insn->imm == BPF_FUNC_get_func_ip) { 21374 /* Load IP address from ctx - 16 */ 21375 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 21376 21377 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 21378 if (!new_prog) 21379 return -ENOMEM; 21380 21381 env->prog = prog = new_prog; 21382 insn = new_prog->insnsi + i + delta; 21383 goto next_insn; 21384 } 21385 21386 /* Implement bpf_get_branch_snapshot inline. */ 21387 if (IS_ENABLED(CONFIG_PERF_EVENTS) && 21388 prog->jit_requested && BITS_PER_LONG == 64 && 21389 insn->imm == BPF_FUNC_get_branch_snapshot) { 21390 /* We are dealing with the following func protos: 21391 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags); 21392 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt); 21393 */ 21394 const u32 br_entry_size = sizeof(struct perf_branch_entry); 21395 21396 /* struct perf_branch_entry is part of UAPI and is 21397 * used as an array element, so extremely unlikely to 21398 * ever grow or shrink 21399 */ 21400 BUILD_BUG_ON(br_entry_size != 24); 21401 21402 /* if (unlikely(flags)) return -EINVAL */ 21403 insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7); 21404 21405 /* Transform size (bytes) into number of entries (cnt = size / 24). 21406 * But to avoid expensive division instruction, we implement 21407 * divide-by-3 through multiplication, followed by further 21408 * division by 8 through 3-bit right shift. 21409 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr., 21410 * p. 227, chapter "Unsigned Division by 3" for details and proofs. 21411 * 21412 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab. 21413 */ 21414 insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab); 21415 insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0); 21416 insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36); 21417 21418 /* call perf_snapshot_branch_stack implementation */ 21419 insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack)); 21420 /* if (entry_cnt == 0) return -ENOENT */ 21421 insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4); 21422 /* return entry_cnt * sizeof(struct perf_branch_entry) */ 21423 insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size); 21424 insn_buf[7] = BPF_JMP_A(3); 21425 /* return -EINVAL; */ 21426 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 21427 insn_buf[9] = BPF_JMP_A(1); 21428 /* return -ENOENT; */ 21429 insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT); 21430 cnt = 11; 21431 21432 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21433 if (!new_prog) 21434 return -ENOMEM; 21435 21436 delta += cnt - 1; 21437 env->prog = prog = new_prog; 21438 insn = new_prog->insnsi + i + delta; 21439 goto next_insn; 21440 } 21441 21442 /* Implement bpf_kptr_xchg inline */ 21443 if (prog->jit_requested && BITS_PER_LONG == 64 && 21444 insn->imm == BPF_FUNC_kptr_xchg && 21445 bpf_jit_supports_ptr_xchg()) { 21446 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2); 21447 insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0); 21448 cnt = 2; 21449 21450 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21451 if (!new_prog) 21452 return -ENOMEM; 21453 21454 delta += cnt - 1; 21455 env->prog = prog = new_prog; 21456 insn = new_prog->insnsi + i + delta; 21457 goto next_insn; 21458 } 21459 patch_call_imm: 21460 fn = env->ops->get_func_proto(insn->imm, env->prog); 21461 /* all functions that have prototype and verifier allowed 21462 * programs to call them, must be real in-kernel functions 21463 */ 21464 if (!fn->func) { 21465 verbose(env, 21466 "kernel subsystem misconfigured func %s#%d\n", 21467 func_id_name(insn->imm), insn->imm); 21468 return -EFAULT; 21469 } 21470 insn->imm = fn->func - __bpf_call_base; 21471 next_insn: 21472 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 21473 subprogs[cur_subprog].stack_depth += stack_depth_extra; 21474 subprogs[cur_subprog].stack_extra = stack_depth_extra; 21475 cur_subprog++; 21476 stack_depth = subprogs[cur_subprog].stack_depth; 21477 stack_depth_extra = 0; 21478 } 21479 i++; 21480 insn++; 21481 } 21482 21483 env->prog->aux->stack_depth = subprogs[0].stack_depth; 21484 for (i = 0; i < env->subprog_cnt; i++) { 21485 int subprog_start = subprogs[i].start; 21486 int stack_slots = subprogs[i].stack_extra / 8; 21487 21488 if (!stack_slots) 21489 continue; 21490 if (stack_slots > 1) { 21491 verbose(env, "verifier bug: stack_slots supports may_goto only\n"); 21492 return -EFAULT; 21493 } 21494 21495 /* Add ST insn to subprog prologue to init extra stack */ 21496 insn_buf[0] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, 21497 -subprogs[i].stack_depth, BPF_MAX_LOOPS); 21498 /* Copy first actual insn to preserve it */ 21499 insn_buf[1] = env->prog->insnsi[subprog_start]; 21500 21501 new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, 2); 21502 if (!new_prog) 21503 return -ENOMEM; 21504 env->prog = prog = new_prog; 21505 /* 21506 * If may_goto is a first insn of a prog there could be a jmp 21507 * insn that points to it, hence adjust all such jmps to point 21508 * to insn after BPF_ST that inits may_goto count. 21509 * Adjustment will succeed because bpf_patch_insn_data() didn't fail. 21510 */ 21511 WARN_ON(adjust_jmp_off(env->prog, subprog_start, 1)); 21512 } 21513 21514 /* Since poke tab is now finalized, publish aux to tracker. */ 21515 for (i = 0; i < prog->aux->size_poke_tab; i++) { 21516 map_ptr = prog->aux->poke_tab[i].tail_call.map; 21517 if (!map_ptr->ops->map_poke_track || 21518 !map_ptr->ops->map_poke_untrack || 21519 !map_ptr->ops->map_poke_run) { 21520 verbose(env, "bpf verifier is misconfigured\n"); 21521 return -EINVAL; 21522 } 21523 21524 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 21525 if (ret < 0) { 21526 verbose(env, "tracking tail call prog failed\n"); 21527 return ret; 21528 } 21529 } 21530 21531 sort_kfunc_descs_by_imm_off(env->prog); 21532 21533 return 0; 21534 } 21535 21536 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 21537 int position, 21538 s32 stack_base, 21539 u32 callback_subprogno, 21540 u32 *total_cnt) 21541 { 21542 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 21543 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 21544 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 21545 int reg_loop_max = BPF_REG_6; 21546 int reg_loop_cnt = BPF_REG_7; 21547 int reg_loop_ctx = BPF_REG_8; 21548 21549 struct bpf_insn *insn_buf = env->insn_buf; 21550 struct bpf_prog *new_prog; 21551 u32 callback_start; 21552 u32 call_insn_offset; 21553 s32 callback_offset; 21554 u32 cnt = 0; 21555 21556 /* This represents an inlined version of bpf_iter.c:bpf_loop, 21557 * be careful to modify this code in sync. 21558 */ 21559 21560 /* Return error and jump to the end of the patch if 21561 * expected number of iterations is too big. 21562 */ 21563 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2); 21564 insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG); 21565 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16); 21566 /* spill R6, R7, R8 to use these as loop vars */ 21567 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset); 21568 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset); 21569 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset); 21570 /* initialize loop vars */ 21571 insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1); 21572 insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0); 21573 insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3); 21574 /* loop header, 21575 * if reg_loop_cnt >= reg_loop_max skip the loop body 21576 */ 21577 insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5); 21578 /* callback call, 21579 * correct callback offset would be set after patching 21580 */ 21581 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt); 21582 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx); 21583 insn_buf[cnt++] = BPF_CALL_REL(0); 21584 /* increment loop counter */ 21585 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1); 21586 /* jump to loop header if callback returned 0 */ 21587 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6); 21588 /* return value of bpf_loop, 21589 * set R0 to the number of iterations 21590 */ 21591 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt); 21592 /* restore original values of R6, R7, R8 */ 21593 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset); 21594 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset); 21595 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset); 21596 21597 *total_cnt = cnt; 21598 new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt); 21599 if (!new_prog) 21600 return new_prog; 21601 21602 /* callback start is known only after patching */ 21603 callback_start = env->subprog_info[callback_subprogno].start; 21604 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 21605 call_insn_offset = position + 12; 21606 callback_offset = callback_start - call_insn_offset - 1; 21607 new_prog->insnsi[call_insn_offset].imm = callback_offset; 21608 21609 return new_prog; 21610 } 21611 21612 static bool is_bpf_loop_call(struct bpf_insn *insn) 21613 { 21614 return insn->code == (BPF_JMP | BPF_CALL) && 21615 insn->src_reg == 0 && 21616 insn->imm == BPF_FUNC_loop; 21617 } 21618 21619 /* For all sub-programs in the program (including main) check 21620 * insn_aux_data to see if there are bpf_loop calls that require 21621 * inlining. If such calls are found the calls are replaced with a 21622 * sequence of instructions produced by `inline_bpf_loop` function and 21623 * subprog stack_depth is increased by the size of 3 registers. 21624 * This stack space is used to spill values of the R6, R7, R8. These 21625 * registers are used to store the loop bound, counter and context 21626 * variables. 21627 */ 21628 static int optimize_bpf_loop(struct bpf_verifier_env *env) 21629 { 21630 struct bpf_subprog_info *subprogs = env->subprog_info; 21631 int i, cur_subprog = 0, cnt, delta = 0; 21632 struct bpf_insn *insn = env->prog->insnsi; 21633 int insn_cnt = env->prog->len; 21634 u16 stack_depth = subprogs[cur_subprog].stack_depth; 21635 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 21636 u16 stack_depth_extra = 0; 21637 21638 for (i = 0; i < insn_cnt; i++, insn++) { 21639 struct bpf_loop_inline_state *inline_state = 21640 &env->insn_aux_data[i + delta].loop_inline_state; 21641 21642 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 21643 struct bpf_prog *new_prog; 21644 21645 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 21646 new_prog = inline_bpf_loop(env, 21647 i + delta, 21648 -(stack_depth + stack_depth_extra), 21649 inline_state->callback_subprogno, 21650 &cnt); 21651 if (!new_prog) 21652 return -ENOMEM; 21653 21654 delta += cnt - 1; 21655 env->prog = new_prog; 21656 insn = new_prog->insnsi + i + delta; 21657 } 21658 21659 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 21660 subprogs[cur_subprog].stack_depth += stack_depth_extra; 21661 cur_subprog++; 21662 stack_depth = subprogs[cur_subprog].stack_depth; 21663 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 21664 stack_depth_extra = 0; 21665 } 21666 } 21667 21668 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 21669 21670 return 0; 21671 } 21672 21673 /* Remove unnecessary spill/fill pairs, members of fastcall pattern, 21674 * adjust subprograms stack depth when possible. 21675 */ 21676 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env) 21677 { 21678 struct bpf_subprog_info *subprog = env->subprog_info; 21679 struct bpf_insn_aux_data *aux = env->insn_aux_data; 21680 struct bpf_insn *insn = env->prog->insnsi; 21681 int insn_cnt = env->prog->len; 21682 u32 spills_num; 21683 bool modified = false; 21684 int i, j; 21685 21686 for (i = 0; i < insn_cnt; i++, insn++) { 21687 if (aux[i].fastcall_spills_num > 0) { 21688 spills_num = aux[i].fastcall_spills_num; 21689 /* NOPs would be removed by opt_remove_nops() */ 21690 for (j = 1; j <= spills_num; ++j) { 21691 *(insn - j) = NOP; 21692 *(insn + j) = NOP; 21693 } 21694 modified = true; 21695 } 21696 if ((subprog + 1)->start == i + 1) { 21697 if (modified && !subprog->keep_fastcall_stack) 21698 subprog->stack_depth = -subprog->fastcall_stack_off; 21699 subprog++; 21700 modified = false; 21701 } 21702 } 21703 21704 return 0; 21705 } 21706 21707 static void free_states(struct bpf_verifier_env *env) 21708 { 21709 struct bpf_verifier_state_list *sl, *sln; 21710 int i; 21711 21712 sl = env->free_list; 21713 while (sl) { 21714 sln = sl->next; 21715 free_verifier_state(&sl->state, false); 21716 kfree(sl); 21717 sl = sln; 21718 } 21719 env->free_list = NULL; 21720 21721 if (!env->explored_states) 21722 return; 21723 21724 for (i = 0; i < state_htab_size(env); i++) { 21725 sl = env->explored_states[i]; 21726 21727 while (sl) { 21728 sln = sl->next; 21729 free_verifier_state(&sl->state, false); 21730 kfree(sl); 21731 sl = sln; 21732 } 21733 env->explored_states[i] = NULL; 21734 } 21735 } 21736 21737 static int do_check_common(struct bpf_verifier_env *env, int subprog) 21738 { 21739 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 21740 struct bpf_subprog_info *sub = subprog_info(env, subprog); 21741 struct bpf_verifier_state *state; 21742 struct bpf_reg_state *regs; 21743 int ret, i; 21744 21745 env->prev_linfo = NULL; 21746 env->pass_cnt++; 21747 21748 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 21749 if (!state) 21750 return -ENOMEM; 21751 state->curframe = 0; 21752 state->speculative = false; 21753 state->branches = 1; 21754 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 21755 if (!state->frame[0]) { 21756 kfree(state); 21757 return -ENOMEM; 21758 } 21759 env->cur_state = state; 21760 init_func_state(env, state->frame[0], 21761 BPF_MAIN_FUNC /* callsite */, 21762 0 /* frameno */, 21763 subprog); 21764 state->first_insn_idx = env->subprog_info[subprog].start; 21765 state->last_insn_idx = -1; 21766 21767 regs = state->frame[state->curframe]->regs; 21768 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 21769 const char *sub_name = subprog_name(env, subprog); 21770 struct bpf_subprog_arg_info *arg; 21771 struct bpf_reg_state *reg; 21772 21773 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 21774 ret = btf_prepare_func_args(env, subprog); 21775 if (ret) 21776 goto out; 21777 21778 if (subprog_is_exc_cb(env, subprog)) { 21779 state->frame[0]->in_exception_callback_fn = true; 21780 /* We have already ensured that the callback returns an integer, just 21781 * like all global subprogs. We need to determine it only has a single 21782 * scalar argument. 21783 */ 21784 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 21785 verbose(env, "exception cb only supports single integer argument\n"); 21786 ret = -EINVAL; 21787 goto out; 21788 } 21789 } 21790 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) { 21791 arg = &sub->args[i - BPF_REG_1]; 21792 reg = ®s[i]; 21793 21794 if (arg->arg_type == ARG_PTR_TO_CTX) { 21795 reg->type = PTR_TO_CTX; 21796 mark_reg_known_zero(env, regs, i); 21797 } else if (arg->arg_type == ARG_ANYTHING) { 21798 reg->type = SCALAR_VALUE; 21799 mark_reg_unknown(env, regs, i); 21800 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 21801 /* assume unspecial LOCAL dynptr type */ 21802 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen); 21803 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 21804 reg->type = PTR_TO_MEM; 21805 if (arg->arg_type & PTR_MAYBE_NULL) 21806 reg->type |= PTR_MAYBE_NULL; 21807 mark_reg_known_zero(env, regs, i); 21808 reg->mem_size = arg->mem_size; 21809 reg->id = ++env->id_gen; 21810 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 21811 reg->type = PTR_TO_BTF_ID; 21812 if (arg->arg_type & PTR_MAYBE_NULL) 21813 reg->type |= PTR_MAYBE_NULL; 21814 if (arg->arg_type & PTR_UNTRUSTED) 21815 reg->type |= PTR_UNTRUSTED; 21816 if (arg->arg_type & PTR_TRUSTED) 21817 reg->type |= PTR_TRUSTED; 21818 mark_reg_known_zero(env, regs, i); 21819 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */ 21820 reg->btf_id = arg->btf_id; 21821 reg->id = ++env->id_gen; 21822 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 21823 /* caller can pass either PTR_TO_ARENA or SCALAR */ 21824 mark_reg_unknown(env, regs, i); 21825 } else { 21826 WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n", 21827 i - BPF_REG_1, arg->arg_type); 21828 ret = -EFAULT; 21829 goto out; 21830 } 21831 } 21832 } else { 21833 /* if main BPF program has associated BTF info, validate that 21834 * it's matching expected signature, and otherwise mark BTF 21835 * info for main program as unreliable 21836 */ 21837 if (env->prog->aux->func_info_aux) { 21838 ret = btf_prepare_func_args(env, 0); 21839 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) 21840 env->prog->aux->func_info_aux[0].unreliable = true; 21841 } 21842 21843 /* 1st arg to a function */ 21844 regs[BPF_REG_1].type = PTR_TO_CTX; 21845 mark_reg_known_zero(env, regs, BPF_REG_1); 21846 } 21847 21848 ret = do_check(env); 21849 out: 21850 /* check for NULL is necessary, since cur_state can be freed inside 21851 * do_check() under memory pressure. 21852 */ 21853 if (env->cur_state) { 21854 free_verifier_state(env->cur_state, true); 21855 env->cur_state = NULL; 21856 } 21857 while (!pop_stack(env, NULL, NULL, false)); 21858 if (!ret && pop_log) 21859 bpf_vlog_reset(&env->log, 0); 21860 free_states(env); 21861 return ret; 21862 } 21863 21864 /* Lazily verify all global functions based on their BTF, if they are called 21865 * from main BPF program or any of subprograms transitively. 21866 * BPF global subprogs called from dead code are not validated. 21867 * All callable global functions must pass verification. 21868 * Otherwise the whole program is rejected. 21869 * Consider: 21870 * int bar(int); 21871 * int foo(int f) 21872 * { 21873 * return bar(f); 21874 * } 21875 * int bar(int b) 21876 * { 21877 * ... 21878 * } 21879 * foo() will be verified first for R1=any_scalar_value. During verification it 21880 * will be assumed that bar() already verified successfully and call to bar() 21881 * from foo() will be checked for type match only. Later bar() will be verified 21882 * independently to check that it's safe for R1=any_scalar_value. 21883 */ 21884 static int do_check_subprogs(struct bpf_verifier_env *env) 21885 { 21886 struct bpf_prog_aux *aux = env->prog->aux; 21887 struct bpf_func_info_aux *sub_aux; 21888 int i, ret, new_cnt; 21889 21890 if (!aux->func_info) 21891 return 0; 21892 21893 /* exception callback is presumed to be always called */ 21894 if (env->exception_callback_subprog) 21895 subprog_aux(env, env->exception_callback_subprog)->called = true; 21896 21897 again: 21898 new_cnt = 0; 21899 for (i = 1; i < env->subprog_cnt; i++) { 21900 if (!subprog_is_global(env, i)) 21901 continue; 21902 21903 sub_aux = subprog_aux(env, i); 21904 if (!sub_aux->called || sub_aux->verified) 21905 continue; 21906 21907 env->insn_idx = env->subprog_info[i].start; 21908 WARN_ON_ONCE(env->insn_idx == 0); 21909 ret = do_check_common(env, i); 21910 if (ret) { 21911 return ret; 21912 } else if (env->log.level & BPF_LOG_LEVEL) { 21913 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 21914 i, subprog_name(env, i)); 21915 } 21916 21917 /* We verified new global subprog, it might have called some 21918 * more global subprogs that we haven't verified yet, so we 21919 * need to do another pass over subprogs to verify those. 21920 */ 21921 sub_aux->verified = true; 21922 new_cnt++; 21923 } 21924 21925 /* We can't loop forever as we verify at least one global subprog on 21926 * each pass. 21927 */ 21928 if (new_cnt) 21929 goto again; 21930 21931 return 0; 21932 } 21933 21934 static int do_check_main(struct bpf_verifier_env *env) 21935 { 21936 int ret; 21937 21938 env->insn_idx = 0; 21939 ret = do_check_common(env, 0); 21940 if (!ret) 21941 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 21942 return ret; 21943 } 21944 21945 21946 static void print_verification_stats(struct bpf_verifier_env *env) 21947 { 21948 int i; 21949 21950 if (env->log.level & BPF_LOG_STATS) { 21951 verbose(env, "verification time %lld usec\n", 21952 div_u64(env->verification_time, 1000)); 21953 verbose(env, "stack depth "); 21954 for (i = 0; i < env->subprog_cnt; i++) { 21955 u32 depth = env->subprog_info[i].stack_depth; 21956 21957 verbose(env, "%d", depth); 21958 if (i + 1 < env->subprog_cnt) 21959 verbose(env, "+"); 21960 } 21961 verbose(env, "\n"); 21962 } 21963 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 21964 "total_states %d peak_states %d mark_read %d\n", 21965 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 21966 env->max_states_per_insn, env->total_states, 21967 env->peak_states, env->longest_mark_read_walk); 21968 } 21969 21970 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 21971 { 21972 const struct btf_type *t, *func_proto; 21973 const struct bpf_struct_ops_desc *st_ops_desc; 21974 const struct bpf_struct_ops *st_ops; 21975 const struct btf_member *member; 21976 struct bpf_prog *prog = env->prog; 21977 u32 btf_id, member_idx; 21978 struct btf *btf; 21979 const char *mname; 21980 int err; 21981 21982 if (!prog->gpl_compatible) { 21983 verbose(env, "struct ops programs must have a GPL compatible license\n"); 21984 return -EINVAL; 21985 } 21986 21987 if (!prog->aux->attach_btf_id) 21988 return -ENOTSUPP; 21989 21990 btf = prog->aux->attach_btf; 21991 if (btf_is_module(btf)) { 21992 /* Make sure st_ops is valid through the lifetime of env */ 21993 env->attach_btf_mod = btf_try_get_module(btf); 21994 if (!env->attach_btf_mod) { 21995 verbose(env, "struct_ops module %s is not found\n", 21996 btf_get_name(btf)); 21997 return -ENOTSUPP; 21998 } 21999 } 22000 22001 btf_id = prog->aux->attach_btf_id; 22002 st_ops_desc = bpf_struct_ops_find(btf, btf_id); 22003 if (!st_ops_desc) { 22004 verbose(env, "attach_btf_id %u is not a supported struct\n", 22005 btf_id); 22006 return -ENOTSUPP; 22007 } 22008 st_ops = st_ops_desc->st_ops; 22009 22010 t = st_ops_desc->type; 22011 member_idx = prog->expected_attach_type; 22012 if (member_idx >= btf_type_vlen(t)) { 22013 verbose(env, "attach to invalid member idx %u of struct %s\n", 22014 member_idx, st_ops->name); 22015 return -EINVAL; 22016 } 22017 22018 member = &btf_type_member(t)[member_idx]; 22019 mname = btf_name_by_offset(btf, member->name_off); 22020 func_proto = btf_type_resolve_func_ptr(btf, member->type, 22021 NULL); 22022 if (!func_proto) { 22023 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 22024 mname, member_idx, st_ops->name); 22025 return -EINVAL; 22026 } 22027 22028 err = bpf_struct_ops_supported(st_ops, __btf_member_bit_offset(t, member) / 8); 22029 if (err) { 22030 verbose(env, "attach to unsupported member %s of struct %s\n", 22031 mname, st_ops->name); 22032 return err; 22033 } 22034 22035 if (st_ops->check_member) { 22036 err = st_ops->check_member(t, member, prog); 22037 22038 if (err) { 22039 verbose(env, "attach to unsupported member %s of struct %s\n", 22040 mname, st_ops->name); 22041 return err; 22042 } 22043 } 22044 22045 if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) { 22046 verbose(env, "Private stack not supported by jit\n"); 22047 return -EACCES; 22048 } 22049 22050 /* btf_ctx_access() used this to provide argument type info */ 22051 prog->aux->ctx_arg_info = 22052 st_ops_desc->arg_info[member_idx].info; 22053 prog->aux->ctx_arg_info_size = 22054 st_ops_desc->arg_info[member_idx].cnt; 22055 22056 prog->aux->attach_func_proto = func_proto; 22057 prog->aux->attach_func_name = mname; 22058 env->ops = st_ops->verifier_ops; 22059 22060 return 0; 22061 } 22062 #define SECURITY_PREFIX "security_" 22063 22064 static int check_attach_modify_return(unsigned long addr, const char *func_name) 22065 { 22066 if (within_error_injection_list(addr) || 22067 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 22068 return 0; 22069 22070 return -EINVAL; 22071 } 22072 22073 /* list of non-sleepable functions that are otherwise on 22074 * ALLOW_ERROR_INJECTION list 22075 */ 22076 BTF_SET_START(btf_non_sleepable_error_inject) 22077 /* Three functions below can be called from sleepable and non-sleepable context. 22078 * Assume non-sleepable from bpf safety point of view. 22079 */ 22080 BTF_ID(func, __filemap_add_folio) 22081 #ifdef CONFIG_FAIL_PAGE_ALLOC 22082 BTF_ID(func, should_fail_alloc_page) 22083 #endif 22084 #ifdef CONFIG_FAILSLAB 22085 BTF_ID(func, should_failslab) 22086 #endif 22087 BTF_SET_END(btf_non_sleepable_error_inject) 22088 22089 static int check_non_sleepable_error_inject(u32 btf_id) 22090 { 22091 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 22092 } 22093 22094 int bpf_check_attach_target(struct bpf_verifier_log *log, 22095 const struct bpf_prog *prog, 22096 const struct bpf_prog *tgt_prog, 22097 u32 btf_id, 22098 struct bpf_attach_target_info *tgt_info) 22099 { 22100 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 22101 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 22102 char trace_symbol[KSYM_SYMBOL_LEN]; 22103 const char prefix[] = "btf_trace_"; 22104 struct bpf_raw_event_map *btp; 22105 int ret = 0, subprog = -1, i; 22106 const struct btf_type *t; 22107 bool conservative = true; 22108 const char *tname, *fname; 22109 struct btf *btf; 22110 long addr = 0; 22111 struct module *mod = NULL; 22112 22113 if (!btf_id) { 22114 bpf_log(log, "Tracing programs must provide btf_id\n"); 22115 return -EINVAL; 22116 } 22117 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 22118 if (!btf) { 22119 bpf_log(log, 22120 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 22121 return -EINVAL; 22122 } 22123 t = btf_type_by_id(btf, btf_id); 22124 if (!t) { 22125 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 22126 return -EINVAL; 22127 } 22128 tname = btf_name_by_offset(btf, t->name_off); 22129 if (!tname) { 22130 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 22131 return -EINVAL; 22132 } 22133 if (tgt_prog) { 22134 struct bpf_prog_aux *aux = tgt_prog->aux; 22135 bool tgt_changes_pkt_data; 22136 22137 if (bpf_prog_is_dev_bound(prog->aux) && 22138 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 22139 bpf_log(log, "Target program bound device mismatch"); 22140 return -EINVAL; 22141 } 22142 22143 for (i = 0; i < aux->func_info_cnt; i++) 22144 if (aux->func_info[i].type_id == btf_id) { 22145 subprog = i; 22146 break; 22147 } 22148 if (subprog == -1) { 22149 bpf_log(log, "Subprog %s doesn't exist\n", tname); 22150 return -EINVAL; 22151 } 22152 if (aux->func && aux->func[subprog]->aux->exception_cb) { 22153 bpf_log(log, 22154 "%s programs cannot attach to exception callback\n", 22155 prog_extension ? "Extension" : "FENTRY/FEXIT"); 22156 return -EINVAL; 22157 } 22158 conservative = aux->func_info_aux[subprog].unreliable; 22159 if (prog_extension) { 22160 if (conservative) { 22161 bpf_log(log, 22162 "Cannot replace static functions\n"); 22163 return -EINVAL; 22164 } 22165 if (!prog->jit_requested) { 22166 bpf_log(log, 22167 "Extension programs should be JITed\n"); 22168 return -EINVAL; 22169 } 22170 tgt_changes_pkt_data = aux->func 22171 ? aux->func[subprog]->aux->changes_pkt_data 22172 : aux->changes_pkt_data; 22173 if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) { 22174 bpf_log(log, 22175 "Extension program changes packet data, while original does not\n"); 22176 return -EINVAL; 22177 } 22178 } 22179 if (!tgt_prog->jited) { 22180 bpf_log(log, "Can attach to only JITed progs\n"); 22181 return -EINVAL; 22182 } 22183 if (prog_tracing) { 22184 if (aux->attach_tracing_prog) { 22185 /* 22186 * Target program is an fentry/fexit which is already attached 22187 * to another tracing program. More levels of nesting 22188 * attachment are not allowed. 22189 */ 22190 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 22191 return -EINVAL; 22192 } 22193 } else if (tgt_prog->type == prog->type) { 22194 /* 22195 * To avoid potential call chain cycles, prevent attaching of a 22196 * program extension to another extension. It's ok to attach 22197 * fentry/fexit to extension program. 22198 */ 22199 bpf_log(log, "Cannot recursively attach\n"); 22200 return -EINVAL; 22201 } 22202 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 22203 prog_extension && 22204 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 22205 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 22206 /* Program extensions can extend all program types 22207 * except fentry/fexit. The reason is the following. 22208 * The fentry/fexit programs are used for performance 22209 * analysis, stats and can be attached to any program 22210 * type. When extension program is replacing XDP function 22211 * it is necessary to allow performance analysis of all 22212 * functions. Both original XDP program and its program 22213 * extension. Hence attaching fentry/fexit to 22214 * BPF_PROG_TYPE_EXT is allowed. If extending of 22215 * fentry/fexit was allowed it would be possible to create 22216 * long call chain fentry->extension->fentry->extension 22217 * beyond reasonable stack size. Hence extending fentry 22218 * is not allowed. 22219 */ 22220 bpf_log(log, "Cannot extend fentry/fexit\n"); 22221 return -EINVAL; 22222 } 22223 } else { 22224 if (prog_extension) { 22225 bpf_log(log, "Cannot replace kernel functions\n"); 22226 return -EINVAL; 22227 } 22228 } 22229 22230 switch (prog->expected_attach_type) { 22231 case BPF_TRACE_RAW_TP: 22232 if (tgt_prog) { 22233 bpf_log(log, 22234 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 22235 return -EINVAL; 22236 } 22237 if (!btf_type_is_typedef(t)) { 22238 bpf_log(log, "attach_btf_id %u is not a typedef\n", 22239 btf_id); 22240 return -EINVAL; 22241 } 22242 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 22243 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 22244 btf_id, tname); 22245 return -EINVAL; 22246 } 22247 tname += sizeof(prefix) - 1; 22248 22249 /* The func_proto of "btf_trace_##tname" is generated from typedef without argument 22250 * names. Thus using bpf_raw_event_map to get argument names. 22251 */ 22252 btp = bpf_get_raw_tracepoint(tname); 22253 if (!btp) 22254 return -EINVAL; 22255 fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL, 22256 trace_symbol); 22257 bpf_put_raw_tracepoint(btp); 22258 22259 if (fname) 22260 ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC); 22261 22262 if (!fname || ret < 0) { 22263 bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n", 22264 prefix, tname); 22265 t = btf_type_by_id(btf, t->type); 22266 if (!btf_type_is_ptr(t)) 22267 /* should never happen in valid vmlinux build */ 22268 return -EINVAL; 22269 } else { 22270 t = btf_type_by_id(btf, ret); 22271 if (!btf_type_is_func(t)) 22272 /* should never happen in valid vmlinux build */ 22273 return -EINVAL; 22274 } 22275 22276 t = btf_type_by_id(btf, t->type); 22277 if (!btf_type_is_func_proto(t)) 22278 /* should never happen in valid vmlinux build */ 22279 return -EINVAL; 22280 22281 break; 22282 case BPF_TRACE_ITER: 22283 if (!btf_type_is_func(t)) { 22284 bpf_log(log, "attach_btf_id %u is not a function\n", 22285 btf_id); 22286 return -EINVAL; 22287 } 22288 t = btf_type_by_id(btf, t->type); 22289 if (!btf_type_is_func_proto(t)) 22290 return -EINVAL; 22291 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 22292 if (ret) 22293 return ret; 22294 break; 22295 default: 22296 if (!prog_extension) 22297 return -EINVAL; 22298 fallthrough; 22299 case BPF_MODIFY_RETURN: 22300 case BPF_LSM_MAC: 22301 case BPF_LSM_CGROUP: 22302 case BPF_TRACE_FENTRY: 22303 case BPF_TRACE_FEXIT: 22304 if (!btf_type_is_func(t)) { 22305 bpf_log(log, "attach_btf_id %u is not a function\n", 22306 btf_id); 22307 return -EINVAL; 22308 } 22309 if (prog_extension && 22310 btf_check_type_match(log, prog, btf, t)) 22311 return -EINVAL; 22312 t = btf_type_by_id(btf, t->type); 22313 if (!btf_type_is_func_proto(t)) 22314 return -EINVAL; 22315 22316 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 22317 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 22318 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 22319 return -EINVAL; 22320 22321 if (tgt_prog && conservative) 22322 t = NULL; 22323 22324 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 22325 if (ret < 0) 22326 return ret; 22327 22328 if (tgt_prog) { 22329 if (subprog == 0) 22330 addr = (long) tgt_prog->bpf_func; 22331 else 22332 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 22333 } else { 22334 if (btf_is_module(btf)) { 22335 mod = btf_try_get_module(btf); 22336 if (mod) 22337 addr = find_kallsyms_symbol_value(mod, tname); 22338 else 22339 addr = 0; 22340 } else { 22341 addr = kallsyms_lookup_name(tname); 22342 } 22343 if (!addr) { 22344 module_put(mod); 22345 bpf_log(log, 22346 "The address of function %s cannot be found\n", 22347 tname); 22348 return -ENOENT; 22349 } 22350 } 22351 22352 if (prog->sleepable) { 22353 ret = -EINVAL; 22354 switch (prog->type) { 22355 case BPF_PROG_TYPE_TRACING: 22356 22357 /* fentry/fexit/fmod_ret progs can be sleepable if they are 22358 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 22359 */ 22360 if (!check_non_sleepable_error_inject(btf_id) && 22361 within_error_injection_list(addr)) 22362 ret = 0; 22363 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 22364 * in the fmodret id set with the KF_SLEEPABLE flag. 22365 */ 22366 else { 22367 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 22368 prog); 22369 22370 if (flags && (*flags & KF_SLEEPABLE)) 22371 ret = 0; 22372 } 22373 break; 22374 case BPF_PROG_TYPE_LSM: 22375 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 22376 * Only some of them are sleepable. 22377 */ 22378 if (bpf_lsm_is_sleepable_hook(btf_id)) 22379 ret = 0; 22380 break; 22381 default: 22382 break; 22383 } 22384 if (ret) { 22385 module_put(mod); 22386 bpf_log(log, "%s is not sleepable\n", tname); 22387 return ret; 22388 } 22389 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 22390 if (tgt_prog) { 22391 module_put(mod); 22392 bpf_log(log, "can't modify return codes of BPF programs\n"); 22393 return -EINVAL; 22394 } 22395 ret = -EINVAL; 22396 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 22397 !check_attach_modify_return(addr, tname)) 22398 ret = 0; 22399 if (ret) { 22400 module_put(mod); 22401 bpf_log(log, "%s() is not modifiable\n", tname); 22402 return ret; 22403 } 22404 } 22405 22406 break; 22407 } 22408 tgt_info->tgt_addr = addr; 22409 tgt_info->tgt_name = tname; 22410 tgt_info->tgt_type = t; 22411 tgt_info->tgt_mod = mod; 22412 return 0; 22413 } 22414 22415 BTF_SET_START(btf_id_deny) 22416 BTF_ID_UNUSED 22417 #ifdef CONFIG_SMP 22418 BTF_ID(func, migrate_disable) 22419 BTF_ID(func, migrate_enable) 22420 #endif 22421 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 22422 BTF_ID(func, rcu_read_unlock_strict) 22423 #endif 22424 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 22425 BTF_ID(func, preempt_count_add) 22426 BTF_ID(func, preempt_count_sub) 22427 #endif 22428 #ifdef CONFIG_PREEMPT_RCU 22429 BTF_ID(func, __rcu_read_lock) 22430 BTF_ID(func, __rcu_read_unlock) 22431 #endif 22432 BTF_SET_END(btf_id_deny) 22433 22434 static bool can_be_sleepable(struct bpf_prog *prog) 22435 { 22436 if (prog->type == BPF_PROG_TYPE_TRACING) { 22437 switch (prog->expected_attach_type) { 22438 case BPF_TRACE_FENTRY: 22439 case BPF_TRACE_FEXIT: 22440 case BPF_MODIFY_RETURN: 22441 case BPF_TRACE_ITER: 22442 return true; 22443 default: 22444 return false; 22445 } 22446 } 22447 return prog->type == BPF_PROG_TYPE_LSM || 22448 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 22449 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 22450 } 22451 22452 static int check_attach_btf_id(struct bpf_verifier_env *env) 22453 { 22454 struct bpf_prog *prog = env->prog; 22455 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 22456 struct bpf_attach_target_info tgt_info = {}; 22457 u32 btf_id = prog->aux->attach_btf_id; 22458 struct bpf_trampoline *tr; 22459 int ret; 22460 u64 key; 22461 22462 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 22463 if (prog->sleepable) 22464 /* attach_btf_id checked to be zero already */ 22465 return 0; 22466 verbose(env, "Syscall programs can only be sleepable\n"); 22467 return -EINVAL; 22468 } 22469 22470 if (prog->sleepable && !can_be_sleepable(prog)) { 22471 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 22472 return -EINVAL; 22473 } 22474 22475 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 22476 return check_struct_ops_btf_id(env); 22477 22478 if (prog->type != BPF_PROG_TYPE_TRACING && 22479 prog->type != BPF_PROG_TYPE_LSM && 22480 prog->type != BPF_PROG_TYPE_EXT) 22481 return 0; 22482 22483 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 22484 if (ret) 22485 return ret; 22486 22487 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 22488 /* to make freplace equivalent to their targets, they need to 22489 * inherit env->ops and expected_attach_type for the rest of the 22490 * verification 22491 */ 22492 env->ops = bpf_verifier_ops[tgt_prog->type]; 22493 prog->expected_attach_type = tgt_prog->expected_attach_type; 22494 } 22495 22496 /* store info about the attachment target that will be used later */ 22497 prog->aux->attach_func_proto = tgt_info.tgt_type; 22498 prog->aux->attach_func_name = tgt_info.tgt_name; 22499 prog->aux->mod = tgt_info.tgt_mod; 22500 22501 if (tgt_prog) { 22502 prog->aux->saved_dst_prog_type = tgt_prog->type; 22503 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 22504 } 22505 22506 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 22507 prog->aux->attach_btf_trace = true; 22508 return 0; 22509 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 22510 if (!bpf_iter_prog_supported(prog)) 22511 return -EINVAL; 22512 return 0; 22513 } 22514 22515 if (prog->type == BPF_PROG_TYPE_LSM) { 22516 ret = bpf_lsm_verify_prog(&env->log, prog); 22517 if (ret < 0) 22518 return ret; 22519 } else if (prog->type == BPF_PROG_TYPE_TRACING && 22520 btf_id_set_contains(&btf_id_deny, btf_id)) { 22521 return -EINVAL; 22522 } 22523 22524 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 22525 tr = bpf_trampoline_get(key, &tgt_info); 22526 if (!tr) 22527 return -ENOMEM; 22528 22529 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 22530 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 22531 22532 prog->aux->dst_trampoline = tr; 22533 return 0; 22534 } 22535 22536 struct btf *bpf_get_btf_vmlinux(void) 22537 { 22538 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 22539 mutex_lock(&bpf_verifier_lock); 22540 if (!btf_vmlinux) 22541 btf_vmlinux = btf_parse_vmlinux(); 22542 mutex_unlock(&bpf_verifier_lock); 22543 } 22544 return btf_vmlinux; 22545 } 22546 22547 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 22548 { 22549 u64 start_time = ktime_get_ns(); 22550 struct bpf_verifier_env *env; 22551 int i, len, ret = -EINVAL, err; 22552 u32 log_true_size; 22553 bool is_priv; 22554 22555 /* no program is valid */ 22556 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 22557 return -EINVAL; 22558 22559 /* 'struct bpf_verifier_env' can be global, but since it's not small, 22560 * allocate/free it every time bpf_check() is called 22561 */ 22562 env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 22563 if (!env) 22564 return -ENOMEM; 22565 22566 env->bt.env = env; 22567 22568 len = (*prog)->len; 22569 env->insn_aux_data = 22570 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 22571 ret = -ENOMEM; 22572 if (!env->insn_aux_data) 22573 goto err_free_env; 22574 for (i = 0; i < len; i++) 22575 env->insn_aux_data[i].orig_idx = i; 22576 env->prog = *prog; 22577 env->ops = bpf_verifier_ops[env->prog->type]; 22578 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 22579 22580 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 22581 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 22582 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 22583 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 22584 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 22585 22586 bpf_get_btf_vmlinux(); 22587 22588 /* grab the mutex to protect few globals used by verifier */ 22589 if (!is_priv) 22590 mutex_lock(&bpf_verifier_lock); 22591 22592 /* user could have requested verbose verifier output 22593 * and supplied buffer to store the verification trace 22594 */ 22595 ret = bpf_vlog_init(&env->log, attr->log_level, 22596 (char __user *) (unsigned long) attr->log_buf, 22597 attr->log_size); 22598 if (ret) 22599 goto err_unlock; 22600 22601 mark_verifier_state_clean(env); 22602 22603 if (IS_ERR(btf_vmlinux)) { 22604 /* Either gcc or pahole or kernel are broken. */ 22605 verbose(env, "in-kernel BTF is malformed\n"); 22606 ret = PTR_ERR(btf_vmlinux); 22607 goto skip_full_check; 22608 } 22609 22610 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 22611 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 22612 env->strict_alignment = true; 22613 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 22614 env->strict_alignment = false; 22615 22616 if (is_priv) 22617 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 22618 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 22619 22620 env->explored_states = kvcalloc(state_htab_size(env), 22621 sizeof(struct bpf_verifier_state_list *), 22622 GFP_USER); 22623 ret = -ENOMEM; 22624 if (!env->explored_states) 22625 goto skip_full_check; 22626 22627 ret = check_btf_info_early(env, attr, uattr); 22628 if (ret < 0) 22629 goto skip_full_check; 22630 22631 ret = add_subprog_and_kfunc(env); 22632 if (ret < 0) 22633 goto skip_full_check; 22634 22635 ret = check_subprogs(env); 22636 if (ret < 0) 22637 goto skip_full_check; 22638 22639 ret = check_btf_info(env, attr, uattr); 22640 if (ret < 0) 22641 goto skip_full_check; 22642 22643 ret = resolve_pseudo_ldimm64(env); 22644 if (ret < 0) 22645 goto skip_full_check; 22646 22647 if (bpf_prog_is_offloaded(env->prog->aux)) { 22648 ret = bpf_prog_offload_verifier_prep(env->prog); 22649 if (ret) 22650 goto skip_full_check; 22651 } 22652 22653 ret = check_cfg(env); 22654 if (ret < 0) 22655 goto skip_full_check; 22656 22657 ret = check_attach_btf_id(env); 22658 if (ret) 22659 goto skip_full_check; 22660 22661 ret = mark_fastcall_patterns(env); 22662 if (ret < 0) 22663 goto skip_full_check; 22664 22665 ret = do_check_main(env); 22666 ret = ret ?: do_check_subprogs(env); 22667 22668 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 22669 ret = bpf_prog_offload_finalize(env); 22670 22671 skip_full_check: 22672 kvfree(env->explored_states); 22673 22674 /* might decrease stack depth, keep it before passes that 22675 * allocate additional slots. 22676 */ 22677 if (ret == 0) 22678 ret = remove_fastcall_spills_fills(env); 22679 22680 if (ret == 0) 22681 ret = check_max_stack_depth(env); 22682 22683 /* instruction rewrites happen after this point */ 22684 if (ret == 0) 22685 ret = optimize_bpf_loop(env); 22686 22687 if (is_priv) { 22688 if (ret == 0) 22689 opt_hard_wire_dead_code_branches(env); 22690 if (ret == 0) 22691 ret = opt_remove_dead_code(env); 22692 if (ret == 0) 22693 ret = opt_remove_nops(env); 22694 } else { 22695 if (ret == 0) 22696 sanitize_dead_code(env); 22697 } 22698 22699 if (ret == 0) 22700 /* program is valid, convert *(u32*)(ctx + off) accesses */ 22701 ret = convert_ctx_accesses(env); 22702 22703 if (ret == 0) 22704 ret = do_misc_fixups(env); 22705 22706 /* do 32-bit optimization after insn patching has done so those patched 22707 * insns could be handled correctly. 22708 */ 22709 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 22710 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 22711 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 22712 : false; 22713 } 22714 22715 if (ret == 0) 22716 ret = fixup_call_args(env); 22717 22718 env->verification_time = ktime_get_ns() - start_time; 22719 print_verification_stats(env); 22720 env->prog->aux->verified_insns = env->insn_processed; 22721 22722 /* preserve original error even if log finalization is successful */ 22723 err = bpf_vlog_finalize(&env->log, &log_true_size); 22724 if (err) 22725 ret = err; 22726 22727 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 22728 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 22729 &log_true_size, sizeof(log_true_size))) { 22730 ret = -EFAULT; 22731 goto err_release_maps; 22732 } 22733 22734 if (ret) 22735 goto err_release_maps; 22736 22737 if (env->used_map_cnt) { 22738 /* if program passed verifier, update used_maps in bpf_prog_info */ 22739 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 22740 sizeof(env->used_maps[0]), 22741 GFP_KERNEL); 22742 22743 if (!env->prog->aux->used_maps) { 22744 ret = -ENOMEM; 22745 goto err_release_maps; 22746 } 22747 22748 memcpy(env->prog->aux->used_maps, env->used_maps, 22749 sizeof(env->used_maps[0]) * env->used_map_cnt); 22750 env->prog->aux->used_map_cnt = env->used_map_cnt; 22751 } 22752 if (env->used_btf_cnt) { 22753 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 22754 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 22755 sizeof(env->used_btfs[0]), 22756 GFP_KERNEL); 22757 if (!env->prog->aux->used_btfs) { 22758 ret = -ENOMEM; 22759 goto err_release_maps; 22760 } 22761 22762 memcpy(env->prog->aux->used_btfs, env->used_btfs, 22763 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 22764 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 22765 } 22766 if (env->used_map_cnt || env->used_btf_cnt) { 22767 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 22768 * bpf_ld_imm64 instructions 22769 */ 22770 convert_pseudo_ld_imm64(env); 22771 } 22772 22773 adjust_btf_func(env); 22774 22775 err_release_maps: 22776 if (!env->prog->aux->used_maps) 22777 /* if we didn't copy map pointers into bpf_prog_info, release 22778 * them now. Otherwise free_used_maps() will release them. 22779 */ 22780 release_maps(env); 22781 if (!env->prog->aux->used_btfs) 22782 release_btfs(env); 22783 22784 /* extension progs temporarily inherit the attach_type of their targets 22785 for verification purposes, so set it back to zero before returning 22786 */ 22787 if (env->prog->type == BPF_PROG_TYPE_EXT) 22788 env->prog->expected_attach_type = 0; 22789 22790 *prog = env->prog; 22791 22792 module_put(env->attach_btf_mod); 22793 err_unlock: 22794 if (!is_priv) 22795 mutex_unlock(&bpf_verifier_lock); 22796 vfree(env->insn_aux_data); 22797 kvfree(env->insn_hist); 22798 err_free_env: 22799 kvfree(env); 22800 return ret; 22801 } 22802