1 // SPDX-License-Identifier: GPL-2.0-only 2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com 3 * Copyright (c) 2016 Facebook 4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io 5 */ 6 #include <uapi/linux/btf.h> 7 #include <linux/bpf-cgroup.h> 8 #include <linux/kernel.h> 9 #include <linux/types.h> 10 #include <linux/slab.h> 11 #include <linux/bpf.h> 12 #include <linux/btf.h> 13 #include <linux/bpf_verifier.h> 14 #include <linux/filter.h> 15 #include <net/netlink.h> 16 #include <linux/file.h> 17 #include <linux/vmalloc.h> 18 #include <linux/stringify.h> 19 #include <linux/bsearch.h> 20 #include <linux/sort.h> 21 #include <linux/perf_event.h> 22 #include <linux/ctype.h> 23 #include <linux/error-injection.h> 24 #include <linux/bpf_lsm.h> 25 #include <linux/btf_ids.h> 26 #include <linux/poison.h> 27 #include <linux/module.h> 28 #include <linux/cpumask.h> 29 #include <linux/bpf_mem_alloc.h> 30 #include <net/xdp.h> 31 #include <linux/trace_events.h> 32 #include <linux/kallsyms.h> 33 34 #include "disasm.h" 35 36 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 37 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \ 38 [_id] = & _name ## _verifier_ops, 39 #define BPF_MAP_TYPE(_id, _ops) 40 #define BPF_LINK_TYPE(_id, _name) 41 #include <linux/bpf_types.h> 42 #undef BPF_PROG_TYPE 43 #undef BPF_MAP_TYPE 44 #undef BPF_LINK_TYPE 45 }; 46 47 struct bpf_mem_alloc bpf_global_percpu_ma; 48 static bool bpf_global_percpu_ma_set; 49 50 /* bpf_check() is a static code analyzer that walks eBPF program 51 * instruction by instruction and updates register/stack state. 52 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 53 * 54 * The first pass is depth-first-search to check that the program is a DAG. 55 * It rejects the following programs: 56 * - larger than BPF_MAXINSNS insns 57 * - if loop is present (detected via back-edge) 58 * - unreachable insns exist (shouldn't be a forest. program = one function) 59 * - out of bounds or malformed jumps 60 * The second pass is all possible path descent from the 1st insn. 61 * Since it's analyzing all paths through the program, the length of the 62 * analysis is limited to 64k insn, which may be hit even if total number of 63 * insn is less then 4K, but there are too many branches that change stack/regs. 64 * Number of 'branches to be analyzed' is limited to 1k 65 * 66 * On entry to each instruction, each register has a type, and the instruction 67 * changes the types of the registers depending on instruction semantics. 68 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 69 * copied to R1. 70 * 71 * All registers are 64-bit. 72 * R0 - return register 73 * R1-R5 argument passing registers 74 * R6-R9 callee saved registers 75 * R10 - frame pointer read-only 76 * 77 * At the start of BPF program the register R1 contains a pointer to bpf_context 78 * and has type PTR_TO_CTX. 79 * 80 * Verifier tracks arithmetic operations on pointers in case: 81 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 82 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 83 * 1st insn copies R10 (which has FRAME_PTR) type into R1 84 * and 2nd arithmetic instruction is pattern matched to recognize 85 * that it wants to construct a pointer to some element within stack. 86 * So after 2nd insn, the register R1 has type PTR_TO_STACK 87 * (and -20 constant is saved for further stack bounds checking). 88 * Meaning that this reg is a pointer to stack plus known immediate constant. 89 * 90 * Most of the time the registers have SCALAR_VALUE type, which 91 * means the register has some value, but it's not a valid pointer. 92 * (like pointer plus pointer becomes SCALAR_VALUE type) 93 * 94 * When verifier sees load or store instructions the type of base register 95 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 96 * four pointer types recognized by check_mem_access() function. 97 * 98 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 99 * and the range of [ptr, ptr + map's value_size) is accessible. 100 * 101 * registers used to pass values to function calls are checked against 102 * function argument constraints. 103 * 104 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 105 * It means that the register type passed to this function must be 106 * PTR_TO_STACK and it will be used inside the function as 107 * 'pointer to map element key' 108 * 109 * For example the argument constraints for bpf_map_lookup_elem(): 110 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 111 * .arg1_type = ARG_CONST_MAP_PTR, 112 * .arg2_type = ARG_PTR_TO_MAP_KEY, 113 * 114 * ret_type says that this function returns 'pointer to map elem value or null' 115 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 116 * 2nd argument should be a pointer to stack, which will be used inside 117 * the helper function as a pointer to map element key. 118 * 119 * On the kernel side the helper function looks like: 120 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 121 * { 122 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 123 * void *key = (void *) (unsigned long) r2; 124 * void *value; 125 * 126 * here kernel can access 'key' and 'map' pointers safely, knowing that 127 * [key, key + map->key_size) bytes are valid and were initialized on 128 * the stack of eBPF program. 129 * } 130 * 131 * Corresponding eBPF program may look like: 132 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 133 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 134 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 135 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 136 * here verifier looks at prototype of map_lookup_elem() and sees: 137 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 138 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 139 * 140 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 141 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 142 * and were initialized prior to this call. 143 * If it's ok, then verifier allows this BPF_CALL insn and looks at 144 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 145 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 146 * returns either pointer to map value or NULL. 147 * 148 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 149 * insn, the register holding that pointer in the true branch changes state to 150 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 151 * branch. See check_cond_jmp_op(). 152 * 153 * After the call R0 is set to return type of the function and registers R1-R5 154 * are set to NOT_INIT to indicate that they are no longer readable. 155 * 156 * The following reference types represent a potential reference to a kernel 157 * resource which, after first being allocated, must be checked and freed by 158 * the BPF program: 159 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 160 * 161 * When the verifier sees a helper call return a reference type, it allocates a 162 * pointer id for the reference and stores it in the current function state. 163 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 164 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 165 * passes through a NULL-check conditional. For the branch wherein the state is 166 * changed to CONST_IMM, the verifier releases the reference. 167 * 168 * For each helper function that allocates a reference, such as 169 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 170 * bpf_sk_release(). When a reference type passes into the release function, 171 * the verifier also releases the reference. If any unchecked or unreleased 172 * reference remains at the end of the program, the verifier rejects it. 173 */ 174 175 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 176 struct bpf_verifier_stack_elem { 177 /* verifier state is 'st' 178 * before processing instruction 'insn_idx' 179 * and after processing instruction 'prev_insn_idx' 180 */ 181 struct bpf_verifier_state st; 182 int insn_idx; 183 int prev_insn_idx; 184 struct bpf_verifier_stack_elem *next; 185 /* length of verifier log at the time this state was pushed on stack */ 186 u32 log_pos; 187 }; 188 189 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192 190 #define BPF_COMPLEXITY_LIMIT_STATES 64 191 192 #define BPF_MAP_KEY_POISON (1ULL << 63) 193 #define BPF_MAP_KEY_SEEN (1ULL << 62) 194 195 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE 512 196 197 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx); 198 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id); 199 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 200 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 201 static int ref_set_non_owning(struct bpf_verifier_env *env, 202 struct bpf_reg_state *reg); 203 static void specialize_kfunc(struct bpf_verifier_env *env, 204 u32 func_id, u16 offset, unsigned long *addr); 205 static bool is_trusted_reg(const struct bpf_reg_state *reg); 206 207 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 208 { 209 return aux->map_ptr_state.poison; 210 } 211 212 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 213 { 214 return aux->map_ptr_state.unpriv; 215 } 216 217 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 218 struct bpf_map *map, 219 bool unpriv, bool poison) 220 { 221 unpriv |= bpf_map_ptr_unpriv(aux); 222 aux->map_ptr_state.unpriv = unpriv; 223 aux->map_ptr_state.poison = poison; 224 aux->map_ptr_state.map_ptr = map; 225 } 226 227 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 228 { 229 return aux->map_key_state & BPF_MAP_KEY_POISON; 230 } 231 232 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 233 { 234 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 235 } 236 237 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 238 { 239 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 240 } 241 242 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 243 { 244 bool poisoned = bpf_map_key_poisoned(aux); 245 246 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 247 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 248 } 249 250 static bool bpf_helper_call(const struct bpf_insn *insn) 251 { 252 return insn->code == (BPF_JMP | BPF_CALL) && 253 insn->src_reg == 0; 254 } 255 256 static bool bpf_pseudo_call(const struct bpf_insn *insn) 257 { 258 return insn->code == (BPF_JMP | BPF_CALL) && 259 insn->src_reg == BPF_PSEUDO_CALL; 260 } 261 262 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 263 { 264 return insn->code == (BPF_JMP | BPF_CALL) && 265 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 266 } 267 268 struct bpf_call_arg_meta { 269 struct bpf_map *map_ptr; 270 bool raw_mode; 271 bool pkt_access; 272 u8 release_regno; 273 int regno; 274 int access_size; 275 int mem_size; 276 u64 msize_max_value; 277 int ref_obj_id; 278 int dynptr_id; 279 int map_uid; 280 int func_id; 281 struct btf *btf; 282 u32 btf_id; 283 struct btf *ret_btf; 284 u32 ret_btf_id; 285 u32 subprogno; 286 struct btf_field *kptr_field; 287 }; 288 289 struct bpf_kfunc_call_arg_meta { 290 /* In parameters */ 291 struct btf *btf; 292 u32 func_id; 293 u32 kfunc_flags; 294 const struct btf_type *func_proto; 295 const char *func_name; 296 /* Out parameters */ 297 u32 ref_obj_id; 298 u8 release_regno; 299 bool r0_rdonly; 300 u32 ret_btf_id; 301 u64 r0_size; 302 u32 subprogno; 303 struct { 304 u64 value; 305 bool found; 306 } arg_constant; 307 308 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling, 309 * generally to pass info about user-defined local kptr types to later 310 * verification logic 311 * bpf_obj_drop/bpf_percpu_obj_drop 312 * Record the local kptr type to be drop'd 313 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type) 314 * Record the local kptr type to be refcount_incr'd and use 315 * arg_owning_ref to determine whether refcount_acquire should be 316 * fallible 317 */ 318 struct btf *arg_btf; 319 u32 arg_btf_id; 320 bool arg_owning_ref; 321 322 struct { 323 struct btf_field *field; 324 } arg_list_head; 325 struct { 326 struct btf_field *field; 327 } arg_rbtree_root; 328 struct { 329 enum bpf_dynptr_type type; 330 u32 id; 331 u32 ref_obj_id; 332 } initialized_dynptr; 333 struct { 334 u8 spi; 335 u8 frameno; 336 } iter; 337 struct { 338 struct bpf_map *ptr; 339 int uid; 340 } map; 341 u64 mem_size; 342 }; 343 344 struct btf *btf_vmlinux; 345 346 static const char *btf_type_name(const struct btf *btf, u32 id) 347 { 348 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 349 } 350 351 static DEFINE_MUTEX(bpf_verifier_lock); 352 static DEFINE_MUTEX(bpf_percpu_ma_lock); 353 354 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 355 { 356 struct bpf_verifier_env *env = private_data; 357 va_list args; 358 359 if (!bpf_verifier_log_needed(&env->log)) 360 return; 361 362 va_start(args, fmt); 363 bpf_verifier_vlog(&env->log, fmt, args); 364 va_end(args); 365 } 366 367 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 368 struct bpf_reg_state *reg, 369 struct bpf_retval_range range, const char *ctx, 370 const char *reg_name) 371 { 372 bool unknown = true; 373 374 verbose(env, "%s the register %s has", ctx, reg_name); 375 if (reg->smin_value > S64_MIN) { 376 verbose(env, " smin=%lld", reg->smin_value); 377 unknown = false; 378 } 379 if (reg->smax_value < S64_MAX) { 380 verbose(env, " smax=%lld", reg->smax_value); 381 unknown = false; 382 } 383 if (unknown) 384 verbose(env, " unknown scalar value"); 385 verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval); 386 } 387 388 static bool reg_not_null(const struct bpf_reg_state *reg) 389 { 390 enum bpf_reg_type type; 391 392 type = reg->type; 393 if (type_may_be_null(type)) 394 return false; 395 396 type = base_type(type); 397 return type == PTR_TO_SOCKET || 398 type == PTR_TO_TCP_SOCK || 399 type == PTR_TO_MAP_VALUE || 400 type == PTR_TO_MAP_KEY || 401 type == PTR_TO_SOCK_COMMON || 402 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) || 403 type == PTR_TO_MEM; 404 } 405 406 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 407 { 408 struct btf_record *rec = NULL; 409 struct btf_struct_meta *meta; 410 411 if (reg->type == PTR_TO_MAP_VALUE) { 412 rec = reg->map_ptr->record; 413 } else if (type_is_ptr_alloc_obj(reg->type)) { 414 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 415 if (meta) 416 rec = meta->record; 417 } 418 return rec; 419 } 420 421 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog) 422 { 423 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 424 425 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 426 } 427 428 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog) 429 { 430 struct bpf_func_info *info; 431 432 if (!env->prog->aux->func_info) 433 return ""; 434 435 info = &env->prog->aux->func_info[subprog]; 436 return btf_type_name(env->prog->aux->btf, info->type_id); 437 } 438 439 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog) 440 { 441 struct bpf_subprog_info *info = subprog_info(env, subprog); 442 443 info->is_cb = true; 444 info->is_async_cb = true; 445 info->is_exception_cb = true; 446 } 447 448 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog) 449 { 450 return subprog_info(env, subprog)->is_exception_cb; 451 } 452 453 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 454 { 455 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK); 456 } 457 458 static bool type_is_rdonly_mem(u32 type) 459 { 460 return type & MEM_RDONLY; 461 } 462 463 static bool is_acquire_function(enum bpf_func_id func_id, 464 const struct bpf_map *map) 465 { 466 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 467 468 if (func_id == BPF_FUNC_sk_lookup_tcp || 469 func_id == BPF_FUNC_sk_lookup_udp || 470 func_id == BPF_FUNC_skc_lookup_tcp || 471 func_id == BPF_FUNC_ringbuf_reserve || 472 func_id == BPF_FUNC_kptr_xchg) 473 return true; 474 475 if (func_id == BPF_FUNC_map_lookup_elem && 476 (map_type == BPF_MAP_TYPE_SOCKMAP || 477 map_type == BPF_MAP_TYPE_SOCKHASH)) 478 return true; 479 480 return false; 481 } 482 483 static bool is_ptr_cast_function(enum bpf_func_id func_id) 484 { 485 return func_id == BPF_FUNC_tcp_sock || 486 func_id == BPF_FUNC_sk_fullsock || 487 func_id == BPF_FUNC_skc_to_tcp_sock || 488 func_id == BPF_FUNC_skc_to_tcp6_sock || 489 func_id == BPF_FUNC_skc_to_udp6_sock || 490 func_id == BPF_FUNC_skc_to_mptcp_sock || 491 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 492 func_id == BPF_FUNC_skc_to_tcp_request_sock; 493 } 494 495 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 496 { 497 return func_id == BPF_FUNC_dynptr_data; 498 } 499 500 static bool is_sync_callback_calling_kfunc(u32 btf_id); 501 static bool is_async_callback_calling_kfunc(u32 btf_id); 502 static bool is_callback_calling_kfunc(u32 btf_id); 503 static bool is_bpf_throw_kfunc(struct bpf_insn *insn); 504 505 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id); 506 507 static bool is_sync_callback_calling_function(enum bpf_func_id func_id) 508 { 509 return func_id == BPF_FUNC_for_each_map_elem || 510 func_id == BPF_FUNC_find_vma || 511 func_id == BPF_FUNC_loop || 512 func_id == BPF_FUNC_user_ringbuf_drain; 513 } 514 515 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 516 { 517 return func_id == BPF_FUNC_timer_set_callback; 518 } 519 520 static bool is_callback_calling_function(enum bpf_func_id func_id) 521 { 522 return is_sync_callback_calling_function(func_id) || 523 is_async_callback_calling_function(func_id); 524 } 525 526 static bool is_sync_callback_calling_insn(struct bpf_insn *insn) 527 { 528 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) || 529 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm)); 530 } 531 532 static bool is_async_callback_calling_insn(struct bpf_insn *insn) 533 { 534 return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) || 535 (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm)); 536 } 537 538 static bool is_may_goto_insn(struct bpf_insn *insn) 539 { 540 return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO; 541 } 542 543 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx) 544 { 545 return is_may_goto_insn(&env->prog->insnsi[insn_idx]); 546 } 547 548 static bool is_storage_get_function(enum bpf_func_id func_id) 549 { 550 return func_id == BPF_FUNC_sk_storage_get || 551 func_id == BPF_FUNC_inode_storage_get || 552 func_id == BPF_FUNC_task_storage_get || 553 func_id == BPF_FUNC_cgrp_storage_get; 554 } 555 556 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 557 const struct bpf_map *map) 558 { 559 int ref_obj_uses = 0; 560 561 if (is_ptr_cast_function(func_id)) 562 ref_obj_uses++; 563 if (is_acquire_function(func_id, map)) 564 ref_obj_uses++; 565 if (is_dynptr_ref_function(func_id)) 566 ref_obj_uses++; 567 568 return ref_obj_uses > 1; 569 } 570 571 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 572 { 573 return BPF_CLASS(insn->code) == BPF_STX && 574 BPF_MODE(insn->code) == BPF_ATOMIC && 575 insn->imm == BPF_CMPXCHG; 576 } 577 578 static int __get_spi(s32 off) 579 { 580 return (-off - 1) / BPF_REG_SIZE; 581 } 582 583 static struct bpf_func_state *func(struct bpf_verifier_env *env, 584 const struct bpf_reg_state *reg) 585 { 586 struct bpf_verifier_state *cur = env->cur_state; 587 588 return cur->frame[reg->frameno]; 589 } 590 591 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 592 { 593 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 594 595 /* We need to check that slots between [spi - nr_slots + 1, spi] are 596 * within [0, allocated_stack). 597 * 598 * Please note that the spi grows downwards. For example, a dynptr 599 * takes the size of two stack slots; the first slot will be at 600 * spi and the second slot will be at spi - 1. 601 */ 602 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 603 } 604 605 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 606 const char *obj_kind, int nr_slots) 607 { 608 int off, spi; 609 610 if (!tnum_is_const(reg->var_off)) { 611 verbose(env, "%s has to be at a constant offset\n", obj_kind); 612 return -EINVAL; 613 } 614 615 off = reg->off + reg->var_off.value; 616 if (off % BPF_REG_SIZE) { 617 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 618 return -EINVAL; 619 } 620 621 spi = __get_spi(off); 622 if (spi + 1 < nr_slots) { 623 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 624 return -EINVAL; 625 } 626 627 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots)) 628 return -ERANGE; 629 return spi; 630 } 631 632 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 633 { 634 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 635 } 636 637 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 638 { 639 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 640 } 641 642 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 643 { 644 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 645 case DYNPTR_TYPE_LOCAL: 646 return BPF_DYNPTR_TYPE_LOCAL; 647 case DYNPTR_TYPE_RINGBUF: 648 return BPF_DYNPTR_TYPE_RINGBUF; 649 case DYNPTR_TYPE_SKB: 650 return BPF_DYNPTR_TYPE_SKB; 651 case DYNPTR_TYPE_XDP: 652 return BPF_DYNPTR_TYPE_XDP; 653 default: 654 return BPF_DYNPTR_TYPE_INVALID; 655 } 656 } 657 658 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 659 { 660 switch (type) { 661 case BPF_DYNPTR_TYPE_LOCAL: 662 return DYNPTR_TYPE_LOCAL; 663 case BPF_DYNPTR_TYPE_RINGBUF: 664 return DYNPTR_TYPE_RINGBUF; 665 case BPF_DYNPTR_TYPE_SKB: 666 return DYNPTR_TYPE_SKB; 667 case BPF_DYNPTR_TYPE_XDP: 668 return DYNPTR_TYPE_XDP; 669 default: 670 return 0; 671 } 672 } 673 674 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 675 { 676 return type == BPF_DYNPTR_TYPE_RINGBUF; 677 } 678 679 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 680 enum bpf_dynptr_type type, 681 bool first_slot, int dynptr_id); 682 683 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 684 struct bpf_reg_state *reg); 685 686 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 687 struct bpf_reg_state *sreg1, 688 struct bpf_reg_state *sreg2, 689 enum bpf_dynptr_type type) 690 { 691 int id = ++env->id_gen; 692 693 __mark_dynptr_reg(sreg1, type, true, id); 694 __mark_dynptr_reg(sreg2, type, false, id); 695 } 696 697 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 698 struct bpf_reg_state *reg, 699 enum bpf_dynptr_type type) 700 { 701 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 702 } 703 704 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 705 struct bpf_func_state *state, int spi); 706 707 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 708 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id) 709 { 710 struct bpf_func_state *state = func(env, reg); 711 enum bpf_dynptr_type type; 712 int spi, i, err; 713 714 spi = dynptr_get_spi(env, reg); 715 if (spi < 0) 716 return spi; 717 718 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 719 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 720 * to ensure that for the following example: 721 * [d1][d1][d2][d2] 722 * spi 3 2 1 0 723 * So marking spi = 2 should lead to destruction of both d1 and d2. In 724 * case they do belong to same dynptr, second call won't see slot_type 725 * as STACK_DYNPTR and will simply skip destruction. 726 */ 727 err = destroy_if_dynptr_stack_slot(env, state, spi); 728 if (err) 729 return err; 730 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 731 if (err) 732 return err; 733 734 for (i = 0; i < BPF_REG_SIZE; i++) { 735 state->stack[spi].slot_type[i] = STACK_DYNPTR; 736 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 737 } 738 739 type = arg_to_dynptr_type(arg_type); 740 if (type == BPF_DYNPTR_TYPE_INVALID) 741 return -EINVAL; 742 743 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 744 &state->stack[spi - 1].spilled_ptr, type); 745 746 if (dynptr_type_refcounted(type)) { 747 /* The id is used to track proper releasing */ 748 int id; 749 750 if (clone_ref_obj_id) 751 id = clone_ref_obj_id; 752 else 753 id = acquire_reference_state(env, insn_idx); 754 755 if (id < 0) 756 return id; 757 758 state->stack[spi].spilled_ptr.ref_obj_id = id; 759 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 760 } 761 762 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 763 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 764 765 return 0; 766 } 767 768 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi) 769 { 770 int i; 771 772 for (i = 0; i < BPF_REG_SIZE; i++) { 773 state->stack[spi].slot_type[i] = STACK_INVALID; 774 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 775 } 776 777 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 778 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 779 780 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot? 781 * 782 * While we don't allow reading STACK_INVALID, it is still possible to 783 * do <8 byte writes marking some but not all slots as STACK_MISC. Then, 784 * helpers or insns can do partial read of that part without failing, 785 * but check_stack_range_initialized, check_stack_read_var_off, and 786 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of 787 * the slot conservatively. Hence we need to prevent those liveness 788 * marking walks. 789 * 790 * This was not a problem before because STACK_INVALID is only set by 791 * default (where the default reg state has its reg->parent as NULL), or 792 * in clean_live_states after REG_LIVE_DONE (at which point 793 * mark_reg_read won't walk reg->parent chain), but not randomly during 794 * verifier state exploration (like we did above). Hence, for our case 795 * parentage chain will still be live (i.e. reg->parent may be 796 * non-NULL), while earlier reg->parent was NULL, so we need 797 * REG_LIVE_WRITTEN to screen off read marker propagation when it is 798 * done later on reads or by mark_dynptr_read as well to unnecessary 799 * mark registers in verifier state. 800 */ 801 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 802 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 803 } 804 805 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 806 { 807 struct bpf_func_state *state = func(env, reg); 808 int spi, ref_obj_id, i; 809 810 spi = dynptr_get_spi(env, reg); 811 if (spi < 0) 812 return spi; 813 814 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 815 invalidate_dynptr(env, state, spi); 816 return 0; 817 } 818 819 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 820 821 /* If the dynptr has a ref_obj_id, then we need to invalidate 822 * two things: 823 * 824 * 1) Any dynptrs with a matching ref_obj_id (clones) 825 * 2) Any slices derived from this dynptr. 826 */ 827 828 /* Invalidate any slices associated with this dynptr */ 829 WARN_ON_ONCE(release_reference(env, ref_obj_id)); 830 831 /* Invalidate any dynptr clones */ 832 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) { 833 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id) 834 continue; 835 836 /* it should always be the case that if the ref obj id 837 * matches then the stack slot also belongs to a 838 * dynptr 839 */ 840 if (state->stack[i].slot_type[0] != STACK_DYNPTR) { 841 verbose(env, "verifier internal error: misconfigured ref_obj_id\n"); 842 return -EFAULT; 843 } 844 if (state->stack[i].spilled_ptr.dynptr.first_slot) 845 invalidate_dynptr(env, state, i); 846 } 847 848 return 0; 849 } 850 851 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 852 struct bpf_reg_state *reg); 853 854 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 855 { 856 if (!env->allow_ptr_leaks) 857 __mark_reg_not_init(env, reg); 858 else 859 __mark_reg_unknown(env, reg); 860 } 861 862 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 863 struct bpf_func_state *state, int spi) 864 { 865 struct bpf_func_state *fstate; 866 struct bpf_reg_state *dreg; 867 int i, dynptr_id; 868 869 /* We always ensure that STACK_DYNPTR is never set partially, 870 * hence just checking for slot_type[0] is enough. This is 871 * different for STACK_SPILL, where it may be only set for 872 * 1 byte, so code has to use is_spilled_reg. 873 */ 874 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 875 return 0; 876 877 /* Reposition spi to first slot */ 878 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 879 spi = spi + 1; 880 881 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 882 verbose(env, "cannot overwrite referenced dynptr\n"); 883 return -EINVAL; 884 } 885 886 mark_stack_slot_scratched(env, spi); 887 mark_stack_slot_scratched(env, spi - 1); 888 889 /* Writing partially to one dynptr stack slot destroys both. */ 890 for (i = 0; i < BPF_REG_SIZE; i++) { 891 state->stack[spi].slot_type[i] = STACK_INVALID; 892 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 893 } 894 895 dynptr_id = state->stack[spi].spilled_ptr.id; 896 /* Invalidate any slices associated with this dynptr */ 897 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 898 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 899 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 900 continue; 901 if (dreg->dynptr_id == dynptr_id) 902 mark_reg_invalid(env, dreg); 903 })); 904 905 /* Do not release reference state, we are destroying dynptr on stack, 906 * not using some helper to release it. Just reset register. 907 */ 908 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 909 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 910 911 /* Same reason as unmark_stack_slots_dynptr above */ 912 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 913 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 914 915 return 0; 916 } 917 918 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 919 { 920 int spi; 921 922 if (reg->type == CONST_PTR_TO_DYNPTR) 923 return false; 924 925 spi = dynptr_get_spi(env, reg); 926 927 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 928 * error because this just means the stack state hasn't been updated yet. 929 * We will do check_mem_access to check and update stack bounds later. 930 */ 931 if (spi < 0 && spi != -ERANGE) 932 return false; 933 934 /* We don't need to check if the stack slots are marked by previous 935 * dynptr initializations because we allow overwriting existing unreferenced 936 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 937 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 938 * touching are completely destructed before we reinitialize them for a new 939 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 940 * instead of delaying it until the end where the user will get "Unreleased 941 * reference" error. 942 */ 943 return true; 944 } 945 946 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 947 { 948 struct bpf_func_state *state = func(env, reg); 949 int i, spi; 950 951 /* This already represents first slot of initialized bpf_dynptr. 952 * 953 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 954 * check_func_arg_reg_off's logic, so we don't need to check its 955 * offset and alignment. 956 */ 957 if (reg->type == CONST_PTR_TO_DYNPTR) 958 return true; 959 960 spi = dynptr_get_spi(env, reg); 961 if (spi < 0) 962 return false; 963 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 964 return false; 965 966 for (i = 0; i < BPF_REG_SIZE; i++) { 967 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 968 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 969 return false; 970 } 971 972 return true; 973 } 974 975 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 976 enum bpf_arg_type arg_type) 977 { 978 struct bpf_func_state *state = func(env, reg); 979 enum bpf_dynptr_type dynptr_type; 980 int spi; 981 982 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 983 if (arg_type == ARG_PTR_TO_DYNPTR) 984 return true; 985 986 dynptr_type = arg_to_dynptr_type(arg_type); 987 if (reg->type == CONST_PTR_TO_DYNPTR) { 988 return reg->dynptr.type == dynptr_type; 989 } else { 990 spi = dynptr_get_spi(env, reg); 991 if (spi < 0) 992 return false; 993 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 994 } 995 } 996 997 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 998 999 static bool in_rcu_cs(struct bpf_verifier_env *env); 1000 1001 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta); 1002 1003 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 1004 struct bpf_kfunc_call_arg_meta *meta, 1005 struct bpf_reg_state *reg, int insn_idx, 1006 struct btf *btf, u32 btf_id, int nr_slots) 1007 { 1008 struct bpf_func_state *state = func(env, reg); 1009 int spi, i, j, id; 1010 1011 spi = iter_get_spi(env, reg, nr_slots); 1012 if (spi < 0) 1013 return spi; 1014 1015 id = acquire_reference_state(env, insn_idx); 1016 if (id < 0) 1017 return id; 1018 1019 for (i = 0; i < nr_slots; i++) { 1020 struct bpf_stack_state *slot = &state->stack[spi - i]; 1021 struct bpf_reg_state *st = &slot->spilled_ptr; 1022 1023 __mark_reg_known_zero(st); 1024 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1025 if (is_kfunc_rcu_protected(meta)) { 1026 if (in_rcu_cs(env)) 1027 st->type |= MEM_RCU; 1028 else 1029 st->type |= PTR_UNTRUSTED; 1030 } 1031 st->live |= REG_LIVE_WRITTEN; 1032 st->ref_obj_id = i == 0 ? id : 0; 1033 st->iter.btf = btf; 1034 st->iter.btf_id = btf_id; 1035 st->iter.state = BPF_ITER_STATE_ACTIVE; 1036 st->iter.depth = 0; 1037 1038 for (j = 0; j < BPF_REG_SIZE; j++) 1039 slot->slot_type[j] = STACK_ITER; 1040 1041 mark_stack_slot_scratched(env, spi - i); 1042 } 1043 1044 return 0; 1045 } 1046 1047 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 1048 struct bpf_reg_state *reg, int nr_slots) 1049 { 1050 struct bpf_func_state *state = func(env, reg); 1051 int spi, i, j; 1052 1053 spi = iter_get_spi(env, reg, nr_slots); 1054 if (spi < 0) 1055 return spi; 1056 1057 for (i = 0; i < nr_slots; i++) { 1058 struct bpf_stack_state *slot = &state->stack[spi - i]; 1059 struct bpf_reg_state *st = &slot->spilled_ptr; 1060 1061 if (i == 0) 1062 WARN_ON_ONCE(release_reference(env, st->ref_obj_id)); 1063 1064 __mark_reg_not_init(env, st); 1065 1066 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1067 st->live |= REG_LIVE_WRITTEN; 1068 1069 for (j = 0; j < BPF_REG_SIZE; j++) 1070 slot->slot_type[j] = STACK_INVALID; 1071 1072 mark_stack_slot_scratched(env, spi - i); 1073 } 1074 1075 return 0; 1076 } 1077 1078 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1079 struct bpf_reg_state *reg, int nr_slots) 1080 { 1081 struct bpf_func_state *state = func(env, reg); 1082 int spi, i, j; 1083 1084 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1085 * will do check_mem_access to check and update stack bounds later, so 1086 * return true for that case. 1087 */ 1088 spi = iter_get_spi(env, reg, nr_slots); 1089 if (spi == -ERANGE) 1090 return true; 1091 if (spi < 0) 1092 return false; 1093 1094 for (i = 0; i < nr_slots; i++) { 1095 struct bpf_stack_state *slot = &state->stack[spi - i]; 1096 1097 for (j = 0; j < BPF_REG_SIZE; j++) 1098 if (slot->slot_type[j] == STACK_ITER) 1099 return false; 1100 } 1101 1102 return true; 1103 } 1104 1105 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1106 struct btf *btf, u32 btf_id, int nr_slots) 1107 { 1108 struct bpf_func_state *state = func(env, reg); 1109 int spi, i, j; 1110 1111 spi = iter_get_spi(env, reg, nr_slots); 1112 if (spi < 0) 1113 return -EINVAL; 1114 1115 for (i = 0; i < nr_slots; i++) { 1116 struct bpf_stack_state *slot = &state->stack[spi - i]; 1117 struct bpf_reg_state *st = &slot->spilled_ptr; 1118 1119 if (st->type & PTR_UNTRUSTED) 1120 return -EPROTO; 1121 /* only main (first) slot has ref_obj_id set */ 1122 if (i == 0 && !st->ref_obj_id) 1123 return -EINVAL; 1124 if (i != 0 && st->ref_obj_id) 1125 return -EINVAL; 1126 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1127 return -EINVAL; 1128 1129 for (j = 0; j < BPF_REG_SIZE; j++) 1130 if (slot->slot_type[j] != STACK_ITER) 1131 return -EINVAL; 1132 } 1133 1134 return 0; 1135 } 1136 1137 /* Check if given stack slot is "special": 1138 * - spilled register state (STACK_SPILL); 1139 * - dynptr state (STACK_DYNPTR); 1140 * - iter state (STACK_ITER). 1141 */ 1142 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1143 { 1144 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1145 1146 switch (type) { 1147 case STACK_SPILL: 1148 case STACK_DYNPTR: 1149 case STACK_ITER: 1150 return true; 1151 case STACK_INVALID: 1152 case STACK_MISC: 1153 case STACK_ZERO: 1154 return false; 1155 default: 1156 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1157 return true; 1158 } 1159 } 1160 1161 /* The reg state of a pointer or a bounded scalar was saved when 1162 * it was spilled to the stack. 1163 */ 1164 static bool is_spilled_reg(const struct bpf_stack_state *stack) 1165 { 1166 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1167 } 1168 1169 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack) 1170 { 1171 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL && 1172 stack->spilled_ptr.type == SCALAR_VALUE; 1173 } 1174 1175 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack) 1176 { 1177 return stack->slot_type[0] == STACK_SPILL && 1178 stack->spilled_ptr.type == SCALAR_VALUE; 1179 } 1180 1181 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which 1182 * case they are equivalent, or it's STACK_ZERO, in which case we preserve 1183 * more precise STACK_ZERO. 1184 * Note, in uprivileged mode leaving STACK_INVALID is wrong, so we take 1185 * env->allow_ptr_leaks into account and force STACK_MISC, if necessary. 1186 */ 1187 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype) 1188 { 1189 if (*stype == STACK_ZERO) 1190 return; 1191 if (env->allow_ptr_leaks && *stype == STACK_INVALID) 1192 return; 1193 *stype = STACK_MISC; 1194 } 1195 1196 static void scrub_spilled_slot(u8 *stype) 1197 { 1198 if (*stype != STACK_INVALID) 1199 *stype = STACK_MISC; 1200 } 1201 1202 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1203 * small to hold src. This is different from krealloc since we don't want to preserve 1204 * the contents of dst. 1205 * 1206 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1207 * not be allocated. 1208 */ 1209 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1210 { 1211 size_t alloc_bytes; 1212 void *orig = dst; 1213 size_t bytes; 1214 1215 if (ZERO_OR_NULL_PTR(src)) 1216 goto out; 1217 1218 if (unlikely(check_mul_overflow(n, size, &bytes))) 1219 return NULL; 1220 1221 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1222 dst = krealloc(orig, alloc_bytes, flags); 1223 if (!dst) { 1224 kfree(orig); 1225 return NULL; 1226 } 1227 1228 memcpy(dst, src, bytes); 1229 out: 1230 return dst ? dst : ZERO_SIZE_PTR; 1231 } 1232 1233 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1234 * small to hold new_n items. new items are zeroed out if the array grows. 1235 * 1236 * Contrary to krealloc_array, does not free arr if new_n is zero. 1237 */ 1238 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1239 { 1240 size_t alloc_size; 1241 void *new_arr; 1242 1243 if (!new_n || old_n == new_n) 1244 goto out; 1245 1246 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1247 new_arr = krealloc(arr, alloc_size, GFP_KERNEL); 1248 if (!new_arr) { 1249 kfree(arr); 1250 return NULL; 1251 } 1252 arr = new_arr; 1253 1254 if (new_n > old_n) 1255 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1256 1257 out: 1258 return arr ? arr : ZERO_SIZE_PTR; 1259 } 1260 1261 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1262 { 1263 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1264 sizeof(struct bpf_reference_state), GFP_KERNEL); 1265 if (!dst->refs) 1266 return -ENOMEM; 1267 1268 dst->acquired_refs = src->acquired_refs; 1269 return 0; 1270 } 1271 1272 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1273 { 1274 size_t n = src->allocated_stack / BPF_REG_SIZE; 1275 1276 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1277 GFP_KERNEL); 1278 if (!dst->stack) 1279 return -ENOMEM; 1280 1281 dst->allocated_stack = src->allocated_stack; 1282 return 0; 1283 } 1284 1285 static int resize_reference_state(struct bpf_func_state *state, size_t n) 1286 { 1287 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1288 sizeof(struct bpf_reference_state)); 1289 if (!state->refs) 1290 return -ENOMEM; 1291 1292 state->acquired_refs = n; 1293 return 0; 1294 } 1295 1296 /* Possibly update state->allocated_stack to be at least size bytes. Also 1297 * possibly update the function's high-water mark in its bpf_subprog_info. 1298 */ 1299 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) 1300 { 1301 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n; 1302 1303 /* The stack size is always a multiple of BPF_REG_SIZE. */ 1304 size = round_up(size, BPF_REG_SIZE); 1305 n = size / BPF_REG_SIZE; 1306 1307 if (old_n >= n) 1308 return 0; 1309 1310 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1311 if (!state->stack) 1312 return -ENOMEM; 1313 1314 state->allocated_stack = size; 1315 1316 /* update known max for given subprogram */ 1317 if (env->subprog_info[state->subprogno].stack_depth < size) 1318 env->subprog_info[state->subprogno].stack_depth = size; 1319 1320 return 0; 1321 } 1322 1323 /* Acquire a pointer id from the env and update the state->refs to include 1324 * this new pointer reference. 1325 * On success, returns a valid pointer id to associate with the register 1326 * On failure, returns a negative errno. 1327 */ 1328 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1329 { 1330 struct bpf_func_state *state = cur_func(env); 1331 int new_ofs = state->acquired_refs; 1332 int id, err; 1333 1334 err = resize_reference_state(state, state->acquired_refs + 1); 1335 if (err) 1336 return err; 1337 id = ++env->id_gen; 1338 state->refs[new_ofs].id = id; 1339 state->refs[new_ofs].insn_idx = insn_idx; 1340 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0; 1341 1342 return id; 1343 } 1344 1345 /* release function corresponding to acquire_reference_state(). Idempotent. */ 1346 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 1347 { 1348 int i, last_idx; 1349 1350 last_idx = state->acquired_refs - 1; 1351 for (i = 0; i < state->acquired_refs; i++) { 1352 if (state->refs[i].id == ptr_id) { 1353 /* Cannot release caller references in callbacks */ 1354 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 1355 return -EINVAL; 1356 if (last_idx && i != last_idx) 1357 memcpy(&state->refs[i], &state->refs[last_idx], 1358 sizeof(*state->refs)); 1359 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1360 state->acquired_refs--; 1361 return 0; 1362 } 1363 } 1364 return -EINVAL; 1365 } 1366 1367 static void free_func_state(struct bpf_func_state *state) 1368 { 1369 if (!state) 1370 return; 1371 kfree(state->refs); 1372 kfree(state->stack); 1373 kfree(state); 1374 } 1375 1376 static void clear_jmp_history(struct bpf_verifier_state *state) 1377 { 1378 kfree(state->jmp_history); 1379 state->jmp_history = NULL; 1380 state->jmp_history_cnt = 0; 1381 } 1382 1383 static void free_verifier_state(struct bpf_verifier_state *state, 1384 bool free_self) 1385 { 1386 int i; 1387 1388 for (i = 0; i <= state->curframe; i++) { 1389 free_func_state(state->frame[i]); 1390 state->frame[i] = NULL; 1391 } 1392 clear_jmp_history(state); 1393 if (free_self) 1394 kfree(state); 1395 } 1396 1397 /* copy verifier state from src to dst growing dst stack space 1398 * when necessary to accommodate larger src stack 1399 */ 1400 static int copy_func_state(struct bpf_func_state *dst, 1401 const struct bpf_func_state *src) 1402 { 1403 int err; 1404 1405 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 1406 err = copy_reference_state(dst, src); 1407 if (err) 1408 return err; 1409 return copy_stack_state(dst, src); 1410 } 1411 1412 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1413 const struct bpf_verifier_state *src) 1414 { 1415 struct bpf_func_state *dst; 1416 int i, err; 1417 1418 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1419 src->jmp_history_cnt, sizeof(*dst_state->jmp_history), 1420 GFP_USER); 1421 if (!dst_state->jmp_history) 1422 return -ENOMEM; 1423 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1424 1425 /* if dst has more stack frames then src frame, free them, this is also 1426 * necessary in case of exceptional exits using bpf_throw. 1427 */ 1428 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1429 free_func_state(dst_state->frame[i]); 1430 dst_state->frame[i] = NULL; 1431 } 1432 dst_state->speculative = src->speculative; 1433 dst_state->active_rcu_lock = src->active_rcu_lock; 1434 dst_state->active_preempt_lock = src->active_preempt_lock; 1435 dst_state->in_sleepable = src->in_sleepable; 1436 dst_state->curframe = src->curframe; 1437 dst_state->active_lock.ptr = src->active_lock.ptr; 1438 dst_state->active_lock.id = src->active_lock.id; 1439 dst_state->branches = src->branches; 1440 dst_state->parent = src->parent; 1441 dst_state->first_insn_idx = src->first_insn_idx; 1442 dst_state->last_insn_idx = src->last_insn_idx; 1443 dst_state->dfs_depth = src->dfs_depth; 1444 dst_state->callback_unroll_depth = src->callback_unroll_depth; 1445 dst_state->used_as_loop_entry = src->used_as_loop_entry; 1446 dst_state->may_goto_depth = src->may_goto_depth; 1447 for (i = 0; i <= src->curframe; i++) { 1448 dst = dst_state->frame[i]; 1449 if (!dst) { 1450 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1451 if (!dst) 1452 return -ENOMEM; 1453 dst_state->frame[i] = dst; 1454 } 1455 err = copy_func_state(dst, src->frame[i]); 1456 if (err) 1457 return err; 1458 } 1459 return 0; 1460 } 1461 1462 static u32 state_htab_size(struct bpf_verifier_env *env) 1463 { 1464 return env->prog->len; 1465 } 1466 1467 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx) 1468 { 1469 struct bpf_verifier_state *cur = env->cur_state; 1470 struct bpf_func_state *state = cur->frame[cur->curframe]; 1471 1472 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 1473 } 1474 1475 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b) 1476 { 1477 int fr; 1478 1479 if (a->curframe != b->curframe) 1480 return false; 1481 1482 for (fr = a->curframe; fr >= 0; fr--) 1483 if (a->frame[fr]->callsite != b->frame[fr]->callsite) 1484 return false; 1485 1486 return true; 1487 } 1488 1489 /* Open coded iterators allow back-edges in the state graph in order to 1490 * check unbounded loops that iterators. 1491 * 1492 * In is_state_visited() it is necessary to know if explored states are 1493 * part of some loops in order to decide whether non-exact states 1494 * comparison could be used: 1495 * - non-exact states comparison establishes sub-state relation and uses 1496 * read and precision marks to do so, these marks are propagated from 1497 * children states and thus are not guaranteed to be final in a loop; 1498 * - exact states comparison just checks if current and explored states 1499 * are identical (and thus form a back-edge). 1500 * 1501 * Paper "A New Algorithm for Identifying Loops in Decompilation" 1502 * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient 1503 * algorithm for loop structure detection and gives an overview of 1504 * relevant terminology. It also has helpful illustrations. 1505 * 1506 * [1] https://api.semanticscholar.org/CorpusID:15784067 1507 * 1508 * We use a similar algorithm but because loop nested structure is 1509 * irrelevant for verifier ours is significantly simpler and resembles 1510 * strongly connected components algorithm from Sedgewick's textbook. 1511 * 1512 * Define topmost loop entry as a first node of the loop traversed in a 1513 * depth first search starting from initial state. The goal of the loop 1514 * tracking algorithm is to associate topmost loop entries with states 1515 * derived from these entries. 1516 * 1517 * For each step in the DFS states traversal algorithm needs to identify 1518 * the following situations: 1519 * 1520 * initial initial initial 1521 * | | | 1522 * V V V 1523 * ... ... .---------> hdr 1524 * | | | | 1525 * V V | V 1526 * cur .-> succ | .------... 1527 * | | | | | | 1528 * V | V | V V 1529 * succ '-- cur | ... ... 1530 * | | | 1531 * | V V 1532 * | succ <- cur 1533 * | | 1534 * | V 1535 * | ... 1536 * | | 1537 * '----' 1538 * 1539 * (A) successor state of cur (B) successor state of cur or it's entry 1540 * not yet traversed are in current DFS path, thus cur and succ 1541 * are members of the same outermost loop 1542 * 1543 * initial initial 1544 * | | 1545 * V V 1546 * ... ... 1547 * | | 1548 * V V 1549 * .------... .------... 1550 * | | | | 1551 * V V V V 1552 * .-> hdr ... ... ... 1553 * | | | | | 1554 * | V V V V 1555 * | succ <- cur succ <- cur 1556 * | | | 1557 * | V V 1558 * | ... ... 1559 * | | | 1560 * '----' exit 1561 * 1562 * (C) successor state of cur is a part of some loop but this loop 1563 * does not include cur or successor state is not in a loop at all. 1564 * 1565 * Algorithm could be described as the following python code: 1566 * 1567 * traversed = set() # Set of traversed nodes 1568 * entries = {} # Mapping from node to loop entry 1569 * depths = {} # Depth level assigned to graph node 1570 * path = set() # Current DFS path 1571 * 1572 * # Find outermost loop entry known for n 1573 * def get_loop_entry(n): 1574 * h = entries.get(n, None) 1575 * while h in entries and entries[h] != h: 1576 * h = entries[h] 1577 * return h 1578 * 1579 * # Update n's loop entry if h's outermost entry comes 1580 * # before n's outermost entry in current DFS path. 1581 * def update_loop_entry(n, h): 1582 * n1 = get_loop_entry(n) or n 1583 * h1 = get_loop_entry(h) or h 1584 * if h1 in path and depths[h1] <= depths[n1]: 1585 * entries[n] = h1 1586 * 1587 * def dfs(n, depth): 1588 * traversed.add(n) 1589 * path.add(n) 1590 * depths[n] = depth 1591 * for succ in G.successors(n): 1592 * if succ not in traversed: 1593 * # Case A: explore succ and update cur's loop entry 1594 * # only if succ's entry is in current DFS path. 1595 * dfs(succ, depth + 1) 1596 * h = get_loop_entry(succ) 1597 * update_loop_entry(n, h) 1598 * else: 1599 * # Case B or C depending on `h1 in path` check in update_loop_entry(). 1600 * update_loop_entry(n, succ) 1601 * path.remove(n) 1602 * 1603 * To adapt this algorithm for use with verifier: 1604 * - use st->branch == 0 as a signal that DFS of succ had been finished 1605 * and cur's loop entry has to be updated (case A), handle this in 1606 * update_branch_counts(); 1607 * - use st->branch > 0 as a signal that st is in the current DFS path; 1608 * - handle cases B and C in is_state_visited(); 1609 * - update topmost loop entry for intermediate states in get_loop_entry(). 1610 */ 1611 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st) 1612 { 1613 struct bpf_verifier_state *topmost = st->loop_entry, *old; 1614 1615 while (topmost && topmost->loop_entry && topmost != topmost->loop_entry) 1616 topmost = topmost->loop_entry; 1617 /* Update loop entries for intermediate states to avoid this 1618 * traversal in future get_loop_entry() calls. 1619 */ 1620 while (st && st->loop_entry != topmost) { 1621 old = st->loop_entry; 1622 st->loop_entry = topmost; 1623 st = old; 1624 } 1625 return topmost; 1626 } 1627 1628 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr) 1629 { 1630 struct bpf_verifier_state *cur1, *hdr1; 1631 1632 cur1 = get_loop_entry(cur) ?: cur; 1633 hdr1 = get_loop_entry(hdr) ?: hdr; 1634 /* The head1->branches check decides between cases B and C in 1635 * comment for get_loop_entry(). If hdr1->branches == 0 then 1636 * head's topmost loop entry is not in current DFS path, 1637 * hence 'cur' and 'hdr' are not in the same loop and there is 1638 * no need to update cur->loop_entry. 1639 */ 1640 if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) { 1641 cur->loop_entry = hdr; 1642 hdr->used_as_loop_entry = true; 1643 } 1644 } 1645 1646 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1647 { 1648 while (st) { 1649 u32 br = --st->branches; 1650 1651 /* br == 0 signals that DFS exploration for 'st' is finished, 1652 * thus it is necessary to update parent's loop entry if it 1653 * turned out that st is a part of some loop. 1654 * This is a part of 'case A' in get_loop_entry() comment. 1655 */ 1656 if (br == 0 && st->parent && st->loop_entry) 1657 update_loop_entry(st->parent, st->loop_entry); 1658 1659 /* WARN_ON(br > 1) technically makes sense here, 1660 * but see comment in push_stack(), hence: 1661 */ 1662 WARN_ONCE((int)br < 0, 1663 "BUG update_branch_counts:branches_to_explore=%d\n", 1664 br); 1665 if (br) 1666 break; 1667 st = st->parent; 1668 } 1669 } 1670 1671 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1672 int *insn_idx, bool pop_log) 1673 { 1674 struct bpf_verifier_state *cur = env->cur_state; 1675 struct bpf_verifier_stack_elem *elem, *head = env->head; 1676 int err; 1677 1678 if (env->head == NULL) 1679 return -ENOENT; 1680 1681 if (cur) { 1682 err = copy_verifier_state(cur, &head->st); 1683 if (err) 1684 return err; 1685 } 1686 if (pop_log) 1687 bpf_vlog_reset(&env->log, head->log_pos); 1688 if (insn_idx) 1689 *insn_idx = head->insn_idx; 1690 if (prev_insn_idx) 1691 *prev_insn_idx = head->prev_insn_idx; 1692 elem = head->next; 1693 free_verifier_state(&head->st, false); 1694 kfree(head); 1695 env->head = elem; 1696 env->stack_size--; 1697 return 0; 1698 } 1699 1700 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1701 int insn_idx, int prev_insn_idx, 1702 bool speculative) 1703 { 1704 struct bpf_verifier_state *cur = env->cur_state; 1705 struct bpf_verifier_stack_elem *elem; 1706 int err; 1707 1708 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1709 if (!elem) 1710 goto err; 1711 1712 elem->insn_idx = insn_idx; 1713 elem->prev_insn_idx = prev_insn_idx; 1714 elem->next = env->head; 1715 elem->log_pos = env->log.end_pos; 1716 env->head = elem; 1717 env->stack_size++; 1718 err = copy_verifier_state(&elem->st, cur); 1719 if (err) 1720 goto err; 1721 elem->st.speculative |= speculative; 1722 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1723 verbose(env, "The sequence of %d jumps is too complex.\n", 1724 env->stack_size); 1725 goto err; 1726 } 1727 if (elem->st.parent) { 1728 ++elem->st.parent->branches; 1729 /* WARN_ON(branches > 2) technically makes sense here, 1730 * but 1731 * 1. speculative states will bump 'branches' for non-branch 1732 * instructions 1733 * 2. is_state_visited() heuristics may decide not to create 1734 * a new state for a sequence of branches and all such current 1735 * and cloned states will be pointing to a single parent state 1736 * which might have large 'branches' count. 1737 */ 1738 } 1739 return &elem->st; 1740 err: 1741 free_verifier_state(env->cur_state, true); 1742 env->cur_state = NULL; 1743 /* pop all elements and return */ 1744 while (!pop_stack(env, NULL, NULL, false)); 1745 return NULL; 1746 } 1747 1748 #define CALLER_SAVED_REGS 6 1749 static const int caller_saved[CALLER_SAVED_REGS] = { 1750 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1751 }; 1752 1753 /* This helper doesn't clear reg->id */ 1754 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1755 { 1756 reg->var_off = tnum_const(imm); 1757 reg->smin_value = (s64)imm; 1758 reg->smax_value = (s64)imm; 1759 reg->umin_value = imm; 1760 reg->umax_value = imm; 1761 1762 reg->s32_min_value = (s32)imm; 1763 reg->s32_max_value = (s32)imm; 1764 reg->u32_min_value = (u32)imm; 1765 reg->u32_max_value = (u32)imm; 1766 } 1767 1768 /* Mark the unknown part of a register (variable offset or scalar value) as 1769 * known to have the value @imm. 1770 */ 1771 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1772 { 1773 /* Clear off and union(map_ptr, range) */ 1774 memset(((u8 *)reg) + sizeof(reg->type), 0, 1775 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1776 reg->id = 0; 1777 reg->ref_obj_id = 0; 1778 ___mark_reg_known(reg, imm); 1779 } 1780 1781 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1782 { 1783 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1784 reg->s32_min_value = (s32)imm; 1785 reg->s32_max_value = (s32)imm; 1786 reg->u32_min_value = (u32)imm; 1787 reg->u32_max_value = (u32)imm; 1788 } 1789 1790 /* Mark the 'variable offset' part of a register as zero. This should be 1791 * used only on registers holding a pointer type. 1792 */ 1793 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1794 { 1795 __mark_reg_known(reg, 0); 1796 } 1797 1798 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1799 { 1800 __mark_reg_known(reg, 0); 1801 reg->type = SCALAR_VALUE; 1802 /* all scalars are assumed imprecise initially (unless unprivileged, 1803 * in which case everything is forced to be precise) 1804 */ 1805 reg->precise = !env->bpf_capable; 1806 } 1807 1808 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1809 struct bpf_reg_state *regs, u32 regno) 1810 { 1811 if (WARN_ON(regno >= MAX_BPF_REG)) { 1812 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1813 /* Something bad happened, let's kill all regs */ 1814 for (regno = 0; regno < MAX_BPF_REG; regno++) 1815 __mark_reg_not_init(env, regs + regno); 1816 return; 1817 } 1818 __mark_reg_known_zero(regs + regno); 1819 } 1820 1821 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1822 bool first_slot, int dynptr_id) 1823 { 1824 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1825 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1826 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1827 */ 1828 __mark_reg_known_zero(reg); 1829 reg->type = CONST_PTR_TO_DYNPTR; 1830 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1831 reg->id = dynptr_id; 1832 reg->dynptr.type = type; 1833 reg->dynptr.first_slot = first_slot; 1834 } 1835 1836 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1837 { 1838 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1839 const struct bpf_map *map = reg->map_ptr; 1840 1841 if (map->inner_map_meta) { 1842 reg->type = CONST_PTR_TO_MAP; 1843 reg->map_ptr = map->inner_map_meta; 1844 /* transfer reg's id which is unique for every map_lookup_elem 1845 * as UID of the inner map. 1846 */ 1847 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 1848 reg->map_uid = reg->id; 1849 if (btf_record_has_field(map->inner_map_meta->record, BPF_WORKQUEUE)) 1850 reg->map_uid = reg->id; 1851 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1852 reg->type = PTR_TO_XDP_SOCK; 1853 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1854 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1855 reg->type = PTR_TO_SOCKET; 1856 } else { 1857 reg->type = PTR_TO_MAP_VALUE; 1858 } 1859 return; 1860 } 1861 1862 reg->type &= ~PTR_MAYBE_NULL; 1863 } 1864 1865 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 1866 struct btf_field_graph_root *ds_head) 1867 { 1868 __mark_reg_known_zero(®s[regno]); 1869 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 1870 regs[regno].btf = ds_head->btf; 1871 regs[regno].btf_id = ds_head->value_btf_id; 1872 regs[regno].off = ds_head->node_offset; 1873 } 1874 1875 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1876 { 1877 return type_is_pkt_pointer(reg->type); 1878 } 1879 1880 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1881 { 1882 return reg_is_pkt_pointer(reg) || 1883 reg->type == PTR_TO_PACKET_END; 1884 } 1885 1886 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 1887 { 1888 return base_type(reg->type) == PTR_TO_MEM && 1889 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP); 1890 } 1891 1892 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1893 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1894 enum bpf_reg_type which) 1895 { 1896 /* The register can already have a range from prior markings. 1897 * This is fine as long as it hasn't been advanced from its 1898 * origin. 1899 */ 1900 return reg->type == which && 1901 reg->id == 0 && 1902 reg->off == 0 && 1903 tnum_equals_const(reg->var_off, 0); 1904 } 1905 1906 /* Reset the min/max bounds of a register */ 1907 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1908 { 1909 reg->smin_value = S64_MIN; 1910 reg->smax_value = S64_MAX; 1911 reg->umin_value = 0; 1912 reg->umax_value = U64_MAX; 1913 1914 reg->s32_min_value = S32_MIN; 1915 reg->s32_max_value = S32_MAX; 1916 reg->u32_min_value = 0; 1917 reg->u32_max_value = U32_MAX; 1918 } 1919 1920 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1921 { 1922 reg->smin_value = S64_MIN; 1923 reg->smax_value = S64_MAX; 1924 reg->umin_value = 0; 1925 reg->umax_value = U64_MAX; 1926 } 1927 1928 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1929 { 1930 reg->s32_min_value = S32_MIN; 1931 reg->s32_max_value = S32_MAX; 1932 reg->u32_min_value = 0; 1933 reg->u32_max_value = U32_MAX; 1934 } 1935 1936 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1937 { 1938 struct tnum var32_off = tnum_subreg(reg->var_off); 1939 1940 /* min signed is max(sign bit) | min(other bits) */ 1941 reg->s32_min_value = max_t(s32, reg->s32_min_value, 1942 var32_off.value | (var32_off.mask & S32_MIN)); 1943 /* max signed is min(sign bit) | max(other bits) */ 1944 reg->s32_max_value = min_t(s32, reg->s32_max_value, 1945 var32_off.value | (var32_off.mask & S32_MAX)); 1946 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 1947 reg->u32_max_value = min(reg->u32_max_value, 1948 (u32)(var32_off.value | var32_off.mask)); 1949 } 1950 1951 static void __update_reg64_bounds(struct bpf_reg_state *reg) 1952 { 1953 /* min signed is max(sign bit) | min(other bits) */ 1954 reg->smin_value = max_t(s64, reg->smin_value, 1955 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 1956 /* max signed is min(sign bit) | max(other bits) */ 1957 reg->smax_value = min_t(s64, reg->smax_value, 1958 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 1959 reg->umin_value = max(reg->umin_value, reg->var_off.value); 1960 reg->umax_value = min(reg->umax_value, 1961 reg->var_off.value | reg->var_off.mask); 1962 } 1963 1964 static void __update_reg_bounds(struct bpf_reg_state *reg) 1965 { 1966 __update_reg32_bounds(reg); 1967 __update_reg64_bounds(reg); 1968 } 1969 1970 /* Uses signed min/max values to inform unsigned, and vice-versa */ 1971 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 1972 { 1973 /* If upper 32 bits of u64/s64 range don't change, we can use lower 32 1974 * bits to improve our u32/s32 boundaries. 1975 * 1976 * E.g., the case where we have upper 32 bits as zero ([10, 20] in 1977 * u64) is pretty trivial, it's obvious that in u32 we'll also have 1978 * [10, 20] range. But this property holds for any 64-bit range as 1979 * long as upper 32 bits in that entire range of values stay the same. 1980 * 1981 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311] 1982 * in decimal) has the same upper 32 bits throughout all the values in 1983 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15]) 1984 * range. 1985 * 1986 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32, 1987 * following the rules outlined below about u64/s64 correspondence 1988 * (which equally applies to u32 vs s32 correspondence). In general it 1989 * depends on actual hexadecimal values of 32-bit range. They can form 1990 * only valid u32, or only valid s32 ranges in some cases. 1991 * 1992 * So we use all these insights to derive bounds for subregisters here. 1993 */ 1994 if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) { 1995 /* u64 to u32 casting preserves validity of low 32 bits as 1996 * a range, if upper 32 bits are the same 1997 */ 1998 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value); 1999 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value); 2000 2001 if ((s32)reg->umin_value <= (s32)reg->umax_value) { 2002 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 2003 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 2004 } 2005 } 2006 if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) { 2007 /* low 32 bits should form a proper u32 range */ 2008 if ((u32)reg->smin_value <= (u32)reg->smax_value) { 2009 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value); 2010 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value); 2011 } 2012 /* low 32 bits should form a proper s32 range */ 2013 if ((s32)reg->smin_value <= (s32)reg->smax_value) { 2014 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 2015 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 2016 } 2017 } 2018 /* Special case where upper bits form a small sequence of two 2019 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to 2020 * 0x00000000 is also valid), while lower bits form a proper s32 range 2021 * going from negative numbers to positive numbers. E.g., let's say we 2022 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]). 2023 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff, 2024 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits, 2025 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]). 2026 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in 2027 * upper 32 bits. As a random example, s64 range 2028 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range 2029 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister. 2030 */ 2031 if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) && 2032 (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) { 2033 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 2034 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 2035 } 2036 if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) && 2037 (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) { 2038 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 2039 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 2040 } 2041 /* if u32 range forms a valid s32 range (due to matching sign bit), 2042 * try to learn from that 2043 */ 2044 if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) { 2045 reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value); 2046 reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value); 2047 } 2048 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2049 * are the same, so combine. This works even in the negative case, e.g. 2050 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2051 */ 2052 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2053 reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value); 2054 reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value); 2055 } 2056 } 2057 2058 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 2059 { 2060 /* If u64 range forms a valid s64 range (due to matching sign bit), 2061 * try to learn from that. Let's do a bit of ASCII art to see when 2062 * this is happening. Let's take u64 range first: 2063 * 2064 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2065 * |-------------------------------|--------------------------------| 2066 * 2067 * Valid u64 range is formed when umin and umax are anywhere in the 2068 * range [0, U64_MAX], and umin <= umax. u64 case is simple and 2069 * straightforward. Let's see how s64 range maps onto the same range 2070 * of values, annotated below the line for comparison: 2071 * 2072 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2073 * |-------------------------------|--------------------------------| 2074 * 0 S64_MAX S64_MIN -1 2075 * 2076 * So s64 values basically start in the middle and they are logically 2077 * contiguous to the right of it, wrapping around from -1 to 0, and 2078 * then finishing as S64_MAX (0x7fffffffffffffff) right before 2079 * S64_MIN. We can try drawing the continuity of u64 vs s64 values 2080 * more visually as mapped to sign-agnostic range of hex values. 2081 * 2082 * u64 start u64 end 2083 * _______________________________________________________________ 2084 * / \ 2085 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2086 * |-------------------------------|--------------------------------| 2087 * 0 S64_MAX S64_MIN -1 2088 * / \ 2089 * >------------------------------ -------------------------------> 2090 * s64 continues... s64 end s64 start s64 "midpoint" 2091 * 2092 * What this means is that, in general, we can't always derive 2093 * something new about u64 from any random s64 range, and vice versa. 2094 * 2095 * But we can do that in two particular cases. One is when entire 2096 * u64/s64 range is *entirely* contained within left half of the above 2097 * diagram or when it is *entirely* contained in the right half. I.e.: 2098 * 2099 * |-------------------------------|--------------------------------| 2100 * ^ ^ ^ ^ 2101 * A B C D 2102 * 2103 * [A, B] and [C, D] are contained entirely in their respective halves 2104 * and form valid contiguous ranges as both u64 and s64 values. [A, B] 2105 * will be non-negative both as u64 and s64 (and in fact it will be 2106 * identical ranges no matter the signedness). [C, D] treated as s64 2107 * will be a range of negative values, while in u64 it will be 2108 * non-negative range of values larger than 0x8000000000000000. 2109 * 2110 * Now, any other range here can't be represented in both u64 and s64 2111 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid 2112 * contiguous u64 ranges, but they are discontinuous in s64. [B, C] 2113 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX], 2114 * for example. Similarly, valid s64 range [D, A] (going from negative 2115 * to positive values), would be two separate [D, U64_MAX] and [0, A] 2116 * ranges as u64. Currently reg_state can't represent two segments per 2117 * numeric domain, so in such situations we can only derive maximal 2118 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64). 2119 * 2120 * So we use these facts to derive umin/umax from smin/smax and vice 2121 * versa only if they stay within the same "half". This is equivalent 2122 * to checking sign bit: lower half will have sign bit as zero, upper 2123 * half have sign bit 1. Below in code we simplify this by just 2124 * casting umin/umax as smin/smax and checking if they form valid 2125 * range, and vice versa. Those are equivalent checks. 2126 */ 2127 if ((s64)reg->umin_value <= (s64)reg->umax_value) { 2128 reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value); 2129 reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value); 2130 } 2131 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2132 * are the same, so combine. This works even in the negative case, e.g. 2133 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2134 */ 2135 if ((u64)reg->smin_value <= (u64)reg->smax_value) { 2136 reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); 2137 reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); 2138 } 2139 } 2140 2141 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg) 2142 { 2143 /* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit 2144 * values on both sides of 64-bit range in hope to have tighter range. 2145 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from 2146 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff]. 2147 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound 2148 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of 2149 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a 2150 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff]. 2151 * We just need to make sure that derived bounds we are intersecting 2152 * with are well-formed ranges in respective s64 or u64 domain, just 2153 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments. 2154 */ 2155 __u64 new_umin, new_umax; 2156 __s64 new_smin, new_smax; 2157 2158 /* u32 -> u64 tightening, it's always well-formed */ 2159 new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value; 2160 new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value; 2161 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2162 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2163 /* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */ 2164 new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value; 2165 new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value; 2166 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2167 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2168 2169 /* if s32 can be treated as valid u32 range, we can use it as well */ 2170 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2171 /* s32 -> u64 tightening */ 2172 new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value; 2173 new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value; 2174 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2175 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2176 /* s32 -> s64 tightening */ 2177 new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value; 2178 new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value; 2179 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2180 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2181 } 2182 2183 /* Here we would like to handle a special case after sign extending load, 2184 * when upper bits for a 64-bit range are all 1s or all 0s. 2185 * 2186 * Upper bits are all 1s when register is in a range: 2187 * [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff] 2188 * Upper bits are all 0s when register is in a range: 2189 * [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff] 2190 * Together this forms are continuous range: 2191 * [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff] 2192 * 2193 * Now, suppose that register range is in fact tighter: 2194 * [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R) 2195 * Also suppose that it's 32-bit range is positive, 2196 * meaning that lower 32-bits of the full 64-bit register 2197 * are in the range: 2198 * [0x0000_0000, 0x7fff_ffff] (W) 2199 * 2200 * If this happens, then any value in a range: 2201 * [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff] 2202 * is smaller than a lowest bound of the range (R): 2203 * 0xffff_ffff_8000_0000 2204 * which means that upper bits of the full 64-bit register 2205 * can't be all 1s, when lower bits are in range (W). 2206 * 2207 * Note that: 2208 * - 0xffff_ffff_8000_0000 == (s64)S32_MIN 2209 * - 0x0000_0000_7fff_ffff == (s64)S32_MAX 2210 * These relations are used in the conditions below. 2211 */ 2212 if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) { 2213 reg->smin_value = reg->s32_min_value; 2214 reg->smax_value = reg->s32_max_value; 2215 reg->umin_value = reg->s32_min_value; 2216 reg->umax_value = reg->s32_max_value; 2217 reg->var_off = tnum_intersect(reg->var_off, 2218 tnum_range(reg->smin_value, reg->smax_value)); 2219 } 2220 } 2221 2222 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2223 { 2224 __reg32_deduce_bounds(reg); 2225 __reg64_deduce_bounds(reg); 2226 __reg_deduce_mixed_bounds(reg); 2227 } 2228 2229 /* Attempts to improve var_off based on unsigned min/max information */ 2230 static void __reg_bound_offset(struct bpf_reg_state *reg) 2231 { 2232 struct tnum var64_off = tnum_intersect(reg->var_off, 2233 tnum_range(reg->umin_value, 2234 reg->umax_value)); 2235 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2236 tnum_range(reg->u32_min_value, 2237 reg->u32_max_value)); 2238 2239 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2240 } 2241 2242 static void reg_bounds_sync(struct bpf_reg_state *reg) 2243 { 2244 /* We might have learned new bounds from the var_off. */ 2245 __update_reg_bounds(reg); 2246 /* We might have learned something about the sign bit. */ 2247 __reg_deduce_bounds(reg); 2248 __reg_deduce_bounds(reg); 2249 /* We might have learned some bits from the bounds. */ 2250 __reg_bound_offset(reg); 2251 /* Intersecting with the old var_off might have improved our bounds 2252 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2253 * then new var_off is (0; 0x7f...fc) which improves our umax. 2254 */ 2255 __update_reg_bounds(reg); 2256 } 2257 2258 static int reg_bounds_sanity_check(struct bpf_verifier_env *env, 2259 struct bpf_reg_state *reg, const char *ctx) 2260 { 2261 const char *msg; 2262 2263 if (reg->umin_value > reg->umax_value || 2264 reg->smin_value > reg->smax_value || 2265 reg->u32_min_value > reg->u32_max_value || 2266 reg->s32_min_value > reg->s32_max_value) { 2267 msg = "range bounds violation"; 2268 goto out; 2269 } 2270 2271 if (tnum_is_const(reg->var_off)) { 2272 u64 uval = reg->var_off.value; 2273 s64 sval = (s64)uval; 2274 2275 if (reg->umin_value != uval || reg->umax_value != uval || 2276 reg->smin_value != sval || reg->smax_value != sval) { 2277 msg = "const tnum out of sync with range bounds"; 2278 goto out; 2279 } 2280 } 2281 2282 if (tnum_subreg_is_const(reg->var_off)) { 2283 u32 uval32 = tnum_subreg(reg->var_off).value; 2284 s32 sval32 = (s32)uval32; 2285 2286 if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 || 2287 reg->s32_min_value != sval32 || reg->s32_max_value != sval32) { 2288 msg = "const subreg tnum out of sync with range bounds"; 2289 goto out; 2290 } 2291 } 2292 2293 return 0; 2294 out: 2295 verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] " 2296 "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n", 2297 ctx, msg, reg->umin_value, reg->umax_value, 2298 reg->smin_value, reg->smax_value, 2299 reg->u32_min_value, reg->u32_max_value, 2300 reg->s32_min_value, reg->s32_max_value, 2301 reg->var_off.value, reg->var_off.mask); 2302 if (env->test_reg_invariants) 2303 return -EFAULT; 2304 __mark_reg_unbounded(reg); 2305 return 0; 2306 } 2307 2308 static bool __reg32_bound_s64(s32 a) 2309 { 2310 return a >= 0 && a <= S32_MAX; 2311 } 2312 2313 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 2314 { 2315 reg->umin_value = reg->u32_min_value; 2316 reg->umax_value = reg->u32_max_value; 2317 2318 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 2319 * be positive otherwise set to worse case bounds and refine later 2320 * from tnum. 2321 */ 2322 if (__reg32_bound_s64(reg->s32_min_value) && 2323 __reg32_bound_s64(reg->s32_max_value)) { 2324 reg->smin_value = reg->s32_min_value; 2325 reg->smax_value = reg->s32_max_value; 2326 } else { 2327 reg->smin_value = 0; 2328 reg->smax_value = U32_MAX; 2329 } 2330 } 2331 2332 /* Mark a register as having a completely unknown (scalar) value. */ 2333 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg) 2334 { 2335 /* 2336 * Clear type, off, and union(map_ptr, range) and 2337 * padding between 'type' and union 2338 */ 2339 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2340 reg->type = SCALAR_VALUE; 2341 reg->id = 0; 2342 reg->ref_obj_id = 0; 2343 reg->var_off = tnum_unknown; 2344 reg->frameno = 0; 2345 reg->precise = false; 2346 __mark_reg_unbounded(reg); 2347 } 2348 2349 /* Mark a register as having a completely unknown (scalar) value, 2350 * initialize .precise as true when not bpf capable. 2351 */ 2352 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2353 struct bpf_reg_state *reg) 2354 { 2355 __mark_reg_unknown_imprecise(reg); 2356 reg->precise = !env->bpf_capable; 2357 } 2358 2359 static void mark_reg_unknown(struct bpf_verifier_env *env, 2360 struct bpf_reg_state *regs, u32 regno) 2361 { 2362 if (WARN_ON(regno >= MAX_BPF_REG)) { 2363 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 2364 /* Something bad happened, let's kill all regs except FP */ 2365 for (regno = 0; regno < BPF_REG_FP; regno++) 2366 __mark_reg_not_init(env, regs + regno); 2367 return; 2368 } 2369 __mark_reg_unknown(env, regs + regno); 2370 } 2371 2372 static int __mark_reg_s32_range(struct bpf_verifier_env *env, 2373 struct bpf_reg_state *regs, 2374 u32 regno, 2375 s32 s32_min, 2376 s32 s32_max) 2377 { 2378 struct bpf_reg_state *reg = regs + regno; 2379 2380 reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min); 2381 reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max); 2382 2383 reg->smin_value = max_t(s64, reg->smin_value, s32_min); 2384 reg->smax_value = min_t(s64, reg->smax_value, s32_max); 2385 2386 reg_bounds_sync(reg); 2387 2388 return reg_bounds_sanity_check(env, reg, "s32_range"); 2389 } 2390 2391 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 2392 struct bpf_reg_state *reg) 2393 { 2394 __mark_reg_unknown(env, reg); 2395 reg->type = NOT_INIT; 2396 } 2397 2398 static void mark_reg_not_init(struct bpf_verifier_env *env, 2399 struct bpf_reg_state *regs, u32 regno) 2400 { 2401 if (WARN_ON(regno >= MAX_BPF_REG)) { 2402 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 2403 /* Something bad happened, let's kill all regs except FP */ 2404 for (regno = 0; regno < BPF_REG_FP; regno++) 2405 __mark_reg_not_init(env, regs + regno); 2406 return; 2407 } 2408 __mark_reg_not_init(env, regs + regno); 2409 } 2410 2411 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 2412 struct bpf_reg_state *regs, u32 regno, 2413 enum bpf_reg_type reg_type, 2414 struct btf *btf, u32 btf_id, 2415 enum bpf_type_flag flag) 2416 { 2417 if (reg_type == SCALAR_VALUE) { 2418 mark_reg_unknown(env, regs, regno); 2419 return; 2420 } 2421 mark_reg_known_zero(env, regs, regno); 2422 regs[regno].type = PTR_TO_BTF_ID | flag; 2423 regs[regno].btf = btf; 2424 regs[regno].btf_id = btf_id; 2425 if (type_may_be_null(flag)) 2426 regs[regno].id = ++env->id_gen; 2427 } 2428 2429 #define DEF_NOT_SUBREG (0) 2430 static void init_reg_state(struct bpf_verifier_env *env, 2431 struct bpf_func_state *state) 2432 { 2433 struct bpf_reg_state *regs = state->regs; 2434 int i; 2435 2436 for (i = 0; i < MAX_BPF_REG; i++) { 2437 mark_reg_not_init(env, regs, i); 2438 regs[i].live = REG_LIVE_NONE; 2439 regs[i].parent = NULL; 2440 regs[i].subreg_def = DEF_NOT_SUBREG; 2441 } 2442 2443 /* frame pointer */ 2444 regs[BPF_REG_FP].type = PTR_TO_STACK; 2445 mark_reg_known_zero(env, regs, BPF_REG_FP); 2446 regs[BPF_REG_FP].frameno = state->frameno; 2447 } 2448 2449 static struct bpf_retval_range retval_range(s32 minval, s32 maxval) 2450 { 2451 return (struct bpf_retval_range){ minval, maxval }; 2452 } 2453 2454 #define BPF_MAIN_FUNC (-1) 2455 static void init_func_state(struct bpf_verifier_env *env, 2456 struct bpf_func_state *state, 2457 int callsite, int frameno, int subprogno) 2458 { 2459 state->callsite = callsite; 2460 state->frameno = frameno; 2461 state->subprogno = subprogno; 2462 state->callback_ret_range = retval_range(0, 0); 2463 init_reg_state(env, state); 2464 mark_verifier_state_scratched(env); 2465 } 2466 2467 /* Similar to push_stack(), but for async callbacks */ 2468 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2469 int insn_idx, int prev_insn_idx, 2470 int subprog, bool is_sleepable) 2471 { 2472 struct bpf_verifier_stack_elem *elem; 2473 struct bpf_func_state *frame; 2474 2475 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2476 if (!elem) 2477 goto err; 2478 2479 elem->insn_idx = insn_idx; 2480 elem->prev_insn_idx = prev_insn_idx; 2481 elem->next = env->head; 2482 elem->log_pos = env->log.end_pos; 2483 env->head = elem; 2484 env->stack_size++; 2485 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2486 verbose(env, 2487 "The sequence of %d jumps is too complex for async cb.\n", 2488 env->stack_size); 2489 goto err; 2490 } 2491 /* Unlike push_stack() do not copy_verifier_state(). 2492 * The caller state doesn't matter. 2493 * This is async callback. It starts in a fresh stack. 2494 * Initialize it similar to do_check_common(). 2495 */ 2496 elem->st.branches = 1; 2497 elem->st.in_sleepable = is_sleepable; 2498 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 2499 if (!frame) 2500 goto err; 2501 init_func_state(env, frame, 2502 BPF_MAIN_FUNC /* callsite */, 2503 0 /* frameno within this callchain */, 2504 subprog /* subprog number within this prog */); 2505 elem->st.frame[0] = frame; 2506 return &elem->st; 2507 err: 2508 free_verifier_state(env->cur_state, true); 2509 env->cur_state = NULL; 2510 /* pop all elements and return */ 2511 while (!pop_stack(env, NULL, NULL, false)); 2512 return NULL; 2513 } 2514 2515 2516 enum reg_arg_type { 2517 SRC_OP, /* register is used as source operand */ 2518 DST_OP, /* register is used as destination operand */ 2519 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2520 }; 2521 2522 static int cmp_subprogs(const void *a, const void *b) 2523 { 2524 return ((struct bpf_subprog_info *)a)->start - 2525 ((struct bpf_subprog_info *)b)->start; 2526 } 2527 2528 static int find_subprog(struct bpf_verifier_env *env, int off) 2529 { 2530 struct bpf_subprog_info *p; 2531 2532 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 2533 sizeof(env->subprog_info[0]), cmp_subprogs); 2534 if (!p) 2535 return -ENOENT; 2536 return p - env->subprog_info; 2537 2538 } 2539 2540 static int add_subprog(struct bpf_verifier_env *env, int off) 2541 { 2542 int insn_cnt = env->prog->len; 2543 int ret; 2544 2545 if (off >= insn_cnt || off < 0) { 2546 verbose(env, "call to invalid destination\n"); 2547 return -EINVAL; 2548 } 2549 ret = find_subprog(env, off); 2550 if (ret >= 0) 2551 return ret; 2552 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2553 verbose(env, "too many subprograms\n"); 2554 return -E2BIG; 2555 } 2556 /* determine subprog starts. The end is one before the next starts */ 2557 env->subprog_info[env->subprog_cnt++].start = off; 2558 sort(env->subprog_info, env->subprog_cnt, 2559 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2560 return env->subprog_cnt - 1; 2561 } 2562 2563 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env) 2564 { 2565 struct bpf_prog_aux *aux = env->prog->aux; 2566 struct btf *btf = aux->btf; 2567 const struct btf_type *t; 2568 u32 main_btf_id, id; 2569 const char *name; 2570 int ret, i; 2571 2572 /* Non-zero func_info_cnt implies valid btf */ 2573 if (!aux->func_info_cnt) 2574 return 0; 2575 main_btf_id = aux->func_info[0].type_id; 2576 2577 t = btf_type_by_id(btf, main_btf_id); 2578 if (!t) { 2579 verbose(env, "invalid btf id for main subprog in func_info\n"); 2580 return -EINVAL; 2581 } 2582 2583 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:"); 2584 if (IS_ERR(name)) { 2585 ret = PTR_ERR(name); 2586 /* If there is no tag present, there is no exception callback */ 2587 if (ret == -ENOENT) 2588 ret = 0; 2589 else if (ret == -EEXIST) 2590 verbose(env, "multiple exception callback tags for main subprog\n"); 2591 return ret; 2592 } 2593 2594 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC); 2595 if (ret < 0) { 2596 verbose(env, "exception callback '%s' could not be found in BTF\n", name); 2597 return ret; 2598 } 2599 id = ret; 2600 t = btf_type_by_id(btf, id); 2601 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) { 2602 verbose(env, "exception callback '%s' must have global linkage\n", name); 2603 return -EINVAL; 2604 } 2605 ret = 0; 2606 for (i = 0; i < aux->func_info_cnt; i++) { 2607 if (aux->func_info[i].type_id != id) 2608 continue; 2609 ret = aux->func_info[i].insn_off; 2610 /* Further func_info and subprog checks will also happen 2611 * later, so assume this is the right insn_off for now. 2612 */ 2613 if (!ret) { 2614 verbose(env, "invalid exception callback insn_off in func_info: 0\n"); 2615 ret = -EINVAL; 2616 } 2617 } 2618 if (!ret) { 2619 verbose(env, "exception callback type id not found in func_info\n"); 2620 ret = -EINVAL; 2621 } 2622 return ret; 2623 } 2624 2625 #define MAX_KFUNC_DESCS 256 2626 #define MAX_KFUNC_BTFS 256 2627 2628 struct bpf_kfunc_desc { 2629 struct btf_func_model func_model; 2630 u32 func_id; 2631 s32 imm; 2632 u16 offset; 2633 unsigned long addr; 2634 }; 2635 2636 struct bpf_kfunc_btf { 2637 struct btf *btf; 2638 struct module *module; 2639 u16 offset; 2640 }; 2641 2642 struct bpf_kfunc_desc_tab { 2643 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during 2644 * verification. JITs do lookups by bpf_insn, where func_id may not be 2645 * available, therefore at the end of verification do_misc_fixups() 2646 * sorts this by imm and offset. 2647 */ 2648 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 2649 u32 nr_descs; 2650 }; 2651 2652 struct bpf_kfunc_btf_tab { 2653 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2654 u32 nr_descs; 2655 }; 2656 2657 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2658 { 2659 const struct bpf_kfunc_desc *d0 = a; 2660 const struct bpf_kfunc_desc *d1 = b; 2661 2662 /* func_id is not greater than BTF_MAX_TYPE */ 2663 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2664 } 2665 2666 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2667 { 2668 const struct bpf_kfunc_btf *d0 = a; 2669 const struct bpf_kfunc_btf *d1 = b; 2670 2671 return d0->offset - d1->offset; 2672 } 2673 2674 static const struct bpf_kfunc_desc * 2675 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2676 { 2677 struct bpf_kfunc_desc desc = { 2678 .func_id = func_id, 2679 .offset = offset, 2680 }; 2681 struct bpf_kfunc_desc_tab *tab; 2682 2683 tab = prog->aux->kfunc_tab; 2684 return bsearch(&desc, tab->descs, tab->nr_descs, 2685 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2686 } 2687 2688 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2689 u16 btf_fd_idx, u8 **func_addr) 2690 { 2691 const struct bpf_kfunc_desc *desc; 2692 2693 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2694 if (!desc) 2695 return -EFAULT; 2696 2697 *func_addr = (u8 *)desc->addr; 2698 return 0; 2699 } 2700 2701 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2702 s16 offset) 2703 { 2704 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2705 struct bpf_kfunc_btf_tab *tab; 2706 struct bpf_kfunc_btf *b; 2707 struct module *mod; 2708 struct btf *btf; 2709 int btf_fd; 2710 2711 tab = env->prog->aux->kfunc_btf_tab; 2712 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2713 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2714 if (!b) { 2715 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2716 verbose(env, "too many different module BTFs\n"); 2717 return ERR_PTR(-E2BIG); 2718 } 2719 2720 if (bpfptr_is_null(env->fd_array)) { 2721 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2722 return ERR_PTR(-EPROTO); 2723 } 2724 2725 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2726 offset * sizeof(btf_fd), 2727 sizeof(btf_fd))) 2728 return ERR_PTR(-EFAULT); 2729 2730 btf = btf_get_by_fd(btf_fd); 2731 if (IS_ERR(btf)) { 2732 verbose(env, "invalid module BTF fd specified\n"); 2733 return btf; 2734 } 2735 2736 if (!btf_is_module(btf)) { 2737 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2738 btf_put(btf); 2739 return ERR_PTR(-EINVAL); 2740 } 2741 2742 mod = btf_try_get_module(btf); 2743 if (!mod) { 2744 btf_put(btf); 2745 return ERR_PTR(-ENXIO); 2746 } 2747 2748 b = &tab->descs[tab->nr_descs++]; 2749 b->btf = btf; 2750 b->module = mod; 2751 b->offset = offset; 2752 2753 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2754 kfunc_btf_cmp_by_off, NULL); 2755 } 2756 return b->btf; 2757 } 2758 2759 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2760 { 2761 if (!tab) 2762 return; 2763 2764 while (tab->nr_descs--) { 2765 module_put(tab->descs[tab->nr_descs].module); 2766 btf_put(tab->descs[tab->nr_descs].btf); 2767 } 2768 kfree(tab); 2769 } 2770 2771 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2772 { 2773 if (offset) { 2774 if (offset < 0) { 2775 /* In the future, this can be allowed to increase limit 2776 * of fd index into fd_array, interpreted as u16. 2777 */ 2778 verbose(env, "negative offset disallowed for kernel module function call\n"); 2779 return ERR_PTR(-EINVAL); 2780 } 2781 2782 return __find_kfunc_desc_btf(env, offset); 2783 } 2784 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2785 } 2786 2787 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 2788 { 2789 const struct btf_type *func, *func_proto; 2790 struct bpf_kfunc_btf_tab *btf_tab; 2791 struct bpf_kfunc_desc_tab *tab; 2792 struct bpf_prog_aux *prog_aux; 2793 struct bpf_kfunc_desc *desc; 2794 const char *func_name; 2795 struct btf *desc_btf; 2796 unsigned long call_imm; 2797 unsigned long addr; 2798 int err; 2799 2800 prog_aux = env->prog->aux; 2801 tab = prog_aux->kfunc_tab; 2802 btf_tab = prog_aux->kfunc_btf_tab; 2803 if (!tab) { 2804 if (!btf_vmlinux) { 2805 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2806 return -ENOTSUPP; 2807 } 2808 2809 if (!env->prog->jit_requested) { 2810 verbose(env, "JIT is required for calling kernel function\n"); 2811 return -ENOTSUPP; 2812 } 2813 2814 if (!bpf_jit_supports_kfunc_call()) { 2815 verbose(env, "JIT does not support calling kernel function\n"); 2816 return -ENOTSUPP; 2817 } 2818 2819 if (!env->prog->gpl_compatible) { 2820 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2821 return -EINVAL; 2822 } 2823 2824 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 2825 if (!tab) 2826 return -ENOMEM; 2827 prog_aux->kfunc_tab = tab; 2828 } 2829 2830 /* func_id == 0 is always invalid, but instead of returning an error, be 2831 * conservative and wait until the code elimination pass before returning 2832 * error, so that invalid calls that get pruned out can be in BPF programs 2833 * loaded from userspace. It is also required that offset be untouched 2834 * for such calls. 2835 */ 2836 if (!func_id && !offset) 2837 return 0; 2838 2839 if (!btf_tab && offset) { 2840 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 2841 if (!btf_tab) 2842 return -ENOMEM; 2843 prog_aux->kfunc_btf_tab = btf_tab; 2844 } 2845 2846 desc_btf = find_kfunc_desc_btf(env, offset); 2847 if (IS_ERR(desc_btf)) { 2848 verbose(env, "failed to find BTF for kernel function\n"); 2849 return PTR_ERR(desc_btf); 2850 } 2851 2852 if (find_kfunc_desc(env->prog, func_id, offset)) 2853 return 0; 2854 2855 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2856 verbose(env, "too many different kernel function calls\n"); 2857 return -E2BIG; 2858 } 2859 2860 func = btf_type_by_id(desc_btf, func_id); 2861 if (!func || !btf_type_is_func(func)) { 2862 verbose(env, "kernel btf_id %u is not a function\n", 2863 func_id); 2864 return -EINVAL; 2865 } 2866 func_proto = btf_type_by_id(desc_btf, func->type); 2867 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2868 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 2869 func_id); 2870 return -EINVAL; 2871 } 2872 2873 func_name = btf_name_by_offset(desc_btf, func->name_off); 2874 addr = kallsyms_lookup_name(func_name); 2875 if (!addr) { 2876 verbose(env, "cannot find address for kernel function %s\n", 2877 func_name); 2878 return -EINVAL; 2879 } 2880 specialize_kfunc(env, func_id, offset, &addr); 2881 2882 if (bpf_jit_supports_far_kfunc_call()) { 2883 call_imm = func_id; 2884 } else { 2885 call_imm = BPF_CALL_IMM(addr); 2886 /* Check whether the relative offset overflows desc->imm */ 2887 if ((unsigned long)(s32)call_imm != call_imm) { 2888 verbose(env, "address of kernel function %s is out of range\n", 2889 func_name); 2890 return -EINVAL; 2891 } 2892 } 2893 2894 if (bpf_dev_bound_kfunc_id(func_id)) { 2895 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2896 if (err) 2897 return err; 2898 } 2899 2900 desc = &tab->descs[tab->nr_descs++]; 2901 desc->func_id = func_id; 2902 desc->imm = call_imm; 2903 desc->offset = offset; 2904 desc->addr = addr; 2905 err = btf_distill_func_proto(&env->log, desc_btf, 2906 func_proto, func_name, 2907 &desc->func_model); 2908 if (!err) 2909 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2910 kfunc_desc_cmp_by_id_off, NULL); 2911 return err; 2912 } 2913 2914 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b) 2915 { 2916 const struct bpf_kfunc_desc *d0 = a; 2917 const struct bpf_kfunc_desc *d1 = b; 2918 2919 if (d0->imm != d1->imm) 2920 return d0->imm < d1->imm ? -1 : 1; 2921 if (d0->offset != d1->offset) 2922 return d0->offset < d1->offset ? -1 : 1; 2923 return 0; 2924 } 2925 2926 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog) 2927 { 2928 struct bpf_kfunc_desc_tab *tab; 2929 2930 tab = prog->aux->kfunc_tab; 2931 if (!tab) 2932 return; 2933 2934 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2935 kfunc_desc_cmp_by_imm_off, NULL); 2936 } 2937 2938 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2939 { 2940 return !!prog->aux->kfunc_tab; 2941 } 2942 2943 const struct btf_func_model * 2944 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 2945 const struct bpf_insn *insn) 2946 { 2947 const struct bpf_kfunc_desc desc = { 2948 .imm = insn->imm, 2949 .offset = insn->off, 2950 }; 2951 const struct bpf_kfunc_desc *res; 2952 struct bpf_kfunc_desc_tab *tab; 2953 2954 tab = prog->aux->kfunc_tab; 2955 res = bsearch(&desc, tab->descs, tab->nr_descs, 2956 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off); 2957 2958 return res ? &res->func_model : NULL; 2959 } 2960 2961 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 2962 { 2963 struct bpf_subprog_info *subprog = env->subprog_info; 2964 int i, ret, insn_cnt = env->prog->len, ex_cb_insn; 2965 struct bpf_insn *insn = env->prog->insnsi; 2966 2967 /* Add entry function. */ 2968 ret = add_subprog(env, 0); 2969 if (ret) 2970 return ret; 2971 2972 for (i = 0; i < insn_cnt; i++, insn++) { 2973 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 2974 !bpf_pseudo_kfunc_call(insn)) 2975 continue; 2976 2977 if (!env->bpf_capable) { 2978 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2979 return -EPERM; 2980 } 2981 2982 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 2983 ret = add_subprog(env, i + insn->imm + 1); 2984 else 2985 ret = add_kfunc_call(env, insn->imm, insn->off); 2986 2987 if (ret < 0) 2988 return ret; 2989 } 2990 2991 ret = bpf_find_exception_callback_insn_off(env); 2992 if (ret < 0) 2993 return ret; 2994 ex_cb_insn = ret; 2995 2996 /* If ex_cb_insn > 0, this means that the main program has a subprog 2997 * marked using BTF decl tag to serve as the exception callback. 2998 */ 2999 if (ex_cb_insn) { 3000 ret = add_subprog(env, ex_cb_insn); 3001 if (ret < 0) 3002 return ret; 3003 for (i = 1; i < env->subprog_cnt; i++) { 3004 if (env->subprog_info[i].start != ex_cb_insn) 3005 continue; 3006 env->exception_callback_subprog = i; 3007 mark_subprog_exc_cb(env, i); 3008 break; 3009 } 3010 } 3011 3012 /* Add a fake 'exit' subprog which could simplify subprog iteration 3013 * logic. 'subprog_cnt' should not be increased. 3014 */ 3015 subprog[env->subprog_cnt].start = insn_cnt; 3016 3017 if (env->log.level & BPF_LOG_LEVEL2) 3018 for (i = 0; i < env->subprog_cnt; i++) 3019 verbose(env, "func#%d @%d\n", i, subprog[i].start); 3020 3021 return 0; 3022 } 3023 3024 static int check_subprogs(struct bpf_verifier_env *env) 3025 { 3026 int i, subprog_start, subprog_end, off, cur_subprog = 0; 3027 struct bpf_subprog_info *subprog = env->subprog_info; 3028 struct bpf_insn *insn = env->prog->insnsi; 3029 int insn_cnt = env->prog->len; 3030 3031 /* now check that all jumps are within the same subprog */ 3032 subprog_start = subprog[cur_subprog].start; 3033 subprog_end = subprog[cur_subprog + 1].start; 3034 for (i = 0; i < insn_cnt; i++) { 3035 u8 code = insn[i].code; 3036 3037 if (code == (BPF_JMP | BPF_CALL) && 3038 insn[i].src_reg == 0 && 3039 insn[i].imm == BPF_FUNC_tail_call) { 3040 subprog[cur_subprog].has_tail_call = true; 3041 subprog[cur_subprog].tail_call_reachable = true; 3042 } 3043 if (BPF_CLASS(code) == BPF_LD && 3044 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 3045 subprog[cur_subprog].has_ld_abs = true; 3046 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 3047 goto next; 3048 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 3049 goto next; 3050 if (code == (BPF_JMP32 | BPF_JA)) 3051 off = i + insn[i].imm + 1; 3052 else 3053 off = i + insn[i].off + 1; 3054 if (off < subprog_start || off >= subprog_end) { 3055 verbose(env, "jump out of range from insn %d to %d\n", i, off); 3056 return -EINVAL; 3057 } 3058 next: 3059 if (i == subprog_end - 1) { 3060 /* to avoid fall-through from one subprog into another 3061 * the last insn of the subprog should be either exit 3062 * or unconditional jump back or bpf_throw call 3063 */ 3064 if (code != (BPF_JMP | BPF_EXIT) && 3065 code != (BPF_JMP32 | BPF_JA) && 3066 code != (BPF_JMP | BPF_JA)) { 3067 verbose(env, "last insn is not an exit or jmp\n"); 3068 return -EINVAL; 3069 } 3070 subprog_start = subprog_end; 3071 cur_subprog++; 3072 if (cur_subprog < env->subprog_cnt) 3073 subprog_end = subprog[cur_subprog + 1].start; 3074 } 3075 } 3076 return 0; 3077 } 3078 3079 /* Parentage chain of this register (or stack slot) should take care of all 3080 * issues like callee-saved registers, stack slot allocation time, etc. 3081 */ 3082 static int mark_reg_read(struct bpf_verifier_env *env, 3083 const struct bpf_reg_state *state, 3084 struct bpf_reg_state *parent, u8 flag) 3085 { 3086 bool writes = parent == state->parent; /* Observe write marks */ 3087 int cnt = 0; 3088 3089 while (parent) { 3090 /* if read wasn't screened by an earlier write ... */ 3091 if (writes && state->live & REG_LIVE_WRITTEN) 3092 break; 3093 if (parent->live & REG_LIVE_DONE) { 3094 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 3095 reg_type_str(env, parent->type), 3096 parent->var_off.value, parent->off); 3097 return -EFAULT; 3098 } 3099 /* The first condition is more likely to be true than the 3100 * second, checked it first. 3101 */ 3102 if ((parent->live & REG_LIVE_READ) == flag || 3103 parent->live & REG_LIVE_READ64) 3104 /* The parentage chain never changes and 3105 * this parent was already marked as LIVE_READ. 3106 * There is no need to keep walking the chain again and 3107 * keep re-marking all parents as LIVE_READ. 3108 * This case happens when the same register is read 3109 * multiple times without writes into it in-between. 3110 * Also, if parent has the stronger REG_LIVE_READ64 set, 3111 * then no need to set the weak REG_LIVE_READ32. 3112 */ 3113 break; 3114 /* ... then we depend on parent's value */ 3115 parent->live |= flag; 3116 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 3117 if (flag == REG_LIVE_READ64) 3118 parent->live &= ~REG_LIVE_READ32; 3119 state = parent; 3120 parent = state->parent; 3121 writes = true; 3122 cnt++; 3123 } 3124 3125 if (env->longest_mark_read_walk < cnt) 3126 env->longest_mark_read_walk = cnt; 3127 return 0; 3128 } 3129 3130 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3131 { 3132 struct bpf_func_state *state = func(env, reg); 3133 int spi, ret; 3134 3135 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 3136 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 3137 * check_kfunc_call. 3138 */ 3139 if (reg->type == CONST_PTR_TO_DYNPTR) 3140 return 0; 3141 spi = dynptr_get_spi(env, reg); 3142 if (spi < 0) 3143 return spi; 3144 /* Caller ensures dynptr is valid and initialized, which means spi is in 3145 * bounds and spi is the first dynptr slot. Simply mark stack slot as 3146 * read. 3147 */ 3148 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr, 3149 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64); 3150 if (ret) 3151 return ret; 3152 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr, 3153 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64); 3154 } 3155 3156 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3157 int spi, int nr_slots) 3158 { 3159 struct bpf_func_state *state = func(env, reg); 3160 int err, i; 3161 3162 for (i = 0; i < nr_slots; i++) { 3163 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr; 3164 3165 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64); 3166 if (err) 3167 return err; 3168 3169 mark_stack_slot_scratched(env, spi - i); 3170 } 3171 3172 return 0; 3173 } 3174 3175 /* This function is supposed to be used by the following 32-bit optimization 3176 * code only. It returns TRUE if the source or destination register operates 3177 * on 64-bit, otherwise return FALSE. 3178 */ 3179 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 3180 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 3181 { 3182 u8 code, class, op; 3183 3184 code = insn->code; 3185 class = BPF_CLASS(code); 3186 op = BPF_OP(code); 3187 if (class == BPF_JMP) { 3188 /* BPF_EXIT for "main" will reach here. Return TRUE 3189 * conservatively. 3190 */ 3191 if (op == BPF_EXIT) 3192 return true; 3193 if (op == BPF_CALL) { 3194 /* BPF to BPF call will reach here because of marking 3195 * caller saved clobber with DST_OP_NO_MARK for which we 3196 * don't care the register def because they are anyway 3197 * marked as NOT_INIT already. 3198 */ 3199 if (insn->src_reg == BPF_PSEUDO_CALL) 3200 return false; 3201 /* Helper call will reach here because of arg type 3202 * check, conservatively return TRUE. 3203 */ 3204 if (t == SRC_OP) 3205 return true; 3206 3207 return false; 3208 } 3209 } 3210 3211 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3212 return false; 3213 3214 if (class == BPF_ALU64 || class == BPF_JMP || 3215 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3216 return true; 3217 3218 if (class == BPF_ALU || class == BPF_JMP32) 3219 return false; 3220 3221 if (class == BPF_LDX) { 3222 if (t != SRC_OP) 3223 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX; 3224 /* LDX source must be ptr. */ 3225 return true; 3226 } 3227 3228 if (class == BPF_STX) { 3229 /* BPF_STX (including atomic variants) has multiple source 3230 * operands, one of which is a ptr. Check whether the caller is 3231 * asking about it. 3232 */ 3233 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3234 return true; 3235 return BPF_SIZE(code) == BPF_DW; 3236 } 3237 3238 if (class == BPF_LD) { 3239 u8 mode = BPF_MODE(code); 3240 3241 /* LD_IMM64 */ 3242 if (mode == BPF_IMM) 3243 return true; 3244 3245 /* Both LD_IND and LD_ABS return 32-bit data. */ 3246 if (t != SRC_OP) 3247 return false; 3248 3249 /* Implicit ctx ptr. */ 3250 if (regno == BPF_REG_6) 3251 return true; 3252 3253 /* Explicit source could be any width. */ 3254 return true; 3255 } 3256 3257 if (class == BPF_ST) 3258 /* The only source register for BPF_ST is a ptr. */ 3259 return true; 3260 3261 /* Conservatively return true at default. */ 3262 return true; 3263 } 3264 3265 /* Return the regno defined by the insn, or -1. */ 3266 static int insn_def_regno(const struct bpf_insn *insn) 3267 { 3268 switch (BPF_CLASS(insn->code)) { 3269 case BPF_JMP: 3270 case BPF_JMP32: 3271 case BPF_ST: 3272 return -1; 3273 case BPF_STX: 3274 if ((BPF_MODE(insn->code) == BPF_ATOMIC || 3275 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) && 3276 (insn->imm & BPF_FETCH)) { 3277 if (insn->imm == BPF_CMPXCHG) 3278 return BPF_REG_0; 3279 else 3280 return insn->src_reg; 3281 } else { 3282 return -1; 3283 } 3284 default: 3285 return insn->dst_reg; 3286 } 3287 } 3288 3289 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 3290 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 3291 { 3292 int dst_reg = insn_def_regno(insn); 3293 3294 if (dst_reg == -1) 3295 return false; 3296 3297 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 3298 } 3299 3300 static void mark_insn_zext(struct bpf_verifier_env *env, 3301 struct bpf_reg_state *reg) 3302 { 3303 s32 def_idx = reg->subreg_def; 3304 3305 if (def_idx == DEF_NOT_SUBREG) 3306 return; 3307 3308 env->insn_aux_data[def_idx - 1].zext_dst = true; 3309 /* The dst will be zero extended, so won't be sub-register anymore. */ 3310 reg->subreg_def = DEF_NOT_SUBREG; 3311 } 3312 3313 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno, 3314 enum reg_arg_type t) 3315 { 3316 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3317 struct bpf_reg_state *reg; 3318 bool rw64; 3319 3320 if (regno >= MAX_BPF_REG) { 3321 verbose(env, "R%d is invalid\n", regno); 3322 return -EINVAL; 3323 } 3324 3325 mark_reg_scratched(env, regno); 3326 3327 reg = ®s[regno]; 3328 rw64 = is_reg64(env, insn, regno, reg, t); 3329 if (t == SRC_OP) { 3330 /* check whether register used as source operand can be read */ 3331 if (reg->type == NOT_INIT) { 3332 verbose(env, "R%d !read_ok\n", regno); 3333 return -EACCES; 3334 } 3335 /* We don't need to worry about FP liveness because it's read-only */ 3336 if (regno == BPF_REG_FP) 3337 return 0; 3338 3339 if (rw64) 3340 mark_insn_zext(env, reg); 3341 3342 return mark_reg_read(env, reg, reg->parent, 3343 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 3344 } else { 3345 /* check whether register used as dest operand can be written to */ 3346 if (regno == BPF_REG_FP) { 3347 verbose(env, "frame pointer is read only\n"); 3348 return -EACCES; 3349 } 3350 reg->live |= REG_LIVE_WRITTEN; 3351 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3352 if (t == DST_OP) 3353 mark_reg_unknown(env, regs, regno); 3354 } 3355 return 0; 3356 } 3357 3358 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3359 enum reg_arg_type t) 3360 { 3361 struct bpf_verifier_state *vstate = env->cur_state; 3362 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3363 3364 return __check_reg_arg(env, state->regs, regno, t); 3365 } 3366 3367 static int insn_stack_access_flags(int frameno, int spi) 3368 { 3369 return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno; 3370 } 3371 3372 static int insn_stack_access_spi(int insn_flags) 3373 { 3374 return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK; 3375 } 3376 3377 static int insn_stack_access_frameno(int insn_flags) 3378 { 3379 return insn_flags & INSN_F_FRAMENO_MASK; 3380 } 3381 3382 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 3383 { 3384 env->insn_aux_data[idx].jmp_point = true; 3385 } 3386 3387 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 3388 { 3389 return env->insn_aux_data[insn_idx].jmp_point; 3390 } 3391 3392 #define LR_FRAMENO_BITS 3 3393 #define LR_SPI_BITS 6 3394 #define LR_ENTRY_BITS (LR_SPI_BITS + LR_FRAMENO_BITS + 1) 3395 #define LR_SIZE_BITS 4 3396 #define LR_FRAMENO_MASK ((1ull << LR_FRAMENO_BITS) - 1) 3397 #define LR_SPI_MASK ((1ull << LR_SPI_BITS) - 1) 3398 #define LR_SIZE_MASK ((1ull << LR_SIZE_BITS) - 1) 3399 #define LR_SPI_OFF LR_FRAMENO_BITS 3400 #define LR_IS_REG_OFF (LR_SPI_BITS + LR_FRAMENO_BITS) 3401 #define LINKED_REGS_MAX 6 3402 3403 struct linked_reg { 3404 u8 frameno; 3405 union { 3406 u8 spi; 3407 u8 regno; 3408 }; 3409 bool is_reg; 3410 }; 3411 3412 struct linked_regs { 3413 int cnt; 3414 struct linked_reg entries[LINKED_REGS_MAX]; 3415 }; 3416 3417 static struct linked_reg *linked_regs_push(struct linked_regs *s) 3418 { 3419 if (s->cnt < LINKED_REGS_MAX) 3420 return &s->entries[s->cnt++]; 3421 3422 return NULL; 3423 } 3424 3425 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track 3426 * number of elements currently in stack. 3427 * Pack one history entry for linked registers as 10 bits in the following format: 3428 * - 3-bits frameno 3429 * - 6-bits spi_or_reg 3430 * - 1-bit is_reg 3431 */ 3432 static u64 linked_regs_pack(struct linked_regs *s) 3433 { 3434 u64 val = 0; 3435 int i; 3436 3437 for (i = 0; i < s->cnt; ++i) { 3438 struct linked_reg *e = &s->entries[i]; 3439 u64 tmp = 0; 3440 3441 tmp |= e->frameno; 3442 tmp |= e->spi << LR_SPI_OFF; 3443 tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF; 3444 3445 val <<= LR_ENTRY_BITS; 3446 val |= tmp; 3447 } 3448 val <<= LR_SIZE_BITS; 3449 val |= s->cnt; 3450 return val; 3451 } 3452 3453 static void linked_regs_unpack(u64 val, struct linked_regs *s) 3454 { 3455 int i; 3456 3457 s->cnt = val & LR_SIZE_MASK; 3458 val >>= LR_SIZE_BITS; 3459 3460 for (i = 0; i < s->cnt; ++i) { 3461 struct linked_reg *e = &s->entries[i]; 3462 3463 e->frameno = val & LR_FRAMENO_MASK; 3464 e->spi = (val >> LR_SPI_OFF) & LR_SPI_MASK; 3465 e->is_reg = (val >> LR_IS_REG_OFF) & 0x1; 3466 val >>= LR_ENTRY_BITS; 3467 } 3468 } 3469 3470 /* for any branch, call, exit record the history of jmps in the given state */ 3471 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur, 3472 int insn_flags, u64 linked_regs) 3473 { 3474 u32 cnt = cur->jmp_history_cnt; 3475 struct bpf_jmp_history_entry *p; 3476 size_t alloc_size; 3477 3478 /* combine instruction flags if we already recorded this instruction */ 3479 if (env->cur_hist_ent) { 3480 /* atomic instructions push insn_flags twice, for READ and 3481 * WRITE sides, but they should agree on stack slot 3482 */ 3483 WARN_ONCE((env->cur_hist_ent->flags & insn_flags) && 3484 (env->cur_hist_ent->flags & insn_flags) != insn_flags, 3485 "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n", 3486 env->insn_idx, env->cur_hist_ent->flags, insn_flags); 3487 env->cur_hist_ent->flags |= insn_flags; 3488 WARN_ONCE(env->cur_hist_ent->linked_regs != 0, 3489 "verifier insn history bug: insn_idx %d linked_regs != 0: %#llx\n", 3490 env->insn_idx, env->cur_hist_ent->linked_regs); 3491 env->cur_hist_ent->linked_regs = linked_regs; 3492 return 0; 3493 } 3494 3495 cnt++; 3496 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 3497 p = krealloc(cur->jmp_history, alloc_size, GFP_USER); 3498 if (!p) 3499 return -ENOMEM; 3500 cur->jmp_history = p; 3501 3502 p = &cur->jmp_history[cnt - 1]; 3503 p->idx = env->insn_idx; 3504 p->prev_idx = env->prev_insn_idx; 3505 p->flags = insn_flags; 3506 p->linked_regs = linked_regs; 3507 cur->jmp_history_cnt = cnt; 3508 env->cur_hist_ent = p; 3509 3510 return 0; 3511 } 3512 3513 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st, 3514 u32 hist_end, int insn_idx) 3515 { 3516 if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx) 3517 return &st->jmp_history[hist_end - 1]; 3518 return NULL; 3519 } 3520 3521 /* Backtrack one insn at a time. If idx is not at the top of recorded 3522 * history then previous instruction came from straight line execution. 3523 * Return -ENOENT if we exhausted all instructions within given state. 3524 * 3525 * It's legal to have a bit of a looping with the same starting and ending 3526 * insn index within the same state, e.g.: 3->4->5->3, so just because current 3527 * instruction index is the same as state's first_idx doesn't mean we are 3528 * done. If there is still some jump history left, we should keep going. We 3529 * need to take into account that we might have a jump history between given 3530 * state's parent and itself, due to checkpointing. In this case, we'll have 3531 * history entry recording a jump from last instruction of parent state and 3532 * first instruction of given state. 3533 */ 3534 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 3535 u32 *history) 3536 { 3537 u32 cnt = *history; 3538 3539 if (i == st->first_insn_idx) { 3540 if (cnt == 0) 3541 return -ENOENT; 3542 if (cnt == 1 && st->jmp_history[0].idx == i) 3543 return -ENOENT; 3544 } 3545 3546 if (cnt && st->jmp_history[cnt - 1].idx == i) { 3547 i = st->jmp_history[cnt - 1].prev_idx; 3548 (*history)--; 3549 } else { 3550 i--; 3551 } 3552 return i; 3553 } 3554 3555 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3556 { 3557 const struct btf_type *func; 3558 struct btf *desc_btf; 3559 3560 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3561 return NULL; 3562 3563 desc_btf = find_kfunc_desc_btf(data, insn->off); 3564 if (IS_ERR(desc_btf)) 3565 return "<error>"; 3566 3567 func = btf_type_by_id(desc_btf, insn->imm); 3568 return btf_name_by_offset(desc_btf, func->name_off); 3569 } 3570 3571 static inline void bt_init(struct backtrack_state *bt, u32 frame) 3572 { 3573 bt->frame = frame; 3574 } 3575 3576 static inline void bt_reset(struct backtrack_state *bt) 3577 { 3578 struct bpf_verifier_env *env = bt->env; 3579 3580 memset(bt, 0, sizeof(*bt)); 3581 bt->env = env; 3582 } 3583 3584 static inline u32 bt_empty(struct backtrack_state *bt) 3585 { 3586 u64 mask = 0; 3587 int i; 3588 3589 for (i = 0; i <= bt->frame; i++) 3590 mask |= bt->reg_masks[i] | bt->stack_masks[i]; 3591 3592 return mask == 0; 3593 } 3594 3595 static inline int bt_subprog_enter(struct backtrack_state *bt) 3596 { 3597 if (bt->frame == MAX_CALL_FRAMES - 1) { 3598 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame); 3599 WARN_ONCE(1, "verifier backtracking bug"); 3600 return -EFAULT; 3601 } 3602 bt->frame++; 3603 return 0; 3604 } 3605 3606 static inline int bt_subprog_exit(struct backtrack_state *bt) 3607 { 3608 if (bt->frame == 0) { 3609 verbose(bt->env, "BUG subprog exit from frame 0\n"); 3610 WARN_ONCE(1, "verifier backtracking bug"); 3611 return -EFAULT; 3612 } 3613 bt->frame--; 3614 return 0; 3615 } 3616 3617 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3618 { 3619 bt->reg_masks[frame] |= 1 << reg; 3620 } 3621 3622 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3623 { 3624 bt->reg_masks[frame] &= ~(1 << reg); 3625 } 3626 3627 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg) 3628 { 3629 bt_set_frame_reg(bt, bt->frame, reg); 3630 } 3631 3632 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg) 3633 { 3634 bt_clear_frame_reg(bt, bt->frame, reg); 3635 } 3636 3637 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3638 { 3639 bt->stack_masks[frame] |= 1ull << slot; 3640 } 3641 3642 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3643 { 3644 bt->stack_masks[frame] &= ~(1ull << slot); 3645 } 3646 3647 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame) 3648 { 3649 return bt->reg_masks[frame]; 3650 } 3651 3652 static inline u32 bt_reg_mask(struct backtrack_state *bt) 3653 { 3654 return bt->reg_masks[bt->frame]; 3655 } 3656 3657 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame) 3658 { 3659 return bt->stack_masks[frame]; 3660 } 3661 3662 static inline u64 bt_stack_mask(struct backtrack_state *bt) 3663 { 3664 return bt->stack_masks[bt->frame]; 3665 } 3666 3667 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg) 3668 { 3669 return bt->reg_masks[bt->frame] & (1 << reg); 3670 } 3671 3672 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg) 3673 { 3674 return bt->reg_masks[frame] & (1 << reg); 3675 } 3676 3677 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot) 3678 { 3679 return bt->stack_masks[frame] & (1ull << slot); 3680 } 3681 3682 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */ 3683 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask) 3684 { 3685 DECLARE_BITMAP(mask, 64); 3686 bool first = true; 3687 int i, n; 3688 3689 buf[0] = '\0'; 3690 3691 bitmap_from_u64(mask, reg_mask); 3692 for_each_set_bit(i, mask, 32) { 3693 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i); 3694 first = false; 3695 buf += n; 3696 buf_sz -= n; 3697 if (buf_sz < 0) 3698 break; 3699 } 3700 } 3701 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */ 3702 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask) 3703 { 3704 DECLARE_BITMAP(mask, 64); 3705 bool first = true; 3706 int i, n; 3707 3708 buf[0] = '\0'; 3709 3710 bitmap_from_u64(mask, stack_mask); 3711 for_each_set_bit(i, mask, 64) { 3712 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8); 3713 first = false; 3714 buf += n; 3715 buf_sz -= n; 3716 if (buf_sz < 0) 3717 break; 3718 } 3719 } 3720 3721 /* If any register R in hist->linked_regs is marked as precise in bt, 3722 * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs. 3723 */ 3724 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist) 3725 { 3726 struct linked_regs linked_regs; 3727 bool some_precise = false; 3728 int i; 3729 3730 if (!hist || hist->linked_regs == 0) 3731 return; 3732 3733 linked_regs_unpack(hist->linked_regs, &linked_regs); 3734 for (i = 0; i < linked_regs.cnt; ++i) { 3735 struct linked_reg *e = &linked_regs.entries[i]; 3736 3737 if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) || 3738 (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) { 3739 some_precise = true; 3740 break; 3741 } 3742 } 3743 3744 if (!some_precise) 3745 return; 3746 3747 for (i = 0; i < linked_regs.cnt; ++i) { 3748 struct linked_reg *e = &linked_regs.entries[i]; 3749 3750 if (e->is_reg) 3751 bt_set_frame_reg(bt, e->frameno, e->regno); 3752 else 3753 bt_set_frame_slot(bt, e->frameno, e->spi); 3754 } 3755 } 3756 3757 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx); 3758 3759 /* For given verifier state backtrack_insn() is called from the last insn to 3760 * the first insn. Its purpose is to compute a bitmask of registers and 3761 * stack slots that needs precision in the parent verifier state. 3762 * 3763 * @idx is an index of the instruction we are currently processing; 3764 * @subseq_idx is an index of the subsequent instruction that: 3765 * - *would be* executed next, if jump history is viewed in forward order; 3766 * - *was* processed previously during backtracking. 3767 */ 3768 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx, 3769 struct bpf_jmp_history_entry *hist, struct backtrack_state *bt) 3770 { 3771 const struct bpf_insn_cbs cbs = { 3772 .cb_call = disasm_kfunc_name, 3773 .cb_print = verbose, 3774 .private_data = env, 3775 }; 3776 struct bpf_insn *insn = env->prog->insnsi + idx; 3777 u8 class = BPF_CLASS(insn->code); 3778 u8 opcode = BPF_OP(insn->code); 3779 u8 mode = BPF_MODE(insn->code); 3780 u32 dreg = insn->dst_reg; 3781 u32 sreg = insn->src_reg; 3782 u32 spi, i, fr; 3783 3784 if (insn->code == 0) 3785 return 0; 3786 if (env->log.level & BPF_LOG_LEVEL2) { 3787 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt)); 3788 verbose(env, "mark_precise: frame%d: regs=%s ", 3789 bt->frame, env->tmp_str_buf); 3790 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt)); 3791 verbose(env, "stack=%s before ", env->tmp_str_buf); 3792 verbose(env, "%d: ", idx); 3793 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3794 } 3795 3796 /* If there is a history record that some registers gained range at this insn, 3797 * propagate precision marks to those registers, so that bt_is_reg_set() 3798 * accounts for these registers. 3799 */ 3800 bt_sync_linked_regs(bt, hist); 3801 3802 if (class == BPF_ALU || class == BPF_ALU64) { 3803 if (!bt_is_reg_set(bt, dreg)) 3804 return 0; 3805 if (opcode == BPF_END || opcode == BPF_NEG) { 3806 /* sreg is reserved and unused 3807 * dreg still need precision before this insn 3808 */ 3809 return 0; 3810 } else if (opcode == BPF_MOV) { 3811 if (BPF_SRC(insn->code) == BPF_X) { 3812 /* dreg = sreg or dreg = (s8, s16, s32)sreg 3813 * dreg needs precision after this insn 3814 * sreg needs precision before this insn 3815 */ 3816 bt_clear_reg(bt, dreg); 3817 if (sreg != BPF_REG_FP) 3818 bt_set_reg(bt, sreg); 3819 } else { 3820 /* dreg = K 3821 * dreg needs precision after this insn. 3822 * Corresponding register is already marked 3823 * as precise=true in this verifier state. 3824 * No further markings in parent are necessary 3825 */ 3826 bt_clear_reg(bt, dreg); 3827 } 3828 } else { 3829 if (BPF_SRC(insn->code) == BPF_X) { 3830 /* dreg += sreg 3831 * both dreg and sreg need precision 3832 * before this insn 3833 */ 3834 if (sreg != BPF_REG_FP) 3835 bt_set_reg(bt, sreg); 3836 } /* else dreg += K 3837 * dreg still needs precision before this insn 3838 */ 3839 } 3840 } else if (class == BPF_LDX) { 3841 if (!bt_is_reg_set(bt, dreg)) 3842 return 0; 3843 bt_clear_reg(bt, dreg); 3844 3845 /* scalars can only be spilled into stack w/o losing precision. 3846 * Load from any other memory can be zero extended. 3847 * The desire to keep that precision is already indicated 3848 * by 'precise' mark in corresponding register of this state. 3849 * No further tracking necessary. 3850 */ 3851 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 3852 return 0; 3853 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 3854 * that [fp - off] slot contains scalar that needs to be 3855 * tracked with precision 3856 */ 3857 spi = insn_stack_access_spi(hist->flags); 3858 fr = insn_stack_access_frameno(hist->flags); 3859 bt_set_frame_slot(bt, fr, spi); 3860 } else if (class == BPF_STX || class == BPF_ST) { 3861 if (bt_is_reg_set(bt, dreg)) 3862 /* stx & st shouldn't be using _scalar_ dst_reg 3863 * to access memory. It means backtracking 3864 * encountered a case of pointer subtraction. 3865 */ 3866 return -ENOTSUPP; 3867 /* scalars can only be spilled into stack */ 3868 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 3869 return 0; 3870 spi = insn_stack_access_spi(hist->flags); 3871 fr = insn_stack_access_frameno(hist->flags); 3872 if (!bt_is_frame_slot_set(bt, fr, spi)) 3873 return 0; 3874 bt_clear_frame_slot(bt, fr, spi); 3875 if (class == BPF_STX) 3876 bt_set_reg(bt, sreg); 3877 } else if (class == BPF_JMP || class == BPF_JMP32) { 3878 if (bpf_pseudo_call(insn)) { 3879 int subprog_insn_idx, subprog; 3880 3881 subprog_insn_idx = idx + insn->imm + 1; 3882 subprog = find_subprog(env, subprog_insn_idx); 3883 if (subprog < 0) 3884 return -EFAULT; 3885 3886 if (subprog_is_global(env, subprog)) { 3887 /* check that jump history doesn't have any 3888 * extra instructions from subprog; the next 3889 * instruction after call to global subprog 3890 * should be literally next instruction in 3891 * caller program 3892 */ 3893 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug"); 3894 /* r1-r5 are invalidated after subprog call, 3895 * so for global func call it shouldn't be set 3896 * anymore 3897 */ 3898 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3899 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3900 WARN_ONCE(1, "verifier backtracking bug"); 3901 return -EFAULT; 3902 } 3903 /* global subprog always sets R0 */ 3904 bt_clear_reg(bt, BPF_REG_0); 3905 return 0; 3906 } else { 3907 /* static subprog call instruction, which 3908 * means that we are exiting current subprog, 3909 * so only r1-r5 could be still requested as 3910 * precise, r0 and r6-r10 or any stack slot in 3911 * the current frame should be zero by now 3912 */ 3913 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3914 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3915 WARN_ONCE(1, "verifier backtracking bug"); 3916 return -EFAULT; 3917 } 3918 /* we are now tracking register spills correctly, 3919 * so any instance of leftover slots is a bug 3920 */ 3921 if (bt_stack_mask(bt) != 0) { 3922 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt)); 3923 WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)"); 3924 return -EFAULT; 3925 } 3926 /* propagate r1-r5 to the caller */ 3927 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 3928 if (bt_is_reg_set(bt, i)) { 3929 bt_clear_reg(bt, i); 3930 bt_set_frame_reg(bt, bt->frame - 1, i); 3931 } 3932 } 3933 if (bt_subprog_exit(bt)) 3934 return -EFAULT; 3935 return 0; 3936 } 3937 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) { 3938 /* exit from callback subprog to callback-calling helper or 3939 * kfunc call. Use idx/subseq_idx check to discern it from 3940 * straight line code backtracking. 3941 * Unlike the subprog call handling above, we shouldn't 3942 * propagate precision of r1-r5 (if any requested), as they are 3943 * not actually arguments passed directly to callback subprogs 3944 */ 3945 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3946 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3947 WARN_ONCE(1, "verifier backtracking bug"); 3948 return -EFAULT; 3949 } 3950 if (bt_stack_mask(bt) != 0) { 3951 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt)); 3952 WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)"); 3953 return -EFAULT; 3954 } 3955 /* clear r1-r5 in callback subprog's mask */ 3956 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3957 bt_clear_reg(bt, i); 3958 if (bt_subprog_exit(bt)) 3959 return -EFAULT; 3960 return 0; 3961 } else if (opcode == BPF_CALL) { 3962 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 3963 * catch this error later. Make backtracking conservative 3964 * with ENOTSUPP. 3965 */ 3966 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 3967 return -ENOTSUPP; 3968 /* regular helper call sets R0 */ 3969 bt_clear_reg(bt, BPF_REG_0); 3970 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3971 /* if backtracing was looking for registers R1-R5 3972 * they should have been found already. 3973 */ 3974 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3975 WARN_ONCE(1, "verifier backtracking bug"); 3976 return -EFAULT; 3977 } 3978 } else if (opcode == BPF_EXIT) { 3979 bool r0_precise; 3980 3981 /* Backtracking to a nested function call, 'idx' is a part of 3982 * the inner frame 'subseq_idx' is a part of the outer frame. 3983 * In case of a regular function call, instructions giving 3984 * precision to registers R1-R5 should have been found already. 3985 * In case of a callback, it is ok to have R1-R5 marked for 3986 * backtracking, as these registers are set by the function 3987 * invoking callback. 3988 */ 3989 if (subseq_idx >= 0 && calls_callback(env, subseq_idx)) 3990 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3991 bt_clear_reg(bt, i); 3992 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3993 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3994 WARN_ONCE(1, "verifier backtracking bug"); 3995 return -EFAULT; 3996 } 3997 3998 /* BPF_EXIT in subprog or callback always returns 3999 * right after the call instruction, so by checking 4000 * whether the instruction at subseq_idx-1 is subprog 4001 * call or not we can distinguish actual exit from 4002 * *subprog* from exit from *callback*. In the former 4003 * case, we need to propagate r0 precision, if 4004 * necessary. In the former we never do that. 4005 */ 4006 r0_precise = subseq_idx - 1 >= 0 && 4007 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) && 4008 bt_is_reg_set(bt, BPF_REG_0); 4009 4010 bt_clear_reg(bt, BPF_REG_0); 4011 if (bt_subprog_enter(bt)) 4012 return -EFAULT; 4013 4014 if (r0_precise) 4015 bt_set_reg(bt, BPF_REG_0); 4016 /* r6-r9 and stack slots will stay set in caller frame 4017 * bitmasks until we return back from callee(s) 4018 */ 4019 return 0; 4020 } else if (BPF_SRC(insn->code) == BPF_X) { 4021 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg)) 4022 return 0; 4023 /* dreg <cond> sreg 4024 * Both dreg and sreg need precision before 4025 * this insn. If only sreg was marked precise 4026 * before it would be equally necessary to 4027 * propagate it to dreg. 4028 */ 4029 bt_set_reg(bt, dreg); 4030 bt_set_reg(bt, sreg); 4031 } else if (BPF_SRC(insn->code) == BPF_K) { 4032 /* dreg <cond> K 4033 * Only dreg still needs precision before 4034 * this insn, so for the K-based conditional 4035 * there is nothing new to be marked. 4036 */ 4037 } 4038 } else if (class == BPF_LD) { 4039 if (!bt_is_reg_set(bt, dreg)) 4040 return 0; 4041 bt_clear_reg(bt, dreg); 4042 /* It's ld_imm64 or ld_abs or ld_ind. 4043 * For ld_imm64 no further tracking of precision 4044 * into parent is necessary 4045 */ 4046 if (mode == BPF_IND || mode == BPF_ABS) 4047 /* to be analyzed */ 4048 return -ENOTSUPP; 4049 } 4050 /* Propagate precision marks to linked registers, to account for 4051 * registers marked as precise in this function. 4052 */ 4053 bt_sync_linked_regs(bt, hist); 4054 return 0; 4055 } 4056 4057 /* the scalar precision tracking algorithm: 4058 * . at the start all registers have precise=false. 4059 * . scalar ranges are tracked as normal through alu and jmp insns. 4060 * . once precise value of the scalar register is used in: 4061 * . ptr + scalar alu 4062 * . if (scalar cond K|scalar) 4063 * . helper_call(.., scalar, ...) where ARG_CONST is expected 4064 * backtrack through the verifier states and mark all registers and 4065 * stack slots with spilled constants that these scalar regisers 4066 * should be precise. 4067 * . during state pruning two registers (or spilled stack slots) 4068 * are equivalent if both are not precise. 4069 * 4070 * Note the verifier cannot simply walk register parentage chain, 4071 * since many different registers and stack slots could have been 4072 * used to compute single precise scalar. 4073 * 4074 * The approach of starting with precise=true for all registers and then 4075 * backtrack to mark a register as not precise when the verifier detects 4076 * that program doesn't care about specific value (e.g., when helper 4077 * takes register as ARG_ANYTHING parameter) is not safe. 4078 * 4079 * It's ok to walk single parentage chain of the verifier states. 4080 * It's possible that this backtracking will go all the way till 1st insn. 4081 * All other branches will be explored for needing precision later. 4082 * 4083 * The backtracking needs to deal with cases like: 4084 * 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) 4085 * r9 -= r8 4086 * r5 = r9 4087 * if r5 > 0x79f goto pc+7 4088 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 4089 * r5 += 1 4090 * ... 4091 * call bpf_perf_event_output#25 4092 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 4093 * 4094 * and this case: 4095 * r6 = 1 4096 * call foo // uses callee's r6 inside to compute r0 4097 * r0 += r6 4098 * if r0 == 0 goto 4099 * 4100 * to track above reg_mask/stack_mask needs to be independent for each frame. 4101 * 4102 * Also if parent's curframe > frame where backtracking started, 4103 * the verifier need to mark registers in both frames, otherwise callees 4104 * may incorrectly prune callers. This is similar to 4105 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 4106 * 4107 * For now backtracking falls back into conservative marking. 4108 */ 4109 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 4110 struct bpf_verifier_state *st) 4111 { 4112 struct bpf_func_state *func; 4113 struct bpf_reg_state *reg; 4114 int i, j; 4115 4116 if (env->log.level & BPF_LOG_LEVEL2) { 4117 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n", 4118 st->curframe); 4119 } 4120 4121 /* big hammer: mark all scalars precise in this path. 4122 * pop_stack may still get !precise scalars. 4123 * We also skip current state and go straight to first parent state, 4124 * because precision markings in current non-checkpointed state are 4125 * not needed. See why in the comment in __mark_chain_precision below. 4126 */ 4127 for (st = st->parent; st; st = st->parent) { 4128 for (i = 0; i <= st->curframe; i++) { 4129 func = st->frame[i]; 4130 for (j = 0; j < BPF_REG_FP; j++) { 4131 reg = &func->regs[j]; 4132 if (reg->type != SCALAR_VALUE || reg->precise) 4133 continue; 4134 reg->precise = true; 4135 if (env->log.level & BPF_LOG_LEVEL2) { 4136 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n", 4137 i, j); 4138 } 4139 } 4140 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 4141 if (!is_spilled_reg(&func->stack[j])) 4142 continue; 4143 reg = &func->stack[j].spilled_ptr; 4144 if (reg->type != SCALAR_VALUE || reg->precise) 4145 continue; 4146 reg->precise = true; 4147 if (env->log.level & BPF_LOG_LEVEL2) { 4148 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n", 4149 i, -(j + 1) * 8); 4150 } 4151 } 4152 } 4153 } 4154 } 4155 4156 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 4157 { 4158 struct bpf_func_state *func; 4159 struct bpf_reg_state *reg; 4160 int i, j; 4161 4162 for (i = 0; i <= st->curframe; i++) { 4163 func = st->frame[i]; 4164 for (j = 0; j < BPF_REG_FP; j++) { 4165 reg = &func->regs[j]; 4166 if (reg->type != SCALAR_VALUE) 4167 continue; 4168 reg->precise = false; 4169 } 4170 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 4171 if (!is_spilled_reg(&func->stack[j])) 4172 continue; 4173 reg = &func->stack[j].spilled_ptr; 4174 if (reg->type != SCALAR_VALUE) 4175 continue; 4176 reg->precise = false; 4177 } 4178 } 4179 } 4180 4181 /* 4182 * __mark_chain_precision() backtracks BPF program instruction sequence and 4183 * chain of verifier states making sure that register *regno* (if regno >= 0) 4184 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 4185 * SCALARS, as well as any other registers and slots that contribute to 4186 * a tracked state of given registers/stack slots, depending on specific BPF 4187 * assembly instructions (see backtrack_insns() for exact instruction handling 4188 * logic). This backtracking relies on recorded jmp_history and is able to 4189 * traverse entire chain of parent states. This process ends only when all the 4190 * necessary registers/slots and their transitive dependencies are marked as 4191 * precise. 4192 * 4193 * One important and subtle aspect is that precise marks *do not matter* in 4194 * the currently verified state (current state). It is important to understand 4195 * why this is the case. 4196 * 4197 * First, note that current state is the state that is not yet "checkpointed", 4198 * i.e., it is not yet put into env->explored_states, and it has no children 4199 * states as well. It's ephemeral, and can end up either a) being discarded if 4200 * compatible explored state is found at some point or BPF_EXIT instruction is 4201 * reached or b) checkpointed and put into env->explored_states, branching out 4202 * into one or more children states. 4203 * 4204 * In the former case, precise markings in current state are completely 4205 * ignored by state comparison code (see regsafe() for details). Only 4206 * checkpointed ("old") state precise markings are important, and if old 4207 * state's register/slot is precise, regsafe() assumes current state's 4208 * register/slot as precise and checks value ranges exactly and precisely. If 4209 * states turn out to be compatible, current state's necessary precise 4210 * markings and any required parent states' precise markings are enforced 4211 * after the fact with propagate_precision() logic, after the fact. But it's 4212 * important to realize that in this case, even after marking current state 4213 * registers/slots as precise, we immediately discard current state. So what 4214 * actually matters is any of the precise markings propagated into current 4215 * state's parent states, which are always checkpointed (due to b) case above). 4216 * As such, for scenario a) it doesn't matter if current state has precise 4217 * markings set or not. 4218 * 4219 * Now, for the scenario b), checkpointing and forking into child(ren) 4220 * state(s). Note that before current state gets to checkpointing step, any 4221 * processed instruction always assumes precise SCALAR register/slot 4222 * knowledge: if precise value or range is useful to prune jump branch, BPF 4223 * verifier takes this opportunity enthusiastically. Similarly, when 4224 * register's value is used to calculate offset or memory address, exact 4225 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 4226 * what we mentioned above about state comparison ignoring precise markings 4227 * during state comparison, BPF verifier ignores and also assumes precise 4228 * markings *at will* during instruction verification process. But as verifier 4229 * assumes precision, it also propagates any precision dependencies across 4230 * parent states, which are not yet finalized, so can be further restricted 4231 * based on new knowledge gained from restrictions enforced by their children 4232 * states. This is so that once those parent states are finalized, i.e., when 4233 * they have no more active children state, state comparison logic in 4234 * is_state_visited() would enforce strict and precise SCALAR ranges, if 4235 * required for correctness. 4236 * 4237 * To build a bit more intuition, note also that once a state is checkpointed, 4238 * the path we took to get to that state is not important. This is crucial 4239 * property for state pruning. When state is checkpointed and finalized at 4240 * some instruction index, it can be correctly and safely used to "short 4241 * circuit" any *compatible* state that reaches exactly the same instruction 4242 * index. I.e., if we jumped to that instruction from a completely different 4243 * code path than original finalized state was derived from, it doesn't 4244 * matter, current state can be discarded because from that instruction 4245 * forward having a compatible state will ensure we will safely reach the 4246 * exit. States describe preconditions for further exploration, but completely 4247 * forget the history of how we got here. 4248 * 4249 * This also means that even if we needed precise SCALAR range to get to 4250 * finalized state, but from that point forward *that same* SCALAR register is 4251 * never used in a precise context (i.e., it's precise value is not needed for 4252 * correctness), it's correct and safe to mark such register as "imprecise" 4253 * (i.e., precise marking set to false). This is what we rely on when we do 4254 * not set precise marking in current state. If no child state requires 4255 * precision for any given SCALAR register, it's safe to dictate that it can 4256 * be imprecise. If any child state does require this register to be precise, 4257 * we'll mark it precise later retroactively during precise markings 4258 * propagation from child state to parent states. 4259 * 4260 * Skipping precise marking setting in current state is a mild version of 4261 * relying on the above observation. But we can utilize this property even 4262 * more aggressively by proactively forgetting any precise marking in the 4263 * current state (which we inherited from the parent state), right before we 4264 * checkpoint it and branch off into new child state. This is done by 4265 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 4266 * finalized states which help in short circuiting more future states. 4267 */ 4268 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno) 4269 { 4270 struct backtrack_state *bt = &env->bt; 4271 struct bpf_verifier_state *st = env->cur_state; 4272 int first_idx = st->first_insn_idx; 4273 int last_idx = env->insn_idx; 4274 int subseq_idx = -1; 4275 struct bpf_func_state *func; 4276 struct bpf_reg_state *reg; 4277 bool skip_first = true; 4278 int i, fr, err; 4279 4280 if (!env->bpf_capable) 4281 return 0; 4282 4283 /* set frame number from which we are starting to backtrack */ 4284 bt_init(bt, env->cur_state->curframe); 4285 4286 /* Do sanity checks against current state of register and/or stack 4287 * slot, but don't set precise flag in current state, as precision 4288 * tracking in the current state is unnecessary. 4289 */ 4290 func = st->frame[bt->frame]; 4291 if (regno >= 0) { 4292 reg = &func->regs[regno]; 4293 if (reg->type != SCALAR_VALUE) { 4294 WARN_ONCE(1, "backtracing misuse"); 4295 return -EFAULT; 4296 } 4297 bt_set_reg(bt, regno); 4298 } 4299 4300 if (bt_empty(bt)) 4301 return 0; 4302 4303 for (;;) { 4304 DECLARE_BITMAP(mask, 64); 4305 u32 history = st->jmp_history_cnt; 4306 struct bpf_jmp_history_entry *hist; 4307 4308 if (env->log.level & BPF_LOG_LEVEL2) { 4309 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n", 4310 bt->frame, last_idx, first_idx, subseq_idx); 4311 } 4312 4313 if (last_idx < 0) { 4314 /* we are at the entry into subprog, which 4315 * is expected for global funcs, but only if 4316 * requested precise registers are R1-R5 4317 * (which are global func's input arguments) 4318 */ 4319 if (st->curframe == 0 && 4320 st->frame[0]->subprogno > 0 && 4321 st->frame[0]->callsite == BPF_MAIN_FUNC && 4322 bt_stack_mask(bt) == 0 && 4323 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) { 4324 bitmap_from_u64(mask, bt_reg_mask(bt)); 4325 for_each_set_bit(i, mask, 32) { 4326 reg = &st->frame[0]->regs[i]; 4327 bt_clear_reg(bt, i); 4328 if (reg->type == SCALAR_VALUE) 4329 reg->precise = true; 4330 } 4331 return 0; 4332 } 4333 4334 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n", 4335 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt)); 4336 WARN_ONCE(1, "verifier backtracking bug"); 4337 return -EFAULT; 4338 } 4339 4340 for (i = last_idx;;) { 4341 if (skip_first) { 4342 err = 0; 4343 skip_first = false; 4344 } else { 4345 hist = get_jmp_hist_entry(st, history, i); 4346 err = backtrack_insn(env, i, subseq_idx, hist, bt); 4347 } 4348 if (err == -ENOTSUPP) { 4349 mark_all_scalars_precise(env, env->cur_state); 4350 bt_reset(bt); 4351 return 0; 4352 } else if (err) { 4353 return err; 4354 } 4355 if (bt_empty(bt)) 4356 /* Found assignment(s) into tracked register in this state. 4357 * Since this state is already marked, just return. 4358 * Nothing to be tracked further in the parent state. 4359 */ 4360 return 0; 4361 subseq_idx = i; 4362 i = get_prev_insn_idx(st, i, &history); 4363 if (i == -ENOENT) 4364 break; 4365 if (i >= env->prog->len) { 4366 /* This can happen if backtracking reached insn 0 4367 * and there are still reg_mask or stack_mask 4368 * to backtrack. 4369 * It means the backtracking missed the spot where 4370 * particular register was initialized with a constant. 4371 */ 4372 verbose(env, "BUG backtracking idx %d\n", i); 4373 WARN_ONCE(1, "verifier backtracking bug"); 4374 return -EFAULT; 4375 } 4376 } 4377 st = st->parent; 4378 if (!st) 4379 break; 4380 4381 for (fr = bt->frame; fr >= 0; fr--) { 4382 func = st->frame[fr]; 4383 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4384 for_each_set_bit(i, mask, 32) { 4385 reg = &func->regs[i]; 4386 if (reg->type != SCALAR_VALUE) { 4387 bt_clear_frame_reg(bt, fr, i); 4388 continue; 4389 } 4390 if (reg->precise) 4391 bt_clear_frame_reg(bt, fr, i); 4392 else 4393 reg->precise = true; 4394 } 4395 4396 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4397 for_each_set_bit(i, mask, 64) { 4398 if (i >= func->allocated_stack / BPF_REG_SIZE) { 4399 verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n", 4400 i, func->allocated_stack / BPF_REG_SIZE); 4401 WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)"); 4402 return -EFAULT; 4403 } 4404 4405 if (!is_spilled_scalar_reg(&func->stack[i])) { 4406 bt_clear_frame_slot(bt, fr, i); 4407 continue; 4408 } 4409 reg = &func->stack[i].spilled_ptr; 4410 if (reg->precise) 4411 bt_clear_frame_slot(bt, fr, i); 4412 else 4413 reg->precise = true; 4414 } 4415 if (env->log.level & BPF_LOG_LEVEL2) { 4416 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4417 bt_frame_reg_mask(bt, fr)); 4418 verbose(env, "mark_precise: frame%d: parent state regs=%s ", 4419 fr, env->tmp_str_buf); 4420 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4421 bt_frame_stack_mask(bt, fr)); 4422 verbose(env, "stack=%s: ", env->tmp_str_buf); 4423 print_verifier_state(env, func, true); 4424 } 4425 } 4426 4427 if (bt_empty(bt)) 4428 return 0; 4429 4430 subseq_idx = first_idx; 4431 last_idx = st->last_insn_idx; 4432 first_idx = st->first_insn_idx; 4433 } 4434 4435 /* if we still have requested precise regs or slots, we missed 4436 * something (e.g., stack access through non-r10 register), so 4437 * fallback to marking all precise 4438 */ 4439 if (!bt_empty(bt)) { 4440 mark_all_scalars_precise(env, env->cur_state); 4441 bt_reset(bt); 4442 } 4443 4444 return 0; 4445 } 4446 4447 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 4448 { 4449 return __mark_chain_precision(env, regno); 4450 } 4451 4452 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 4453 * desired reg and stack masks across all relevant frames 4454 */ 4455 static int mark_chain_precision_batch(struct bpf_verifier_env *env) 4456 { 4457 return __mark_chain_precision(env, -1); 4458 } 4459 4460 static bool is_spillable_regtype(enum bpf_reg_type type) 4461 { 4462 switch (base_type(type)) { 4463 case PTR_TO_MAP_VALUE: 4464 case PTR_TO_STACK: 4465 case PTR_TO_CTX: 4466 case PTR_TO_PACKET: 4467 case PTR_TO_PACKET_META: 4468 case PTR_TO_PACKET_END: 4469 case PTR_TO_FLOW_KEYS: 4470 case CONST_PTR_TO_MAP: 4471 case PTR_TO_SOCKET: 4472 case PTR_TO_SOCK_COMMON: 4473 case PTR_TO_TCP_SOCK: 4474 case PTR_TO_XDP_SOCK: 4475 case PTR_TO_BTF_ID: 4476 case PTR_TO_BUF: 4477 case PTR_TO_MEM: 4478 case PTR_TO_FUNC: 4479 case PTR_TO_MAP_KEY: 4480 case PTR_TO_ARENA: 4481 return true; 4482 default: 4483 return false; 4484 } 4485 } 4486 4487 /* Does this register contain a constant zero? */ 4488 static bool register_is_null(struct bpf_reg_state *reg) 4489 { 4490 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 4491 } 4492 4493 /* check if register is a constant scalar value */ 4494 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32) 4495 { 4496 return reg->type == SCALAR_VALUE && 4497 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off); 4498 } 4499 4500 /* assuming is_reg_const() is true, return constant value of a register */ 4501 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32) 4502 { 4503 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value; 4504 } 4505 4506 static bool __is_pointer_value(bool allow_ptr_leaks, 4507 const struct bpf_reg_state *reg) 4508 { 4509 if (allow_ptr_leaks) 4510 return false; 4511 4512 return reg->type != SCALAR_VALUE; 4513 } 4514 4515 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env, 4516 struct bpf_reg_state *src_reg) 4517 { 4518 if (src_reg->type != SCALAR_VALUE) 4519 return; 4520 4521 if (src_reg->id & BPF_ADD_CONST) { 4522 /* 4523 * The verifier is processing rX = rY insn and 4524 * rY->id has special linked register already. 4525 * Cleared it, since multiple rX += const are not supported. 4526 */ 4527 src_reg->id = 0; 4528 src_reg->off = 0; 4529 } 4530 4531 if (!src_reg->id && !tnum_is_const(src_reg->var_off)) 4532 /* Ensure that src_reg has a valid ID that will be copied to 4533 * dst_reg and then will be used by sync_linked_regs() to 4534 * propagate min/max range. 4535 */ 4536 src_reg->id = ++env->id_gen; 4537 } 4538 4539 /* Copy src state preserving dst->parent and dst->live fields */ 4540 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 4541 { 4542 struct bpf_reg_state *parent = dst->parent; 4543 enum bpf_reg_liveness live = dst->live; 4544 4545 *dst = *src; 4546 dst->parent = parent; 4547 dst->live = live; 4548 } 4549 4550 static void save_register_state(struct bpf_verifier_env *env, 4551 struct bpf_func_state *state, 4552 int spi, struct bpf_reg_state *reg, 4553 int size) 4554 { 4555 int i; 4556 4557 copy_register_state(&state->stack[spi].spilled_ptr, reg); 4558 if (size == BPF_REG_SIZE) 4559 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4560 4561 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 4562 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 4563 4564 /* size < 8 bytes spill */ 4565 for (; i; i--) 4566 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]); 4567 } 4568 4569 static bool is_bpf_st_mem(struct bpf_insn *insn) 4570 { 4571 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 4572 } 4573 4574 static int get_reg_width(struct bpf_reg_state *reg) 4575 { 4576 return fls64(reg->umax_value); 4577 } 4578 4579 /* See comment for mark_fastcall_pattern_for_call() */ 4580 static void check_fastcall_stack_contract(struct bpf_verifier_env *env, 4581 struct bpf_func_state *state, int insn_idx, int off) 4582 { 4583 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 4584 struct bpf_insn_aux_data *aux = env->insn_aux_data; 4585 int i; 4586 4587 if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern) 4588 return; 4589 /* access to the region [max_stack_depth .. fastcall_stack_off) 4590 * from something that is not a part of the fastcall pattern, 4591 * disable fastcall rewrites for current subprogram by setting 4592 * fastcall_stack_off to a value smaller than any possible offset. 4593 */ 4594 subprog->fastcall_stack_off = S16_MIN; 4595 /* reset fastcall aux flags within subprogram, 4596 * happens at most once per subprogram 4597 */ 4598 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 4599 aux[i].fastcall_spills_num = 0; 4600 aux[i].fastcall_pattern = 0; 4601 } 4602 } 4603 4604 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 4605 * stack boundary and alignment are checked in check_mem_access() 4606 */ 4607 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 4608 /* stack frame we're writing to */ 4609 struct bpf_func_state *state, 4610 int off, int size, int value_regno, 4611 int insn_idx) 4612 { 4613 struct bpf_func_state *cur; /* state of the current function */ 4614 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 4615 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4616 struct bpf_reg_state *reg = NULL; 4617 int insn_flags = insn_stack_access_flags(state->frameno, spi); 4618 4619 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 4620 * so it's aligned access and [off, off + size) are within stack limits 4621 */ 4622 if (!env->allow_ptr_leaks && 4623 is_spilled_reg(&state->stack[spi]) && 4624 size != BPF_REG_SIZE) { 4625 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 4626 return -EACCES; 4627 } 4628 4629 cur = env->cur_state->frame[env->cur_state->curframe]; 4630 if (value_regno >= 0) 4631 reg = &cur->regs[value_regno]; 4632 if (!env->bypass_spec_v4) { 4633 bool sanitize = reg && is_spillable_regtype(reg->type); 4634 4635 for (i = 0; i < size; i++) { 4636 u8 type = state->stack[spi].slot_type[i]; 4637 4638 if (type != STACK_MISC && type != STACK_ZERO) { 4639 sanitize = true; 4640 break; 4641 } 4642 } 4643 4644 if (sanitize) 4645 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 4646 } 4647 4648 err = destroy_if_dynptr_stack_slot(env, state, spi); 4649 if (err) 4650 return err; 4651 4652 check_fastcall_stack_contract(env, state, insn_idx, off); 4653 mark_stack_slot_scratched(env, spi); 4654 if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) { 4655 bool reg_value_fits; 4656 4657 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size; 4658 /* Make sure that reg had an ID to build a relation on spill. */ 4659 if (reg_value_fits) 4660 assign_scalar_id_before_mov(env, reg); 4661 save_register_state(env, state, spi, reg, size); 4662 /* Break the relation on a narrowing spill. */ 4663 if (!reg_value_fits) 4664 state->stack[spi].spilled_ptr.id = 0; 4665 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 4666 env->bpf_capable) { 4667 struct bpf_reg_state *tmp_reg = &env->fake_reg[0]; 4668 4669 memset(tmp_reg, 0, sizeof(*tmp_reg)); 4670 __mark_reg_known(tmp_reg, insn->imm); 4671 tmp_reg->type = SCALAR_VALUE; 4672 save_register_state(env, state, spi, tmp_reg, size); 4673 } else if (reg && is_spillable_regtype(reg->type)) { 4674 /* register containing pointer is being spilled into stack */ 4675 if (size != BPF_REG_SIZE) { 4676 verbose_linfo(env, insn_idx, "; "); 4677 verbose(env, "invalid size of register spill\n"); 4678 return -EACCES; 4679 } 4680 if (state != cur && reg->type == PTR_TO_STACK) { 4681 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4682 return -EINVAL; 4683 } 4684 save_register_state(env, state, spi, reg, size); 4685 } else { 4686 u8 type = STACK_MISC; 4687 4688 /* regular write of data into stack destroys any spilled ptr */ 4689 state->stack[spi].spilled_ptr.type = NOT_INIT; 4690 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 4691 if (is_stack_slot_special(&state->stack[spi])) 4692 for (i = 0; i < BPF_REG_SIZE; i++) 4693 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 4694 4695 /* only mark the slot as written if all 8 bytes were written 4696 * otherwise read propagation may incorrectly stop too soon 4697 * when stack slots are partially written. 4698 * This heuristic means that read propagation will be 4699 * conservative, since it will add reg_live_read marks 4700 * to stack slots all the way to first state when programs 4701 * writes+reads less than 8 bytes 4702 */ 4703 if (size == BPF_REG_SIZE) 4704 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4705 4706 /* when we zero initialize stack slots mark them as such */ 4707 if ((reg && register_is_null(reg)) || 4708 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4709 /* STACK_ZERO case happened because register spill 4710 * wasn't properly aligned at the stack slot boundary, 4711 * so it's not a register spill anymore; force 4712 * originating register to be precise to make 4713 * STACK_ZERO correct for subsequent states 4714 */ 4715 err = mark_chain_precision(env, value_regno); 4716 if (err) 4717 return err; 4718 type = STACK_ZERO; 4719 } 4720 4721 /* Mark slots affected by this stack write. */ 4722 for (i = 0; i < size; i++) 4723 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 4724 insn_flags = 0; /* not a register spill */ 4725 } 4726 4727 if (insn_flags) 4728 return push_jmp_history(env, env->cur_state, insn_flags, 0); 4729 return 0; 4730 } 4731 4732 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 4733 * known to contain a variable offset. 4734 * This function checks whether the write is permitted and conservatively 4735 * tracks the effects of the write, considering that each stack slot in the 4736 * dynamic range is potentially written to. 4737 * 4738 * 'off' includes 'regno->off'. 4739 * 'value_regno' can be -1, meaning that an unknown value is being written to 4740 * the stack. 4741 * 4742 * Spilled pointers in range are not marked as written because we don't know 4743 * what's going to be actually written. This means that read propagation for 4744 * future reads cannot be terminated by this write. 4745 * 4746 * For privileged programs, uninitialized stack slots are considered 4747 * initialized by this write (even though we don't know exactly what offsets 4748 * are going to be written to). The idea is that we don't want the verifier to 4749 * reject future reads that access slots written to through variable offsets. 4750 */ 4751 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4752 /* func where register points to */ 4753 struct bpf_func_state *state, 4754 int ptr_regno, int off, int size, 4755 int value_regno, int insn_idx) 4756 { 4757 struct bpf_func_state *cur; /* state of the current function */ 4758 int min_off, max_off; 4759 int i, err; 4760 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 4761 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4762 bool writing_zero = false; 4763 /* set if the fact that we're writing a zero is used to let any 4764 * stack slots remain STACK_ZERO 4765 */ 4766 bool zero_used = false; 4767 4768 cur = env->cur_state->frame[env->cur_state->curframe]; 4769 ptr_reg = &cur->regs[ptr_regno]; 4770 min_off = ptr_reg->smin_value + off; 4771 max_off = ptr_reg->smax_value + off + size; 4772 if (value_regno >= 0) 4773 value_reg = &cur->regs[value_regno]; 4774 if ((value_reg && register_is_null(value_reg)) || 4775 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4776 writing_zero = true; 4777 4778 for (i = min_off; i < max_off; i++) { 4779 int spi; 4780 4781 spi = __get_spi(i); 4782 err = destroy_if_dynptr_stack_slot(env, state, spi); 4783 if (err) 4784 return err; 4785 } 4786 4787 check_fastcall_stack_contract(env, state, insn_idx, min_off); 4788 /* Variable offset writes destroy any spilled pointers in range. */ 4789 for (i = min_off; i < max_off; i++) { 4790 u8 new_type, *stype; 4791 int slot, spi; 4792 4793 slot = -i - 1; 4794 spi = slot / BPF_REG_SIZE; 4795 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4796 mark_stack_slot_scratched(env, spi); 4797 4798 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4799 /* Reject the write if range we may write to has not 4800 * been initialized beforehand. If we didn't reject 4801 * here, the ptr status would be erased below (even 4802 * though not all slots are actually overwritten), 4803 * possibly opening the door to leaks. 4804 * 4805 * We do however catch STACK_INVALID case below, and 4806 * only allow reading possibly uninitialized memory 4807 * later for CAP_PERFMON, as the write may not happen to 4808 * that slot. 4809 */ 4810 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4811 insn_idx, i); 4812 return -EINVAL; 4813 } 4814 4815 /* If writing_zero and the spi slot contains a spill of value 0, 4816 * maintain the spill type. 4817 */ 4818 if (writing_zero && *stype == STACK_SPILL && 4819 is_spilled_scalar_reg(&state->stack[spi])) { 4820 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr; 4821 4822 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) { 4823 zero_used = true; 4824 continue; 4825 } 4826 } 4827 4828 /* Erase all other spilled pointers. */ 4829 state->stack[spi].spilled_ptr.type = NOT_INIT; 4830 4831 /* Update the slot type. */ 4832 new_type = STACK_MISC; 4833 if (writing_zero && *stype == STACK_ZERO) { 4834 new_type = STACK_ZERO; 4835 zero_used = true; 4836 } 4837 /* If the slot is STACK_INVALID, we check whether it's OK to 4838 * pretend that it will be initialized by this write. The slot 4839 * might not actually be written to, and so if we mark it as 4840 * initialized future reads might leak uninitialized memory. 4841 * For privileged programs, we will accept such reads to slots 4842 * that may or may not be written because, if we're reject 4843 * them, the error would be too confusing. 4844 */ 4845 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4846 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4847 insn_idx, i); 4848 return -EINVAL; 4849 } 4850 *stype = new_type; 4851 } 4852 if (zero_used) { 4853 /* backtracking doesn't work for STACK_ZERO yet. */ 4854 err = mark_chain_precision(env, value_regno); 4855 if (err) 4856 return err; 4857 } 4858 return 0; 4859 } 4860 4861 /* When register 'dst_regno' is assigned some values from stack[min_off, 4862 * max_off), we set the register's type according to the types of the 4863 * respective stack slots. If all the stack values are known to be zeros, then 4864 * so is the destination reg. Otherwise, the register is considered to be 4865 * SCALAR. This function does not deal with register filling; the caller must 4866 * ensure that all spilled registers in the stack range have been marked as 4867 * read. 4868 */ 4869 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4870 /* func where src register points to */ 4871 struct bpf_func_state *ptr_state, 4872 int min_off, int max_off, int dst_regno) 4873 { 4874 struct bpf_verifier_state *vstate = env->cur_state; 4875 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4876 int i, slot, spi; 4877 u8 *stype; 4878 int zeros = 0; 4879 4880 for (i = min_off; i < max_off; i++) { 4881 slot = -i - 1; 4882 spi = slot / BPF_REG_SIZE; 4883 mark_stack_slot_scratched(env, spi); 4884 stype = ptr_state->stack[spi].slot_type; 4885 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4886 break; 4887 zeros++; 4888 } 4889 if (zeros == max_off - min_off) { 4890 /* Any access_size read into register is zero extended, 4891 * so the whole register == const_zero. 4892 */ 4893 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4894 } else { 4895 /* have read misc data from the stack */ 4896 mark_reg_unknown(env, state->regs, dst_regno); 4897 } 4898 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4899 } 4900 4901 /* Read the stack at 'off' and put the results into the register indicated by 4902 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4903 * spilled reg. 4904 * 4905 * 'dst_regno' can be -1, meaning that the read value is not going to a 4906 * register. 4907 * 4908 * The access is assumed to be within the current stack bounds. 4909 */ 4910 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4911 /* func where src register points to */ 4912 struct bpf_func_state *reg_state, 4913 int off, int size, int dst_regno) 4914 { 4915 struct bpf_verifier_state *vstate = env->cur_state; 4916 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4917 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4918 struct bpf_reg_state *reg; 4919 u8 *stype, type; 4920 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi); 4921 4922 stype = reg_state->stack[spi].slot_type; 4923 reg = ®_state->stack[spi].spilled_ptr; 4924 4925 mark_stack_slot_scratched(env, spi); 4926 check_fastcall_stack_contract(env, state, env->insn_idx, off); 4927 4928 if (is_spilled_reg(®_state->stack[spi])) { 4929 u8 spill_size = 1; 4930 4931 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4932 spill_size++; 4933 4934 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4935 if (reg->type != SCALAR_VALUE) { 4936 verbose_linfo(env, env->insn_idx, "; "); 4937 verbose(env, "invalid size of register fill\n"); 4938 return -EACCES; 4939 } 4940 4941 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4942 if (dst_regno < 0) 4943 return 0; 4944 4945 if (size <= spill_size && 4946 bpf_stack_narrow_access_ok(off, size, spill_size)) { 4947 /* The earlier check_reg_arg() has decided the 4948 * subreg_def for this insn. Save it first. 4949 */ 4950 s32 subreg_def = state->regs[dst_regno].subreg_def; 4951 4952 copy_register_state(&state->regs[dst_regno], reg); 4953 state->regs[dst_regno].subreg_def = subreg_def; 4954 4955 /* Break the relation on a narrowing fill. 4956 * coerce_reg_to_size will adjust the boundaries. 4957 */ 4958 if (get_reg_width(reg) > size * BITS_PER_BYTE) 4959 state->regs[dst_regno].id = 0; 4960 } else { 4961 int spill_cnt = 0, zero_cnt = 0; 4962 4963 for (i = 0; i < size; i++) { 4964 type = stype[(slot - i) % BPF_REG_SIZE]; 4965 if (type == STACK_SPILL) { 4966 spill_cnt++; 4967 continue; 4968 } 4969 if (type == STACK_MISC) 4970 continue; 4971 if (type == STACK_ZERO) { 4972 zero_cnt++; 4973 continue; 4974 } 4975 if (type == STACK_INVALID && env->allow_uninit_stack) 4976 continue; 4977 verbose(env, "invalid read from stack off %d+%d size %d\n", 4978 off, i, size); 4979 return -EACCES; 4980 } 4981 4982 if (spill_cnt == size && 4983 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 4984 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4985 /* this IS register fill, so keep insn_flags */ 4986 } else if (zero_cnt == size) { 4987 /* similarly to mark_reg_stack_read(), preserve zeroes */ 4988 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4989 insn_flags = 0; /* not restoring original register state */ 4990 } else { 4991 mark_reg_unknown(env, state->regs, dst_regno); 4992 insn_flags = 0; /* not restoring original register state */ 4993 } 4994 } 4995 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4996 } else if (dst_regno >= 0) { 4997 /* restore register state from stack */ 4998 copy_register_state(&state->regs[dst_regno], reg); 4999 /* mark reg as written since spilled pointer state likely 5000 * has its liveness marks cleared by is_state_visited() 5001 * which resets stack/reg liveness for state transitions 5002 */ 5003 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 5004 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 5005 /* If dst_regno==-1, the caller is asking us whether 5006 * it is acceptable to use this value as a SCALAR_VALUE 5007 * (e.g. for XADD). 5008 * We must not allow unprivileged callers to do that 5009 * with spilled pointers. 5010 */ 5011 verbose(env, "leaking pointer from stack off %d\n", 5012 off); 5013 return -EACCES; 5014 } 5015 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 5016 } else { 5017 for (i = 0; i < size; i++) { 5018 type = stype[(slot - i) % BPF_REG_SIZE]; 5019 if (type == STACK_MISC) 5020 continue; 5021 if (type == STACK_ZERO) 5022 continue; 5023 if (type == STACK_INVALID && env->allow_uninit_stack) 5024 continue; 5025 verbose(env, "invalid read from stack off %d+%d size %d\n", 5026 off, i, size); 5027 return -EACCES; 5028 } 5029 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 5030 if (dst_regno >= 0) 5031 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 5032 insn_flags = 0; /* we are not restoring spilled register */ 5033 } 5034 if (insn_flags) 5035 return push_jmp_history(env, env->cur_state, insn_flags, 0); 5036 return 0; 5037 } 5038 5039 enum bpf_access_src { 5040 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 5041 ACCESS_HELPER = 2, /* the access is performed by a helper */ 5042 }; 5043 5044 static int check_stack_range_initialized(struct bpf_verifier_env *env, 5045 int regno, int off, int access_size, 5046 bool zero_size_allowed, 5047 enum bpf_access_src type, 5048 struct bpf_call_arg_meta *meta); 5049 5050 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 5051 { 5052 return cur_regs(env) + regno; 5053 } 5054 5055 /* Read the stack at 'ptr_regno + off' and put the result into the register 5056 * 'dst_regno'. 5057 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 5058 * but not its variable offset. 5059 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 5060 * 5061 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 5062 * filling registers (i.e. reads of spilled register cannot be detected when 5063 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 5064 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 5065 * offset; for a fixed offset check_stack_read_fixed_off should be used 5066 * instead. 5067 */ 5068 static int check_stack_read_var_off(struct bpf_verifier_env *env, 5069 int ptr_regno, int off, int size, int dst_regno) 5070 { 5071 /* The state of the source register. */ 5072 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5073 struct bpf_func_state *ptr_state = func(env, reg); 5074 int err; 5075 int min_off, max_off; 5076 5077 /* Note that we pass a NULL meta, so raw access will not be permitted. 5078 */ 5079 err = check_stack_range_initialized(env, ptr_regno, off, size, 5080 false, ACCESS_DIRECT, NULL); 5081 if (err) 5082 return err; 5083 5084 min_off = reg->smin_value + off; 5085 max_off = reg->smax_value + off; 5086 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 5087 check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off); 5088 return 0; 5089 } 5090 5091 /* check_stack_read dispatches to check_stack_read_fixed_off or 5092 * check_stack_read_var_off. 5093 * 5094 * The caller must ensure that the offset falls within the allocated stack 5095 * bounds. 5096 * 5097 * 'dst_regno' is a register which will receive the value from the stack. It 5098 * can be -1, meaning that the read value is not going to a register. 5099 */ 5100 static int check_stack_read(struct bpf_verifier_env *env, 5101 int ptr_regno, int off, int size, 5102 int dst_regno) 5103 { 5104 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5105 struct bpf_func_state *state = func(env, reg); 5106 int err; 5107 /* Some accesses are only permitted with a static offset. */ 5108 bool var_off = !tnum_is_const(reg->var_off); 5109 5110 /* The offset is required to be static when reads don't go to a 5111 * register, in order to not leak pointers (see 5112 * check_stack_read_fixed_off). 5113 */ 5114 if (dst_regno < 0 && var_off) { 5115 char tn_buf[48]; 5116 5117 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5118 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 5119 tn_buf, off, size); 5120 return -EACCES; 5121 } 5122 /* Variable offset is prohibited for unprivileged mode for simplicity 5123 * since it requires corresponding support in Spectre masking for stack 5124 * ALU. See also retrieve_ptr_limit(). The check in 5125 * check_stack_access_for_ptr_arithmetic() called by 5126 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 5127 * with variable offsets, therefore no check is required here. Further, 5128 * just checking it here would be insufficient as speculative stack 5129 * writes could still lead to unsafe speculative behaviour. 5130 */ 5131 if (!var_off) { 5132 off += reg->var_off.value; 5133 err = check_stack_read_fixed_off(env, state, off, size, 5134 dst_regno); 5135 } else { 5136 /* Variable offset stack reads need more conservative handling 5137 * than fixed offset ones. Note that dst_regno >= 0 on this 5138 * branch. 5139 */ 5140 err = check_stack_read_var_off(env, ptr_regno, off, size, 5141 dst_regno); 5142 } 5143 return err; 5144 } 5145 5146 5147 /* check_stack_write dispatches to check_stack_write_fixed_off or 5148 * check_stack_write_var_off. 5149 * 5150 * 'ptr_regno' is the register used as a pointer into the stack. 5151 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 5152 * 'value_regno' is the register whose value we're writing to the stack. It can 5153 * be -1, meaning that we're not writing from a register. 5154 * 5155 * The caller must ensure that the offset falls within the maximum stack size. 5156 */ 5157 static int check_stack_write(struct bpf_verifier_env *env, 5158 int ptr_regno, int off, int size, 5159 int value_regno, int insn_idx) 5160 { 5161 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5162 struct bpf_func_state *state = func(env, reg); 5163 int err; 5164 5165 if (tnum_is_const(reg->var_off)) { 5166 off += reg->var_off.value; 5167 err = check_stack_write_fixed_off(env, state, off, size, 5168 value_regno, insn_idx); 5169 } else { 5170 /* Variable offset stack reads need more conservative handling 5171 * than fixed offset ones. 5172 */ 5173 err = check_stack_write_var_off(env, state, 5174 ptr_regno, off, size, 5175 value_regno, insn_idx); 5176 } 5177 return err; 5178 } 5179 5180 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 5181 int off, int size, enum bpf_access_type type) 5182 { 5183 struct bpf_reg_state *regs = cur_regs(env); 5184 struct bpf_map *map = regs[regno].map_ptr; 5185 u32 cap = bpf_map_flags_to_cap(map); 5186 5187 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 5188 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 5189 map->value_size, off, size); 5190 return -EACCES; 5191 } 5192 5193 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 5194 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 5195 map->value_size, off, size); 5196 return -EACCES; 5197 } 5198 5199 return 0; 5200 } 5201 5202 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 5203 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 5204 int off, int size, u32 mem_size, 5205 bool zero_size_allowed) 5206 { 5207 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 5208 struct bpf_reg_state *reg; 5209 5210 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 5211 return 0; 5212 5213 reg = &cur_regs(env)[regno]; 5214 switch (reg->type) { 5215 case PTR_TO_MAP_KEY: 5216 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 5217 mem_size, off, size); 5218 break; 5219 case PTR_TO_MAP_VALUE: 5220 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 5221 mem_size, off, size); 5222 break; 5223 case PTR_TO_PACKET: 5224 case PTR_TO_PACKET_META: 5225 case PTR_TO_PACKET_END: 5226 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 5227 off, size, regno, reg->id, off, mem_size); 5228 break; 5229 case PTR_TO_MEM: 5230 default: 5231 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 5232 mem_size, off, size); 5233 } 5234 5235 return -EACCES; 5236 } 5237 5238 /* check read/write into a memory region with possible variable offset */ 5239 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 5240 int off, int size, u32 mem_size, 5241 bool zero_size_allowed) 5242 { 5243 struct bpf_verifier_state *vstate = env->cur_state; 5244 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5245 struct bpf_reg_state *reg = &state->regs[regno]; 5246 int err; 5247 5248 /* We may have adjusted the register pointing to memory region, so we 5249 * need to try adding each of min_value and max_value to off 5250 * to make sure our theoretical access will be safe. 5251 * 5252 * The minimum value is only important with signed 5253 * comparisons where we can't assume the floor of a 5254 * value is 0. If we are using signed variables for our 5255 * index'es we need to make sure that whatever we use 5256 * will have a set floor within our range. 5257 */ 5258 if (reg->smin_value < 0 && 5259 (reg->smin_value == S64_MIN || 5260 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5261 reg->smin_value + off < 0)) { 5262 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5263 regno); 5264 return -EACCES; 5265 } 5266 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5267 mem_size, zero_size_allowed); 5268 if (err) { 5269 verbose(env, "R%d min value is outside of the allowed memory range\n", 5270 regno); 5271 return err; 5272 } 5273 5274 /* If we haven't set a max value then we need to bail since we can't be 5275 * sure we won't do bad things. 5276 * If reg->umax_value + off could overflow, treat that as unbounded too. 5277 */ 5278 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5279 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5280 regno); 5281 return -EACCES; 5282 } 5283 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5284 mem_size, zero_size_allowed); 5285 if (err) { 5286 verbose(env, "R%d max value is outside of the allowed memory range\n", 5287 regno); 5288 return err; 5289 } 5290 5291 return 0; 5292 } 5293 5294 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5295 const struct bpf_reg_state *reg, int regno, 5296 bool fixed_off_ok) 5297 { 5298 /* Access to this pointer-typed register or passing it to a helper 5299 * is only allowed in its original, unmodified form. 5300 */ 5301 5302 if (reg->off < 0) { 5303 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5304 reg_type_str(env, reg->type), regno, reg->off); 5305 return -EACCES; 5306 } 5307 5308 if (!fixed_off_ok && reg->off) { 5309 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5310 reg_type_str(env, reg->type), regno, reg->off); 5311 return -EACCES; 5312 } 5313 5314 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5315 char tn_buf[48]; 5316 5317 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5318 verbose(env, "variable %s access var_off=%s disallowed\n", 5319 reg_type_str(env, reg->type), tn_buf); 5320 return -EACCES; 5321 } 5322 5323 return 0; 5324 } 5325 5326 static int check_ptr_off_reg(struct bpf_verifier_env *env, 5327 const struct bpf_reg_state *reg, int regno) 5328 { 5329 return __check_ptr_off_reg(env, reg, regno, false); 5330 } 5331 5332 static int map_kptr_match_type(struct bpf_verifier_env *env, 5333 struct btf_field *kptr_field, 5334 struct bpf_reg_state *reg, u32 regno) 5335 { 5336 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5337 int perm_flags; 5338 const char *reg_name = ""; 5339 5340 if (btf_is_kernel(reg->btf)) { 5341 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5342 5343 /* Only unreferenced case accepts untrusted pointers */ 5344 if (kptr_field->type == BPF_KPTR_UNREF) 5345 perm_flags |= PTR_UNTRUSTED; 5346 } else { 5347 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5348 if (kptr_field->type == BPF_KPTR_PERCPU) 5349 perm_flags |= MEM_PERCPU; 5350 } 5351 5352 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5353 goto bad_type; 5354 5355 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5356 reg_name = btf_type_name(reg->btf, reg->btf_id); 5357 5358 /* For ref_ptr case, release function check should ensure we get one 5359 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5360 * normal store of unreferenced kptr, we must ensure var_off is zero. 5361 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5362 * reg->off and reg->ref_obj_id are not needed here. 5363 */ 5364 if (__check_ptr_off_reg(env, reg, regno, true)) 5365 return -EACCES; 5366 5367 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5368 * we also need to take into account the reg->off. 5369 * 5370 * We want to support cases like: 5371 * 5372 * struct foo { 5373 * struct bar br; 5374 * struct baz bz; 5375 * }; 5376 * 5377 * struct foo *v; 5378 * v = func(); // PTR_TO_BTF_ID 5379 * val->foo = v; // reg->off is zero, btf and btf_id match type 5380 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5381 * // first member type of struct after comparison fails 5382 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5383 * // to match type 5384 * 5385 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5386 * is zero. We must also ensure that btf_struct_ids_match does not walk 5387 * the struct to match type against first member of struct, i.e. reject 5388 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5389 * strict mode to true for type match. 5390 */ 5391 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5392 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5393 kptr_field->type != BPF_KPTR_UNREF)) 5394 goto bad_type; 5395 return 0; 5396 bad_type: 5397 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5398 reg_type_str(env, reg->type), reg_name); 5399 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5400 if (kptr_field->type == BPF_KPTR_UNREF) 5401 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5402 targ_name); 5403 else 5404 verbose(env, "\n"); 5405 return -EINVAL; 5406 } 5407 5408 static bool in_sleepable(struct bpf_verifier_env *env) 5409 { 5410 return env->prog->sleepable || 5411 (env->cur_state && env->cur_state->in_sleepable); 5412 } 5413 5414 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5415 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5416 */ 5417 static bool in_rcu_cs(struct bpf_verifier_env *env) 5418 { 5419 return env->cur_state->active_rcu_lock || 5420 env->cur_state->active_lock.ptr || 5421 !in_sleepable(env); 5422 } 5423 5424 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5425 BTF_SET_START(rcu_protected_types) 5426 BTF_ID(struct, prog_test_ref_kfunc) 5427 #ifdef CONFIG_CGROUPS 5428 BTF_ID(struct, cgroup) 5429 #endif 5430 #ifdef CONFIG_BPF_JIT 5431 BTF_ID(struct, bpf_cpumask) 5432 #endif 5433 BTF_ID(struct, task_struct) 5434 BTF_ID(struct, bpf_crypto_ctx) 5435 BTF_SET_END(rcu_protected_types) 5436 5437 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5438 { 5439 if (!btf_is_kernel(btf)) 5440 return true; 5441 return btf_id_set_contains(&rcu_protected_types, btf_id); 5442 } 5443 5444 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 5445 { 5446 struct btf_struct_meta *meta; 5447 5448 if (btf_is_kernel(kptr_field->kptr.btf)) 5449 return NULL; 5450 5451 meta = btf_find_struct_meta(kptr_field->kptr.btf, 5452 kptr_field->kptr.btf_id); 5453 5454 return meta ? meta->record : NULL; 5455 } 5456 5457 static bool rcu_safe_kptr(const struct btf_field *field) 5458 { 5459 const struct btf_field_kptr *kptr = &field->kptr; 5460 5461 return field->type == BPF_KPTR_PERCPU || 5462 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 5463 } 5464 5465 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 5466 { 5467 struct btf_record *rec; 5468 u32 ret; 5469 5470 ret = PTR_MAYBE_NULL; 5471 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 5472 ret |= MEM_RCU; 5473 if (kptr_field->type == BPF_KPTR_PERCPU) 5474 ret |= MEM_PERCPU; 5475 else if (!btf_is_kernel(kptr_field->kptr.btf)) 5476 ret |= MEM_ALLOC; 5477 5478 rec = kptr_pointee_btf_record(kptr_field); 5479 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 5480 ret |= NON_OWN_REF; 5481 } else { 5482 ret |= PTR_UNTRUSTED; 5483 } 5484 5485 return ret; 5486 } 5487 5488 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5489 int value_regno, int insn_idx, 5490 struct btf_field *kptr_field) 5491 { 5492 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5493 int class = BPF_CLASS(insn->code); 5494 struct bpf_reg_state *val_reg; 5495 5496 /* Things we already checked for in check_map_access and caller: 5497 * - Reject cases where variable offset may touch kptr 5498 * - size of access (must be BPF_DW) 5499 * - tnum_is_const(reg->var_off) 5500 * - kptr_field->offset == off + reg->var_off.value 5501 */ 5502 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5503 if (BPF_MODE(insn->code) != BPF_MEM) { 5504 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5505 return -EACCES; 5506 } 5507 5508 /* We only allow loading referenced kptr, since it will be marked as 5509 * untrusted, similar to unreferenced kptr. 5510 */ 5511 if (class != BPF_LDX && 5512 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 5513 verbose(env, "store to referenced kptr disallowed\n"); 5514 return -EACCES; 5515 } 5516 5517 if (class == BPF_LDX) { 5518 val_reg = reg_state(env, value_regno); 5519 /* We can simply mark the value_regno receiving the pointer 5520 * value from map as PTR_TO_BTF_ID, with the correct type. 5521 */ 5522 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5523 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field)); 5524 } else if (class == BPF_STX) { 5525 val_reg = reg_state(env, value_regno); 5526 if (!register_is_null(val_reg) && 5527 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5528 return -EACCES; 5529 } else if (class == BPF_ST) { 5530 if (insn->imm) { 5531 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5532 kptr_field->offset); 5533 return -EACCES; 5534 } 5535 } else { 5536 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5537 return -EACCES; 5538 } 5539 return 0; 5540 } 5541 5542 /* check read/write into a map element with possible variable offset */ 5543 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5544 int off, int size, bool zero_size_allowed, 5545 enum bpf_access_src src) 5546 { 5547 struct bpf_verifier_state *vstate = env->cur_state; 5548 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5549 struct bpf_reg_state *reg = &state->regs[regno]; 5550 struct bpf_map *map = reg->map_ptr; 5551 struct btf_record *rec; 5552 int err, i; 5553 5554 err = check_mem_region_access(env, regno, off, size, map->value_size, 5555 zero_size_allowed); 5556 if (err) 5557 return err; 5558 5559 if (IS_ERR_OR_NULL(map->record)) 5560 return 0; 5561 rec = map->record; 5562 for (i = 0; i < rec->cnt; i++) { 5563 struct btf_field *field = &rec->fields[i]; 5564 u32 p = field->offset; 5565 5566 /* If any part of a field can be touched by load/store, reject 5567 * this program. To check that [x1, x2) overlaps with [y1, y2), 5568 * it is sufficient to check x1 < y2 && y1 < x2. 5569 */ 5570 if (reg->smin_value + off < p + field->size && 5571 p < reg->umax_value + off + size) { 5572 switch (field->type) { 5573 case BPF_KPTR_UNREF: 5574 case BPF_KPTR_REF: 5575 case BPF_KPTR_PERCPU: 5576 if (src != ACCESS_DIRECT) { 5577 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 5578 return -EACCES; 5579 } 5580 if (!tnum_is_const(reg->var_off)) { 5581 verbose(env, "kptr access cannot have variable offset\n"); 5582 return -EACCES; 5583 } 5584 if (p != off + reg->var_off.value) { 5585 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 5586 p, off + reg->var_off.value); 5587 return -EACCES; 5588 } 5589 if (size != bpf_size_to_bytes(BPF_DW)) { 5590 verbose(env, "kptr access size must be BPF_DW\n"); 5591 return -EACCES; 5592 } 5593 break; 5594 default: 5595 verbose(env, "%s cannot be accessed directly by load/store\n", 5596 btf_field_type_name(field->type)); 5597 return -EACCES; 5598 } 5599 } 5600 } 5601 return 0; 5602 } 5603 5604 #define MAX_PACKET_OFF 0xffff 5605 5606 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5607 const struct bpf_call_arg_meta *meta, 5608 enum bpf_access_type t) 5609 { 5610 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5611 5612 switch (prog_type) { 5613 /* Program types only with direct read access go here! */ 5614 case BPF_PROG_TYPE_LWT_IN: 5615 case BPF_PROG_TYPE_LWT_OUT: 5616 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5617 case BPF_PROG_TYPE_SK_REUSEPORT: 5618 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5619 case BPF_PROG_TYPE_CGROUP_SKB: 5620 if (t == BPF_WRITE) 5621 return false; 5622 fallthrough; 5623 5624 /* Program types with direct read + write access go here! */ 5625 case BPF_PROG_TYPE_SCHED_CLS: 5626 case BPF_PROG_TYPE_SCHED_ACT: 5627 case BPF_PROG_TYPE_XDP: 5628 case BPF_PROG_TYPE_LWT_XMIT: 5629 case BPF_PROG_TYPE_SK_SKB: 5630 case BPF_PROG_TYPE_SK_MSG: 5631 if (meta) 5632 return meta->pkt_access; 5633 5634 env->seen_direct_write = true; 5635 return true; 5636 5637 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5638 if (t == BPF_WRITE) 5639 env->seen_direct_write = true; 5640 5641 return true; 5642 5643 default: 5644 return false; 5645 } 5646 } 5647 5648 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5649 int size, bool zero_size_allowed) 5650 { 5651 struct bpf_reg_state *regs = cur_regs(env); 5652 struct bpf_reg_state *reg = ®s[regno]; 5653 int err; 5654 5655 /* We may have added a variable offset to the packet pointer; but any 5656 * reg->range we have comes after that. We are only checking the fixed 5657 * offset. 5658 */ 5659 5660 /* We don't allow negative numbers, because we aren't tracking enough 5661 * detail to prove they're safe. 5662 */ 5663 if (reg->smin_value < 0) { 5664 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5665 regno); 5666 return -EACCES; 5667 } 5668 5669 err = reg->range < 0 ? -EINVAL : 5670 __check_mem_access(env, regno, off, size, reg->range, 5671 zero_size_allowed); 5672 if (err) { 5673 verbose(env, "R%d offset is outside of the packet\n", regno); 5674 return err; 5675 } 5676 5677 /* __check_mem_access has made sure "off + size - 1" is within u16. 5678 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5679 * otherwise find_good_pkt_pointers would have refused to set range info 5680 * that __check_mem_access would have rejected this pkt access. 5681 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5682 */ 5683 env->prog->aux->max_pkt_offset = 5684 max_t(u32, env->prog->aux->max_pkt_offset, 5685 off + reg->umax_value + size - 1); 5686 5687 return err; 5688 } 5689 5690 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5691 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5692 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5693 struct btf **btf, u32 *btf_id, bool *is_retval, bool is_ldsx) 5694 { 5695 struct bpf_insn_access_aux info = { 5696 .reg_type = *reg_type, 5697 .log = &env->log, 5698 .is_retval = false, 5699 .is_ldsx = is_ldsx, 5700 }; 5701 5702 if (env->ops->is_valid_access && 5703 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5704 /* A non zero info.ctx_field_size indicates that this field is a 5705 * candidate for later verifier transformation to load the whole 5706 * field and then apply a mask when accessed with a narrower 5707 * access than actual ctx access size. A zero info.ctx_field_size 5708 * will only allow for whole field access and rejects any other 5709 * type of narrower access. 5710 */ 5711 *reg_type = info.reg_type; 5712 *is_retval = info.is_retval; 5713 5714 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5715 *btf = info.btf; 5716 *btf_id = info.btf_id; 5717 } else { 5718 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5719 } 5720 /* remember the offset of last byte accessed in ctx */ 5721 if (env->prog->aux->max_ctx_offset < off + size) 5722 env->prog->aux->max_ctx_offset = off + size; 5723 return 0; 5724 } 5725 5726 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5727 return -EACCES; 5728 } 5729 5730 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5731 int size) 5732 { 5733 if (size < 0 || off < 0 || 5734 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5735 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5736 off, size); 5737 return -EACCES; 5738 } 5739 return 0; 5740 } 5741 5742 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5743 u32 regno, int off, int size, 5744 enum bpf_access_type t) 5745 { 5746 struct bpf_reg_state *regs = cur_regs(env); 5747 struct bpf_reg_state *reg = ®s[regno]; 5748 struct bpf_insn_access_aux info = {}; 5749 bool valid; 5750 5751 if (reg->smin_value < 0) { 5752 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5753 regno); 5754 return -EACCES; 5755 } 5756 5757 switch (reg->type) { 5758 case PTR_TO_SOCK_COMMON: 5759 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5760 break; 5761 case PTR_TO_SOCKET: 5762 valid = bpf_sock_is_valid_access(off, size, t, &info); 5763 break; 5764 case PTR_TO_TCP_SOCK: 5765 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5766 break; 5767 case PTR_TO_XDP_SOCK: 5768 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5769 break; 5770 default: 5771 valid = false; 5772 } 5773 5774 5775 if (valid) { 5776 env->insn_aux_data[insn_idx].ctx_field_size = 5777 info.ctx_field_size; 5778 return 0; 5779 } 5780 5781 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5782 regno, reg_type_str(env, reg->type), off, size); 5783 5784 return -EACCES; 5785 } 5786 5787 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5788 { 5789 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5790 } 5791 5792 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5793 { 5794 const struct bpf_reg_state *reg = reg_state(env, regno); 5795 5796 return reg->type == PTR_TO_CTX; 5797 } 5798 5799 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5800 { 5801 const struct bpf_reg_state *reg = reg_state(env, regno); 5802 5803 return type_is_sk_pointer(reg->type); 5804 } 5805 5806 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5807 { 5808 const struct bpf_reg_state *reg = reg_state(env, regno); 5809 5810 return type_is_pkt_pointer(reg->type); 5811 } 5812 5813 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5814 { 5815 const struct bpf_reg_state *reg = reg_state(env, regno); 5816 5817 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5818 return reg->type == PTR_TO_FLOW_KEYS; 5819 } 5820 5821 static bool is_arena_reg(struct bpf_verifier_env *env, int regno) 5822 { 5823 const struct bpf_reg_state *reg = reg_state(env, regno); 5824 5825 return reg->type == PTR_TO_ARENA; 5826 } 5827 5828 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5829 #ifdef CONFIG_NET 5830 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5831 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5832 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5833 #endif 5834 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5835 }; 5836 5837 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5838 { 5839 /* A referenced register is always trusted. */ 5840 if (reg->ref_obj_id) 5841 return true; 5842 5843 /* Types listed in the reg2btf_ids are always trusted */ 5844 if (reg2btf_ids[base_type(reg->type)] && 5845 !bpf_type_has_unsafe_modifiers(reg->type)) 5846 return true; 5847 5848 /* If a register is not referenced, it is trusted if it has the 5849 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5850 * other type modifiers may be safe, but we elect to take an opt-in 5851 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5852 * not. 5853 * 5854 * Eventually, we should make PTR_TRUSTED the single source of truth 5855 * for whether a register is trusted. 5856 */ 5857 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5858 !bpf_type_has_unsafe_modifiers(reg->type); 5859 } 5860 5861 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5862 { 5863 return reg->type & MEM_RCU; 5864 } 5865 5866 static void clear_trusted_flags(enum bpf_type_flag *flag) 5867 { 5868 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5869 } 5870 5871 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5872 const struct bpf_reg_state *reg, 5873 int off, int size, bool strict) 5874 { 5875 struct tnum reg_off; 5876 int ip_align; 5877 5878 /* Byte size accesses are always allowed. */ 5879 if (!strict || size == 1) 5880 return 0; 5881 5882 /* For platforms that do not have a Kconfig enabling 5883 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5884 * NET_IP_ALIGN is universally set to '2'. And on platforms 5885 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5886 * to this code only in strict mode where we want to emulate 5887 * the NET_IP_ALIGN==2 checking. Therefore use an 5888 * unconditional IP align value of '2'. 5889 */ 5890 ip_align = 2; 5891 5892 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5893 if (!tnum_is_aligned(reg_off, size)) { 5894 char tn_buf[48]; 5895 5896 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5897 verbose(env, 5898 "misaligned packet access off %d+%s+%d+%d size %d\n", 5899 ip_align, tn_buf, reg->off, off, size); 5900 return -EACCES; 5901 } 5902 5903 return 0; 5904 } 5905 5906 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5907 const struct bpf_reg_state *reg, 5908 const char *pointer_desc, 5909 int off, int size, bool strict) 5910 { 5911 struct tnum reg_off; 5912 5913 /* Byte size accesses are always allowed. */ 5914 if (!strict || size == 1) 5915 return 0; 5916 5917 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5918 if (!tnum_is_aligned(reg_off, size)) { 5919 char tn_buf[48]; 5920 5921 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5922 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5923 pointer_desc, tn_buf, reg->off, off, size); 5924 return -EACCES; 5925 } 5926 5927 return 0; 5928 } 5929 5930 static int check_ptr_alignment(struct bpf_verifier_env *env, 5931 const struct bpf_reg_state *reg, int off, 5932 int size, bool strict_alignment_once) 5933 { 5934 bool strict = env->strict_alignment || strict_alignment_once; 5935 const char *pointer_desc = ""; 5936 5937 switch (reg->type) { 5938 case PTR_TO_PACKET: 5939 case PTR_TO_PACKET_META: 5940 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5941 * right in front, treat it the very same way. 5942 */ 5943 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5944 case PTR_TO_FLOW_KEYS: 5945 pointer_desc = "flow keys "; 5946 break; 5947 case PTR_TO_MAP_KEY: 5948 pointer_desc = "key "; 5949 break; 5950 case PTR_TO_MAP_VALUE: 5951 pointer_desc = "value "; 5952 break; 5953 case PTR_TO_CTX: 5954 pointer_desc = "context "; 5955 break; 5956 case PTR_TO_STACK: 5957 pointer_desc = "stack "; 5958 /* The stack spill tracking logic in check_stack_write_fixed_off() 5959 * and check_stack_read_fixed_off() relies on stack accesses being 5960 * aligned. 5961 */ 5962 strict = true; 5963 break; 5964 case PTR_TO_SOCKET: 5965 pointer_desc = "sock "; 5966 break; 5967 case PTR_TO_SOCK_COMMON: 5968 pointer_desc = "sock_common "; 5969 break; 5970 case PTR_TO_TCP_SOCK: 5971 pointer_desc = "tcp_sock "; 5972 break; 5973 case PTR_TO_XDP_SOCK: 5974 pointer_desc = "xdp_sock "; 5975 break; 5976 case PTR_TO_ARENA: 5977 return 0; 5978 default: 5979 break; 5980 } 5981 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5982 strict); 5983 } 5984 5985 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth) 5986 { 5987 if (env->prog->jit_requested) 5988 return round_up(stack_depth, 16); 5989 5990 /* round up to 32-bytes, since this is granularity 5991 * of interpreter stack size 5992 */ 5993 return round_up(max_t(u32, stack_depth, 1), 32); 5994 } 5995 5996 /* starting from main bpf function walk all instructions of the function 5997 * and recursively walk all callees that given function can call. 5998 * Ignore jump and exit insns. 5999 * Since recursion is prevented by check_cfg() this algorithm 6000 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 6001 */ 6002 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx) 6003 { 6004 struct bpf_subprog_info *subprog = env->subprog_info; 6005 struct bpf_insn *insn = env->prog->insnsi; 6006 int depth = 0, frame = 0, i, subprog_end; 6007 bool tail_call_reachable = false; 6008 int ret_insn[MAX_CALL_FRAMES]; 6009 int ret_prog[MAX_CALL_FRAMES]; 6010 int j; 6011 6012 i = subprog[idx].start; 6013 process_func: 6014 /* protect against potential stack overflow that might happen when 6015 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 6016 * depth for such case down to 256 so that the worst case scenario 6017 * would result in 8k stack size (32 which is tailcall limit * 256 = 6018 * 8k). 6019 * 6020 * To get the idea what might happen, see an example: 6021 * func1 -> sub rsp, 128 6022 * subfunc1 -> sub rsp, 256 6023 * tailcall1 -> add rsp, 256 6024 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 6025 * subfunc2 -> sub rsp, 64 6026 * subfunc22 -> sub rsp, 128 6027 * tailcall2 -> add rsp, 128 6028 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 6029 * 6030 * tailcall will unwind the current stack frame but it will not get rid 6031 * of caller's stack as shown on the example above. 6032 */ 6033 if (idx && subprog[idx].has_tail_call && depth >= 256) { 6034 verbose(env, 6035 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 6036 depth); 6037 return -EACCES; 6038 } 6039 depth += round_up_stack_depth(env, subprog[idx].stack_depth); 6040 if (depth > MAX_BPF_STACK) { 6041 verbose(env, "combined stack size of %d calls is %d. Too large\n", 6042 frame + 1, depth); 6043 return -EACCES; 6044 } 6045 continue_func: 6046 subprog_end = subprog[idx + 1].start; 6047 for (; i < subprog_end; i++) { 6048 int next_insn, sidx; 6049 6050 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 6051 bool err = false; 6052 6053 if (!is_bpf_throw_kfunc(insn + i)) 6054 continue; 6055 if (subprog[idx].is_cb) 6056 err = true; 6057 for (int c = 0; c < frame && !err; c++) { 6058 if (subprog[ret_prog[c]].is_cb) { 6059 err = true; 6060 break; 6061 } 6062 } 6063 if (!err) 6064 continue; 6065 verbose(env, 6066 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 6067 i, idx); 6068 return -EINVAL; 6069 } 6070 6071 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 6072 continue; 6073 /* remember insn and function to return to */ 6074 ret_insn[frame] = i + 1; 6075 ret_prog[frame] = idx; 6076 6077 /* find the callee */ 6078 next_insn = i + insn[i].imm + 1; 6079 sidx = find_subprog(env, next_insn); 6080 if (sidx < 0) { 6081 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 6082 next_insn); 6083 return -EFAULT; 6084 } 6085 if (subprog[sidx].is_async_cb) { 6086 if (subprog[sidx].has_tail_call) { 6087 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 6088 return -EFAULT; 6089 } 6090 /* async callbacks don't increase bpf prog stack size unless called directly */ 6091 if (!bpf_pseudo_call(insn + i)) 6092 continue; 6093 if (subprog[sidx].is_exception_cb) { 6094 verbose(env, "insn %d cannot call exception cb directly\n", i); 6095 return -EINVAL; 6096 } 6097 } 6098 i = next_insn; 6099 idx = sidx; 6100 6101 if (subprog[idx].has_tail_call) 6102 tail_call_reachable = true; 6103 6104 frame++; 6105 if (frame >= MAX_CALL_FRAMES) { 6106 verbose(env, "the call stack of %d frames is too deep !\n", 6107 frame); 6108 return -E2BIG; 6109 } 6110 goto process_func; 6111 } 6112 /* if tail call got detected across bpf2bpf calls then mark each of the 6113 * currently present subprog frames as tail call reachable subprogs; 6114 * this info will be utilized by JIT so that we will be preserving the 6115 * tail call counter throughout bpf2bpf calls combined with tailcalls 6116 */ 6117 if (tail_call_reachable) 6118 for (j = 0; j < frame; j++) { 6119 if (subprog[ret_prog[j]].is_exception_cb) { 6120 verbose(env, "cannot tail call within exception cb\n"); 6121 return -EINVAL; 6122 } 6123 subprog[ret_prog[j]].tail_call_reachable = true; 6124 } 6125 if (subprog[0].tail_call_reachable) 6126 env->prog->aux->tail_call_reachable = true; 6127 6128 /* end of for() loop means the last insn of the 'subprog' 6129 * was reached. Doesn't matter whether it was JA or EXIT 6130 */ 6131 if (frame == 0) 6132 return 0; 6133 depth -= round_up_stack_depth(env, subprog[idx].stack_depth); 6134 frame--; 6135 i = ret_insn[frame]; 6136 idx = ret_prog[frame]; 6137 goto continue_func; 6138 } 6139 6140 static int check_max_stack_depth(struct bpf_verifier_env *env) 6141 { 6142 struct bpf_subprog_info *si = env->subprog_info; 6143 int ret; 6144 6145 for (int i = 0; i < env->subprog_cnt; i++) { 6146 if (!i || si[i].is_async_cb) { 6147 ret = check_max_stack_depth_subprog(env, i); 6148 if (ret < 0) 6149 return ret; 6150 } 6151 continue; 6152 } 6153 return 0; 6154 } 6155 6156 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 6157 static int get_callee_stack_depth(struct bpf_verifier_env *env, 6158 const struct bpf_insn *insn, int idx) 6159 { 6160 int start = idx + insn->imm + 1, subprog; 6161 6162 subprog = find_subprog(env, start); 6163 if (subprog < 0) { 6164 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 6165 start); 6166 return -EFAULT; 6167 } 6168 return env->subprog_info[subprog].stack_depth; 6169 } 6170 #endif 6171 6172 static int __check_buffer_access(struct bpf_verifier_env *env, 6173 const char *buf_info, 6174 const struct bpf_reg_state *reg, 6175 int regno, int off, int size) 6176 { 6177 if (off < 0) { 6178 verbose(env, 6179 "R%d invalid %s buffer access: off=%d, size=%d\n", 6180 regno, buf_info, off, size); 6181 return -EACCES; 6182 } 6183 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6184 char tn_buf[48]; 6185 6186 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6187 verbose(env, 6188 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 6189 regno, off, tn_buf); 6190 return -EACCES; 6191 } 6192 6193 return 0; 6194 } 6195 6196 static int check_tp_buffer_access(struct bpf_verifier_env *env, 6197 const struct bpf_reg_state *reg, 6198 int regno, int off, int size) 6199 { 6200 int err; 6201 6202 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 6203 if (err) 6204 return err; 6205 6206 if (off + size > env->prog->aux->max_tp_access) 6207 env->prog->aux->max_tp_access = off + size; 6208 6209 return 0; 6210 } 6211 6212 static int check_buffer_access(struct bpf_verifier_env *env, 6213 const struct bpf_reg_state *reg, 6214 int regno, int off, int size, 6215 bool zero_size_allowed, 6216 u32 *max_access) 6217 { 6218 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 6219 int err; 6220 6221 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 6222 if (err) 6223 return err; 6224 6225 if (off + size > *max_access) 6226 *max_access = off + size; 6227 6228 return 0; 6229 } 6230 6231 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 6232 static void zext_32_to_64(struct bpf_reg_state *reg) 6233 { 6234 reg->var_off = tnum_subreg(reg->var_off); 6235 __reg_assign_32_into_64(reg); 6236 } 6237 6238 /* truncate register to smaller size (in bytes) 6239 * must be called with size < BPF_REG_SIZE 6240 */ 6241 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 6242 { 6243 u64 mask; 6244 6245 /* clear high bits in bit representation */ 6246 reg->var_off = tnum_cast(reg->var_off, size); 6247 6248 /* fix arithmetic bounds */ 6249 mask = ((u64)1 << (size * 8)) - 1; 6250 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 6251 reg->umin_value &= mask; 6252 reg->umax_value &= mask; 6253 } else { 6254 reg->umin_value = 0; 6255 reg->umax_value = mask; 6256 } 6257 reg->smin_value = reg->umin_value; 6258 reg->smax_value = reg->umax_value; 6259 6260 /* If size is smaller than 32bit register the 32bit register 6261 * values are also truncated so we push 64-bit bounds into 6262 * 32-bit bounds. Above were truncated < 32-bits already. 6263 */ 6264 if (size < 4) 6265 __mark_reg32_unbounded(reg); 6266 6267 reg_bounds_sync(reg); 6268 } 6269 6270 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 6271 { 6272 if (size == 1) { 6273 reg->smin_value = reg->s32_min_value = S8_MIN; 6274 reg->smax_value = reg->s32_max_value = S8_MAX; 6275 } else if (size == 2) { 6276 reg->smin_value = reg->s32_min_value = S16_MIN; 6277 reg->smax_value = reg->s32_max_value = S16_MAX; 6278 } else { 6279 /* size == 4 */ 6280 reg->smin_value = reg->s32_min_value = S32_MIN; 6281 reg->smax_value = reg->s32_max_value = S32_MAX; 6282 } 6283 reg->umin_value = reg->u32_min_value = 0; 6284 reg->umax_value = U64_MAX; 6285 reg->u32_max_value = U32_MAX; 6286 reg->var_off = tnum_unknown; 6287 } 6288 6289 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6290 { 6291 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6292 u64 top_smax_value, top_smin_value; 6293 u64 num_bits = size * 8; 6294 6295 if (tnum_is_const(reg->var_off)) { 6296 u64_cval = reg->var_off.value; 6297 if (size == 1) 6298 reg->var_off = tnum_const((s8)u64_cval); 6299 else if (size == 2) 6300 reg->var_off = tnum_const((s16)u64_cval); 6301 else 6302 /* size == 4 */ 6303 reg->var_off = tnum_const((s32)u64_cval); 6304 6305 u64_cval = reg->var_off.value; 6306 reg->smax_value = reg->smin_value = u64_cval; 6307 reg->umax_value = reg->umin_value = u64_cval; 6308 reg->s32_max_value = reg->s32_min_value = u64_cval; 6309 reg->u32_max_value = reg->u32_min_value = u64_cval; 6310 return; 6311 } 6312 6313 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6314 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6315 6316 if (top_smax_value != top_smin_value) 6317 goto out; 6318 6319 /* find the s64_min and s64_min after sign extension */ 6320 if (size == 1) { 6321 init_s64_max = (s8)reg->smax_value; 6322 init_s64_min = (s8)reg->smin_value; 6323 } else if (size == 2) { 6324 init_s64_max = (s16)reg->smax_value; 6325 init_s64_min = (s16)reg->smin_value; 6326 } else { 6327 init_s64_max = (s32)reg->smax_value; 6328 init_s64_min = (s32)reg->smin_value; 6329 } 6330 6331 s64_max = max(init_s64_max, init_s64_min); 6332 s64_min = min(init_s64_max, init_s64_min); 6333 6334 /* both of s64_max/s64_min positive or negative */ 6335 if ((s64_max >= 0) == (s64_min >= 0)) { 6336 reg->smin_value = reg->s32_min_value = s64_min; 6337 reg->smax_value = reg->s32_max_value = s64_max; 6338 reg->umin_value = reg->u32_min_value = s64_min; 6339 reg->umax_value = reg->u32_max_value = s64_max; 6340 reg->var_off = tnum_range(s64_min, s64_max); 6341 return; 6342 } 6343 6344 out: 6345 set_sext64_default_val(reg, size); 6346 } 6347 6348 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6349 { 6350 if (size == 1) { 6351 reg->s32_min_value = S8_MIN; 6352 reg->s32_max_value = S8_MAX; 6353 } else { 6354 /* size == 2 */ 6355 reg->s32_min_value = S16_MIN; 6356 reg->s32_max_value = S16_MAX; 6357 } 6358 reg->u32_min_value = 0; 6359 reg->u32_max_value = U32_MAX; 6360 reg->var_off = tnum_subreg(tnum_unknown); 6361 } 6362 6363 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6364 { 6365 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6366 u32 top_smax_value, top_smin_value; 6367 u32 num_bits = size * 8; 6368 6369 if (tnum_is_const(reg->var_off)) { 6370 u32_val = reg->var_off.value; 6371 if (size == 1) 6372 reg->var_off = tnum_const((s8)u32_val); 6373 else 6374 reg->var_off = tnum_const((s16)u32_val); 6375 6376 u32_val = reg->var_off.value; 6377 reg->s32_min_value = reg->s32_max_value = u32_val; 6378 reg->u32_min_value = reg->u32_max_value = u32_val; 6379 return; 6380 } 6381 6382 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 6383 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 6384 6385 if (top_smax_value != top_smin_value) 6386 goto out; 6387 6388 /* find the s32_min and s32_min after sign extension */ 6389 if (size == 1) { 6390 init_s32_max = (s8)reg->s32_max_value; 6391 init_s32_min = (s8)reg->s32_min_value; 6392 } else { 6393 /* size == 2 */ 6394 init_s32_max = (s16)reg->s32_max_value; 6395 init_s32_min = (s16)reg->s32_min_value; 6396 } 6397 s32_max = max(init_s32_max, init_s32_min); 6398 s32_min = min(init_s32_max, init_s32_min); 6399 6400 if ((s32_min >= 0) == (s32_max >= 0)) { 6401 reg->s32_min_value = s32_min; 6402 reg->s32_max_value = s32_max; 6403 reg->u32_min_value = (u32)s32_min; 6404 reg->u32_max_value = (u32)s32_max; 6405 reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max)); 6406 return; 6407 } 6408 6409 out: 6410 set_sext32_default_val(reg, size); 6411 } 6412 6413 static bool bpf_map_is_rdonly(const struct bpf_map *map) 6414 { 6415 /* A map is considered read-only if the following condition are true: 6416 * 6417 * 1) BPF program side cannot change any of the map content. The 6418 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6419 * and was set at map creation time. 6420 * 2) The map value(s) have been initialized from user space by a 6421 * loader and then "frozen", such that no new map update/delete 6422 * operations from syscall side are possible for the rest of 6423 * the map's lifetime from that point onwards. 6424 * 3) Any parallel/pending map update/delete operations from syscall 6425 * side have been completed. Only after that point, it's safe to 6426 * assume that map value(s) are immutable. 6427 */ 6428 return (map->map_flags & BPF_F_RDONLY_PROG) && 6429 READ_ONCE(map->frozen) && 6430 !bpf_map_write_active(map); 6431 } 6432 6433 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6434 bool is_ldsx) 6435 { 6436 void *ptr; 6437 u64 addr; 6438 int err; 6439 6440 err = map->ops->map_direct_value_addr(map, &addr, off); 6441 if (err) 6442 return err; 6443 ptr = (void *)(long)addr + off; 6444 6445 switch (size) { 6446 case sizeof(u8): 6447 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6448 break; 6449 case sizeof(u16): 6450 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6451 break; 6452 case sizeof(u32): 6453 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6454 break; 6455 case sizeof(u64): 6456 *val = *(u64 *)ptr; 6457 break; 6458 default: 6459 return -EINVAL; 6460 } 6461 return 0; 6462 } 6463 6464 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6465 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6466 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6467 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null) 6468 6469 /* 6470 * Allow list few fields as RCU trusted or full trusted. 6471 * This logic doesn't allow mix tagging and will be removed once GCC supports 6472 * btf_type_tag. 6473 */ 6474 6475 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6476 BTF_TYPE_SAFE_RCU(struct task_struct) { 6477 const cpumask_t *cpus_ptr; 6478 struct css_set __rcu *cgroups; 6479 struct task_struct __rcu *real_parent; 6480 struct task_struct *group_leader; 6481 }; 6482 6483 BTF_TYPE_SAFE_RCU(struct cgroup) { 6484 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6485 struct kernfs_node *kn; 6486 }; 6487 6488 BTF_TYPE_SAFE_RCU(struct css_set) { 6489 struct cgroup *dfl_cgrp; 6490 }; 6491 6492 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6493 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6494 struct file __rcu *exe_file; 6495 }; 6496 6497 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6498 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6499 */ 6500 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6501 struct sock *sk; 6502 }; 6503 6504 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6505 struct sock *sk; 6506 }; 6507 6508 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6509 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6510 struct seq_file *seq; 6511 }; 6512 6513 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6514 struct bpf_iter_meta *meta; 6515 struct task_struct *task; 6516 }; 6517 6518 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6519 struct file *file; 6520 }; 6521 6522 BTF_TYPE_SAFE_TRUSTED(struct file) { 6523 struct inode *f_inode; 6524 }; 6525 6526 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 6527 /* no negative dentry-s in places where bpf can see it */ 6528 struct inode *d_inode; 6529 }; 6530 6531 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) { 6532 struct sock *sk; 6533 }; 6534 6535 static bool type_is_rcu(struct bpf_verifier_env *env, 6536 struct bpf_reg_state *reg, 6537 const char *field_name, u32 btf_id) 6538 { 6539 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6540 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6541 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6542 6543 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6544 } 6545 6546 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6547 struct bpf_reg_state *reg, 6548 const char *field_name, u32 btf_id) 6549 { 6550 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6551 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6552 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6553 6554 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6555 } 6556 6557 static bool type_is_trusted(struct bpf_verifier_env *env, 6558 struct bpf_reg_state *reg, 6559 const char *field_name, u32 btf_id) 6560 { 6561 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 6562 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6563 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6564 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6565 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 6566 6567 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6568 } 6569 6570 static bool type_is_trusted_or_null(struct bpf_verifier_env *env, 6571 struct bpf_reg_state *reg, 6572 const char *field_name, u32 btf_id) 6573 { 6574 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)); 6575 6576 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, 6577 "__safe_trusted_or_null"); 6578 } 6579 6580 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6581 struct bpf_reg_state *regs, 6582 int regno, int off, int size, 6583 enum bpf_access_type atype, 6584 int value_regno) 6585 { 6586 struct bpf_reg_state *reg = regs + regno; 6587 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6588 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6589 const char *field_name = NULL; 6590 enum bpf_type_flag flag = 0; 6591 u32 btf_id = 0; 6592 int ret; 6593 6594 if (!env->allow_ptr_leaks) { 6595 verbose(env, 6596 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6597 tname); 6598 return -EPERM; 6599 } 6600 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6601 verbose(env, 6602 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6603 tname); 6604 return -EINVAL; 6605 } 6606 if (off < 0) { 6607 verbose(env, 6608 "R%d is ptr_%s invalid negative access: off=%d\n", 6609 regno, tname, off); 6610 return -EACCES; 6611 } 6612 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6613 char tn_buf[48]; 6614 6615 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6616 verbose(env, 6617 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6618 regno, tname, off, tn_buf); 6619 return -EACCES; 6620 } 6621 6622 if (reg->type & MEM_USER) { 6623 verbose(env, 6624 "R%d is ptr_%s access user memory: off=%d\n", 6625 regno, tname, off); 6626 return -EACCES; 6627 } 6628 6629 if (reg->type & MEM_PERCPU) { 6630 verbose(env, 6631 "R%d is ptr_%s access percpu memory: off=%d\n", 6632 regno, tname, off); 6633 return -EACCES; 6634 } 6635 6636 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6637 if (!btf_is_kernel(reg->btf)) { 6638 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 6639 return -EFAULT; 6640 } 6641 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6642 } else { 6643 /* Writes are permitted with default btf_struct_access for 6644 * program allocated objects (which always have ref_obj_id > 0), 6645 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6646 */ 6647 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6648 verbose(env, "only read is supported\n"); 6649 return -EACCES; 6650 } 6651 6652 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6653 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 6654 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 6655 return -EFAULT; 6656 } 6657 6658 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6659 } 6660 6661 if (ret < 0) 6662 return ret; 6663 6664 if (ret != PTR_TO_BTF_ID) { 6665 /* just mark; */ 6666 6667 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6668 /* If this is an untrusted pointer, all pointers formed by walking it 6669 * also inherit the untrusted flag. 6670 */ 6671 flag = PTR_UNTRUSTED; 6672 6673 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6674 /* By default any pointer obtained from walking a trusted pointer is no 6675 * longer trusted, unless the field being accessed has explicitly been 6676 * marked as inheriting its parent's state of trust (either full or RCU). 6677 * For example: 6678 * 'cgroups' pointer is untrusted if task->cgroups dereference 6679 * happened in a sleepable program outside of bpf_rcu_read_lock() 6680 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6681 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6682 * 6683 * A regular RCU-protected pointer with __rcu tag can also be deemed 6684 * trusted if we are in an RCU CS. Such pointer can be NULL. 6685 */ 6686 if (type_is_trusted(env, reg, field_name, btf_id)) { 6687 flag |= PTR_TRUSTED; 6688 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) { 6689 flag |= PTR_TRUSTED | PTR_MAYBE_NULL; 6690 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6691 if (type_is_rcu(env, reg, field_name, btf_id)) { 6692 /* ignore __rcu tag and mark it MEM_RCU */ 6693 flag |= MEM_RCU; 6694 } else if (flag & MEM_RCU || 6695 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6696 /* __rcu tagged pointers can be NULL */ 6697 flag |= MEM_RCU | PTR_MAYBE_NULL; 6698 6699 /* We always trust them */ 6700 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6701 flag & PTR_UNTRUSTED) 6702 flag &= ~PTR_UNTRUSTED; 6703 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6704 /* keep as-is */ 6705 } else { 6706 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6707 clear_trusted_flags(&flag); 6708 } 6709 } else { 6710 /* 6711 * If not in RCU CS or MEM_RCU pointer can be NULL then 6712 * aggressively mark as untrusted otherwise such 6713 * pointers will be plain PTR_TO_BTF_ID without flags 6714 * and will be allowed to be passed into helpers for 6715 * compat reasons. 6716 */ 6717 flag = PTR_UNTRUSTED; 6718 } 6719 } else { 6720 /* Old compat. Deprecated */ 6721 clear_trusted_flags(&flag); 6722 } 6723 6724 if (atype == BPF_READ && value_regno >= 0) 6725 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6726 6727 return 0; 6728 } 6729 6730 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6731 struct bpf_reg_state *regs, 6732 int regno, int off, int size, 6733 enum bpf_access_type atype, 6734 int value_regno) 6735 { 6736 struct bpf_reg_state *reg = regs + regno; 6737 struct bpf_map *map = reg->map_ptr; 6738 struct bpf_reg_state map_reg; 6739 enum bpf_type_flag flag = 0; 6740 const struct btf_type *t; 6741 const char *tname; 6742 u32 btf_id; 6743 int ret; 6744 6745 if (!btf_vmlinux) { 6746 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6747 return -ENOTSUPP; 6748 } 6749 6750 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6751 verbose(env, "map_ptr access not supported for map type %d\n", 6752 map->map_type); 6753 return -ENOTSUPP; 6754 } 6755 6756 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6757 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6758 6759 if (!env->allow_ptr_leaks) { 6760 verbose(env, 6761 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6762 tname); 6763 return -EPERM; 6764 } 6765 6766 if (off < 0) { 6767 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6768 regno, tname, off); 6769 return -EACCES; 6770 } 6771 6772 if (atype != BPF_READ) { 6773 verbose(env, "only read from %s is supported\n", tname); 6774 return -EACCES; 6775 } 6776 6777 /* Simulate access to a PTR_TO_BTF_ID */ 6778 memset(&map_reg, 0, sizeof(map_reg)); 6779 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6780 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6781 if (ret < 0) 6782 return ret; 6783 6784 if (value_regno >= 0) 6785 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6786 6787 return 0; 6788 } 6789 6790 /* Check that the stack access at the given offset is within bounds. The 6791 * maximum valid offset is -1. 6792 * 6793 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6794 * -state->allocated_stack for reads. 6795 */ 6796 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 6797 s64 off, 6798 struct bpf_func_state *state, 6799 enum bpf_access_type t) 6800 { 6801 struct bpf_insn_aux_data *aux = &env->insn_aux_data[env->insn_idx]; 6802 int min_valid_off, max_bpf_stack; 6803 6804 /* If accessing instruction is a spill/fill from bpf_fastcall pattern, 6805 * add room for all caller saved registers below MAX_BPF_STACK. 6806 * In case if bpf_fastcall rewrite won't happen maximal stack depth 6807 * would be checked by check_max_stack_depth_subprog(). 6808 */ 6809 max_bpf_stack = MAX_BPF_STACK; 6810 if (aux->fastcall_pattern) 6811 max_bpf_stack += CALLER_SAVED_REGS * BPF_REG_SIZE; 6812 6813 if (t == BPF_WRITE || env->allow_uninit_stack) 6814 min_valid_off = -max_bpf_stack; 6815 else 6816 min_valid_off = -state->allocated_stack; 6817 6818 if (off < min_valid_off || off > -1) 6819 return -EACCES; 6820 return 0; 6821 } 6822 6823 /* Check that the stack access at 'regno + off' falls within the maximum stack 6824 * bounds. 6825 * 6826 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6827 */ 6828 static int check_stack_access_within_bounds( 6829 struct bpf_verifier_env *env, 6830 int regno, int off, int access_size, 6831 enum bpf_access_src src, enum bpf_access_type type) 6832 { 6833 struct bpf_reg_state *regs = cur_regs(env); 6834 struct bpf_reg_state *reg = regs + regno; 6835 struct bpf_func_state *state = func(env, reg); 6836 s64 min_off, max_off; 6837 int err; 6838 char *err_extra; 6839 6840 if (src == ACCESS_HELPER) 6841 /* We don't know if helpers are reading or writing (or both). */ 6842 err_extra = " indirect access to"; 6843 else if (type == BPF_READ) 6844 err_extra = " read from"; 6845 else 6846 err_extra = " write to"; 6847 6848 if (tnum_is_const(reg->var_off)) { 6849 min_off = (s64)reg->var_off.value + off; 6850 max_off = min_off + access_size; 6851 } else { 6852 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6853 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6854 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6855 err_extra, regno); 6856 return -EACCES; 6857 } 6858 min_off = reg->smin_value + off; 6859 max_off = reg->smax_value + off + access_size; 6860 } 6861 6862 err = check_stack_slot_within_bounds(env, min_off, state, type); 6863 if (!err && max_off > 0) 6864 err = -EINVAL; /* out of stack access into non-negative offsets */ 6865 if (!err && access_size < 0) 6866 /* access_size should not be negative (or overflow an int); others checks 6867 * along the way should have prevented such an access. 6868 */ 6869 err = -EFAULT; /* invalid negative access size; integer overflow? */ 6870 6871 if (err) { 6872 if (tnum_is_const(reg->var_off)) { 6873 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 6874 err_extra, regno, off, access_size); 6875 } else { 6876 char tn_buf[48]; 6877 6878 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6879 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n", 6880 err_extra, regno, tn_buf, off, access_size); 6881 } 6882 return err; 6883 } 6884 6885 /* Note that there is no stack access with offset zero, so the needed stack 6886 * size is -min_off, not -min_off+1. 6887 */ 6888 return grow_stack_state(env, state, -min_off /* size */); 6889 } 6890 6891 static bool get_func_retval_range(struct bpf_prog *prog, 6892 struct bpf_retval_range *range) 6893 { 6894 if (prog->type == BPF_PROG_TYPE_LSM && 6895 prog->expected_attach_type == BPF_LSM_MAC && 6896 !bpf_lsm_get_retval_range(prog, range)) { 6897 return true; 6898 } 6899 return false; 6900 } 6901 6902 /* check whether memory at (regno + off) is accessible for t = (read | write) 6903 * if t==write, value_regno is a register which value is stored into memory 6904 * if t==read, value_regno is a register which will receive the value from memory 6905 * if t==write && value_regno==-1, some unknown value is stored into memory 6906 * if t==read && value_regno==-1, don't care what we read from memory 6907 */ 6908 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6909 int off, int bpf_size, enum bpf_access_type t, 6910 int value_regno, bool strict_alignment_once, bool is_ldsx) 6911 { 6912 struct bpf_reg_state *regs = cur_regs(env); 6913 struct bpf_reg_state *reg = regs + regno; 6914 int size, err = 0; 6915 6916 size = bpf_size_to_bytes(bpf_size); 6917 if (size < 0) 6918 return size; 6919 6920 /* alignment checks will add in reg->off themselves */ 6921 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6922 if (err) 6923 return err; 6924 6925 /* for access checks, reg->off is just part of off */ 6926 off += reg->off; 6927 6928 if (reg->type == PTR_TO_MAP_KEY) { 6929 if (t == BPF_WRITE) { 6930 verbose(env, "write to change key R%d not allowed\n", regno); 6931 return -EACCES; 6932 } 6933 6934 err = check_mem_region_access(env, regno, off, size, 6935 reg->map_ptr->key_size, false); 6936 if (err) 6937 return err; 6938 if (value_regno >= 0) 6939 mark_reg_unknown(env, regs, value_regno); 6940 } else if (reg->type == PTR_TO_MAP_VALUE) { 6941 struct btf_field *kptr_field = NULL; 6942 6943 if (t == BPF_WRITE && value_regno >= 0 && 6944 is_pointer_value(env, value_regno)) { 6945 verbose(env, "R%d leaks addr into map\n", value_regno); 6946 return -EACCES; 6947 } 6948 err = check_map_access_type(env, regno, off, size, t); 6949 if (err) 6950 return err; 6951 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6952 if (err) 6953 return err; 6954 if (tnum_is_const(reg->var_off)) 6955 kptr_field = btf_record_find(reg->map_ptr->record, 6956 off + reg->var_off.value, BPF_KPTR); 6957 if (kptr_field) { 6958 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6959 } else if (t == BPF_READ && value_regno >= 0) { 6960 struct bpf_map *map = reg->map_ptr; 6961 6962 /* if map is read-only, track its contents as scalars */ 6963 if (tnum_is_const(reg->var_off) && 6964 bpf_map_is_rdonly(map) && 6965 map->ops->map_direct_value_addr) { 6966 int map_off = off + reg->var_off.value; 6967 u64 val = 0; 6968 6969 err = bpf_map_direct_read(map, map_off, size, 6970 &val, is_ldsx); 6971 if (err) 6972 return err; 6973 6974 regs[value_regno].type = SCALAR_VALUE; 6975 __mark_reg_known(®s[value_regno], val); 6976 } else { 6977 mark_reg_unknown(env, regs, value_regno); 6978 } 6979 } 6980 } else if (base_type(reg->type) == PTR_TO_MEM) { 6981 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6982 6983 if (type_may_be_null(reg->type)) { 6984 verbose(env, "R%d invalid mem access '%s'\n", regno, 6985 reg_type_str(env, reg->type)); 6986 return -EACCES; 6987 } 6988 6989 if (t == BPF_WRITE && rdonly_mem) { 6990 verbose(env, "R%d cannot write into %s\n", 6991 regno, reg_type_str(env, reg->type)); 6992 return -EACCES; 6993 } 6994 6995 if (t == BPF_WRITE && value_regno >= 0 && 6996 is_pointer_value(env, value_regno)) { 6997 verbose(env, "R%d leaks addr into mem\n", value_regno); 6998 return -EACCES; 6999 } 7000 7001 err = check_mem_region_access(env, regno, off, size, 7002 reg->mem_size, false); 7003 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 7004 mark_reg_unknown(env, regs, value_regno); 7005 } else if (reg->type == PTR_TO_CTX) { 7006 bool is_retval = false; 7007 struct bpf_retval_range range; 7008 enum bpf_reg_type reg_type = SCALAR_VALUE; 7009 struct btf *btf = NULL; 7010 u32 btf_id = 0; 7011 7012 if (t == BPF_WRITE && value_regno >= 0 && 7013 is_pointer_value(env, value_regno)) { 7014 verbose(env, "R%d leaks addr into ctx\n", value_regno); 7015 return -EACCES; 7016 } 7017 7018 err = check_ptr_off_reg(env, reg, regno); 7019 if (err < 0) 7020 return err; 7021 7022 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 7023 &btf_id, &is_retval, is_ldsx); 7024 if (err) 7025 verbose_linfo(env, insn_idx, "; "); 7026 if (!err && t == BPF_READ && value_regno >= 0) { 7027 /* ctx access returns either a scalar, or a 7028 * PTR_TO_PACKET[_META,_END]. In the latter 7029 * case, we know the offset is zero. 7030 */ 7031 if (reg_type == SCALAR_VALUE) { 7032 if (is_retval && get_func_retval_range(env->prog, &range)) { 7033 err = __mark_reg_s32_range(env, regs, value_regno, 7034 range.minval, range.maxval); 7035 if (err) 7036 return err; 7037 } else { 7038 mark_reg_unknown(env, regs, value_regno); 7039 } 7040 } else { 7041 mark_reg_known_zero(env, regs, 7042 value_regno); 7043 if (type_may_be_null(reg_type)) 7044 regs[value_regno].id = ++env->id_gen; 7045 /* A load of ctx field could have different 7046 * actual load size with the one encoded in the 7047 * insn. When the dst is PTR, it is for sure not 7048 * a sub-register. 7049 */ 7050 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 7051 if (base_type(reg_type) == PTR_TO_BTF_ID) { 7052 regs[value_regno].btf = btf; 7053 regs[value_regno].btf_id = btf_id; 7054 } 7055 } 7056 regs[value_regno].type = reg_type; 7057 } 7058 7059 } else if (reg->type == PTR_TO_STACK) { 7060 /* Basic bounds checks. */ 7061 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 7062 if (err) 7063 return err; 7064 7065 if (t == BPF_READ) 7066 err = check_stack_read(env, regno, off, size, 7067 value_regno); 7068 else 7069 err = check_stack_write(env, regno, off, size, 7070 value_regno, insn_idx); 7071 } else if (reg_is_pkt_pointer(reg)) { 7072 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 7073 verbose(env, "cannot write into packet\n"); 7074 return -EACCES; 7075 } 7076 if (t == BPF_WRITE && value_regno >= 0 && 7077 is_pointer_value(env, value_regno)) { 7078 verbose(env, "R%d leaks addr into packet\n", 7079 value_regno); 7080 return -EACCES; 7081 } 7082 err = check_packet_access(env, regno, off, size, false); 7083 if (!err && t == BPF_READ && value_regno >= 0) 7084 mark_reg_unknown(env, regs, value_regno); 7085 } else if (reg->type == PTR_TO_FLOW_KEYS) { 7086 if (t == BPF_WRITE && value_regno >= 0 && 7087 is_pointer_value(env, value_regno)) { 7088 verbose(env, "R%d leaks addr into flow keys\n", 7089 value_regno); 7090 return -EACCES; 7091 } 7092 7093 err = check_flow_keys_access(env, off, size); 7094 if (!err && t == BPF_READ && value_regno >= 0) 7095 mark_reg_unknown(env, regs, value_regno); 7096 } else if (type_is_sk_pointer(reg->type)) { 7097 if (t == BPF_WRITE) { 7098 verbose(env, "R%d cannot write into %s\n", 7099 regno, reg_type_str(env, reg->type)); 7100 return -EACCES; 7101 } 7102 err = check_sock_access(env, insn_idx, regno, off, size, t); 7103 if (!err && value_regno >= 0) 7104 mark_reg_unknown(env, regs, value_regno); 7105 } else if (reg->type == PTR_TO_TP_BUFFER) { 7106 err = check_tp_buffer_access(env, reg, regno, off, size); 7107 if (!err && t == BPF_READ && value_regno >= 0) 7108 mark_reg_unknown(env, regs, value_regno); 7109 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 7110 !type_may_be_null(reg->type)) { 7111 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 7112 value_regno); 7113 } else if (reg->type == CONST_PTR_TO_MAP) { 7114 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 7115 value_regno); 7116 } else if (base_type(reg->type) == PTR_TO_BUF) { 7117 bool rdonly_mem = type_is_rdonly_mem(reg->type); 7118 u32 *max_access; 7119 7120 if (rdonly_mem) { 7121 if (t == BPF_WRITE) { 7122 verbose(env, "R%d cannot write into %s\n", 7123 regno, reg_type_str(env, reg->type)); 7124 return -EACCES; 7125 } 7126 max_access = &env->prog->aux->max_rdonly_access; 7127 } else { 7128 max_access = &env->prog->aux->max_rdwr_access; 7129 } 7130 7131 err = check_buffer_access(env, reg, regno, off, size, false, 7132 max_access); 7133 7134 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 7135 mark_reg_unknown(env, regs, value_regno); 7136 } else if (reg->type == PTR_TO_ARENA) { 7137 if (t == BPF_READ && value_regno >= 0) 7138 mark_reg_unknown(env, regs, value_regno); 7139 } else { 7140 verbose(env, "R%d invalid mem access '%s'\n", regno, 7141 reg_type_str(env, reg->type)); 7142 return -EACCES; 7143 } 7144 7145 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 7146 regs[value_regno].type == SCALAR_VALUE) { 7147 if (!is_ldsx) 7148 /* b/h/w load zero-extends, mark upper bits as known 0 */ 7149 coerce_reg_to_size(®s[value_regno], size); 7150 else 7151 coerce_reg_to_size_sx(®s[value_regno], size); 7152 } 7153 return err; 7154 } 7155 7156 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 7157 bool allow_trust_mismatch); 7158 7159 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 7160 { 7161 int load_reg; 7162 int err; 7163 7164 switch (insn->imm) { 7165 case BPF_ADD: 7166 case BPF_ADD | BPF_FETCH: 7167 case BPF_AND: 7168 case BPF_AND | BPF_FETCH: 7169 case BPF_OR: 7170 case BPF_OR | BPF_FETCH: 7171 case BPF_XOR: 7172 case BPF_XOR | BPF_FETCH: 7173 case BPF_XCHG: 7174 case BPF_CMPXCHG: 7175 break; 7176 default: 7177 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 7178 return -EINVAL; 7179 } 7180 7181 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 7182 verbose(env, "invalid atomic operand size\n"); 7183 return -EINVAL; 7184 } 7185 7186 /* check src1 operand */ 7187 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7188 if (err) 7189 return err; 7190 7191 /* check src2 operand */ 7192 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 7193 if (err) 7194 return err; 7195 7196 if (insn->imm == BPF_CMPXCHG) { 7197 /* Check comparison of R0 with memory location */ 7198 const u32 aux_reg = BPF_REG_0; 7199 7200 err = check_reg_arg(env, aux_reg, SRC_OP); 7201 if (err) 7202 return err; 7203 7204 if (is_pointer_value(env, aux_reg)) { 7205 verbose(env, "R%d leaks addr into mem\n", aux_reg); 7206 return -EACCES; 7207 } 7208 } 7209 7210 if (is_pointer_value(env, insn->src_reg)) { 7211 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 7212 return -EACCES; 7213 } 7214 7215 if (is_ctx_reg(env, insn->dst_reg) || 7216 is_pkt_reg(env, insn->dst_reg) || 7217 is_flow_key_reg(env, insn->dst_reg) || 7218 is_sk_reg(env, insn->dst_reg) || 7219 (is_arena_reg(env, insn->dst_reg) && !bpf_jit_supports_insn(insn, true))) { 7220 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 7221 insn->dst_reg, 7222 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 7223 return -EACCES; 7224 } 7225 7226 if (insn->imm & BPF_FETCH) { 7227 if (insn->imm == BPF_CMPXCHG) 7228 load_reg = BPF_REG_0; 7229 else 7230 load_reg = insn->src_reg; 7231 7232 /* check and record load of old value */ 7233 err = check_reg_arg(env, load_reg, DST_OP); 7234 if (err) 7235 return err; 7236 } else { 7237 /* This instruction accesses a memory location but doesn't 7238 * actually load it into a register. 7239 */ 7240 load_reg = -1; 7241 } 7242 7243 /* Check whether we can read the memory, with second call for fetch 7244 * case to simulate the register fill. 7245 */ 7246 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7247 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 7248 if (!err && load_reg >= 0) 7249 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7250 BPF_SIZE(insn->code), BPF_READ, load_reg, 7251 true, false); 7252 if (err) 7253 return err; 7254 7255 if (is_arena_reg(env, insn->dst_reg)) { 7256 err = save_aux_ptr_type(env, PTR_TO_ARENA, false); 7257 if (err) 7258 return err; 7259 } 7260 /* Check whether we can write into the same memory. */ 7261 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7262 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 7263 if (err) 7264 return err; 7265 return 0; 7266 } 7267 7268 /* When register 'regno' is used to read the stack (either directly or through 7269 * a helper function) make sure that it's within stack boundary and, depending 7270 * on the access type and privileges, that all elements of the stack are 7271 * initialized. 7272 * 7273 * 'off' includes 'regno->off', but not its dynamic part (if any). 7274 * 7275 * All registers that have been spilled on the stack in the slots within the 7276 * read offsets are marked as read. 7277 */ 7278 static int check_stack_range_initialized( 7279 struct bpf_verifier_env *env, int regno, int off, 7280 int access_size, bool zero_size_allowed, 7281 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 7282 { 7283 struct bpf_reg_state *reg = reg_state(env, regno); 7284 struct bpf_func_state *state = func(env, reg); 7285 int err, min_off, max_off, i, j, slot, spi; 7286 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 7287 enum bpf_access_type bounds_check_type; 7288 /* Some accesses can write anything into the stack, others are 7289 * read-only. 7290 */ 7291 bool clobber = false; 7292 7293 if (access_size == 0 && !zero_size_allowed) { 7294 verbose(env, "invalid zero-sized read\n"); 7295 return -EACCES; 7296 } 7297 7298 if (type == ACCESS_HELPER) { 7299 /* The bounds checks for writes are more permissive than for 7300 * reads. However, if raw_mode is not set, we'll do extra 7301 * checks below. 7302 */ 7303 bounds_check_type = BPF_WRITE; 7304 clobber = true; 7305 } else { 7306 bounds_check_type = BPF_READ; 7307 } 7308 err = check_stack_access_within_bounds(env, regno, off, access_size, 7309 type, bounds_check_type); 7310 if (err) 7311 return err; 7312 7313 7314 if (tnum_is_const(reg->var_off)) { 7315 min_off = max_off = reg->var_off.value + off; 7316 } else { 7317 /* Variable offset is prohibited for unprivileged mode for 7318 * simplicity since it requires corresponding support in 7319 * Spectre masking for stack ALU. 7320 * See also retrieve_ptr_limit(). 7321 */ 7322 if (!env->bypass_spec_v1) { 7323 char tn_buf[48]; 7324 7325 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7326 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 7327 regno, err_extra, tn_buf); 7328 return -EACCES; 7329 } 7330 /* Only initialized buffer on stack is allowed to be accessed 7331 * with variable offset. With uninitialized buffer it's hard to 7332 * guarantee that whole memory is marked as initialized on 7333 * helper return since specific bounds are unknown what may 7334 * cause uninitialized stack leaking. 7335 */ 7336 if (meta && meta->raw_mode) 7337 meta = NULL; 7338 7339 min_off = reg->smin_value + off; 7340 max_off = reg->smax_value + off; 7341 } 7342 7343 if (meta && meta->raw_mode) { 7344 /* Ensure we won't be overwriting dynptrs when simulating byte 7345 * by byte access in check_helper_call using meta.access_size. 7346 * This would be a problem if we have a helper in the future 7347 * which takes: 7348 * 7349 * helper(uninit_mem, len, dynptr) 7350 * 7351 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 7352 * may end up writing to dynptr itself when touching memory from 7353 * arg 1. This can be relaxed on a case by case basis for known 7354 * safe cases, but reject due to the possibilitiy of aliasing by 7355 * default. 7356 */ 7357 for (i = min_off; i < max_off + access_size; i++) { 7358 int stack_off = -i - 1; 7359 7360 spi = __get_spi(i); 7361 /* raw_mode may write past allocated_stack */ 7362 if (state->allocated_stack <= stack_off) 7363 continue; 7364 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 7365 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 7366 return -EACCES; 7367 } 7368 } 7369 meta->access_size = access_size; 7370 meta->regno = regno; 7371 return 0; 7372 } 7373 7374 for (i = min_off; i < max_off + access_size; i++) { 7375 u8 *stype; 7376 7377 slot = -i - 1; 7378 spi = slot / BPF_REG_SIZE; 7379 if (state->allocated_stack <= slot) { 7380 verbose(env, "verifier bug: allocated_stack too small"); 7381 return -EFAULT; 7382 } 7383 7384 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 7385 if (*stype == STACK_MISC) 7386 goto mark; 7387 if ((*stype == STACK_ZERO) || 7388 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 7389 if (clobber) { 7390 /* helper can write anything into the stack */ 7391 *stype = STACK_MISC; 7392 } 7393 goto mark; 7394 } 7395 7396 if (is_spilled_reg(&state->stack[spi]) && 7397 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 7398 env->allow_ptr_leaks)) { 7399 if (clobber) { 7400 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 7401 for (j = 0; j < BPF_REG_SIZE; j++) 7402 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 7403 } 7404 goto mark; 7405 } 7406 7407 if (tnum_is_const(reg->var_off)) { 7408 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 7409 err_extra, regno, min_off, i - min_off, access_size); 7410 } else { 7411 char tn_buf[48]; 7412 7413 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7414 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 7415 err_extra, regno, tn_buf, i - min_off, access_size); 7416 } 7417 return -EACCES; 7418 mark: 7419 /* reading any byte out of 8-byte 'spill_slot' will cause 7420 * the whole slot to be marked as 'read' 7421 */ 7422 mark_reg_read(env, &state->stack[spi].spilled_ptr, 7423 state->stack[spi].spilled_ptr.parent, 7424 REG_LIVE_READ64); 7425 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 7426 * be sure that whether stack slot is written to or not. Hence, 7427 * we must still conservatively propagate reads upwards even if 7428 * helper may write to the entire memory range. 7429 */ 7430 } 7431 return 0; 7432 } 7433 7434 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 7435 int access_size, bool zero_size_allowed, 7436 struct bpf_call_arg_meta *meta) 7437 { 7438 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7439 u32 *max_access; 7440 7441 switch (base_type(reg->type)) { 7442 case PTR_TO_PACKET: 7443 case PTR_TO_PACKET_META: 7444 return check_packet_access(env, regno, reg->off, access_size, 7445 zero_size_allowed); 7446 case PTR_TO_MAP_KEY: 7447 if (meta && meta->raw_mode) { 7448 verbose(env, "R%d cannot write into %s\n", regno, 7449 reg_type_str(env, reg->type)); 7450 return -EACCES; 7451 } 7452 return check_mem_region_access(env, regno, reg->off, access_size, 7453 reg->map_ptr->key_size, false); 7454 case PTR_TO_MAP_VALUE: 7455 if (check_map_access_type(env, regno, reg->off, access_size, 7456 meta && meta->raw_mode ? BPF_WRITE : 7457 BPF_READ)) 7458 return -EACCES; 7459 return check_map_access(env, regno, reg->off, access_size, 7460 zero_size_allowed, ACCESS_HELPER); 7461 case PTR_TO_MEM: 7462 if (type_is_rdonly_mem(reg->type)) { 7463 if (meta && meta->raw_mode) { 7464 verbose(env, "R%d cannot write into %s\n", regno, 7465 reg_type_str(env, reg->type)); 7466 return -EACCES; 7467 } 7468 } 7469 return check_mem_region_access(env, regno, reg->off, 7470 access_size, reg->mem_size, 7471 zero_size_allowed); 7472 case PTR_TO_BUF: 7473 if (type_is_rdonly_mem(reg->type)) { 7474 if (meta && meta->raw_mode) { 7475 verbose(env, "R%d cannot write into %s\n", regno, 7476 reg_type_str(env, reg->type)); 7477 return -EACCES; 7478 } 7479 7480 max_access = &env->prog->aux->max_rdonly_access; 7481 } else { 7482 max_access = &env->prog->aux->max_rdwr_access; 7483 } 7484 return check_buffer_access(env, reg, regno, reg->off, 7485 access_size, zero_size_allowed, 7486 max_access); 7487 case PTR_TO_STACK: 7488 return check_stack_range_initialized( 7489 env, 7490 regno, reg->off, access_size, 7491 zero_size_allowed, ACCESS_HELPER, meta); 7492 case PTR_TO_BTF_ID: 7493 return check_ptr_to_btf_access(env, regs, regno, reg->off, 7494 access_size, BPF_READ, -1); 7495 case PTR_TO_CTX: 7496 /* in case the function doesn't know how to access the context, 7497 * (because we are in a program of type SYSCALL for example), we 7498 * can not statically check its size. 7499 * Dynamically check it now. 7500 */ 7501 if (!env->ops->convert_ctx_access) { 7502 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 7503 int offset = access_size - 1; 7504 7505 /* Allow zero-byte read from PTR_TO_CTX */ 7506 if (access_size == 0) 7507 return zero_size_allowed ? 0 : -EACCES; 7508 7509 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 7510 atype, -1, false, false); 7511 } 7512 7513 fallthrough; 7514 default: /* scalar_value or invalid ptr */ 7515 /* Allow zero-byte read from NULL, regardless of pointer type */ 7516 if (zero_size_allowed && access_size == 0 && 7517 register_is_null(reg)) 7518 return 0; 7519 7520 verbose(env, "R%d type=%s ", regno, 7521 reg_type_str(env, reg->type)); 7522 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7523 return -EACCES; 7524 } 7525 } 7526 7527 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 7528 * size. 7529 * 7530 * @regno is the register containing the access size. regno-1 is the register 7531 * containing the pointer. 7532 */ 7533 static int check_mem_size_reg(struct bpf_verifier_env *env, 7534 struct bpf_reg_state *reg, u32 regno, 7535 bool zero_size_allowed, 7536 struct bpf_call_arg_meta *meta) 7537 { 7538 int err; 7539 7540 /* This is used to refine r0 return value bounds for helpers 7541 * that enforce this value as an upper bound on return values. 7542 * See do_refine_retval_range() for helpers that can refine 7543 * the return value. C type of helper is u32 so we pull register 7544 * bound from umax_value however, if negative verifier errors 7545 * out. Only upper bounds can be learned because retval is an 7546 * int type and negative retvals are allowed. 7547 */ 7548 meta->msize_max_value = reg->umax_value; 7549 7550 /* The register is SCALAR_VALUE; the access check 7551 * happens using its boundaries. 7552 */ 7553 if (!tnum_is_const(reg->var_off)) 7554 /* For unprivileged variable accesses, disable raw 7555 * mode so that the program is required to 7556 * initialize all the memory that the helper could 7557 * just partially fill up. 7558 */ 7559 meta = NULL; 7560 7561 if (reg->smin_value < 0) { 7562 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7563 regno); 7564 return -EACCES; 7565 } 7566 7567 if (reg->umin_value == 0 && !zero_size_allowed) { 7568 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n", 7569 regno, reg->umin_value, reg->umax_value); 7570 return -EACCES; 7571 } 7572 7573 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7574 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7575 regno); 7576 return -EACCES; 7577 } 7578 err = check_helper_mem_access(env, regno - 1, 7579 reg->umax_value, 7580 zero_size_allowed, meta); 7581 if (!err) 7582 err = mark_chain_precision(env, regno); 7583 return err; 7584 } 7585 7586 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7587 u32 regno, u32 mem_size) 7588 { 7589 bool may_be_null = type_may_be_null(reg->type); 7590 struct bpf_reg_state saved_reg; 7591 struct bpf_call_arg_meta meta; 7592 int err; 7593 7594 if (register_is_null(reg)) 7595 return 0; 7596 7597 memset(&meta, 0, sizeof(meta)); 7598 /* Assuming that the register contains a value check if the memory 7599 * access is safe. Temporarily save and restore the register's state as 7600 * the conversion shouldn't be visible to a caller. 7601 */ 7602 if (may_be_null) { 7603 saved_reg = *reg; 7604 mark_ptr_not_null_reg(reg); 7605 } 7606 7607 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 7608 /* Check access for BPF_WRITE */ 7609 meta.raw_mode = true; 7610 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 7611 7612 if (may_be_null) 7613 *reg = saved_reg; 7614 7615 return err; 7616 } 7617 7618 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7619 u32 regno) 7620 { 7621 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7622 bool may_be_null = type_may_be_null(mem_reg->type); 7623 struct bpf_reg_state saved_reg; 7624 struct bpf_call_arg_meta meta; 7625 int err; 7626 7627 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7628 7629 memset(&meta, 0, sizeof(meta)); 7630 7631 if (may_be_null) { 7632 saved_reg = *mem_reg; 7633 mark_ptr_not_null_reg(mem_reg); 7634 } 7635 7636 err = check_mem_size_reg(env, reg, regno, true, &meta); 7637 /* Check access for BPF_WRITE */ 7638 meta.raw_mode = true; 7639 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 7640 7641 if (may_be_null) 7642 *mem_reg = saved_reg; 7643 return err; 7644 } 7645 7646 /* Implementation details: 7647 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7648 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7649 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7650 * Two separate bpf_obj_new will also have different reg->id. 7651 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7652 * clears reg->id after value_or_null->value transition, since the verifier only 7653 * cares about the range of access to valid map value pointer and doesn't care 7654 * about actual address of the map element. 7655 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7656 * reg->id > 0 after value_or_null->value transition. By doing so 7657 * two bpf_map_lookups will be considered two different pointers that 7658 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7659 * returned from bpf_obj_new. 7660 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7661 * dead-locks. 7662 * Since only one bpf_spin_lock is allowed the checks are simpler than 7663 * reg_is_refcounted() logic. The verifier needs to remember only 7664 * one spin_lock instead of array of acquired_refs. 7665 * cur_state->active_lock remembers which map value element or allocated 7666 * object got locked and clears it after bpf_spin_unlock. 7667 */ 7668 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 7669 bool is_lock) 7670 { 7671 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7672 struct bpf_verifier_state *cur = env->cur_state; 7673 bool is_const = tnum_is_const(reg->var_off); 7674 u64 val = reg->var_off.value; 7675 struct bpf_map *map = NULL; 7676 struct btf *btf = NULL; 7677 struct btf_record *rec; 7678 7679 if (!is_const) { 7680 verbose(env, 7681 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 7682 regno); 7683 return -EINVAL; 7684 } 7685 if (reg->type == PTR_TO_MAP_VALUE) { 7686 map = reg->map_ptr; 7687 if (!map->btf) { 7688 verbose(env, 7689 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 7690 map->name); 7691 return -EINVAL; 7692 } 7693 } else { 7694 btf = reg->btf; 7695 } 7696 7697 rec = reg_btf_record(reg); 7698 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 7699 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 7700 map ? map->name : "kptr"); 7701 return -EINVAL; 7702 } 7703 if (rec->spin_lock_off != val + reg->off) { 7704 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 7705 val + reg->off, rec->spin_lock_off); 7706 return -EINVAL; 7707 } 7708 if (is_lock) { 7709 if (cur->active_lock.ptr) { 7710 verbose(env, 7711 "Locking two bpf_spin_locks are not allowed\n"); 7712 return -EINVAL; 7713 } 7714 if (map) 7715 cur->active_lock.ptr = map; 7716 else 7717 cur->active_lock.ptr = btf; 7718 cur->active_lock.id = reg->id; 7719 } else { 7720 void *ptr; 7721 7722 if (map) 7723 ptr = map; 7724 else 7725 ptr = btf; 7726 7727 if (!cur->active_lock.ptr) { 7728 verbose(env, "bpf_spin_unlock without taking a lock\n"); 7729 return -EINVAL; 7730 } 7731 if (cur->active_lock.ptr != ptr || 7732 cur->active_lock.id != reg->id) { 7733 verbose(env, "bpf_spin_unlock of different lock\n"); 7734 return -EINVAL; 7735 } 7736 7737 invalidate_non_owning_refs(env); 7738 7739 cur->active_lock.ptr = NULL; 7740 cur->active_lock.id = 0; 7741 } 7742 return 0; 7743 } 7744 7745 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7746 struct bpf_call_arg_meta *meta) 7747 { 7748 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7749 bool is_const = tnum_is_const(reg->var_off); 7750 struct bpf_map *map = reg->map_ptr; 7751 u64 val = reg->var_off.value; 7752 7753 if (!is_const) { 7754 verbose(env, 7755 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 7756 regno); 7757 return -EINVAL; 7758 } 7759 if (!map->btf) { 7760 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 7761 map->name); 7762 return -EINVAL; 7763 } 7764 if (!btf_record_has_field(map->record, BPF_TIMER)) { 7765 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 7766 return -EINVAL; 7767 } 7768 if (map->record->timer_off != val + reg->off) { 7769 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 7770 val + reg->off, map->record->timer_off); 7771 return -EINVAL; 7772 } 7773 if (meta->map_ptr) { 7774 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 7775 return -EFAULT; 7776 } 7777 meta->map_uid = reg->map_uid; 7778 meta->map_ptr = map; 7779 return 0; 7780 } 7781 7782 static int process_wq_func(struct bpf_verifier_env *env, int regno, 7783 struct bpf_kfunc_call_arg_meta *meta) 7784 { 7785 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7786 struct bpf_map *map = reg->map_ptr; 7787 u64 val = reg->var_off.value; 7788 7789 if (map->record->wq_off != val + reg->off) { 7790 verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n", 7791 val + reg->off, map->record->wq_off); 7792 return -EINVAL; 7793 } 7794 meta->map.uid = reg->map_uid; 7795 meta->map.ptr = map; 7796 return 0; 7797 } 7798 7799 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7800 struct bpf_call_arg_meta *meta) 7801 { 7802 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7803 struct btf_field *kptr_field; 7804 struct bpf_map *map_ptr; 7805 struct btf_record *rec; 7806 u32 kptr_off; 7807 7808 if (type_is_ptr_alloc_obj(reg->type)) { 7809 rec = reg_btf_record(reg); 7810 } else { /* PTR_TO_MAP_VALUE */ 7811 map_ptr = reg->map_ptr; 7812 if (!map_ptr->btf) { 7813 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7814 map_ptr->name); 7815 return -EINVAL; 7816 } 7817 rec = map_ptr->record; 7818 meta->map_ptr = map_ptr; 7819 } 7820 7821 if (!tnum_is_const(reg->var_off)) { 7822 verbose(env, 7823 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7824 regno); 7825 return -EINVAL; 7826 } 7827 7828 if (!btf_record_has_field(rec, BPF_KPTR)) { 7829 verbose(env, "R%d has no valid kptr\n", regno); 7830 return -EINVAL; 7831 } 7832 7833 kptr_off = reg->off + reg->var_off.value; 7834 kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR); 7835 if (!kptr_field) { 7836 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7837 return -EACCES; 7838 } 7839 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7840 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7841 return -EACCES; 7842 } 7843 meta->kptr_field = kptr_field; 7844 return 0; 7845 } 7846 7847 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7848 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7849 * 7850 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7851 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7852 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7853 * 7854 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7855 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7856 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7857 * mutate the view of the dynptr and also possibly destroy it. In the latter 7858 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7859 * memory that dynptr points to. 7860 * 7861 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7862 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7863 * readonly dynptr view yet, hence only the first case is tracked and checked. 7864 * 7865 * This is consistent with how C applies the const modifier to a struct object, 7866 * where the pointer itself inside bpf_dynptr becomes const but not what it 7867 * points to. 7868 * 7869 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7870 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7871 */ 7872 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7873 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7874 { 7875 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7876 int err; 7877 7878 if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) { 7879 verbose(env, 7880 "arg#%d expected pointer to stack or const struct bpf_dynptr\n", 7881 regno); 7882 return -EINVAL; 7883 } 7884 7885 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7886 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7887 */ 7888 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7889 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 7890 return -EFAULT; 7891 } 7892 7893 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7894 * constructing a mutable bpf_dynptr object. 7895 * 7896 * Currently, this is only possible with PTR_TO_STACK 7897 * pointing to a region of at least 16 bytes which doesn't 7898 * contain an existing bpf_dynptr. 7899 * 7900 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7901 * mutated or destroyed. However, the memory it points to 7902 * may be mutated. 7903 * 7904 * None - Points to a initialized dynptr that can be mutated and 7905 * destroyed, including mutation of the memory it points 7906 * to. 7907 */ 7908 if (arg_type & MEM_UNINIT) { 7909 int i; 7910 7911 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7912 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7913 return -EINVAL; 7914 } 7915 7916 /* we write BPF_DW bits (8 bytes) at a time */ 7917 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7918 err = check_mem_access(env, insn_idx, regno, 7919 i, BPF_DW, BPF_WRITE, -1, false, false); 7920 if (err) 7921 return err; 7922 } 7923 7924 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7925 } else /* MEM_RDONLY and None case from above */ { 7926 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7927 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7928 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7929 return -EINVAL; 7930 } 7931 7932 if (!is_dynptr_reg_valid_init(env, reg)) { 7933 verbose(env, 7934 "Expected an initialized dynptr as arg #%d\n", 7935 regno); 7936 return -EINVAL; 7937 } 7938 7939 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7940 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7941 verbose(env, 7942 "Expected a dynptr of type %s as arg #%d\n", 7943 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 7944 return -EINVAL; 7945 } 7946 7947 err = mark_dynptr_read(env, reg); 7948 } 7949 return err; 7950 } 7951 7952 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7953 { 7954 struct bpf_func_state *state = func(env, reg); 7955 7956 return state->stack[spi].spilled_ptr.ref_obj_id; 7957 } 7958 7959 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7960 { 7961 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7962 } 7963 7964 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7965 { 7966 return meta->kfunc_flags & KF_ITER_NEW; 7967 } 7968 7969 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7970 { 7971 return meta->kfunc_flags & KF_ITER_NEXT; 7972 } 7973 7974 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7975 { 7976 return meta->kfunc_flags & KF_ITER_DESTROY; 7977 } 7978 7979 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx, 7980 const struct btf_param *arg) 7981 { 7982 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7983 * kfunc is iter state pointer 7984 */ 7985 if (is_iter_kfunc(meta)) 7986 return arg_idx == 0; 7987 7988 /* iter passed as an argument to a generic kfunc */ 7989 return btf_param_match_suffix(meta->btf, arg, "__iter"); 7990 } 7991 7992 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7993 struct bpf_kfunc_call_arg_meta *meta) 7994 { 7995 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7996 const struct btf_type *t; 7997 int spi, err, i, nr_slots, btf_id; 7998 7999 /* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs() 8000 * ensures struct convention, so we wouldn't need to do any BTF 8001 * validation here. But given iter state can be passed as a parameter 8002 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more 8003 * conservative here. 8004 */ 8005 btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1); 8006 if (btf_id < 0) { 8007 verbose(env, "expected valid iter pointer as arg #%d\n", regno); 8008 return -EINVAL; 8009 } 8010 t = btf_type_by_id(meta->btf, btf_id); 8011 nr_slots = t->size / BPF_REG_SIZE; 8012 8013 if (is_iter_new_kfunc(meta)) { 8014 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 8015 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 8016 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 8017 iter_type_str(meta->btf, btf_id), regno); 8018 return -EINVAL; 8019 } 8020 8021 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 8022 err = check_mem_access(env, insn_idx, regno, 8023 i, BPF_DW, BPF_WRITE, -1, false, false); 8024 if (err) 8025 return err; 8026 } 8027 8028 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 8029 if (err) 8030 return err; 8031 } else { 8032 /* iter_next() or iter_destroy(), as well as any kfunc 8033 * accepting iter argument, expect initialized iter state 8034 */ 8035 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 8036 switch (err) { 8037 case 0: 8038 break; 8039 case -EINVAL: 8040 verbose(env, "expected an initialized iter_%s as arg #%d\n", 8041 iter_type_str(meta->btf, btf_id), regno); 8042 return err; 8043 case -EPROTO: 8044 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 8045 return err; 8046 default: 8047 return err; 8048 } 8049 8050 spi = iter_get_spi(env, reg, nr_slots); 8051 if (spi < 0) 8052 return spi; 8053 8054 err = mark_iter_read(env, reg, spi, nr_slots); 8055 if (err) 8056 return err; 8057 8058 /* remember meta->iter info for process_iter_next_call() */ 8059 meta->iter.spi = spi; 8060 meta->iter.frameno = reg->frameno; 8061 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 8062 8063 if (is_iter_destroy_kfunc(meta)) { 8064 err = unmark_stack_slots_iter(env, reg, nr_slots); 8065 if (err) 8066 return err; 8067 } 8068 } 8069 8070 return 0; 8071 } 8072 8073 /* Look for a previous loop entry at insn_idx: nearest parent state 8074 * stopped at insn_idx with callsites matching those in cur->frame. 8075 */ 8076 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 8077 struct bpf_verifier_state *cur, 8078 int insn_idx) 8079 { 8080 struct bpf_verifier_state_list *sl; 8081 struct bpf_verifier_state *st; 8082 8083 /* Explored states are pushed in stack order, most recent states come first */ 8084 sl = *explored_state(env, insn_idx); 8085 for (; sl; sl = sl->next) { 8086 /* If st->branches != 0 state is a part of current DFS verification path, 8087 * hence cur & st for a loop. 8088 */ 8089 st = &sl->state; 8090 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 8091 st->dfs_depth < cur->dfs_depth) 8092 return st; 8093 } 8094 8095 return NULL; 8096 } 8097 8098 static void reset_idmap_scratch(struct bpf_verifier_env *env); 8099 static bool regs_exact(const struct bpf_reg_state *rold, 8100 const struct bpf_reg_state *rcur, 8101 struct bpf_idmap *idmap); 8102 8103 static void maybe_widen_reg(struct bpf_verifier_env *env, 8104 struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 8105 struct bpf_idmap *idmap) 8106 { 8107 if (rold->type != SCALAR_VALUE) 8108 return; 8109 if (rold->type != rcur->type) 8110 return; 8111 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap)) 8112 return; 8113 __mark_reg_unknown(env, rcur); 8114 } 8115 8116 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 8117 struct bpf_verifier_state *old, 8118 struct bpf_verifier_state *cur) 8119 { 8120 struct bpf_func_state *fold, *fcur; 8121 int i, fr; 8122 8123 reset_idmap_scratch(env); 8124 for (fr = old->curframe; fr >= 0; fr--) { 8125 fold = old->frame[fr]; 8126 fcur = cur->frame[fr]; 8127 8128 for (i = 0; i < MAX_BPF_REG; i++) 8129 maybe_widen_reg(env, 8130 &fold->regs[i], 8131 &fcur->regs[i], 8132 &env->idmap_scratch); 8133 8134 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) { 8135 if (!is_spilled_reg(&fold->stack[i]) || 8136 !is_spilled_reg(&fcur->stack[i])) 8137 continue; 8138 8139 maybe_widen_reg(env, 8140 &fold->stack[i].spilled_ptr, 8141 &fcur->stack[i].spilled_ptr, 8142 &env->idmap_scratch); 8143 } 8144 } 8145 return 0; 8146 } 8147 8148 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st, 8149 struct bpf_kfunc_call_arg_meta *meta) 8150 { 8151 int iter_frameno = meta->iter.frameno; 8152 int iter_spi = meta->iter.spi; 8153 8154 return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 8155 } 8156 8157 /* process_iter_next_call() is called when verifier gets to iterator's next 8158 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 8159 * to it as just "iter_next()" in comments below. 8160 * 8161 * BPF verifier relies on a crucial contract for any iter_next() 8162 * implementation: it should *eventually* return NULL, and once that happens 8163 * it should keep returning NULL. That is, once iterator exhausts elements to 8164 * iterate, it should never reset or spuriously return new elements. 8165 * 8166 * With the assumption of such contract, process_iter_next_call() simulates 8167 * a fork in the verifier state to validate loop logic correctness and safety 8168 * without having to simulate infinite amount of iterations. 8169 * 8170 * In current state, we first assume that iter_next() returned NULL and 8171 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 8172 * conditions we should not form an infinite loop and should eventually reach 8173 * exit. 8174 * 8175 * Besides that, we also fork current state and enqueue it for later 8176 * verification. In a forked state we keep iterator state as ACTIVE 8177 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 8178 * also bump iteration depth to prevent erroneous infinite loop detection 8179 * later on (see iter_active_depths_differ() comment for details). In this 8180 * state we assume that we'll eventually loop back to another iter_next() 8181 * calls (it could be in exactly same location or in some other instruction, 8182 * it doesn't matter, we don't make any unnecessary assumptions about this, 8183 * everything revolves around iterator state in a stack slot, not which 8184 * instruction is calling iter_next()). When that happens, we either will come 8185 * to iter_next() with equivalent state and can conclude that next iteration 8186 * will proceed in exactly the same way as we just verified, so it's safe to 8187 * assume that loop converges. If not, we'll go on another iteration 8188 * simulation with a different input state, until all possible starting states 8189 * are validated or we reach maximum number of instructions limit. 8190 * 8191 * This way, we will either exhaustively discover all possible input states 8192 * that iterator loop can start with and eventually will converge, or we'll 8193 * effectively regress into bounded loop simulation logic and either reach 8194 * maximum number of instructions if loop is not provably convergent, or there 8195 * is some statically known limit on number of iterations (e.g., if there is 8196 * an explicit `if n > 100 then break;` statement somewhere in the loop). 8197 * 8198 * Iteration convergence logic in is_state_visited() relies on exact 8199 * states comparison, which ignores read and precision marks. 8200 * This is necessary because read and precision marks are not finalized 8201 * while in the loop. Exact comparison might preclude convergence for 8202 * simple programs like below: 8203 * 8204 * i = 0; 8205 * while(iter_next(&it)) 8206 * i++; 8207 * 8208 * At each iteration step i++ would produce a new distinct state and 8209 * eventually instruction processing limit would be reached. 8210 * 8211 * To avoid such behavior speculatively forget (widen) range for 8212 * imprecise scalar registers, if those registers were not precise at the 8213 * end of the previous iteration and do not match exactly. 8214 * 8215 * This is a conservative heuristic that allows to verify wide range of programs, 8216 * however it precludes verification of programs that conjure an 8217 * imprecise value on the first loop iteration and use it as precise on a second. 8218 * For example, the following safe program would fail to verify: 8219 * 8220 * struct bpf_num_iter it; 8221 * int arr[10]; 8222 * int i = 0, a = 0; 8223 * bpf_iter_num_new(&it, 0, 10); 8224 * while (bpf_iter_num_next(&it)) { 8225 * if (a == 0) { 8226 * a = 1; 8227 * i = 7; // Because i changed verifier would forget 8228 * // it's range on second loop entry. 8229 * } else { 8230 * arr[i] = 42; // This would fail to verify. 8231 * } 8232 * } 8233 * bpf_iter_num_destroy(&it); 8234 */ 8235 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 8236 struct bpf_kfunc_call_arg_meta *meta) 8237 { 8238 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 8239 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 8240 struct bpf_reg_state *cur_iter, *queued_iter; 8241 8242 BTF_TYPE_EMIT(struct bpf_iter); 8243 8244 cur_iter = get_iter_from_state(cur_st, meta); 8245 8246 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 8247 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 8248 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 8249 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 8250 return -EFAULT; 8251 } 8252 8253 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 8254 /* Because iter_next() call is a checkpoint is_state_visitied() 8255 * should guarantee parent state with same call sites and insn_idx. 8256 */ 8257 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 8258 !same_callsites(cur_st->parent, cur_st)) { 8259 verbose(env, "bug: bad parent state for iter next call"); 8260 return -EFAULT; 8261 } 8262 /* Note cur_st->parent in the call below, it is necessary to skip 8263 * checkpoint created for cur_st by is_state_visited() 8264 * right at this instruction. 8265 */ 8266 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 8267 /* branch out active iter state */ 8268 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 8269 if (!queued_st) 8270 return -ENOMEM; 8271 8272 queued_iter = get_iter_from_state(queued_st, meta); 8273 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 8274 queued_iter->iter.depth++; 8275 if (prev_st) 8276 widen_imprecise_scalars(env, prev_st, queued_st); 8277 8278 queued_fr = queued_st->frame[queued_st->curframe]; 8279 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 8280 } 8281 8282 /* switch to DRAINED state, but keep the depth unchanged */ 8283 /* mark current iter state as drained and assume returned NULL */ 8284 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 8285 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 8286 8287 return 0; 8288 } 8289 8290 static bool arg_type_is_mem_size(enum bpf_arg_type type) 8291 { 8292 return type == ARG_CONST_SIZE || 8293 type == ARG_CONST_SIZE_OR_ZERO; 8294 } 8295 8296 static bool arg_type_is_raw_mem(enum bpf_arg_type type) 8297 { 8298 return base_type(type) == ARG_PTR_TO_MEM && 8299 type & MEM_UNINIT; 8300 } 8301 8302 static bool arg_type_is_release(enum bpf_arg_type type) 8303 { 8304 return type & OBJ_RELEASE; 8305 } 8306 8307 static bool arg_type_is_dynptr(enum bpf_arg_type type) 8308 { 8309 return base_type(type) == ARG_PTR_TO_DYNPTR; 8310 } 8311 8312 static int resolve_map_arg_type(struct bpf_verifier_env *env, 8313 const struct bpf_call_arg_meta *meta, 8314 enum bpf_arg_type *arg_type) 8315 { 8316 if (!meta->map_ptr) { 8317 /* kernel subsystem misconfigured verifier */ 8318 verbose(env, "invalid map_ptr to access map->type\n"); 8319 return -EACCES; 8320 } 8321 8322 switch (meta->map_ptr->map_type) { 8323 case BPF_MAP_TYPE_SOCKMAP: 8324 case BPF_MAP_TYPE_SOCKHASH: 8325 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 8326 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 8327 } else { 8328 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 8329 return -EINVAL; 8330 } 8331 break; 8332 case BPF_MAP_TYPE_BLOOM_FILTER: 8333 if (meta->func_id == BPF_FUNC_map_peek_elem) 8334 *arg_type = ARG_PTR_TO_MAP_VALUE; 8335 break; 8336 default: 8337 break; 8338 } 8339 return 0; 8340 } 8341 8342 struct bpf_reg_types { 8343 const enum bpf_reg_type types[10]; 8344 u32 *btf_id; 8345 }; 8346 8347 static const struct bpf_reg_types sock_types = { 8348 .types = { 8349 PTR_TO_SOCK_COMMON, 8350 PTR_TO_SOCKET, 8351 PTR_TO_TCP_SOCK, 8352 PTR_TO_XDP_SOCK, 8353 }, 8354 }; 8355 8356 #ifdef CONFIG_NET 8357 static const struct bpf_reg_types btf_id_sock_common_types = { 8358 .types = { 8359 PTR_TO_SOCK_COMMON, 8360 PTR_TO_SOCKET, 8361 PTR_TO_TCP_SOCK, 8362 PTR_TO_XDP_SOCK, 8363 PTR_TO_BTF_ID, 8364 PTR_TO_BTF_ID | PTR_TRUSTED, 8365 }, 8366 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 8367 }; 8368 #endif 8369 8370 static const struct bpf_reg_types mem_types = { 8371 .types = { 8372 PTR_TO_STACK, 8373 PTR_TO_PACKET, 8374 PTR_TO_PACKET_META, 8375 PTR_TO_MAP_KEY, 8376 PTR_TO_MAP_VALUE, 8377 PTR_TO_MEM, 8378 PTR_TO_MEM | MEM_RINGBUF, 8379 PTR_TO_BUF, 8380 PTR_TO_BTF_ID | PTR_TRUSTED, 8381 }, 8382 }; 8383 8384 static const struct bpf_reg_types spin_lock_types = { 8385 .types = { 8386 PTR_TO_MAP_VALUE, 8387 PTR_TO_BTF_ID | MEM_ALLOC, 8388 } 8389 }; 8390 8391 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 8392 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 8393 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 8394 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 8395 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 8396 static const struct bpf_reg_types btf_ptr_types = { 8397 .types = { 8398 PTR_TO_BTF_ID, 8399 PTR_TO_BTF_ID | PTR_TRUSTED, 8400 PTR_TO_BTF_ID | MEM_RCU, 8401 }, 8402 }; 8403 static const struct bpf_reg_types percpu_btf_ptr_types = { 8404 .types = { 8405 PTR_TO_BTF_ID | MEM_PERCPU, 8406 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 8407 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 8408 } 8409 }; 8410 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 8411 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 8412 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8413 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 8414 static const struct bpf_reg_types kptr_xchg_dest_types = { 8415 .types = { 8416 PTR_TO_MAP_VALUE, 8417 PTR_TO_BTF_ID | MEM_ALLOC 8418 } 8419 }; 8420 static const struct bpf_reg_types dynptr_types = { 8421 .types = { 8422 PTR_TO_STACK, 8423 CONST_PTR_TO_DYNPTR, 8424 } 8425 }; 8426 8427 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 8428 [ARG_PTR_TO_MAP_KEY] = &mem_types, 8429 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 8430 [ARG_CONST_SIZE] = &scalar_types, 8431 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 8432 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 8433 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 8434 [ARG_PTR_TO_CTX] = &context_types, 8435 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 8436 #ifdef CONFIG_NET 8437 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 8438 #endif 8439 [ARG_PTR_TO_SOCKET] = &fullsock_types, 8440 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 8441 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 8442 [ARG_PTR_TO_MEM] = &mem_types, 8443 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 8444 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 8445 [ARG_PTR_TO_FUNC] = &func_ptr_types, 8446 [ARG_PTR_TO_STACK] = &stack_ptr_types, 8447 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 8448 [ARG_PTR_TO_TIMER] = &timer_types, 8449 [ARG_KPTR_XCHG_DEST] = &kptr_xchg_dest_types, 8450 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 8451 }; 8452 8453 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 8454 enum bpf_arg_type arg_type, 8455 const u32 *arg_btf_id, 8456 struct bpf_call_arg_meta *meta) 8457 { 8458 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8459 enum bpf_reg_type expected, type = reg->type; 8460 const struct bpf_reg_types *compatible; 8461 int i, j; 8462 8463 compatible = compatible_reg_types[base_type(arg_type)]; 8464 if (!compatible) { 8465 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 8466 return -EFAULT; 8467 } 8468 8469 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 8470 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 8471 * 8472 * Same for MAYBE_NULL: 8473 * 8474 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 8475 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 8476 * 8477 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 8478 * 8479 * Therefore we fold these flags depending on the arg_type before comparison. 8480 */ 8481 if (arg_type & MEM_RDONLY) 8482 type &= ~MEM_RDONLY; 8483 if (arg_type & PTR_MAYBE_NULL) 8484 type &= ~PTR_MAYBE_NULL; 8485 if (base_type(arg_type) == ARG_PTR_TO_MEM) 8486 type &= ~DYNPTR_TYPE_FLAG_MASK; 8487 8488 /* Local kptr types are allowed as the source argument of bpf_kptr_xchg */ 8489 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) { 8490 type &= ~MEM_ALLOC; 8491 type &= ~MEM_PERCPU; 8492 } 8493 8494 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 8495 expected = compatible->types[i]; 8496 if (expected == NOT_INIT) 8497 break; 8498 8499 if (type == expected) 8500 goto found; 8501 } 8502 8503 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 8504 for (j = 0; j + 1 < i; j++) 8505 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 8506 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 8507 return -EACCES; 8508 8509 found: 8510 if (base_type(reg->type) != PTR_TO_BTF_ID) 8511 return 0; 8512 8513 if (compatible == &mem_types) { 8514 if (!(arg_type & MEM_RDONLY)) { 8515 verbose(env, 8516 "%s() may write into memory pointed by R%d type=%s\n", 8517 func_id_name(meta->func_id), 8518 regno, reg_type_str(env, reg->type)); 8519 return -EACCES; 8520 } 8521 return 0; 8522 } 8523 8524 switch ((int)reg->type) { 8525 case PTR_TO_BTF_ID: 8526 case PTR_TO_BTF_ID | PTR_TRUSTED: 8527 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL: 8528 case PTR_TO_BTF_ID | MEM_RCU: 8529 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 8530 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 8531 { 8532 /* For bpf_sk_release, it needs to match against first member 8533 * 'struct sock_common', hence make an exception for it. This 8534 * allows bpf_sk_release to work for multiple socket types. 8535 */ 8536 bool strict_type_match = arg_type_is_release(arg_type) && 8537 meta->func_id != BPF_FUNC_sk_release; 8538 8539 if (type_may_be_null(reg->type) && 8540 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 8541 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 8542 return -EACCES; 8543 } 8544 8545 if (!arg_btf_id) { 8546 if (!compatible->btf_id) { 8547 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 8548 return -EFAULT; 8549 } 8550 arg_btf_id = compatible->btf_id; 8551 } 8552 8553 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8554 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8555 return -EACCES; 8556 } else { 8557 if (arg_btf_id == BPF_PTR_POISON) { 8558 verbose(env, "verifier internal error:"); 8559 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 8560 regno); 8561 return -EACCES; 8562 } 8563 8564 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 8565 btf_vmlinux, *arg_btf_id, 8566 strict_type_match)) { 8567 verbose(env, "R%d is of type %s but %s is expected\n", 8568 regno, btf_type_name(reg->btf, reg->btf_id), 8569 btf_type_name(btf_vmlinux, *arg_btf_id)); 8570 return -EACCES; 8571 } 8572 } 8573 break; 8574 } 8575 case PTR_TO_BTF_ID | MEM_ALLOC: 8576 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 8577 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8578 meta->func_id != BPF_FUNC_kptr_xchg) { 8579 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 8580 return -EFAULT; 8581 } 8582 /* Check if local kptr in src arg matches kptr in dst arg */ 8583 if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) { 8584 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8585 return -EACCES; 8586 } 8587 break; 8588 case PTR_TO_BTF_ID | MEM_PERCPU: 8589 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 8590 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8591 /* Handled by helper specific checks */ 8592 break; 8593 default: 8594 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 8595 return -EFAULT; 8596 } 8597 return 0; 8598 } 8599 8600 static struct btf_field * 8601 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8602 { 8603 struct btf_field *field; 8604 struct btf_record *rec; 8605 8606 rec = reg_btf_record(reg); 8607 if (!rec) 8608 return NULL; 8609 8610 field = btf_record_find(rec, off, fields); 8611 if (!field) 8612 return NULL; 8613 8614 return field; 8615 } 8616 8617 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 8618 const struct bpf_reg_state *reg, int regno, 8619 enum bpf_arg_type arg_type) 8620 { 8621 u32 type = reg->type; 8622 8623 /* When referenced register is passed to release function, its fixed 8624 * offset must be 0. 8625 * 8626 * We will check arg_type_is_release reg has ref_obj_id when storing 8627 * meta->release_regno. 8628 */ 8629 if (arg_type_is_release(arg_type)) { 8630 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8631 * may not directly point to the object being released, but to 8632 * dynptr pointing to such object, which might be at some offset 8633 * on the stack. In that case, we simply to fallback to the 8634 * default handling. 8635 */ 8636 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8637 return 0; 8638 8639 /* Doing check_ptr_off_reg check for the offset will catch this 8640 * because fixed_off_ok is false, but checking here allows us 8641 * to give the user a better error message. 8642 */ 8643 if (reg->off) { 8644 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 8645 regno); 8646 return -EINVAL; 8647 } 8648 return __check_ptr_off_reg(env, reg, regno, false); 8649 } 8650 8651 switch (type) { 8652 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8653 case PTR_TO_STACK: 8654 case PTR_TO_PACKET: 8655 case PTR_TO_PACKET_META: 8656 case PTR_TO_MAP_KEY: 8657 case PTR_TO_MAP_VALUE: 8658 case PTR_TO_MEM: 8659 case PTR_TO_MEM | MEM_RDONLY: 8660 case PTR_TO_MEM | MEM_RINGBUF: 8661 case PTR_TO_BUF: 8662 case PTR_TO_BUF | MEM_RDONLY: 8663 case PTR_TO_ARENA: 8664 case SCALAR_VALUE: 8665 return 0; 8666 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8667 * fixed offset. 8668 */ 8669 case PTR_TO_BTF_ID: 8670 case PTR_TO_BTF_ID | MEM_ALLOC: 8671 case PTR_TO_BTF_ID | PTR_TRUSTED: 8672 case PTR_TO_BTF_ID | MEM_RCU: 8673 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8674 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8675 /* When referenced PTR_TO_BTF_ID is passed to release function, 8676 * its fixed offset must be 0. In the other cases, fixed offset 8677 * can be non-zero. This was already checked above. So pass 8678 * fixed_off_ok as true to allow fixed offset for all other 8679 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8680 * still need to do checks instead of returning. 8681 */ 8682 return __check_ptr_off_reg(env, reg, regno, true); 8683 default: 8684 return __check_ptr_off_reg(env, reg, regno, false); 8685 } 8686 } 8687 8688 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8689 const struct bpf_func_proto *fn, 8690 struct bpf_reg_state *regs) 8691 { 8692 struct bpf_reg_state *state = NULL; 8693 int i; 8694 8695 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8696 if (arg_type_is_dynptr(fn->arg_type[i])) { 8697 if (state) { 8698 verbose(env, "verifier internal error: multiple dynptr args\n"); 8699 return NULL; 8700 } 8701 state = ®s[BPF_REG_1 + i]; 8702 } 8703 8704 if (!state) 8705 verbose(env, "verifier internal error: no dynptr arg found\n"); 8706 8707 return state; 8708 } 8709 8710 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8711 { 8712 struct bpf_func_state *state = func(env, reg); 8713 int spi; 8714 8715 if (reg->type == CONST_PTR_TO_DYNPTR) 8716 return reg->id; 8717 spi = dynptr_get_spi(env, reg); 8718 if (spi < 0) 8719 return spi; 8720 return state->stack[spi].spilled_ptr.id; 8721 } 8722 8723 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8724 { 8725 struct bpf_func_state *state = func(env, reg); 8726 int spi; 8727 8728 if (reg->type == CONST_PTR_TO_DYNPTR) 8729 return reg->ref_obj_id; 8730 spi = dynptr_get_spi(env, reg); 8731 if (spi < 0) 8732 return spi; 8733 return state->stack[spi].spilled_ptr.ref_obj_id; 8734 } 8735 8736 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8737 struct bpf_reg_state *reg) 8738 { 8739 struct bpf_func_state *state = func(env, reg); 8740 int spi; 8741 8742 if (reg->type == CONST_PTR_TO_DYNPTR) 8743 return reg->dynptr.type; 8744 8745 spi = __get_spi(reg->off); 8746 if (spi < 0) { 8747 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8748 return BPF_DYNPTR_TYPE_INVALID; 8749 } 8750 8751 return state->stack[spi].spilled_ptr.dynptr.type; 8752 } 8753 8754 static int check_reg_const_str(struct bpf_verifier_env *env, 8755 struct bpf_reg_state *reg, u32 regno) 8756 { 8757 struct bpf_map *map = reg->map_ptr; 8758 int err; 8759 int map_off; 8760 u64 map_addr; 8761 char *str_ptr; 8762 8763 if (reg->type != PTR_TO_MAP_VALUE) 8764 return -EINVAL; 8765 8766 if (!bpf_map_is_rdonly(map)) { 8767 verbose(env, "R%d does not point to a readonly map'\n", regno); 8768 return -EACCES; 8769 } 8770 8771 if (!tnum_is_const(reg->var_off)) { 8772 verbose(env, "R%d is not a constant address'\n", regno); 8773 return -EACCES; 8774 } 8775 8776 if (!map->ops->map_direct_value_addr) { 8777 verbose(env, "no direct value access support for this map type\n"); 8778 return -EACCES; 8779 } 8780 8781 err = check_map_access(env, regno, reg->off, 8782 map->value_size - reg->off, false, 8783 ACCESS_HELPER); 8784 if (err) 8785 return err; 8786 8787 map_off = reg->off + reg->var_off.value; 8788 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8789 if (err) { 8790 verbose(env, "direct value access on string failed\n"); 8791 return err; 8792 } 8793 8794 str_ptr = (char *)(long)(map_addr); 8795 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8796 verbose(env, "string is not zero-terminated\n"); 8797 return -EINVAL; 8798 } 8799 return 0; 8800 } 8801 8802 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8803 struct bpf_call_arg_meta *meta, 8804 const struct bpf_func_proto *fn, 8805 int insn_idx) 8806 { 8807 u32 regno = BPF_REG_1 + arg; 8808 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8809 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8810 enum bpf_reg_type type = reg->type; 8811 u32 *arg_btf_id = NULL; 8812 int err = 0; 8813 8814 if (arg_type == ARG_DONTCARE) 8815 return 0; 8816 8817 err = check_reg_arg(env, regno, SRC_OP); 8818 if (err) 8819 return err; 8820 8821 if (arg_type == ARG_ANYTHING) { 8822 if (is_pointer_value(env, regno)) { 8823 verbose(env, "R%d leaks addr into helper function\n", 8824 regno); 8825 return -EACCES; 8826 } 8827 return 0; 8828 } 8829 8830 if (type_is_pkt_pointer(type) && 8831 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8832 verbose(env, "helper access to the packet is not allowed\n"); 8833 return -EACCES; 8834 } 8835 8836 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8837 err = resolve_map_arg_type(env, meta, &arg_type); 8838 if (err) 8839 return err; 8840 } 8841 8842 if (register_is_null(reg) && type_may_be_null(arg_type)) 8843 /* A NULL register has a SCALAR_VALUE type, so skip 8844 * type checking. 8845 */ 8846 goto skip_type_check; 8847 8848 /* arg_btf_id and arg_size are in a union. */ 8849 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8850 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8851 arg_btf_id = fn->arg_btf_id[arg]; 8852 8853 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 8854 if (err) 8855 return err; 8856 8857 err = check_func_arg_reg_off(env, reg, regno, arg_type); 8858 if (err) 8859 return err; 8860 8861 skip_type_check: 8862 if (arg_type_is_release(arg_type)) { 8863 if (arg_type_is_dynptr(arg_type)) { 8864 struct bpf_func_state *state = func(env, reg); 8865 int spi; 8866 8867 /* Only dynptr created on stack can be released, thus 8868 * the get_spi and stack state checks for spilled_ptr 8869 * should only be done before process_dynptr_func for 8870 * PTR_TO_STACK. 8871 */ 8872 if (reg->type == PTR_TO_STACK) { 8873 spi = dynptr_get_spi(env, reg); 8874 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8875 verbose(env, "arg %d is an unacquired reference\n", regno); 8876 return -EINVAL; 8877 } 8878 } else { 8879 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8880 return -EINVAL; 8881 } 8882 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 8883 verbose(env, "R%d must be referenced when passed to release function\n", 8884 regno); 8885 return -EINVAL; 8886 } 8887 if (meta->release_regno) { 8888 verbose(env, "verifier internal error: more than one release argument\n"); 8889 return -EFAULT; 8890 } 8891 meta->release_regno = regno; 8892 } 8893 8894 if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) { 8895 if (meta->ref_obj_id) { 8896 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 8897 regno, reg->ref_obj_id, 8898 meta->ref_obj_id); 8899 return -EFAULT; 8900 } 8901 meta->ref_obj_id = reg->ref_obj_id; 8902 } 8903 8904 switch (base_type(arg_type)) { 8905 case ARG_CONST_MAP_PTR: 8906 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8907 if (meta->map_ptr) { 8908 /* Use map_uid (which is unique id of inner map) to reject: 8909 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8910 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8911 * if (inner_map1 && inner_map2) { 8912 * timer = bpf_map_lookup_elem(inner_map1); 8913 * if (timer) 8914 * // mismatch would have been allowed 8915 * bpf_timer_init(timer, inner_map2); 8916 * } 8917 * 8918 * Comparing map_ptr is enough to distinguish normal and outer maps. 8919 */ 8920 if (meta->map_ptr != reg->map_ptr || 8921 meta->map_uid != reg->map_uid) { 8922 verbose(env, 8923 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8924 meta->map_uid, reg->map_uid); 8925 return -EINVAL; 8926 } 8927 } 8928 meta->map_ptr = reg->map_ptr; 8929 meta->map_uid = reg->map_uid; 8930 break; 8931 case ARG_PTR_TO_MAP_KEY: 8932 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8933 * check that [key, key + map->key_size) are within 8934 * stack limits and initialized 8935 */ 8936 if (!meta->map_ptr) { 8937 /* in function declaration map_ptr must come before 8938 * map_key, so that it's verified and known before 8939 * we have to check map_key here. Otherwise it means 8940 * that kernel subsystem misconfigured verifier 8941 */ 8942 verbose(env, "invalid map_ptr to access map->key\n"); 8943 return -EACCES; 8944 } 8945 err = check_helper_mem_access(env, regno, 8946 meta->map_ptr->key_size, false, 8947 NULL); 8948 break; 8949 case ARG_PTR_TO_MAP_VALUE: 8950 if (type_may_be_null(arg_type) && register_is_null(reg)) 8951 return 0; 8952 8953 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8954 * check [value, value + map->value_size) validity 8955 */ 8956 if (!meta->map_ptr) { 8957 /* kernel subsystem misconfigured verifier */ 8958 verbose(env, "invalid map_ptr to access map->value\n"); 8959 return -EACCES; 8960 } 8961 meta->raw_mode = arg_type & MEM_UNINIT; 8962 err = check_helper_mem_access(env, regno, 8963 meta->map_ptr->value_size, false, 8964 meta); 8965 break; 8966 case ARG_PTR_TO_PERCPU_BTF_ID: 8967 if (!reg->btf_id) { 8968 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8969 return -EACCES; 8970 } 8971 meta->ret_btf = reg->btf; 8972 meta->ret_btf_id = reg->btf_id; 8973 break; 8974 case ARG_PTR_TO_SPIN_LOCK: 8975 if (in_rbtree_lock_required_cb(env)) { 8976 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8977 return -EACCES; 8978 } 8979 if (meta->func_id == BPF_FUNC_spin_lock) { 8980 err = process_spin_lock(env, regno, true); 8981 if (err) 8982 return err; 8983 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8984 err = process_spin_lock(env, regno, false); 8985 if (err) 8986 return err; 8987 } else { 8988 verbose(env, "verifier internal error\n"); 8989 return -EFAULT; 8990 } 8991 break; 8992 case ARG_PTR_TO_TIMER: 8993 err = process_timer_func(env, regno, meta); 8994 if (err) 8995 return err; 8996 break; 8997 case ARG_PTR_TO_FUNC: 8998 meta->subprogno = reg->subprogno; 8999 break; 9000 case ARG_PTR_TO_MEM: 9001 /* The access to this pointer is only checked when we hit the 9002 * next is_mem_size argument below. 9003 */ 9004 meta->raw_mode = arg_type & MEM_UNINIT; 9005 if (arg_type & MEM_FIXED_SIZE) { 9006 err = check_helper_mem_access(env, regno, fn->arg_size[arg], false, meta); 9007 if (err) 9008 return err; 9009 if (arg_type & MEM_ALIGNED) 9010 err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true); 9011 } 9012 break; 9013 case ARG_CONST_SIZE: 9014 err = check_mem_size_reg(env, reg, regno, false, meta); 9015 break; 9016 case ARG_CONST_SIZE_OR_ZERO: 9017 err = check_mem_size_reg(env, reg, regno, true, meta); 9018 break; 9019 case ARG_PTR_TO_DYNPTR: 9020 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 9021 if (err) 9022 return err; 9023 break; 9024 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 9025 if (!tnum_is_const(reg->var_off)) { 9026 verbose(env, "R%d is not a known constant'\n", 9027 regno); 9028 return -EACCES; 9029 } 9030 meta->mem_size = reg->var_off.value; 9031 err = mark_chain_precision(env, regno); 9032 if (err) 9033 return err; 9034 break; 9035 case ARG_PTR_TO_CONST_STR: 9036 { 9037 err = check_reg_const_str(env, reg, regno); 9038 if (err) 9039 return err; 9040 break; 9041 } 9042 case ARG_KPTR_XCHG_DEST: 9043 err = process_kptr_func(env, regno, meta); 9044 if (err) 9045 return err; 9046 break; 9047 } 9048 9049 return err; 9050 } 9051 9052 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 9053 { 9054 enum bpf_attach_type eatype = env->prog->expected_attach_type; 9055 enum bpf_prog_type type = resolve_prog_type(env->prog); 9056 9057 if (func_id != BPF_FUNC_map_update_elem && 9058 func_id != BPF_FUNC_map_delete_elem) 9059 return false; 9060 9061 /* It's not possible to get access to a locked struct sock in these 9062 * contexts, so updating is safe. 9063 */ 9064 switch (type) { 9065 case BPF_PROG_TYPE_TRACING: 9066 if (eatype == BPF_TRACE_ITER) 9067 return true; 9068 break; 9069 case BPF_PROG_TYPE_SOCK_OPS: 9070 /* map_update allowed only via dedicated helpers with event type checks */ 9071 if (func_id == BPF_FUNC_map_delete_elem) 9072 return true; 9073 break; 9074 case BPF_PROG_TYPE_SOCKET_FILTER: 9075 case BPF_PROG_TYPE_SCHED_CLS: 9076 case BPF_PROG_TYPE_SCHED_ACT: 9077 case BPF_PROG_TYPE_XDP: 9078 case BPF_PROG_TYPE_SK_REUSEPORT: 9079 case BPF_PROG_TYPE_FLOW_DISSECTOR: 9080 case BPF_PROG_TYPE_SK_LOOKUP: 9081 return true; 9082 default: 9083 break; 9084 } 9085 9086 verbose(env, "cannot update sockmap in this context\n"); 9087 return false; 9088 } 9089 9090 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 9091 { 9092 return env->prog->jit_requested && 9093 bpf_jit_supports_subprog_tailcalls(); 9094 } 9095 9096 static int check_map_func_compatibility(struct bpf_verifier_env *env, 9097 struct bpf_map *map, int func_id) 9098 { 9099 if (!map) 9100 return 0; 9101 9102 /* We need a two way check, first is from map perspective ... */ 9103 switch (map->map_type) { 9104 case BPF_MAP_TYPE_PROG_ARRAY: 9105 if (func_id != BPF_FUNC_tail_call) 9106 goto error; 9107 break; 9108 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 9109 if (func_id != BPF_FUNC_perf_event_read && 9110 func_id != BPF_FUNC_perf_event_output && 9111 func_id != BPF_FUNC_skb_output && 9112 func_id != BPF_FUNC_perf_event_read_value && 9113 func_id != BPF_FUNC_xdp_output) 9114 goto error; 9115 break; 9116 case BPF_MAP_TYPE_RINGBUF: 9117 if (func_id != BPF_FUNC_ringbuf_output && 9118 func_id != BPF_FUNC_ringbuf_reserve && 9119 func_id != BPF_FUNC_ringbuf_query && 9120 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 9121 func_id != BPF_FUNC_ringbuf_submit_dynptr && 9122 func_id != BPF_FUNC_ringbuf_discard_dynptr) 9123 goto error; 9124 break; 9125 case BPF_MAP_TYPE_USER_RINGBUF: 9126 if (func_id != BPF_FUNC_user_ringbuf_drain) 9127 goto error; 9128 break; 9129 case BPF_MAP_TYPE_STACK_TRACE: 9130 if (func_id != BPF_FUNC_get_stackid) 9131 goto error; 9132 break; 9133 case BPF_MAP_TYPE_CGROUP_ARRAY: 9134 if (func_id != BPF_FUNC_skb_under_cgroup && 9135 func_id != BPF_FUNC_current_task_under_cgroup) 9136 goto error; 9137 break; 9138 case BPF_MAP_TYPE_CGROUP_STORAGE: 9139 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 9140 if (func_id != BPF_FUNC_get_local_storage) 9141 goto error; 9142 break; 9143 case BPF_MAP_TYPE_DEVMAP: 9144 case BPF_MAP_TYPE_DEVMAP_HASH: 9145 if (func_id != BPF_FUNC_redirect_map && 9146 func_id != BPF_FUNC_map_lookup_elem) 9147 goto error; 9148 break; 9149 /* Restrict bpf side of cpumap and xskmap, open when use-cases 9150 * appear. 9151 */ 9152 case BPF_MAP_TYPE_CPUMAP: 9153 if (func_id != BPF_FUNC_redirect_map) 9154 goto error; 9155 break; 9156 case BPF_MAP_TYPE_XSKMAP: 9157 if (func_id != BPF_FUNC_redirect_map && 9158 func_id != BPF_FUNC_map_lookup_elem) 9159 goto error; 9160 break; 9161 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 9162 case BPF_MAP_TYPE_HASH_OF_MAPS: 9163 if (func_id != BPF_FUNC_map_lookup_elem) 9164 goto error; 9165 break; 9166 case BPF_MAP_TYPE_SOCKMAP: 9167 if (func_id != BPF_FUNC_sk_redirect_map && 9168 func_id != BPF_FUNC_sock_map_update && 9169 func_id != BPF_FUNC_msg_redirect_map && 9170 func_id != BPF_FUNC_sk_select_reuseport && 9171 func_id != BPF_FUNC_map_lookup_elem && 9172 !may_update_sockmap(env, func_id)) 9173 goto error; 9174 break; 9175 case BPF_MAP_TYPE_SOCKHASH: 9176 if (func_id != BPF_FUNC_sk_redirect_hash && 9177 func_id != BPF_FUNC_sock_hash_update && 9178 func_id != BPF_FUNC_msg_redirect_hash && 9179 func_id != BPF_FUNC_sk_select_reuseport && 9180 func_id != BPF_FUNC_map_lookup_elem && 9181 !may_update_sockmap(env, func_id)) 9182 goto error; 9183 break; 9184 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 9185 if (func_id != BPF_FUNC_sk_select_reuseport) 9186 goto error; 9187 break; 9188 case BPF_MAP_TYPE_QUEUE: 9189 case BPF_MAP_TYPE_STACK: 9190 if (func_id != BPF_FUNC_map_peek_elem && 9191 func_id != BPF_FUNC_map_pop_elem && 9192 func_id != BPF_FUNC_map_push_elem) 9193 goto error; 9194 break; 9195 case BPF_MAP_TYPE_SK_STORAGE: 9196 if (func_id != BPF_FUNC_sk_storage_get && 9197 func_id != BPF_FUNC_sk_storage_delete && 9198 func_id != BPF_FUNC_kptr_xchg) 9199 goto error; 9200 break; 9201 case BPF_MAP_TYPE_INODE_STORAGE: 9202 if (func_id != BPF_FUNC_inode_storage_get && 9203 func_id != BPF_FUNC_inode_storage_delete && 9204 func_id != BPF_FUNC_kptr_xchg) 9205 goto error; 9206 break; 9207 case BPF_MAP_TYPE_TASK_STORAGE: 9208 if (func_id != BPF_FUNC_task_storage_get && 9209 func_id != BPF_FUNC_task_storage_delete && 9210 func_id != BPF_FUNC_kptr_xchg) 9211 goto error; 9212 break; 9213 case BPF_MAP_TYPE_CGRP_STORAGE: 9214 if (func_id != BPF_FUNC_cgrp_storage_get && 9215 func_id != BPF_FUNC_cgrp_storage_delete && 9216 func_id != BPF_FUNC_kptr_xchg) 9217 goto error; 9218 break; 9219 case BPF_MAP_TYPE_BLOOM_FILTER: 9220 if (func_id != BPF_FUNC_map_peek_elem && 9221 func_id != BPF_FUNC_map_push_elem) 9222 goto error; 9223 break; 9224 default: 9225 break; 9226 } 9227 9228 /* ... and second from the function itself. */ 9229 switch (func_id) { 9230 case BPF_FUNC_tail_call: 9231 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 9232 goto error; 9233 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 9234 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 9235 return -EINVAL; 9236 } 9237 break; 9238 case BPF_FUNC_perf_event_read: 9239 case BPF_FUNC_perf_event_output: 9240 case BPF_FUNC_perf_event_read_value: 9241 case BPF_FUNC_skb_output: 9242 case BPF_FUNC_xdp_output: 9243 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 9244 goto error; 9245 break; 9246 case BPF_FUNC_ringbuf_output: 9247 case BPF_FUNC_ringbuf_reserve: 9248 case BPF_FUNC_ringbuf_query: 9249 case BPF_FUNC_ringbuf_reserve_dynptr: 9250 case BPF_FUNC_ringbuf_submit_dynptr: 9251 case BPF_FUNC_ringbuf_discard_dynptr: 9252 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 9253 goto error; 9254 break; 9255 case BPF_FUNC_user_ringbuf_drain: 9256 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 9257 goto error; 9258 break; 9259 case BPF_FUNC_get_stackid: 9260 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 9261 goto error; 9262 break; 9263 case BPF_FUNC_current_task_under_cgroup: 9264 case BPF_FUNC_skb_under_cgroup: 9265 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 9266 goto error; 9267 break; 9268 case BPF_FUNC_redirect_map: 9269 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 9270 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 9271 map->map_type != BPF_MAP_TYPE_CPUMAP && 9272 map->map_type != BPF_MAP_TYPE_XSKMAP) 9273 goto error; 9274 break; 9275 case BPF_FUNC_sk_redirect_map: 9276 case BPF_FUNC_msg_redirect_map: 9277 case BPF_FUNC_sock_map_update: 9278 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 9279 goto error; 9280 break; 9281 case BPF_FUNC_sk_redirect_hash: 9282 case BPF_FUNC_msg_redirect_hash: 9283 case BPF_FUNC_sock_hash_update: 9284 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 9285 goto error; 9286 break; 9287 case BPF_FUNC_get_local_storage: 9288 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 9289 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 9290 goto error; 9291 break; 9292 case BPF_FUNC_sk_select_reuseport: 9293 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 9294 map->map_type != BPF_MAP_TYPE_SOCKMAP && 9295 map->map_type != BPF_MAP_TYPE_SOCKHASH) 9296 goto error; 9297 break; 9298 case BPF_FUNC_map_pop_elem: 9299 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9300 map->map_type != BPF_MAP_TYPE_STACK) 9301 goto error; 9302 break; 9303 case BPF_FUNC_map_peek_elem: 9304 case BPF_FUNC_map_push_elem: 9305 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9306 map->map_type != BPF_MAP_TYPE_STACK && 9307 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 9308 goto error; 9309 break; 9310 case BPF_FUNC_map_lookup_percpu_elem: 9311 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 9312 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 9313 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 9314 goto error; 9315 break; 9316 case BPF_FUNC_sk_storage_get: 9317 case BPF_FUNC_sk_storage_delete: 9318 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 9319 goto error; 9320 break; 9321 case BPF_FUNC_inode_storage_get: 9322 case BPF_FUNC_inode_storage_delete: 9323 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 9324 goto error; 9325 break; 9326 case BPF_FUNC_task_storage_get: 9327 case BPF_FUNC_task_storage_delete: 9328 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 9329 goto error; 9330 break; 9331 case BPF_FUNC_cgrp_storage_get: 9332 case BPF_FUNC_cgrp_storage_delete: 9333 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 9334 goto error; 9335 break; 9336 default: 9337 break; 9338 } 9339 9340 return 0; 9341 error: 9342 verbose(env, "cannot pass map_type %d into func %s#%d\n", 9343 map->map_type, func_id_name(func_id), func_id); 9344 return -EINVAL; 9345 } 9346 9347 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 9348 { 9349 int count = 0; 9350 9351 if (arg_type_is_raw_mem(fn->arg1_type)) 9352 count++; 9353 if (arg_type_is_raw_mem(fn->arg2_type)) 9354 count++; 9355 if (arg_type_is_raw_mem(fn->arg3_type)) 9356 count++; 9357 if (arg_type_is_raw_mem(fn->arg4_type)) 9358 count++; 9359 if (arg_type_is_raw_mem(fn->arg5_type)) 9360 count++; 9361 9362 /* We only support one arg being in raw mode at the moment, 9363 * which is sufficient for the helper functions we have 9364 * right now. 9365 */ 9366 return count <= 1; 9367 } 9368 9369 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 9370 { 9371 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 9372 bool has_size = fn->arg_size[arg] != 0; 9373 bool is_next_size = false; 9374 9375 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 9376 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 9377 9378 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 9379 return is_next_size; 9380 9381 return has_size == is_next_size || is_next_size == is_fixed; 9382 } 9383 9384 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 9385 { 9386 /* bpf_xxx(..., buf, len) call will access 'len' 9387 * bytes from memory 'buf'. Both arg types need 9388 * to be paired, so make sure there's no buggy 9389 * helper function specification. 9390 */ 9391 if (arg_type_is_mem_size(fn->arg1_type) || 9392 check_args_pair_invalid(fn, 0) || 9393 check_args_pair_invalid(fn, 1) || 9394 check_args_pair_invalid(fn, 2) || 9395 check_args_pair_invalid(fn, 3) || 9396 check_args_pair_invalid(fn, 4)) 9397 return false; 9398 9399 return true; 9400 } 9401 9402 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 9403 { 9404 int i; 9405 9406 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 9407 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 9408 return !!fn->arg_btf_id[i]; 9409 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 9410 return fn->arg_btf_id[i] == BPF_PTR_POISON; 9411 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 9412 /* arg_btf_id and arg_size are in a union. */ 9413 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 9414 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 9415 return false; 9416 } 9417 9418 return true; 9419 } 9420 9421 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 9422 { 9423 return check_raw_mode_ok(fn) && 9424 check_arg_pair_ok(fn) && 9425 check_btf_id_ok(fn) ? 0 : -EINVAL; 9426 } 9427 9428 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 9429 * are now invalid, so turn them into unknown SCALAR_VALUE. 9430 * 9431 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 9432 * since these slices point to packet data. 9433 */ 9434 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 9435 { 9436 struct bpf_func_state *state; 9437 struct bpf_reg_state *reg; 9438 9439 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9440 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 9441 mark_reg_invalid(env, reg); 9442 })); 9443 } 9444 9445 enum { 9446 AT_PKT_END = -1, 9447 BEYOND_PKT_END = -2, 9448 }; 9449 9450 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 9451 { 9452 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9453 struct bpf_reg_state *reg = &state->regs[regn]; 9454 9455 if (reg->type != PTR_TO_PACKET) 9456 /* PTR_TO_PACKET_META is not supported yet */ 9457 return; 9458 9459 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 9460 * How far beyond pkt_end it goes is unknown. 9461 * if (!range_open) it's the case of pkt >= pkt_end 9462 * if (range_open) it's the case of pkt > pkt_end 9463 * hence this pointer is at least 1 byte bigger than pkt_end 9464 */ 9465 if (range_open) 9466 reg->range = BEYOND_PKT_END; 9467 else 9468 reg->range = AT_PKT_END; 9469 } 9470 9471 /* The pointer with the specified id has released its reference to kernel 9472 * resources. Identify all copies of the same pointer and clear the reference. 9473 */ 9474 static int release_reference(struct bpf_verifier_env *env, 9475 int ref_obj_id) 9476 { 9477 struct bpf_func_state *state; 9478 struct bpf_reg_state *reg; 9479 int err; 9480 9481 err = release_reference_state(cur_func(env), ref_obj_id); 9482 if (err) 9483 return err; 9484 9485 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9486 if (reg->ref_obj_id == ref_obj_id) 9487 mark_reg_invalid(env, reg); 9488 })); 9489 9490 return 0; 9491 } 9492 9493 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9494 { 9495 struct bpf_func_state *unused; 9496 struct bpf_reg_state *reg; 9497 9498 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9499 if (type_is_non_owning_ref(reg->type)) 9500 mark_reg_invalid(env, reg); 9501 })); 9502 } 9503 9504 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9505 struct bpf_reg_state *regs) 9506 { 9507 int i; 9508 9509 /* after the call registers r0 - r5 were scratched */ 9510 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9511 mark_reg_not_init(env, regs, caller_saved[i]); 9512 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9513 } 9514 } 9515 9516 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9517 struct bpf_func_state *caller, 9518 struct bpf_func_state *callee, 9519 int insn_idx); 9520 9521 static int set_callee_state(struct bpf_verifier_env *env, 9522 struct bpf_func_state *caller, 9523 struct bpf_func_state *callee, int insn_idx); 9524 9525 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9526 set_callee_state_fn set_callee_state_cb, 9527 struct bpf_verifier_state *state) 9528 { 9529 struct bpf_func_state *caller, *callee; 9530 int err; 9531 9532 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9533 verbose(env, "the call stack of %d frames is too deep\n", 9534 state->curframe + 2); 9535 return -E2BIG; 9536 } 9537 9538 if (state->frame[state->curframe + 1]) { 9539 verbose(env, "verifier bug. Frame %d already allocated\n", 9540 state->curframe + 1); 9541 return -EFAULT; 9542 } 9543 9544 caller = state->frame[state->curframe]; 9545 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 9546 if (!callee) 9547 return -ENOMEM; 9548 state->frame[state->curframe + 1] = callee; 9549 9550 /* callee cannot access r0, r6 - r9 for reading and has to write 9551 * into its own stack before reading from it. 9552 * callee can read/write into caller's stack 9553 */ 9554 init_func_state(env, callee, 9555 /* remember the callsite, it will be used by bpf_exit */ 9556 callsite, 9557 state->curframe + 1 /* frameno within this callchain */, 9558 subprog /* subprog number within this prog */); 9559 /* Transfer references to the callee */ 9560 err = copy_reference_state(callee, caller); 9561 err = err ?: set_callee_state_cb(env, caller, callee, callsite); 9562 if (err) 9563 goto err_out; 9564 9565 /* only increment it after check_reg_arg() finished */ 9566 state->curframe++; 9567 9568 return 0; 9569 9570 err_out: 9571 free_func_state(callee); 9572 state->frame[state->curframe + 1] = NULL; 9573 return err; 9574 } 9575 9576 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, 9577 const struct btf *btf, 9578 struct bpf_reg_state *regs) 9579 { 9580 struct bpf_subprog_info *sub = subprog_info(env, subprog); 9581 struct bpf_verifier_log *log = &env->log; 9582 u32 i; 9583 int ret; 9584 9585 ret = btf_prepare_func_args(env, subprog); 9586 if (ret) 9587 return ret; 9588 9589 /* check that BTF function arguments match actual types that the 9590 * verifier sees. 9591 */ 9592 for (i = 0; i < sub->arg_cnt; i++) { 9593 u32 regno = i + 1; 9594 struct bpf_reg_state *reg = ®s[regno]; 9595 struct bpf_subprog_arg_info *arg = &sub->args[i]; 9596 9597 if (arg->arg_type == ARG_ANYTHING) { 9598 if (reg->type != SCALAR_VALUE) { 9599 bpf_log(log, "R%d is not a scalar\n", regno); 9600 return -EINVAL; 9601 } 9602 } else if (arg->arg_type == ARG_PTR_TO_CTX) { 9603 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9604 if (ret < 0) 9605 return ret; 9606 /* If function expects ctx type in BTF check that caller 9607 * is passing PTR_TO_CTX. 9608 */ 9609 if (reg->type != PTR_TO_CTX) { 9610 bpf_log(log, "arg#%d expects pointer to ctx\n", i); 9611 return -EINVAL; 9612 } 9613 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 9614 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9615 if (ret < 0) 9616 return ret; 9617 if (check_mem_reg(env, reg, regno, arg->mem_size)) 9618 return -EINVAL; 9619 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) { 9620 bpf_log(log, "arg#%d is expected to be non-NULL\n", i); 9621 return -EINVAL; 9622 } 9623 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 9624 /* 9625 * Can pass any value and the kernel won't crash, but 9626 * only PTR_TO_ARENA or SCALAR make sense. Everything 9627 * else is a bug in the bpf program. Point it out to 9628 * the user at the verification time instead of 9629 * run-time debug nightmare. 9630 */ 9631 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) { 9632 bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno); 9633 return -EINVAL; 9634 } 9635 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 9636 ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR); 9637 if (ret) 9638 return ret; 9639 9640 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0); 9641 if (ret) 9642 return ret; 9643 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 9644 struct bpf_call_arg_meta meta; 9645 int err; 9646 9647 if (register_is_null(reg) && type_may_be_null(arg->arg_type)) 9648 continue; 9649 9650 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */ 9651 err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta); 9652 err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type); 9653 if (err) 9654 return err; 9655 } else { 9656 bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n", 9657 i, arg->arg_type); 9658 return -EFAULT; 9659 } 9660 } 9661 9662 return 0; 9663 } 9664 9665 /* Compare BTF of a function call with given bpf_reg_state. 9666 * Returns: 9667 * EFAULT - there is a verifier bug. Abort verification. 9668 * EINVAL - there is a type mismatch or BTF is not available. 9669 * 0 - BTF matches with what bpf_reg_state expects. 9670 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized. 9671 */ 9672 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog, 9673 struct bpf_reg_state *regs) 9674 { 9675 struct bpf_prog *prog = env->prog; 9676 struct btf *btf = prog->aux->btf; 9677 u32 btf_id; 9678 int err; 9679 9680 if (!prog->aux->func_info) 9681 return -EINVAL; 9682 9683 btf_id = prog->aux->func_info[subprog].type_id; 9684 if (!btf_id) 9685 return -EFAULT; 9686 9687 if (prog->aux->func_info_aux[subprog].unreliable) 9688 return -EINVAL; 9689 9690 err = btf_check_func_arg_match(env, subprog, btf, regs); 9691 /* Compiler optimizations can remove arguments from static functions 9692 * or mismatched type can be passed into a global function. 9693 * In such cases mark the function as unreliable from BTF point of view. 9694 */ 9695 if (err) 9696 prog->aux->func_info_aux[subprog].unreliable = true; 9697 return err; 9698 } 9699 9700 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9701 int insn_idx, int subprog, 9702 set_callee_state_fn set_callee_state_cb) 9703 { 9704 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9705 struct bpf_func_state *caller, *callee; 9706 int err; 9707 9708 caller = state->frame[state->curframe]; 9709 err = btf_check_subprog_call(env, subprog, caller->regs); 9710 if (err == -EFAULT) 9711 return err; 9712 9713 /* set_callee_state is used for direct subprog calls, but we are 9714 * interested in validating only BPF helpers that can call subprogs as 9715 * callbacks 9716 */ 9717 env->subprog_info[subprog].is_cb = true; 9718 if (bpf_pseudo_kfunc_call(insn) && 9719 !is_callback_calling_kfunc(insn->imm)) { 9720 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 9721 func_id_name(insn->imm), insn->imm); 9722 return -EFAULT; 9723 } else if (!bpf_pseudo_kfunc_call(insn) && 9724 !is_callback_calling_function(insn->imm)) { /* helper */ 9725 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 9726 func_id_name(insn->imm), insn->imm); 9727 return -EFAULT; 9728 } 9729 9730 if (is_async_callback_calling_insn(insn)) { 9731 struct bpf_verifier_state *async_cb; 9732 9733 /* there is no real recursion here. timer and workqueue callbacks are async */ 9734 env->subprog_info[subprog].is_async_cb = true; 9735 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9736 insn_idx, subprog, 9737 is_bpf_wq_set_callback_impl_kfunc(insn->imm)); 9738 if (!async_cb) 9739 return -EFAULT; 9740 callee = async_cb->frame[0]; 9741 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9742 9743 /* Convert bpf_timer_set_callback() args into timer callback args */ 9744 err = set_callee_state_cb(env, caller, callee, insn_idx); 9745 if (err) 9746 return err; 9747 9748 return 0; 9749 } 9750 9751 /* for callback functions enqueue entry to callback and 9752 * proceed with next instruction within current frame. 9753 */ 9754 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9755 if (!callback_state) 9756 return -ENOMEM; 9757 9758 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9759 callback_state); 9760 if (err) 9761 return err; 9762 9763 callback_state->callback_unroll_depth++; 9764 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9765 caller->callback_depth = 0; 9766 return 0; 9767 } 9768 9769 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9770 int *insn_idx) 9771 { 9772 struct bpf_verifier_state *state = env->cur_state; 9773 struct bpf_func_state *caller; 9774 int err, subprog, target_insn; 9775 9776 target_insn = *insn_idx + insn->imm + 1; 9777 subprog = find_subprog(env, target_insn); 9778 if (subprog < 0) { 9779 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn); 9780 return -EFAULT; 9781 } 9782 9783 caller = state->frame[state->curframe]; 9784 err = btf_check_subprog_call(env, subprog, caller->regs); 9785 if (err == -EFAULT) 9786 return err; 9787 if (subprog_is_global(env, subprog)) { 9788 const char *sub_name = subprog_name(env, subprog); 9789 9790 /* Only global subprogs cannot be called with a lock held. */ 9791 if (env->cur_state->active_lock.ptr) { 9792 verbose(env, "global function calls are not allowed while holding a lock,\n" 9793 "use static function instead\n"); 9794 return -EINVAL; 9795 } 9796 9797 /* Only global subprogs cannot be called with preemption disabled. */ 9798 if (env->cur_state->active_preempt_lock) { 9799 verbose(env, "global function calls are not allowed with preemption disabled,\n" 9800 "use static function instead\n"); 9801 return -EINVAL; 9802 } 9803 9804 if (err) { 9805 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 9806 subprog, sub_name); 9807 return err; 9808 } 9809 9810 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 9811 subprog, sub_name); 9812 /* mark global subprog for verifying after main prog */ 9813 subprog_aux(env, subprog)->called = true; 9814 clear_caller_saved_regs(env, caller->regs); 9815 9816 /* All global functions return a 64-bit SCALAR_VALUE */ 9817 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9818 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9819 9820 /* continue with next insn after call */ 9821 return 0; 9822 } 9823 9824 /* for regular function entry setup new frame and continue 9825 * from that frame. 9826 */ 9827 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9828 if (err) 9829 return err; 9830 9831 clear_caller_saved_regs(env, caller->regs); 9832 9833 /* and go analyze first insn of the callee */ 9834 *insn_idx = env->subprog_info[subprog].start - 1; 9835 9836 if (env->log.level & BPF_LOG_LEVEL) { 9837 verbose(env, "caller:\n"); 9838 print_verifier_state(env, caller, true); 9839 verbose(env, "callee:\n"); 9840 print_verifier_state(env, state->frame[state->curframe], true); 9841 } 9842 9843 return 0; 9844 } 9845 9846 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9847 struct bpf_func_state *caller, 9848 struct bpf_func_state *callee) 9849 { 9850 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9851 * void *callback_ctx, u64 flags); 9852 * callback_fn(struct bpf_map *map, void *key, void *value, 9853 * void *callback_ctx); 9854 */ 9855 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9856 9857 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9858 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9859 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9860 9861 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9862 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9863 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9864 9865 /* pointer to stack or null */ 9866 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9867 9868 /* unused */ 9869 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9870 return 0; 9871 } 9872 9873 static int set_callee_state(struct bpf_verifier_env *env, 9874 struct bpf_func_state *caller, 9875 struct bpf_func_state *callee, int insn_idx) 9876 { 9877 int i; 9878 9879 /* copy r1 - r5 args that callee can access. The copy includes parent 9880 * pointers, which connects us up to the liveness chain 9881 */ 9882 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9883 callee->regs[i] = caller->regs[i]; 9884 return 0; 9885 } 9886 9887 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9888 struct bpf_func_state *caller, 9889 struct bpf_func_state *callee, 9890 int insn_idx) 9891 { 9892 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9893 struct bpf_map *map; 9894 int err; 9895 9896 /* valid map_ptr and poison value does not matter */ 9897 map = insn_aux->map_ptr_state.map_ptr; 9898 if (!map->ops->map_set_for_each_callback_args || 9899 !map->ops->map_for_each_callback) { 9900 verbose(env, "callback function not allowed for map\n"); 9901 return -ENOTSUPP; 9902 } 9903 9904 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9905 if (err) 9906 return err; 9907 9908 callee->in_callback_fn = true; 9909 callee->callback_ret_range = retval_range(0, 1); 9910 return 0; 9911 } 9912 9913 static int set_loop_callback_state(struct bpf_verifier_env *env, 9914 struct bpf_func_state *caller, 9915 struct bpf_func_state *callee, 9916 int insn_idx) 9917 { 9918 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9919 * u64 flags); 9920 * callback_fn(u32 index, void *callback_ctx); 9921 */ 9922 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9923 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9924 9925 /* unused */ 9926 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9927 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9928 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9929 9930 callee->in_callback_fn = true; 9931 callee->callback_ret_range = retval_range(0, 1); 9932 return 0; 9933 } 9934 9935 static int set_timer_callback_state(struct bpf_verifier_env *env, 9936 struct bpf_func_state *caller, 9937 struct bpf_func_state *callee, 9938 int insn_idx) 9939 { 9940 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9941 9942 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9943 * callback_fn(struct bpf_map *map, void *key, void *value); 9944 */ 9945 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9946 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9947 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9948 9949 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9950 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9951 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9952 9953 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9954 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9955 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9956 9957 /* unused */ 9958 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9959 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9960 callee->in_async_callback_fn = true; 9961 callee->callback_ret_range = retval_range(0, 1); 9962 return 0; 9963 } 9964 9965 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9966 struct bpf_func_state *caller, 9967 struct bpf_func_state *callee, 9968 int insn_idx) 9969 { 9970 /* bpf_find_vma(struct task_struct *task, u64 addr, 9971 * void *callback_fn, void *callback_ctx, u64 flags) 9972 * (callback_fn)(struct task_struct *task, 9973 * struct vm_area_struct *vma, void *callback_ctx); 9974 */ 9975 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9976 9977 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9978 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9979 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9980 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 9981 9982 /* pointer to stack or null */ 9983 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9984 9985 /* unused */ 9986 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9987 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9988 callee->in_callback_fn = true; 9989 callee->callback_ret_range = retval_range(0, 1); 9990 return 0; 9991 } 9992 9993 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9994 struct bpf_func_state *caller, 9995 struct bpf_func_state *callee, 9996 int insn_idx) 9997 { 9998 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9999 * callback_ctx, u64 flags); 10000 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 10001 */ 10002 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 10003 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 10004 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 10005 10006 /* unused */ 10007 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 10008 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10009 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10010 10011 callee->in_callback_fn = true; 10012 callee->callback_ret_range = retval_range(0, 1); 10013 return 0; 10014 } 10015 10016 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 10017 struct bpf_func_state *caller, 10018 struct bpf_func_state *callee, 10019 int insn_idx) 10020 { 10021 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 10022 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 10023 * 10024 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 10025 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 10026 * by this point, so look at 'root' 10027 */ 10028 struct btf_field *field; 10029 10030 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 10031 BPF_RB_ROOT); 10032 if (!field || !field->graph_root.value_btf_id) 10033 return -EFAULT; 10034 10035 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 10036 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 10037 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 10038 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 10039 10040 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 10041 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10042 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10043 callee->in_callback_fn = true; 10044 callee->callback_ret_range = retval_range(0, 1); 10045 return 0; 10046 } 10047 10048 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 10049 10050 /* Are we currently verifying the callback for a rbtree helper that must 10051 * be called with lock held? If so, no need to complain about unreleased 10052 * lock 10053 */ 10054 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 10055 { 10056 struct bpf_verifier_state *state = env->cur_state; 10057 struct bpf_insn *insn = env->prog->insnsi; 10058 struct bpf_func_state *callee; 10059 int kfunc_btf_id; 10060 10061 if (!state->curframe) 10062 return false; 10063 10064 callee = state->frame[state->curframe]; 10065 10066 if (!callee->in_callback_fn) 10067 return false; 10068 10069 kfunc_btf_id = insn[callee->callsite].imm; 10070 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 10071 } 10072 10073 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg, 10074 bool return_32bit) 10075 { 10076 if (return_32bit) 10077 return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval; 10078 else 10079 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval; 10080 } 10081 10082 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 10083 { 10084 struct bpf_verifier_state *state = env->cur_state, *prev_st; 10085 struct bpf_func_state *caller, *callee; 10086 struct bpf_reg_state *r0; 10087 bool in_callback_fn; 10088 int err; 10089 10090 callee = state->frame[state->curframe]; 10091 r0 = &callee->regs[BPF_REG_0]; 10092 if (r0->type == PTR_TO_STACK) { 10093 /* technically it's ok to return caller's stack pointer 10094 * (or caller's caller's pointer) back to the caller, 10095 * since these pointers are valid. Only current stack 10096 * pointer will be invalid as soon as function exits, 10097 * but let's be conservative 10098 */ 10099 verbose(env, "cannot return stack pointer to the caller\n"); 10100 return -EINVAL; 10101 } 10102 10103 caller = state->frame[state->curframe - 1]; 10104 if (callee->in_callback_fn) { 10105 if (r0->type != SCALAR_VALUE) { 10106 verbose(env, "R0 not a scalar value\n"); 10107 return -EACCES; 10108 } 10109 10110 /* we are going to rely on register's precise value */ 10111 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64); 10112 err = err ?: mark_chain_precision(env, BPF_REG_0); 10113 if (err) 10114 return err; 10115 10116 /* enforce R0 return value range, and bpf_callback_t returns 64bit */ 10117 if (!retval_range_within(callee->callback_ret_range, r0, false)) { 10118 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 10119 "At callback return", "R0"); 10120 return -EINVAL; 10121 } 10122 if (!calls_callback(env, callee->callsite)) { 10123 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n", 10124 *insn_idx, callee->callsite); 10125 return -EFAULT; 10126 } 10127 } else { 10128 /* return to the caller whatever r0 had in the callee */ 10129 caller->regs[BPF_REG_0] = *r0; 10130 } 10131 10132 /* callback_fn frame should have released its own additions to parent's 10133 * reference state at this point, or check_reference_leak would 10134 * complain, hence it must be the same as the caller. There is no need 10135 * to copy it back. 10136 */ 10137 if (!callee->in_callback_fn) { 10138 /* Transfer references to the caller */ 10139 err = copy_reference_state(caller, callee); 10140 if (err) 10141 return err; 10142 } 10143 10144 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 10145 * there function call logic would reschedule callback visit. If iteration 10146 * converges is_state_visited() would prune that visit eventually. 10147 */ 10148 in_callback_fn = callee->in_callback_fn; 10149 if (in_callback_fn) 10150 *insn_idx = callee->callsite; 10151 else 10152 *insn_idx = callee->callsite + 1; 10153 10154 if (env->log.level & BPF_LOG_LEVEL) { 10155 verbose(env, "returning from callee:\n"); 10156 print_verifier_state(env, callee, true); 10157 verbose(env, "to caller at %d:\n", *insn_idx); 10158 print_verifier_state(env, caller, true); 10159 } 10160 /* clear everything in the callee. In case of exceptional exits using 10161 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 10162 free_func_state(callee); 10163 state->frame[state->curframe--] = NULL; 10164 10165 /* for callbacks widen imprecise scalars to make programs like below verify: 10166 * 10167 * struct ctx { int i; } 10168 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 10169 * ... 10170 * struct ctx = { .i = 0; } 10171 * bpf_loop(100, cb, &ctx, 0); 10172 * 10173 * This is similar to what is done in process_iter_next_call() for open 10174 * coded iterators. 10175 */ 10176 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 10177 if (prev_st) { 10178 err = widen_imprecise_scalars(env, prev_st, state); 10179 if (err) 10180 return err; 10181 } 10182 return 0; 10183 } 10184 10185 static int do_refine_retval_range(struct bpf_verifier_env *env, 10186 struct bpf_reg_state *regs, int ret_type, 10187 int func_id, 10188 struct bpf_call_arg_meta *meta) 10189 { 10190 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 10191 10192 if (ret_type != RET_INTEGER) 10193 return 0; 10194 10195 switch (func_id) { 10196 case BPF_FUNC_get_stack: 10197 case BPF_FUNC_get_task_stack: 10198 case BPF_FUNC_probe_read_str: 10199 case BPF_FUNC_probe_read_kernel_str: 10200 case BPF_FUNC_probe_read_user_str: 10201 ret_reg->smax_value = meta->msize_max_value; 10202 ret_reg->s32_max_value = meta->msize_max_value; 10203 ret_reg->smin_value = -MAX_ERRNO; 10204 ret_reg->s32_min_value = -MAX_ERRNO; 10205 reg_bounds_sync(ret_reg); 10206 break; 10207 case BPF_FUNC_get_smp_processor_id: 10208 ret_reg->umax_value = nr_cpu_ids - 1; 10209 ret_reg->u32_max_value = nr_cpu_ids - 1; 10210 ret_reg->smax_value = nr_cpu_ids - 1; 10211 ret_reg->s32_max_value = nr_cpu_ids - 1; 10212 ret_reg->umin_value = 0; 10213 ret_reg->u32_min_value = 0; 10214 ret_reg->smin_value = 0; 10215 ret_reg->s32_min_value = 0; 10216 reg_bounds_sync(ret_reg); 10217 break; 10218 } 10219 10220 return reg_bounds_sanity_check(env, ret_reg, "retval"); 10221 } 10222 10223 static int 10224 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 10225 int func_id, int insn_idx) 10226 { 10227 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 10228 struct bpf_map *map = meta->map_ptr; 10229 10230 if (func_id != BPF_FUNC_tail_call && 10231 func_id != BPF_FUNC_map_lookup_elem && 10232 func_id != BPF_FUNC_map_update_elem && 10233 func_id != BPF_FUNC_map_delete_elem && 10234 func_id != BPF_FUNC_map_push_elem && 10235 func_id != BPF_FUNC_map_pop_elem && 10236 func_id != BPF_FUNC_map_peek_elem && 10237 func_id != BPF_FUNC_for_each_map_elem && 10238 func_id != BPF_FUNC_redirect_map && 10239 func_id != BPF_FUNC_map_lookup_percpu_elem) 10240 return 0; 10241 10242 if (map == NULL) { 10243 verbose(env, "kernel subsystem misconfigured verifier\n"); 10244 return -EINVAL; 10245 } 10246 10247 /* In case of read-only, some additional restrictions 10248 * need to be applied in order to prevent altering the 10249 * state of the map from program side. 10250 */ 10251 if ((map->map_flags & BPF_F_RDONLY_PROG) && 10252 (func_id == BPF_FUNC_map_delete_elem || 10253 func_id == BPF_FUNC_map_update_elem || 10254 func_id == BPF_FUNC_map_push_elem || 10255 func_id == BPF_FUNC_map_pop_elem)) { 10256 verbose(env, "write into map forbidden\n"); 10257 return -EACCES; 10258 } 10259 10260 if (!aux->map_ptr_state.map_ptr) 10261 bpf_map_ptr_store(aux, meta->map_ptr, 10262 !meta->map_ptr->bypass_spec_v1, false); 10263 else if (aux->map_ptr_state.map_ptr != meta->map_ptr) 10264 bpf_map_ptr_store(aux, meta->map_ptr, 10265 !meta->map_ptr->bypass_spec_v1, true); 10266 return 0; 10267 } 10268 10269 static int 10270 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 10271 int func_id, int insn_idx) 10272 { 10273 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 10274 struct bpf_reg_state *regs = cur_regs(env), *reg; 10275 struct bpf_map *map = meta->map_ptr; 10276 u64 val, max; 10277 int err; 10278 10279 if (func_id != BPF_FUNC_tail_call) 10280 return 0; 10281 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 10282 verbose(env, "kernel subsystem misconfigured verifier\n"); 10283 return -EINVAL; 10284 } 10285 10286 reg = ®s[BPF_REG_3]; 10287 val = reg->var_off.value; 10288 max = map->max_entries; 10289 10290 if (!(is_reg_const(reg, false) && val < max)) { 10291 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 10292 return 0; 10293 } 10294 10295 err = mark_chain_precision(env, BPF_REG_3); 10296 if (err) 10297 return err; 10298 if (bpf_map_key_unseen(aux)) 10299 bpf_map_key_store(aux, val); 10300 else if (!bpf_map_key_poisoned(aux) && 10301 bpf_map_key_immediate(aux) != val) 10302 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 10303 return 0; 10304 } 10305 10306 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 10307 { 10308 struct bpf_func_state *state = cur_func(env); 10309 bool refs_lingering = false; 10310 int i; 10311 10312 if (!exception_exit && state->frameno && !state->in_callback_fn) 10313 return 0; 10314 10315 for (i = 0; i < state->acquired_refs; i++) { 10316 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 10317 continue; 10318 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 10319 state->refs[i].id, state->refs[i].insn_idx); 10320 refs_lingering = true; 10321 } 10322 return refs_lingering ? -EINVAL : 0; 10323 } 10324 10325 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 10326 struct bpf_reg_state *regs) 10327 { 10328 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 10329 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 10330 struct bpf_map *fmt_map = fmt_reg->map_ptr; 10331 struct bpf_bprintf_data data = {}; 10332 int err, fmt_map_off, num_args; 10333 u64 fmt_addr; 10334 char *fmt; 10335 10336 /* data must be an array of u64 */ 10337 if (data_len_reg->var_off.value % 8) 10338 return -EINVAL; 10339 num_args = data_len_reg->var_off.value / 8; 10340 10341 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 10342 * and map_direct_value_addr is set. 10343 */ 10344 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 10345 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 10346 fmt_map_off); 10347 if (err) { 10348 verbose(env, "verifier bug\n"); 10349 return -EFAULT; 10350 } 10351 fmt = (char *)(long)fmt_addr + fmt_map_off; 10352 10353 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 10354 * can focus on validating the format specifiers. 10355 */ 10356 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 10357 if (err < 0) 10358 verbose(env, "Invalid format string\n"); 10359 10360 return err; 10361 } 10362 10363 static int check_get_func_ip(struct bpf_verifier_env *env) 10364 { 10365 enum bpf_prog_type type = resolve_prog_type(env->prog); 10366 int func_id = BPF_FUNC_get_func_ip; 10367 10368 if (type == BPF_PROG_TYPE_TRACING) { 10369 if (!bpf_prog_has_trampoline(env->prog)) { 10370 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 10371 func_id_name(func_id), func_id); 10372 return -ENOTSUPP; 10373 } 10374 return 0; 10375 } else if (type == BPF_PROG_TYPE_KPROBE) { 10376 return 0; 10377 } 10378 10379 verbose(env, "func %s#%d not supported for program type %d\n", 10380 func_id_name(func_id), func_id, type); 10381 return -ENOTSUPP; 10382 } 10383 10384 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 10385 { 10386 return &env->insn_aux_data[env->insn_idx]; 10387 } 10388 10389 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 10390 { 10391 struct bpf_reg_state *regs = cur_regs(env); 10392 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 10393 bool reg_is_null = register_is_null(reg); 10394 10395 if (reg_is_null) 10396 mark_chain_precision(env, BPF_REG_4); 10397 10398 return reg_is_null; 10399 } 10400 10401 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 10402 { 10403 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 10404 10405 if (!state->initialized) { 10406 state->initialized = 1; 10407 state->fit_for_inline = loop_flag_is_zero(env); 10408 state->callback_subprogno = subprogno; 10409 return; 10410 } 10411 10412 if (!state->fit_for_inline) 10413 return; 10414 10415 state->fit_for_inline = (loop_flag_is_zero(env) && 10416 state->callback_subprogno == subprogno); 10417 } 10418 10419 static int get_helper_proto(struct bpf_verifier_env *env, int func_id, 10420 const struct bpf_func_proto **ptr) 10421 { 10422 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) 10423 return -ERANGE; 10424 10425 if (!env->ops->get_func_proto) 10426 return -EINVAL; 10427 10428 *ptr = env->ops->get_func_proto(func_id, env->prog); 10429 return *ptr ? 0 : -EINVAL; 10430 } 10431 10432 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10433 int *insn_idx_p) 10434 { 10435 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 10436 bool returns_cpu_specific_alloc_ptr = false; 10437 const struct bpf_func_proto *fn = NULL; 10438 enum bpf_return_type ret_type; 10439 enum bpf_type_flag ret_flag; 10440 struct bpf_reg_state *regs; 10441 struct bpf_call_arg_meta meta; 10442 int insn_idx = *insn_idx_p; 10443 bool changes_data; 10444 int i, err, func_id; 10445 10446 /* find function prototype */ 10447 func_id = insn->imm; 10448 err = get_helper_proto(env, insn->imm, &fn); 10449 if (err == -ERANGE) { 10450 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id); 10451 return -EINVAL; 10452 } 10453 10454 if (err) { 10455 verbose(env, "program of this type cannot use helper %s#%d\n", 10456 func_id_name(func_id), func_id); 10457 return err; 10458 } 10459 10460 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 10461 if (!env->prog->gpl_compatible && fn->gpl_only) { 10462 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10463 return -EINVAL; 10464 } 10465 10466 if (fn->allowed && !fn->allowed(env->prog)) { 10467 verbose(env, "helper call is not allowed in probe\n"); 10468 return -EINVAL; 10469 } 10470 10471 if (!in_sleepable(env) && fn->might_sleep) { 10472 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 10473 return -EINVAL; 10474 } 10475 10476 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10477 changes_data = bpf_helper_changes_pkt_data(fn->func); 10478 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10479 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 10480 func_id_name(func_id), func_id); 10481 return -EINVAL; 10482 } 10483 10484 memset(&meta, 0, sizeof(meta)); 10485 meta.pkt_access = fn->pkt_access; 10486 10487 err = check_func_proto(fn, func_id); 10488 if (err) { 10489 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 10490 func_id_name(func_id), func_id); 10491 return err; 10492 } 10493 10494 if (env->cur_state->active_rcu_lock) { 10495 if (fn->might_sleep) { 10496 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 10497 func_id_name(func_id), func_id); 10498 return -EINVAL; 10499 } 10500 10501 if (in_sleepable(env) && is_storage_get_function(func_id)) 10502 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10503 } 10504 10505 if (env->cur_state->active_preempt_lock) { 10506 if (fn->might_sleep) { 10507 verbose(env, "sleepable helper %s#%d in non-preemptible region\n", 10508 func_id_name(func_id), func_id); 10509 return -EINVAL; 10510 } 10511 10512 if (in_sleepable(env) && is_storage_get_function(func_id)) 10513 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10514 } 10515 10516 meta.func_id = func_id; 10517 /* check args */ 10518 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10519 err = check_func_arg(env, i, &meta, fn, insn_idx); 10520 if (err) 10521 return err; 10522 } 10523 10524 err = record_func_map(env, &meta, func_id, insn_idx); 10525 if (err) 10526 return err; 10527 10528 err = record_func_key(env, &meta, func_id, insn_idx); 10529 if (err) 10530 return err; 10531 10532 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10533 * is inferred from register state. 10534 */ 10535 for (i = 0; i < meta.access_size; i++) { 10536 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 10537 BPF_WRITE, -1, false, false); 10538 if (err) 10539 return err; 10540 } 10541 10542 regs = cur_regs(env); 10543 10544 if (meta.release_regno) { 10545 err = -EINVAL; 10546 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 10547 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 10548 * is safe to do directly. 10549 */ 10550 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 10551 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 10552 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 10553 return -EFAULT; 10554 } 10555 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 10556 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 10557 u32 ref_obj_id = meta.ref_obj_id; 10558 bool in_rcu = in_rcu_cs(env); 10559 struct bpf_func_state *state; 10560 struct bpf_reg_state *reg; 10561 10562 err = release_reference_state(cur_func(env), ref_obj_id); 10563 if (!err) { 10564 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10565 if (reg->ref_obj_id == ref_obj_id) { 10566 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 10567 reg->ref_obj_id = 0; 10568 reg->type &= ~MEM_ALLOC; 10569 reg->type |= MEM_RCU; 10570 } else { 10571 mark_reg_invalid(env, reg); 10572 } 10573 } 10574 })); 10575 } 10576 } else if (meta.ref_obj_id) { 10577 err = release_reference(env, meta.ref_obj_id); 10578 } else if (register_is_null(®s[meta.release_regno])) { 10579 /* meta.ref_obj_id can only be 0 if register that is meant to be 10580 * released is NULL, which must be > R0. 10581 */ 10582 err = 0; 10583 } 10584 if (err) { 10585 verbose(env, "func %s#%d reference has not been acquired before\n", 10586 func_id_name(func_id), func_id); 10587 return err; 10588 } 10589 } 10590 10591 switch (func_id) { 10592 case BPF_FUNC_tail_call: 10593 err = check_reference_leak(env, false); 10594 if (err) { 10595 verbose(env, "tail_call would lead to reference leak\n"); 10596 return err; 10597 } 10598 break; 10599 case BPF_FUNC_get_local_storage: 10600 /* check that flags argument in get_local_storage(map, flags) is 0, 10601 * this is required because get_local_storage() can't return an error. 10602 */ 10603 if (!register_is_null(®s[BPF_REG_2])) { 10604 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10605 return -EINVAL; 10606 } 10607 break; 10608 case BPF_FUNC_for_each_map_elem: 10609 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10610 set_map_elem_callback_state); 10611 break; 10612 case BPF_FUNC_timer_set_callback: 10613 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10614 set_timer_callback_state); 10615 break; 10616 case BPF_FUNC_find_vma: 10617 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10618 set_find_vma_callback_state); 10619 break; 10620 case BPF_FUNC_snprintf: 10621 err = check_bpf_snprintf_call(env, regs); 10622 break; 10623 case BPF_FUNC_loop: 10624 update_loop_inline_state(env, meta.subprogno); 10625 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10626 * is finished, thus mark it precise. 10627 */ 10628 err = mark_chain_precision(env, BPF_REG_1); 10629 if (err) 10630 return err; 10631 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) { 10632 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10633 set_loop_callback_state); 10634 } else { 10635 cur_func(env)->callback_depth = 0; 10636 if (env->log.level & BPF_LOG_LEVEL2) 10637 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10638 env->cur_state->curframe); 10639 } 10640 break; 10641 case BPF_FUNC_dynptr_from_mem: 10642 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10643 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10644 reg_type_str(env, regs[BPF_REG_1].type)); 10645 return -EACCES; 10646 } 10647 break; 10648 case BPF_FUNC_set_retval: 10649 if (prog_type == BPF_PROG_TYPE_LSM && 10650 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10651 if (!env->prog->aux->attach_func_proto->type) { 10652 /* Make sure programs that attach to void 10653 * hooks don't try to modify return value. 10654 */ 10655 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10656 return -EINVAL; 10657 } 10658 } 10659 break; 10660 case BPF_FUNC_dynptr_data: 10661 { 10662 struct bpf_reg_state *reg; 10663 int id, ref_obj_id; 10664 10665 reg = get_dynptr_arg_reg(env, fn, regs); 10666 if (!reg) 10667 return -EFAULT; 10668 10669 10670 if (meta.dynptr_id) { 10671 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 10672 return -EFAULT; 10673 } 10674 if (meta.ref_obj_id) { 10675 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 10676 return -EFAULT; 10677 } 10678 10679 id = dynptr_id(env, reg); 10680 if (id < 0) { 10681 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 10682 return id; 10683 } 10684 10685 ref_obj_id = dynptr_ref_obj_id(env, reg); 10686 if (ref_obj_id < 0) { 10687 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 10688 return ref_obj_id; 10689 } 10690 10691 meta.dynptr_id = id; 10692 meta.ref_obj_id = ref_obj_id; 10693 10694 break; 10695 } 10696 case BPF_FUNC_dynptr_write: 10697 { 10698 enum bpf_dynptr_type dynptr_type; 10699 struct bpf_reg_state *reg; 10700 10701 reg = get_dynptr_arg_reg(env, fn, regs); 10702 if (!reg) 10703 return -EFAULT; 10704 10705 dynptr_type = dynptr_get_type(env, reg); 10706 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10707 return -EFAULT; 10708 10709 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 10710 /* this will trigger clear_all_pkt_pointers(), which will 10711 * invalidate all dynptr slices associated with the skb 10712 */ 10713 changes_data = true; 10714 10715 break; 10716 } 10717 case BPF_FUNC_per_cpu_ptr: 10718 case BPF_FUNC_this_cpu_ptr: 10719 { 10720 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 10721 const struct btf_type *type; 10722 10723 if (reg->type & MEM_RCU) { 10724 type = btf_type_by_id(reg->btf, reg->btf_id); 10725 if (!type || !btf_type_is_struct(type)) { 10726 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 10727 return -EFAULT; 10728 } 10729 returns_cpu_specific_alloc_ptr = true; 10730 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 10731 } 10732 break; 10733 } 10734 case BPF_FUNC_user_ringbuf_drain: 10735 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10736 set_user_ringbuf_callback_state); 10737 break; 10738 } 10739 10740 if (err) 10741 return err; 10742 10743 /* reset caller saved regs */ 10744 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10745 mark_reg_not_init(env, regs, caller_saved[i]); 10746 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10747 } 10748 10749 /* helper call returns 64-bit value. */ 10750 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10751 10752 /* update return register (already marked as written above) */ 10753 ret_type = fn->ret_type; 10754 ret_flag = type_flag(ret_type); 10755 10756 switch (base_type(ret_type)) { 10757 case RET_INTEGER: 10758 /* sets type to SCALAR_VALUE */ 10759 mark_reg_unknown(env, regs, BPF_REG_0); 10760 break; 10761 case RET_VOID: 10762 regs[BPF_REG_0].type = NOT_INIT; 10763 break; 10764 case RET_PTR_TO_MAP_VALUE: 10765 /* There is no offset yet applied, variable or fixed */ 10766 mark_reg_known_zero(env, regs, BPF_REG_0); 10767 /* remember map_ptr, so that check_map_access() 10768 * can check 'value_size' boundary of memory access 10769 * to map element returned from bpf_map_lookup_elem() 10770 */ 10771 if (meta.map_ptr == NULL) { 10772 verbose(env, 10773 "kernel subsystem misconfigured verifier\n"); 10774 return -EINVAL; 10775 } 10776 regs[BPF_REG_0].map_ptr = meta.map_ptr; 10777 regs[BPF_REG_0].map_uid = meta.map_uid; 10778 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10779 if (!type_may_be_null(ret_type) && 10780 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 10781 regs[BPF_REG_0].id = ++env->id_gen; 10782 } 10783 break; 10784 case RET_PTR_TO_SOCKET: 10785 mark_reg_known_zero(env, regs, BPF_REG_0); 10786 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10787 break; 10788 case RET_PTR_TO_SOCK_COMMON: 10789 mark_reg_known_zero(env, regs, BPF_REG_0); 10790 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10791 break; 10792 case RET_PTR_TO_TCP_SOCK: 10793 mark_reg_known_zero(env, regs, BPF_REG_0); 10794 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10795 break; 10796 case RET_PTR_TO_MEM: 10797 mark_reg_known_zero(env, regs, BPF_REG_0); 10798 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10799 regs[BPF_REG_0].mem_size = meta.mem_size; 10800 break; 10801 case RET_PTR_TO_MEM_OR_BTF_ID: 10802 { 10803 const struct btf_type *t; 10804 10805 mark_reg_known_zero(env, regs, BPF_REG_0); 10806 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10807 if (!btf_type_is_struct(t)) { 10808 u32 tsize; 10809 const struct btf_type *ret; 10810 const char *tname; 10811 10812 /* resolve the type size of ksym. */ 10813 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10814 if (IS_ERR(ret)) { 10815 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10816 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10817 tname, PTR_ERR(ret)); 10818 return -EINVAL; 10819 } 10820 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10821 regs[BPF_REG_0].mem_size = tsize; 10822 } else { 10823 if (returns_cpu_specific_alloc_ptr) { 10824 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10825 } else { 10826 /* MEM_RDONLY may be carried from ret_flag, but it 10827 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10828 * it will confuse the check of PTR_TO_BTF_ID in 10829 * check_mem_access(). 10830 */ 10831 ret_flag &= ~MEM_RDONLY; 10832 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10833 } 10834 10835 regs[BPF_REG_0].btf = meta.ret_btf; 10836 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10837 } 10838 break; 10839 } 10840 case RET_PTR_TO_BTF_ID: 10841 { 10842 struct btf *ret_btf; 10843 int ret_btf_id; 10844 10845 mark_reg_known_zero(env, regs, BPF_REG_0); 10846 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10847 if (func_id == BPF_FUNC_kptr_xchg) { 10848 ret_btf = meta.kptr_field->kptr.btf; 10849 ret_btf_id = meta.kptr_field->kptr.btf_id; 10850 if (!btf_is_kernel(ret_btf)) { 10851 regs[BPF_REG_0].type |= MEM_ALLOC; 10852 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10853 regs[BPF_REG_0].type |= MEM_PERCPU; 10854 } 10855 } else { 10856 if (fn->ret_btf_id == BPF_PTR_POISON) { 10857 verbose(env, "verifier internal error:"); 10858 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 10859 func_id_name(func_id)); 10860 return -EINVAL; 10861 } 10862 ret_btf = btf_vmlinux; 10863 ret_btf_id = *fn->ret_btf_id; 10864 } 10865 if (ret_btf_id == 0) { 10866 verbose(env, "invalid return type %u of func %s#%d\n", 10867 base_type(ret_type), func_id_name(func_id), 10868 func_id); 10869 return -EINVAL; 10870 } 10871 regs[BPF_REG_0].btf = ret_btf; 10872 regs[BPF_REG_0].btf_id = ret_btf_id; 10873 break; 10874 } 10875 default: 10876 verbose(env, "unknown return type %u of func %s#%d\n", 10877 base_type(ret_type), func_id_name(func_id), func_id); 10878 return -EINVAL; 10879 } 10880 10881 if (type_may_be_null(regs[BPF_REG_0].type)) 10882 regs[BPF_REG_0].id = ++env->id_gen; 10883 10884 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 10885 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 10886 func_id_name(func_id), func_id); 10887 return -EFAULT; 10888 } 10889 10890 if (is_dynptr_ref_function(func_id)) 10891 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 10892 10893 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 10894 /* For release_reference() */ 10895 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10896 } else if (is_acquire_function(func_id, meta.map_ptr)) { 10897 int id = acquire_reference_state(env, insn_idx); 10898 10899 if (id < 0) 10900 return id; 10901 /* For mark_ptr_or_null_reg() */ 10902 regs[BPF_REG_0].id = id; 10903 /* For release_reference() */ 10904 regs[BPF_REG_0].ref_obj_id = id; 10905 } 10906 10907 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 10908 if (err) 10909 return err; 10910 10911 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 10912 if (err) 10913 return err; 10914 10915 if ((func_id == BPF_FUNC_get_stack || 10916 func_id == BPF_FUNC_get_task_stack) && 10917 !env->prog->has_callchain_buf) { 10918 const char *err_str; 10919 10920 #ifdef CONFIG_PERF_EVENTS 10921 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10922 err_str = "cannot get callchain buffer for func %s#%d\n"; 10923 #else 10924 err = -ENOTSUPP; 10925 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10926 #endif 10927 if (err) { 10928 verbose(env, err_str, func_id_name(func_id), func_id); 10929 return err; 10930 } 10931 10932 env->prog->has_callchain_buf = true; 10933 } 10934 10935 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10936 env->prog->call_get_stack = true; 10937 10938 if (func_id == BPF_FUNC_get_func_ip) { 10939 if (check_get_func_ip(env)) 10940 return -ENOTSUPP; 10941 env->prog->call_get_func_ip = true; 10942 } 10943 10944 if (changes_data) 10945 clear_all_pkt_pointers(env); 10946 return 0; 10947 } 10948 10949 /* mark_btf_func_reg_size() is used when the reg size is determined by 10950 * the BTF func_proto's return value size and argument. 10951 */ 10952 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10953 size_t reg_size) 10954 { 10955 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 10956 10957 if (regno == BPF_REG_0) { 10958 /* Function return value */ 10959 reg->live |= REG_LIVE_WRITTEN; 10960 reg->subreg_def = reg_size == sizeof(u64) ? 10961 DEF_NOT_SUBREG : env->insn_idx + 1; 10962 } else { 10963 /* Function argument */ 10964 if (reg_size == sizeof(u64)) { 10965 mark_insn_zext(env, reg); 10966 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 10967 } else { 10968 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 10969 } 10970 } 10971 } 10972 10973 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10974 { 10975 return meta->kfunc_flags & KF_ACQUIRE; 10976 } 10977 10978 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10979 { 10980 return meta->kfunc_flags & KF_RELEASE; 10981 } 10982 10983 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 10984 { 10985 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 10986 } 10987 10988 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 10989 { 10990 return meta->kfunc_flags & KF_SLEEPABLE; 10991 } 10992 10993 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10994 { 10995 return meta->kfunc_flags & KF_DESTRUCTIVE; 10996 } 10997 10998 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10999 { 11000 return meta->kfunc_flags & KF_RCU; 11001 } 11002 11003 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 11004 { 11005 return meta->kfunc_flags & KF_RCU_PROTECTED; 11006 } 11007 11008 static bool is_kfunc_arg_mem_size(const struct btf *btf, 11009 const struct btf_param *arg, 11010 const struct bpf_reg_state *reg) 11011 { 11012 const struct btf_type *t; 11013 11014 t = btf_type_skip_modifiers(btf, arg->type, NULL); 11015 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 11016 return false; 11017 11018 return btf_param_match_suffix(btf, arg, "__sz"); 11019 } 11020 11021 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 11022 const struct btf_param *arg, 11023 const struct bpf_reg_state *reg) 11024 { 11025 const struct btf_type *t; 11026 11027 t = btf_type_skip_modifiers(btf, arg->type, NULL); 11028 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 11029 return false; 11030 11031 return btf_param_match_suffix(btf, arg, "__szk"); 11032 } 11033 11034 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 11035 { 11036 return btf_param_match_suffix(btf, arg, "__opt"); 11037 } 11038 11039 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 11040 { 11041 return btf_param_match_suffix(btf, arg, "__k"); 11042 } 11043 11044 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 11045 { 11046 return btf_param_match_suffix(btf, arg, "__ign"); 11047 } 11048 11049 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg) 11050 { 11051 return btf_param_match_suffix(btf, arg, "__map"); 11052 } 11053 11054 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 11055 { 11056 return btf_param_match_suffix(btf, arg, "__alloc"); 11057 } 11058 11059 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 11060 { 11061 return btf_param_match_suffix(btf, arg, "__uninit"); 11062 } 11063 11064 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 11065 { 11066 return btf_param_match_suffix(btf, arg, "__refcounted_kptr"); 11067 } 11068 11069 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 11070 { 11071 return btf_param_match_suffix(btf, arg, "__nullable"); 11072 } 11073 11074 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 11075 { 11076 return btf_param_match_suffix(btf, arg, "__str"); 11077 } 11078 11079 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 11080 const struct btf_param *arg, 11081 const char *name) 11082 { 11083 int len, target_len = strlen(name); 11084 const char *param_name; 11085 11086 param_name = btf_name_by_offset(btf, arg->name_off); 11087 if (str_is_empty(param_name)) 11088 return false; 11089 len = strlen(param_name); 11090 if (len != target_len) 11091 return false; 11092 if (strcmp(param_name, name)) 11093 return false; 11094 11095 return true; 11096 } 11097 11098 enum { 11099 KF_ARG_DYNPTR_ID, 11100 KF_ARG_LIST_HEAD_ID, 11101 KF_ARG_LIST_NODE_ID, 11102 KF_ARG_RB_ROOT_ID, 11103 KF_ARG_RB_NODE_ID, 11104 KF_ARG_WORKQUEUE_ID, 11105 }; 11106 11107 BTF_ID_LIST(kf_arg_btf_ids) 11108 BTF_ID(struct, bpf_dynptr) 11109 BTF_ID(struct, bpf_list_head) 11110 BTF_ID(struct, bpf_list_node) 11111 BTF_ID(struct, bpf_rb_root) 11112 BTF_ID(struct, bpf_rb_node) 11113 BTF_ID(struct, bpf_wq) 11114 11115 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 11116 const struct btf_param *arg, int type) 11117 { 11118 const struct btf_type *t; 11119 u32 res_id; 11120 11121 t = btf_type_skip_modifiers(btf, arg->type, NULL); 11122 if (!t) 11123 return false; 11124 if (!btf_type_is_ptr(t)) 11125 return false; 11126 t = btf_type_skip_modifiers(btf, t->type, &res_id); 11127 if (!t) 11128 return false; 11129 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 11130 } 11131 11132 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 11133 { 11134 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 11135 } 11136 11137 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 11138 { 11139 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 11140 } 11141 11142 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 11143 { 11144 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 11145 } 11146 11147 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 11148 { 11149 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 11150 } 11151 11152 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 11153 { 11154 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 11155 } 11156 11157 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg) 11158 { 11159 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID); 11160 } 11161 11162 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 11163 const struct btf_param *arg) 11164 { 11165 const struct btf_type *t; 11166 11167 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 11168 if (!t) 11169 return false; 11170 11171 return true; 11172 } 11173 11174 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 11175 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 11176 const struct btf *btf, 11177 const struct btf_type *t, int rec) 11178 { 11179 const struct btf_type *member_type; 11180 const struct btf_member *member; 11181 u32 i; 11182 11183 if (!btf_type_is_struct(t)) 11184 return false; 11185 11186 for_each_member(i, t, member) { 11187 const struct btf_array *array; 11188 11189 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 11190 if (btf_type_is_struct(member_type)) { 11191 if (rec >= 3) { 11192 verbose(env, "max struct nesting depth exceeded\n"); 11193 return false; 11194 } 11195 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 11196 return false; 11197 continue; 11198 } 11199 if (btf_type_is_array(member_type)) { 11200 array = btf_array(member_type); 11201 if (!array->nelems) 11202 return false; 11203 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 11204 if (!btf_type_is_scalar(member_type)) 11205 return false; 11206 continue; 11207 } 11208 if (!btf_type_is_scalar(member_type)) 11209 return false; 11210 } 11211 return true; 11212 } 11213 11214 enum kfunc_ptr_arg_type { 11215 KF_ARG_PTR_TO_CTX, 11216 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 11217 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 11218 KF_ARG_PTR_TO_DYNPTR, 11219 KF_ARG_PTR_TO_ITER, 11220 KF_ARG_PTR_TO_LIST_HEAD, 11221 KF_ARG_PTR_TO_LIST_NODE, 11222 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 11223 KF_ARG_PTR_TO_MEM, 11224 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 11225 KF_ARG_PTR_TO_CALLBACK, 11226 KF_ARG_PTR_TO_RB_ROOT, 11227 KF_ARG_PTR_TO_RB_NODE, 11228 KF_ARG_PTR_TO_NULL, 11229 KF_ARG_PTR_TO_CONST_STR, 11230 KF_ARG_PTR_TO_MAP, 11231 KF_ARG_PTR_TO_WORKQUEUE, 11232 }; 11233 11234 enum special_kfunc_type { 11235 KF_bpf_obj_new_impl, 11236 KF_bpf_obj_drop_impl, 11237 KF_bpf_refcount_acquire_impl, 11238 KF_bpf_list_push_front_impl, 11239 KF_bpf_list_push_back_impl, 11240 KF_bpf_list_pop_front, 11241 KF_bpf_list_pop_back, 11242 KF_bpf_cast_to_kern_ctx, 11243 KF_bpf_rdonly_cast, 11244 KF_bpf_rcu_read_lock, 11245 KF_bpf_rcu_read_unlock, 11246 KF_bpf_rbtree_remove, 11247 KF_bpf_rbtree_add_impl, 11248 KF_bpf_rbtree_first, 11249 KF_bpf_dynptr_from_skb, 11250 KF_bpf_dynptr_from_xdp, 11251 KF_bpf_dynptr_slice, 11252 KF_bpf_dynptr_slice_rdwr, 11253 KF_bpf_dynptr_clone, 11254 KF_bpf_percpu_obj_new_impl, 11255 KF_bpf_percpu_obj_drop_impl, 11256 KF_bpf_throw, 11257 KF_bpf_wq_set_callback_impl, 11258 KF_bpf_preempt_disable, 11259 KF_bpf_preempt_enable, 11260 KF_bpf_iter_css_task_new, 11261 KF_bpf_session_cookie, 11262 }; 11263 11264 BTF_SET_START(special_kfunc_set) 11265 BTF_ID(func, bpf_obj_new_impl) 11266 BTF_ID(func, bpf_obj_drop_impl) 11267 BTF_ID(func, bpf_refcount_acquire_impl) 11268 BTF_ID(func, bpf_list_push_front_impl) 11269 BTF_ID(func, bpf_list_push_back_impl) 11270 BTF_ID(func, bpf_list_pop_front) 11271 BTF_ID(func, bpf_list_pop_back) 11272 BTF_ID(func, bpf_cast_to_kern_ctx) 11273 BTF_ID(func, bpf_rdonly_cast) 11274 BTF_ID(func, bpf_rbtree_remove) 11275 BTF_ID(func, bpf_rbtree_add_impl) 11276 BTF_ID(func, bpf_rbtree_first) 11277 BTF_ID(func, bpf_dynptr_from_skb) 11278 BTF_ID(func, bpf_dynptr_from_xdp) 11279 BTF_ID(func, bpf_dynptr_slice) 11280 BTF_ID(func, bpf_dynptr_slice_rdwr) 11281 BTF_ID(func, bpf_dynptr_clone) 11282 BTF_ID(func, bpf_percpu_obj_new_impl) 11283 BTF_ID(func, bpf_percpu_obj_drop_impl) 11284 BTF_ID(func, bpf_throw) 11285 BTF_ID(func, bpf_wq_set_callback_impl) 11286 #ifdef CONFIG_CGROUPS 11287 BTF_ID(func, bpf_iter_css_task_new) 11288 #endif 11289 BTF_SET_END(special_kfunc_set) 11290 11291 BTF_ID_LIST(special_kfunc_list) 11292 BTF_ID(func, bpf_obj_new_impl) 11293 BTF_ID(func, bpf_obj_drop_impl) 11294 BTF_ID(func, bpf_refcount_acquire_impl) 11295 BTF_ID(func, bpf_list_push_front_impl) 11296 BTF_ID(func, bpf_list_push_back_impl) 11297 BTF_ID(func, bpf_list_pop_front) 11298 BTF_ID(func, bpf_list_pop_back) 11299 BTF_ID(func, bpf_cast_to_kern_ctx) 11300 BTF_ID(func, bpf_rdonly_cast) 11301 BTF_ID(func, bpf_rcu_read_lock) 11302 BTF_ID(func, bpf_rcu_read_unlock) 11303 BTF_ID(func, bpf_rbtree_remove) 11304 BTF_ID(func, bpf_rbtree_add_impl) 11305 BTF_ID(func, bpf_rbtree_first) 11306 BTF_ID(func, bpf_dynptr_from_skb) 11307 BTF_ID(func, bpf_dynptr_from_xdp) 11308 BTF_ID(func, bpf_dynptr_slice) 11309 BTF_ID(func, bpf_dynptr_slice_rdwr) 11310 BTF_ID(func, bpf_dynptr_clone) 11311 BTF_ID(func, bpf_percpu_obj_new_impl) 11312 BTF_ID(func, bpf_percpu_obj_drop_impl) 11313 BTF_ID(func, bpf_throw) 11314 BTF_ID(func, bpf_wq_set_callback_impl) 11315 BTF_ID(func, bpf_preempt_disable) 11316 BTF_ID(func, bpf_preempt_enable) 11317 #ifdef CONFIG_CGROUPS 11318 BTF_ID(func, bpf_iter_css_task_new) 11319 #else 11320 BTF_ID_UNUSED 11321 #endif 11322 #ifdef CONFIG_BPF_EVENTS 11323 BTF_ID(func, bpf_session_cookie) 11324 #else 11325 BTF_ID_UNUSED 11326 #endif 11327 11328 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 11329 { 11330 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 11331 meta->arg_owning_ref) { 11332 return false; 11333 } 11334 11335 return meta->kfunc_flags & KF_RET_NULL; 11336 } 11337 11338 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 11339 { 11340 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 11341 } 11342 11343 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 11344 { 11345 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 11346 } 11347 11348 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta) 11349 { 11350 return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable]; 11351 } 11352 11353 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta) 11354 { 11355 return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable]; 11356 } 11357 11358 static enum kfunc_ptr_arg_type 11359 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 11360 struct bpf_kfunc_call_arg_meta *meta, 11361 const struct btf_type *t, const struct btf_type *ref_t, 11362 const char *ref_tname, const struct btf_param *args, 11363 int argno, int nargs) 11364 { 11365 u32 regno = argno + 1; 11366 struct bpf_reg_state *regs = cur_regs(env); 11367 struct bpf_reg_state *reg = ®s[regno]; 11368 bool arg_mem_size = false; 11369 11370 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 11371 return KF_ARG_PTR_TO_CTX; 11372 11373 /* In this function, we verify the kfunc's BTF as per the argument type, 11374 * leaving the rest of the verification with respect to the register 11375 * type to our caller. When a set of conditions hold in the BTF type of 11376 * arguments, we resolve it to a known kfunc_ptr_arg_type. 11377 */ 11378 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 11379 return KF_ARG_PTR_TO_CTX; 11380 11381 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg)) 11382 return KF_ARG_PTR_TO_NULL; 11383 11384 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 11385 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 11386 11387 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 11388 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 11389 11390 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 11391 return KF_ARG_PTR_TO_DYNPTR; 11392 11393 if (is_kfunc_arg_iter(meta, argno, &args[argno])) 11394 return KF_ARG_PTR_TO_ITER; 11395 11396 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 11397 return KF_ARG_PTR_TO_LIST_HEAD; 11398 11399 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 11400 return KF_ARG_PTR_TO_LIST_NODE; 11401 11402 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 11403 return KF_ARG_PTR_TO_RB_ROOT; 11404 11405 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 11406 return KF_ARG_PTR_TO_RB_NODE; 11407 11408 if (is_kfunc_arg_const_str(meta->btf, &args[argno])) 11409 return KF_ARG_PTR_TO_CONST_STR; 11410 11411 if (is_kfunc_arg_map(meta->btf, &args[argno])) 11412 return KF_ARG_PTR_TO_MAP; 11413 11414 if (is_kfunc_arg_wq(meta->btf, &args[argno])) 11415 return KF_ARG_PTR_TO_WORKQUEUE; 11416 11417 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 11418 if (!btf_type_is_struct(ref_t)) { 11419 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 11420 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 11421 return -EINVAL; 11422 } 11423 return KF_ARG_PTR_TO_BTF_ID; 11424 } 11425 11426 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 11427 return KF_ARG_PTR_TO_CALLBACK; 11428 11429 if (argno + 1 < nargs && 11430 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 11431 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 11432 arg_mem_size = true; 11433 11434 /* This is the catch all argument type of register types supported by 11435 * check_helper_mem_access. However, we only allow when argument type is 11436 * pointer to scalar, or struct composed (recursively) of scalars. When 11437 * arg_mem_size is true, the pointer can be void *. 11438 */ 11439 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 11440 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 11441 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 11442 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 11443 return -EINVAL; 11444 } 11445 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 11446 } 11447 11448 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 11449 struct bpf_reg_state *reg, 11450 const struct btf_type *ref_t, 11451 const char *ref_tname, u32 ref_id, 11452 struct bpf_kfunc_call_arg_meta *meta, 11453 int argno) 11454 { 11455 const struct btf_type *reg_ref_t; 11456 bool strict_type_match = false; 11457 const struct btf *reg_btf; 11458 const char *reg_ref_tname; 11459 bool taking_projection; 11460 bool struct_same; 11461 u32 reg_ref_id; 11462 11463 if (base_type(reg->type) == PTR_TO_BTF_ID) { 11464 reg_btf = reg->btf; 11465 reg_ref_id = reg->btf_id; 11466 } else { 11467 reg_btf = btf_vmlinux; 11468 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 11469 } 11470 11471 /* Enforce strict type matching for calls to kfuncs that are acquiring 11472 * or releasing a reference, or are no-cast aliases. We do _not_ 11473 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 11474 * as we want to enable BPF programs to pass types that are bitwise 11475 * equivalent without forcing them to explicitly cast with something 11476 * like bpf_cast_to_kern_ctx(). 11477 * 11478 * For example, say we had a type like the following: 11479 * 11480 * struct bpf_cpumask { 11481 * cpumask_t cpumask; 11482 * refcount_t usage; 11483 * }; 11484 * 11485 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 11486 * to a struct cpumask, so it would be safe to pass a struct 11487 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 11488 * 11489 * The philosophy here is similar to how we allow scalars of different 11490 * types to be passed to kfuncs as long as the size is the same. The 11491 * only difference here is that we're simply allowing 11492 * btf_struct_ids_match() to walk the struct at the 0th offset, and 11493 * resolve types. 11494 */ 11495 if ((is_kfunc_release(meta) && reg->ref_obj_id) || 11496 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 11497 strict_type_match = true; 11498 11499 WARN_ON_ONCE(is_kfunc_release(meta) && 11500 (reg->off || !tnum_is_const(reg->var_off) || 11501 reg->var_off.value)); 11502 11503 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 11504 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 11505 struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match); 11506 /* If kfunc is accepting a projection type (ie. __sk_buff), it cannot 11507 * actually use it -- it must cast to the underlying type. So we allow 11508 * caller to pass in the underlying type. 11509 */ 11510 taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname); 11511 if (!taking_projection && !struct_same) { 11512 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 11513 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 11514 btf_type_str(reg_ref_t), reg_ref_tname); 11515 return -EINVAL; 11516 } 11517 return 0; 11518 } 11519 11520 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11521 { 11522 struct bpf_verifier_state *state = env->cur_state; 11523 struct btf_record *rec = reg_btf_record(reg); 11524 11525 if (!state->active_lock.ptr) { 11526 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 11527 return -EFAULT; 11528 } 11529 11530 if (type_flag(reg->type) & NON_OWN_REF) { 11531 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 11532 return -EFAULT; 11533 } 11534 11535 reg->type |= NON_OWN_REF; 11536 if (rec->refcount_off >= 0) 11537 reg->type |= MEM_RCU; 11538 11539 return 0; 11540 } 11541 11542 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 11543 { 11544 struct bpf_func_state *state, *unused; 11545 struct bpf_reg_state *reg; 11546 int i; 11547 11548 state = cur_func(env); 11549 11550 if (!ref_obj_id) { 11551 verbose(env, "verifier internal error: ref_obj_id is zero for " 11552 "owning -> non-owning conversion\n"); 11553 return -EFAULT; 11554 } 11555 11556 for (i = 0; i < state->acquired_refs; i++) { 11557 if (state->refs[i].id != ref_obj_id) 11558 continue; 11559 11560 /* Clear ref_obj_id here so release_reference doesn't clobber 11561 * the whole reg 11562 */ 11563 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11564 if (reg->ref_obj_id == ref_obj_id) { 11565 reg->ref_obj_id = 0; 11566 ref_set_non_owning(env, reg); 11567 } 11568 })); 11569 return 0; 11570 } 11571 11572 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 11573 return -EFAULT; 11574 } 11575 11576 /* Implementation details: 11577 * 11578 * Each register points to some region of memory, which we define as an 11579 * allocation. Each allocation may embed a bpf_spin_lock which protects any 11580 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 11581 * allocation. The lock and the data it protects are colocated in the same 11582 * memory region. 11583 * 11584 * Hence, everytime a register holds a pointer value pointing to such 11585 * allocation, the verifier preserves a unique reg->id for it. 11586 * 11587 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 11588 * bpf_spin_lock is called. 11589 * 11590 * To enable this, lock state in the verifier captures two values: 11591 * active_lock.ptr = Register's type specific pointer 11592 * active_lock.id = A unique ID for each register pointer value 11593 * 11594 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11595 * supported register types. 11596 * 11597 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11598 * allocated objects is the reg->btf pointer. 11599 * 11600 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11601 * can establish the provenance of the map value statically for each distinct 11602 * lookup into such maps. They always contain a single map value hence unique 11603 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11604 * 11605 * So, in case of global variables, they use array maps with max_entries = 1, 11606 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11607 * into the same map value as max_entries is 1, as described above). 11608 * 11609 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11610 * outer map pointer (in verifier context), but each lookup into an inner map 11611 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11612 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11613 * will get different reg->id assigned to each lookup, hence different 11614 * active_lock.id. 11615 * 11616 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11617 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11618 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11619 */ 11620 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11621 { 11622 void *ptr; 11623 u32 id; 11624 11625 switch ((int)reg->type) { 11626 case PTR_TO_MAP_VALUE: 11627 ptr = reg->map_ptr; 11628 break; 11629 case PTR_TO_BTF_ID | MEM_ALLOC: 11630 ptr = reg->btf; 11631 break; 11632 default: 11633 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 11634 return -EFAULT; 11635 } 11636 id = reg->id; 11637 11638 if (!env->cur_state->active_lock.ptr) 11639 return -EINVAL; 11640 if (env->cur_state->active_lock.ptr != ptr || 11641 env->cur_state->active_lock.id != id) { 11642 verbose(env, "held lock and object are not in the same allocation\n"); 11643 return -EINVAL; 11644 } 11645 return 0; 11646 } 11647 11648 static bool is_bpf_list_api_kfunc(u32 btf_id) 11649 { 11650 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11651 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11652 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11653 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 11654 } 11655 11656 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11657 { 11658 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 11659 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11660 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 11661 } 11662 11663 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11664 { 11665 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 11666 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11667 } 11668 11669 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11670 { 11671 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11672 } 11673 11674 static bool is_async_callback_calling_kfunc(u32 btf_id) 11675 { 11676 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl]; 11677 } 11678 11679 static bool is_bpf_throw_kfunc(struct bpf_insn *insn) 11680 { 11681 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 11682 insn->imm == special_kfunc_list[KF_bpf_throw]; 11683 } 11684 11685 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id) 11686 { 11687 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl]; 11688 } 11689 11690 static bool is_callback_calling_kfunc(u32 btf_id) 11691 { 11692 return is_sync_callback_calling_kfunc(btf_id) || 11693 is_async_callback_calling_kfunc(btf_id); 11694 } 11695 11696 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11697 { 11698 return is_bpf_rbtree_api_kfunc(btf_id); 11699 } 11700 11701 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11702 enum btf_field_type head_field_type, 11703 u32 kfunc_btf_id) 11704 { 11705 bool ret; 11706 11707 switch (head_field_type) { 11708 case BPF_LIST_HEAD: 11709 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11710 break; 11711 case BPF_RB_ROOT: 11712 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11713 break; 11714 default: 11715 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11716 btf_field_type_name(head_field_type)); 11717 return false; 11718 } 11719 11720 if (!ret) 11721 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11722 btf_field_type_name(head_field_type)); 11723 return ret; 11724 } 11725 11726 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11727 enum btf_field_type node_field_type, 11728 u32 kfunc_btf_id) 11729 { 11730 bool ret; 11731 11732 switch (node_field_type) { 11733 case BPF_LIST_NODE: 11734 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11735 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 11736 break; 11737 case BPF_RB_NODE: 11738 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11739 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 11740 break; 11741 default: 11742 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11743 btf_field_type_name(node_field_type)); 11744 return false; 11745 } 11746 11747 if (!ret) 11748 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11749 btf_field_type_name(node_field_type)); 11750 return ret; 11751 } 11752 11753 static int 11754 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11755 struct bpf_reg_state *reg, u32 regno, 11756 struct bpf_kfunc_call_arg_meta *meta, 11757 enum btf_field_type head_field_type, 11758 struct btf_field **head_field) 11759 { 11760 const char *head_type_name; 11761 struct btf_field *field; 11762 struct btf_record *rec; 11763 u32 head_off; 11764 11765 if (meta->btf != btf_vmlinux) { 11766 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11767 return -EFAULT; 11768 } 11769 11770 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11771 return -EFAULT; 11772 11773 head_type_name = btf_field_type_name(head_field_type); 11774 if (!tnum_is_const(reg->var_off)) { 11775 verbose(env, 11776 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11777 regno, head_type_name); 11778 return -EINVAL; 11779 } 11780 11781 rec = reg_btf_record(reg); 11782 head_off = reg->off + reg->var_off.value; 11783 field = btf_record_find(rec, head_off, head_field_type); 11784 if (!field) { 11785 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11786 return -EINVAL; 11787 } 11788 11789 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11790 if (check_reg_allocation_locked(env, reg)) { 11791 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11792 rec->spin_lock_off, head_type_name); 11793 return -EINVAL; 11794 } 11795 11796 if (*head_field) { 11797 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 11798 return -EFAULT; 11799 } 11800 *head_field = field; 11801 return 0; 11802 } 11803 11804 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11805 struct bpf_reg_state *reg, u32 regno, 11806 struct bpf_kfunc_call_arg_meta *meta) 11807 { 11808 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 11809 &meta->arg_list_head.field); 11810 } 11811 11812 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11813 struct bpf_reg_state *reg, u32 regno, 11814 struct bpf_kfunc_call_arg_meta *meta) 11815 { 11816 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 11817 &meta->arg_rbtree_root.field); 11818 } 11819 11820 static int 11821 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11822 struct bpf_reg_state *reg, u32 regno, 11823 struct bpf_kfunc_call_arg_meta *meta, 11824 enum btf_field_type head_field_type, 11825 enum btf_field_type node_field_type, 11826 struct btf_field **node_field) 11827 { 11828 const char *node_type_name; 11829 const struct btf_type *et, *t; 11830 struct btf_field *field; 11831 u32 node_off; 11832 11833 if (meta->btf != btf_vmlinux) { 11834 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11835 return -EFAULT; 11836 } 11837 11838 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11839 return -EFAULT; 11840 11841 node_type_name = btf_field_type_name(node_field_type); 11842 if (!tnum_is_const(reg->var_off)) { 11843 verbose(env, 11844 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11845 regno, node_type_name); 11846 return -EINVAL; 11847 } 11848 11849 node_off = reg->off + reg->var_off.value; 11850 field = reg_find_field_offset(reg, node_off, node_field_type); 11851 if (!field) { 11852 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11853 return -EINVAL; 11854 } 11855 11856 field = *node_field; 11857 11858 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11859 t = btf_type_by_id(reg->btf, reg->btf_id); 11860 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11861 field->graph_root.value_btf_id, true)) { 11862 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11863 "in struct %s, but arg is at offset=%d in struct %s\n", 11864 btf_field_type_name(head_field_type), 11865 btf_field_type_name(node_field_type), 11866 field->graph_root.node_offset, 11867 btf_name_by_offset(field->graph_root.btf, et->name_off), 11868 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11869 return -EINVAL; 11870 } 11871 meta->arg_btf = reg->btf; 11872 meta->arg_btf_id = reg->btf_id; 11873 11874 if (node_off != field->graph_root.node_offset) { 11875 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11876 node_off, btf_field_type_name(node_field_type), 11877 field->graph_root.node_offset, 11878 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11879 return -EINVAL; 11880 } 11881 11882 return 0; 11883 } 11884 11885 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11886 struct bpf_reg_state *reg, u32 regno, 11887 struct bpf_kfunc_call_arg_meta *meta) 11888 { 11889 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11890 BPF_LIST_HEAD, BPF_LIST_NODE, 11891 &meta->arg_list_head.field); 11892 } 11893 11894 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11895 struct bpf_reg_state *reg, u32 regno, 11896 struct bpf_kfunc_call_arg_meta *meta) 11897 { 11898 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11899 BPF_RB_ROOT, BPF_RB_NODE, 11900 &meta->arg_rbtree_root.field); 11901 } 11902 11903 /* 11904 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 11905 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 11906 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 11907 * them can only be attached to some specific hook points. 11908 */ 11909 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 11910 { 11911 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11912 11913 switch (prog_type) { 11914 case BPF_PROG_TYPE_LSM: 11915 return true; 11916 case BPF_PROG_TYPE_TRACING: 11917 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 11918 return true; 11919 fallthrough; 11920 default: 11921 return in_sleepable(env); 11922 } 11923 } 11924 11925 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11926 int insn_idx) 11927 { 11928 const char *func_name = meta->func_name, *ref_tname; 11929 const struct btf *btf = meta->btf; 11930 const struct btf_param *args; 11931 struct btf_record *rec; 11932 u32 i, nargs; 11933 int ret; 11934 11935 args = (const struct btf_param *)(meta->func_proto + 1); 11936 nargs = btf_type_vlen(meta->func_proto); 11937 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 11938 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11939 MAX_BPF_FUNC_REG_ARGS); 11940 return -EINVAL; 11941 } 11942 11943 /* Check that BTF function arguments match actual types that the 11944 * verifier sees. 11945 */ 11946 for (i = 0; i < nargs; i++) { 11947 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 11948 const struct btf_type *t, *ref_t, *resolve_ret; 11949 enum bpf_arg_type arg_type = ARG_DONTCARE; 11950 u32 regno = i + 1, ref_id, type_size; 11951 bool is_ret_buf_sz = false; 11952 int kf_arg_type; 11953 11954 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11955 11956 if (is_kfunc_arg_ignore(btf, &args[i])) 11957 continue; 11958 11959 if (btf_type_is_scalar(t)) { 11960 if (reg->type != SCALAR_VALUE) { 11961 verbose(env, "R%d is not a scalar\n", regno); 11962 return -EINVAL; 11963 } 11964 11965 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11966 if (meta->arg_constant.found) { 11967 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11968 return -EFAULT; 11969 } 11970 if (!tnum_is_const(reg->var_off)) { 11971 verbose(env, "R%d must be a known constant\n", regno); 11972 return -EINVAL; 11973 } 11974 ret = mark_chain_precision(env, regno); 11975 if (ret < 0) 11976 return ret; 11977 meta->arg_constant.found = true; 11978 meta->arg_constant.value = reg->var_off.value; 11979 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 11980 meta->r0_rdonly = true; 11981 is_ret_buf_sz = true; 11982 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 11983 is_ret_buf_sz = true; 11984 } 11985 11986 if (is_ret_buf_sz) { 11987 if (meta->r0_size) { 11988 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 11989 return -EINVAL; 11990 } 11991 11992 if (!tnum_is_const(reg->var_off)) { 11993 verbose(env, "R%d is not a const\n", regno); 11994 return -EINVAL; 11995 } 11996 11997 meta->r0_size = reg->var_off.value; 11998 ret = mark_chain_precision(env, regno); 11999 if (ret) 12000 return ret; 12001 } 12002 continue; 12003 } 12004 12005 if (!btf_type_is_ptr(t)) { 12006 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 12007 return -EINVAL; 12008 } 12009 12010 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 12011 (register_is_null(reg) || type_may_be_null(reg->type)) && 12012 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 12013 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 12014 return -EACCES; 12015 } 12016 12017 if (reg->ref_obj_id) { 12018 if (is_kfunc_release(meta) && meta->ref_obj_id) { 12019 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 12020 regno, reg->ref_obj_id, 12021 meta->ref_obj_id); 12022 return -EFAULT; 12023 } 12024 meta->ref_obj_id = reg->ref_obj_id; 12025 if (is_kfunc_release(meta)) 12026 meta->release_regno = regno; 12027 } 12028 12029 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 12030 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12031 12032 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 12033 if (kf_arg_type < 0) 12034 return kf_arg_type; 12035 12036 switch (kf_arg_type) { 12037 case KF_ARG_PTR_TO_NULL: 12038 continue; 12039 case KF_ARG_PTR_TO_MAP: 12040 if (!reg->map_ptr) { 12041 verbose(env, "pointer in R%d isn't map pointer\n", regno); 12042 return -EINVAL; 12043 } 12044 if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) { 12045 /* Use map_uid (which is unique id of inner map) to reject: 12046 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 12047 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 12048 * if (inner_map1 && inner_map2) { 12049 * wq = bpf_map_lookup_elem(inner_map1); 12050 * if (wq) 12051 * // mismatch would have been allowed 12052 * bpf_wq_init(wq, inner_map2); 12053 * } 12054 * 12055 * Comparing map_ptr is enough to distinguish normal and outer maps. 12056 */ 12057 if (meta->map.ptr != reg->map_ptr || 12058 meta->map.uid != reg->map_uid) { 12059 verbose(env, 12060 "workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 12061 meta->map.uid, reg->map_uid); 12062 return -EINVAL; 12063 } 12064 } 12065 meta->map.ptr = reg->map_ptr; 12066 meta->map.uid = reg->map_uid; 12067 fallthrough; 12068 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 12069 case KF_ARG_PTR_TO_BTF_ID: 12070 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 12071 break; 12072 12073 if (!is_trusted_reg(reg)) { 12074 if (!is_kfunc_rcu(meta)) { 12075 verbose(env, "R%d must be referenced or trusted\n", regno); 12076 return -EINVAL; 12077 } 12078 if (!is_rcu_reg(reg)) { 12079 verbose(env, "R%d must be a rcu pointer\n", regno); 12080 return -EINVAL; 12081 } 12082 } 12083 fallthrough; 12084 case KF_ARG_PTR_TO_CTX: 12085 case KF_ARG_PTR_TO_DYNPTR: 12086 case KF_ARG_PTR_TO_ITER: 12087 case KF_ARG_PTR_TO_LIST_HEAD: 12088 case KF_ARG_PTR_TO_LIST_NODE: 12089 case KF_ARG_PTR_TO_RB_ROOT: 12090 case KF_ARG_PTR_TO_RB_NODE: 12091 case KF_ARG_PTR_TO_MEM: 12092 case KF_ARG_PTR_TO_MEM_SIZE: 12093 case KF_ARG_PTR_TO_CALLBACK: 12094 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12095 case KF_ARG_PTR_TO_CONST_STR: 12096 case KF_ARG_PTR_TO_WORKQUEUE: 12097 break; 12098 default: 12099 WARN_ON_ONCE(1); 12100 return -EFAULT; 12101 } 12102 12103 if (is_kfunc_release(meta) && reg->ref_obj_id) 12104 arg_type |= OBJ_RELEASE; 12105 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 12106 if (ret < 0) 12107 return ret; 12108 12109 switch (kf_arg_type) { 12110 case KF_ARG_PTR_TO_CTX: 12111 if (reg->type != PTR_TO_CTX) { 12112 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", 12113 i, reg_type_str(env, reg->type)); 12114 return -EINVAL; 12115 } 12116 12117 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12118 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 12119 if (ret < 0) 12120 return -EINVAL; 12121 meta->ret_btf_id = ret; 12122 } 12123 break; 12124 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 12125 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 12126 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) { 12127 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i); 12128 return -EINVAL; 12129 } 12130 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 12131 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 12132 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i); 12133 return -EINVAL; 12134 } 12135 } else { 12136 verbose(env, "arg#%d expected pointer to allocated object\n", i); 12137 return -EINVAL; 12138 } 12139 if (!reg->ref_obj_id) { 12140 verbose(env, "allocated object must be referenced\n"); 12141 return -EINVAL; 12142 } 12143 if (meta->btf == btf_vmlinux) { 12144 meta->arg_btf = reg->btf; 12145 meta->arg_btf_id = reg->btf_id; 12146 } 12147 break; 12148 case KF_ARG_PTR_TO_DYNPTR: 12149 { 12150 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 12151 int clone_ref_obj_id = 0; 12152 12153 if (reg->type == CONST_PTR_TO_DYNPTR) 12154 dynptr_arg_type |= MEM_RDONLY; 12155 12156 if (is_kfunc_arg_uninit(btf, &args[i])) 12157 dynptr_arg_type |= MEM_UNINIT; 12158 12159 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 12160 dynptr_arg_type |= DYNPTR_TYPE_SKB; 12161 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 12162 dynptr_arg_type |= DYNPTR_TYPE_XDP; 12163 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 12164 (dynptr_arg_type & MEM_UNINIT)) { 12165 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 12166 12167 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 12168 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 12169 return -EFAULT; 12170 } 12171 12172 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 12173 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 12174 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 12175 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 12176 return -EFAULT; 12177 } 12178 } 12179 12180 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 12181 if (ret < 0) 12182 return ret; 12183 12184 if (!(dynptr_arg_type & MEM_UNINIT)) { 12185 int id = dynptr_id(env, reg); 12186 12187 if (id < 0) { 12188 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 12189 return id; 12190 } 12191 meta->initialized_dynptr.id = id; 12192 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 12193 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 12194 } 12195 12196 break; 12197 } 12198 case KF_ARG_PTR_TO_ITER: 12199 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 12200 if (!check_css_task_iter_allowlist(env)) { 12201 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 12202 return -EINVAL; 12203 } 12204 } 12205 ret = process_iter_arg(env, regno, insn_idx, meta); 12206 if (ret < 0) 12207 return ret; 12208 break; 12209 case KF_ARG_PTR_TO_LIST_HEAD: 12210 if (reg->type != PTR_TO_MAP_VALUE && 12211 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12212 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 12213 return -EINVAL; 12214 } 12215 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 12216 verbose(env, "allocated object must be referenced\n"); 12217 return -EINVAL; 12218 } 12219 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 12220 if (ret < 0) 12221 return ret; 12222 break; 12223 case KF_ARG_PTR_TO_RB_ROOT: 12224 if (reg->type != PTR_TO_MAP_VALUE && 12225 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12226 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 12227 return -EINVAL; 12228 } 12229 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 12230 verbose(env, "allocated object must be referenced\n"); 12231 return -EINVAL; 12232 } 12233 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 12234 if (ret < 0) 12235 return ret; 12236 break; 12237 case KF_ARG_PTR_TO_LIST_NODE: 12238 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12239 verbose(env, "arg#%d expected pointer to allocated object\n", i); 12240 return -EINVAL; 12241 } 12242 if (!reg->ref_obj_id) { 12243 verbose(env, "allocated object must be referenced\n"); 12244 return -EINVAL; 12245 } 12246 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 12247 if (ret < 0) 12248 return ret; 12249 break; 12250 case KF_ARG_PTR_TO_RB_NODE: 12251 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 12252 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 12253 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 12254 return -EINVAL; 12255 } 12256 if (in_rbtree_lock_required_cb(env)) { 12257 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 12258 return -EINVAL; 12259 } 12260 } else { 12261 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12262 verbose(env, "arg#%d expected pointer to allocated object\n", i); 12263 return -EINVAL; 12264 } 12265 if (!reg->ref_obj_id) { 12266 verbose(env, "allocated object must be referenced\n"); 12267 return -EINVAL; 12268 } 12269 } 12270 12271 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 12272 if (ret < 0) 12273 return ret; 12274 break; 12275 case KF_ARG_PTR_TO_MAP: 12276 /* If argument has '__map' suffix expect 'struct bpf_map *' */ 12277 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP]; 12278 ref_t = btf_type_by_id(btf_vmlinux, ref_id); 12279 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12280 fallthrough; 12281 case KF_ARG_PTR_TO_BTF_ID: 12282 /* Only base_type is checked, further checks are done here */ 12283 if ((base_type(reg->type) != PTR_TO_BTF_ID || 12284 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 12285 !reg2btf_ids[base_type(reg->type)]) { 12286 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 12287 verbose(env, "expected %s or socket\n", 12288 reg_type_str(env, base_type(reg->type) | 12289 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 12290 return -EINVAL; 12291 } 12292 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 12293 if (ret < 0) 12294 return ret; 12295 break; 12296 case KF_ARG_PTR_TO_MEM: 12297 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 12298 if (IS_ERR(resolve_ret)) { 12299 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 12300 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 12301 return -EINVAL; 12302 } 12303 ret = check_mem_reg(env, reg, regno, type_size); 12304 if (ret < 0) 12305 return ret; 12306 break; 12307 case KF_ARG_PTR_TO_MEM_SIZE: 12308 { 12309 struct bpf_reg_state *buff_reg = ®s[regno]; 12310 const struct btf_param *buff_arg = &args[i]; 12311 struct bpf_reg_state *size_reg = ®s[regno + 1]; 12312 const struct btf_param *size_arg = &args[i + 1]; 12313 12314 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 12315 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 12316 if (ret < 0) { 12317 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 12318 return ret; 12319 } 12320 } 12321 12322 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 12323 if (meta->arg_constant.found) { 12324 verbose(env, "verifier internal error: only one constant argument permitted\n"); 12325 return -EFAULT; 12326 } 12327 if (!tnum_is_const(size_reg->var_off)) { 12328 verbose(env, "R%d must be a known constant\n", regno + 1); 12329 return -EINVAL; 12330 } 12331 meta->arg_constant.found = true; 12332 meta->arg_constant.value = size_reg->var_off.value; 12333 } 12334 12335 /* Skip next '__sz' or '__szk' argument */ 12336 i++; 12337 break; 12338 } 12339 case KF_ARG_PTR_TO_CALLBACK: 12340 if (reg->type != PTR_TO_FUNC) { 12341 verbose(env, "arg%d expected pointer to func\n", i); 12342 return -EINVAL; 12343 } 12344 meta->subprogno = reg->subprogno; 12345 break; 12346 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12347 if (!type_is_ptr_alloc_obj(reg->type)) { 12348 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 12349 return -EINVAL; 12350 } 12351 if (!type_is_non_owning_ref(reg->type)) 12352 meta->arg_owning_ref = true; 12353 12354 rec = reg_btf_record(reg); 12355 if (!rec) { 12356 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 12357 return -EFAULT; 12358 } 12359 12360 if (rec->refcount_off < 0) { 12361 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 12362 return -EINVAL; 12363 } 12364 12365 meta->arg_btf = reg->btf; 12366 meta->arg_btf_id = reg->btf_id; 12367 break; 12368 case KF_ARG_PTR_TO_CONST_STR: 12369 if (reg->type != PTR_TO_MAP_VALUE) { 12370 verbose(env, "arg#%d doesn't point to a const string\n", i); 12371 return -EINVAL; 12372 } 12373 ret = check_reg_const_str(env, reg, regno); 12374 if (ret) 12375 return ret; 12376 break; 12377 case KF_ARG_PTR_TO_WORKQUEUE: 12378 if (reg->type != PTR_TO_MAP_VALUE) { 12379 verbose(env, "arg#%d doesn't point to a map value\n", i); 12380 return -EINVAL; 12381 } 12382 ret = process_wq_func(env, regno, meta); 12383 if (ret < 0) 12384 return ret; 12385 break; 12386 } 12387 } 12388 12389 if (is_kfunc_release(meta) && !meta->release_regno) { 12390 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 12391 func_name); 12392 return -EINVAL; 12393 } 12394 12395 return 0; 12396 } 12397 12398 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 12399 struct bpf_insn *insn, 12400 struct bpf_kfunc_call_arg_meta *meta, 12401 const char **kfunc_name) 12402 { 12403 const struct btf_type *func, *func_proto; 12404 u32 func_id, *kfunc_flags; 12405 const char *func_name; 12406 struct btf *desc_btf; 12407 12408 if (kfunc_name) 12409 *kfunc_name = NULL; 12410 12411 if (!insn->imm) 12412 return -EINVAL; 12413 12414 desc_btf = find_kfunc_desc_btf(env, insn->off); 12415 if (IS_ERR(desc_btf)) 12416 return PTR_ERR(desc_btf); 12417 12418 func_id = insn->imm; 12419 func = btf_type_by_id(desc_btf, func_id); 12420 func_name = btf_name_by_offset(desc_btf, func->name_off); 12421 if (kfunc_name) 12422 *kfunc_name = func_name; 12423 func_proto = btf_type_by_id(desc_btf, func->type); 12424 12425 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 12426 if (!kfunc_flags) { 12427 return -EACCES; 12428 } 12429 12430 memset(meta, 0, sizeof(*meta)); 12431 meta->btf = desc_btf; 12432 meta->func_id = func_id; 12433 meta->kfunc_flags = *kfunc_flags; 12434 meta->func_proto = func_proto; 12435 meta->func_name = func_name; 12436 12437 return 0; 12438 } 12439 12440 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 12441 12442 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 12443 int *insn_idx_p) 12444 { 12445 bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable; 12446 u32 i, nargs, ptr_type_id, release_ref_obj_id; 12447 struct bpf_reg_state *regs = cur_regs(env); 12448 const char *func_name, *ptr_type_name; 12449 const struct btf_type *t, *ptr_type; 12450 struct bpf_kfunc_call_arg_meta meta; 12451 struct bpf_insn_aux_data *insn_aux; 12452 int err, insn_idx = *insn_idx_p; 12453 const struct btf_param *args; 12454 const struct btf_type *ret_t; 12455 struct btf *desc_btf; 12456 12457 /* skip for now, but return error when we find this in fixup_kfunc_call */ 12458 if (!insn->imm) 12459 return 0; 12460 12461 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 12462 if (err == -EACCES && func_name) 12463 verbose(env, "calling kernel function %s is not allowed\n", func_name); 12464 if (err) 12465 return err; 12466 desc_btf = meta.btf; 12467 insn_aux = &env->insn_aux_data[insn_idx]; 12468 12469 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 12470 12471 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 12472 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 12473 return -EACCES; 12474 } 12475 12476 sleepable = is_kfunc_sleepable(&meta); 12477 if (sleepable && !in_sleepable(env)) { 12478 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 12479 return -EACCES; 12480 } 12481 12482 /* Check the arguments */ 12483 err = check_kfunc_args(env, &meta, insn_idx); 12484 if (err < 0) 12485 return err; 12486 12487 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12488 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12489 set_rbtree_add_callback_state); 12490 if (err) { 12491 verbose(env, "kfunc %s#%d failed callback verification\n", 12492 func_name, meta.func_id); 12493 return err; 12494 } 12495 } 12496 12497 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) { 12498 meta.r0_size = sizeof(u64); 12499 meta.r0_rdonly = false; 12500 } 12501 12502 if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) { 12503 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12504 set_timer_callback_state); 12505 if (err) { 12506 verbose(env, "kfunc %s#%d failed callback verification\n", 12507 func_name, meta.func_id); 12508 return err; 12509 } 12510 } 12511 12512 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 12513 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 12514 12515 preempt_disable = is_kfunc_bpf_preempt_disable(&meta); 12516 preempt_enable = is_kfunc_bpf_preempt_enable(&meta); 12517 12518 if (env->cur_state->active_rcu_lock) { 12519 struct bpf_func_state *state; 12520 struct bpf_reg_state *reg; 12521 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 12522 12523 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 12524 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 12525 return -EACCES; 12526 } 12527 12528 if (rcu_lock) { 12529 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 12530 return -EINVAL; 12531 } else if (rcu_unlock) { 12532 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({ 12533 if (reg->type & MEM_RCU) { 12534 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 12535 reg->type |= PTR_UNTRUSTED; 12536 } 12537 })); 12538 env->cur_state->active_rcu_lock = false; 12539 } else if (sleepable) { 12540 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 12541 return -EACCES; 12542 } 12543 } else if (rcu_lock) { 12544 env->cur_state->active_rcu_lock = true; 12545 } else if (rcu_unlock) { 12546 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 12547 return -EINVAL; 12548 } 12549 12550 if (env->cur_state->active_preempt_lock) { 12551 if (preempt_disable) { 12552 env->cur_state->active_preempt_lock++; 12553 } else if (preempt_enable) { 12554 env->cur_state->active_preempt_lock--; 12555 } else if (sleepable) { 12556 verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name); 12557 return -EACCES; 12558 } 12559 } else if (preempt_disable) { 12560 env->cur_state->active_preempt_lock++; 12561 } else if (preempt_enable) { 12562 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name); 12563 return -EINVAL; 12564 } 12565 12566 /* In case of release function, we get register number of refcounted 12567 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 12568 */ 12569 if (meta.release_regno) { 12570 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 12571 if (err) { 12572 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12573 func_name, meta.func_id); 12574 return err; 12575 } 12576 } 12577 12578 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 12579 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 12580 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12581 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 12582 insn_aux->insert_off = regs[BPF_REG_2].off; 12583 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 12584 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 12585 if (err) { 12586 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 12587 func_name, meta.func_id); 12588 return err; 12589 } 12590 12591 err = release_reference(env, release_ref_obj_id); 12592 if (err) { 12593 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12594 func_name, meta.func_id); 12595 return err; 12596 } 12597 } 12598 12599 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 12600 if (!bpf_jit_supports_exceptions()) { 12601 verbose(env, "JIT does not support calling kfunc %s#%d\n", 12602 func_name, meta.func_id); 12603 return -ENOTSUPP; 12604 } 12605 env->seen_exception = true; 12606 12607 /* In the case of the default callback, the cookie value passed 12608 * to bpf_throw becomes the return value of the program. 12609 */ 12610 if (!env->exception_callback_subprog) { 12611 err = check_return_code(env, BPF_REG_1, "R1"); 12612 if (err < 0) 12613 return err; 12614 } 12615 } 12616 12617 for (i = 0; i < CALLER_SAVED_REGS; i++) 12618 mark_reg_not_init(env, regs, caller_saved[i]); 12619 12620 /* Check return type */ 12621 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 12622 12623 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 12624 /* Only exception is bpf_obj_new_impl */ 12625 if (meta.btf != btf_vmlinux || 12626 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 12627 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] && 12628 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 12629 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 12630 return -EINVAL; 12631 } 12632 } 12633 12634 if (btf_type_is_scalar(t)) { 12635 mark_reg_unknown(env, regs, BPF_REG_0); 12636 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 12637 } else if (btf_type_is_ptr(t)) { 12638 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 12639 12640 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12641 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 12642 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12643 struct btf_struct_meta *struct_meta; 12644 struct btf *ret_btf; 12645 u32 ret_btf_id; 12646 12647 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set) 12648 return -ENOMEM; 12649 12650 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 12651 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 12652 return -EINVAL; 12653 } 12654 12655 ret_btf = env->prog->aux->btf; 12656 ret_btf_id = meta.arg_constant.value; 12657 12658 /* This may be NULL due to user not supplying a BTF */ 12659 if (!ret_btf) { 12660 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 12661 return -EINVAL; 12662 } 12663 12664 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 12665 if (!ret_t || !__btf_type_is_struct(ret_t)) { 12666 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 12667 return -EINVAL; 12668 } 12669 12670 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12671 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 12672 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 12673 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 12674 return -EINVAL; 12675 } 12676 12677 if (!bpf_global_percpu_ma_set) { 12678 mutex_lock(&bpf_percpu_ma_lock); 12679 if (!bpf_global_percpu_ma_set) { 12680 /* Charge memory allocated with bpf_global_percpu_ma to 12681 * root memcg. The obj_cgroup for root memcg is NULL. 12682 */ 12683 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 12684 if (!err) 12685 bpf_global_percpu_ma_set = true; 12686 } 12687 mutex_unlock(&bpf_percpu_ma_lock); 12688 if (err) 12689 return err; 12690 } 12691 12692 mutex_lock(&bpf_percpu_ma_lock); 12693 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 12694 mutex_unlock(&bpf_percpu_ma_lock); 12695 if (err) 12696 return err; 12697 } 12698 12699 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 12700 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12701 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 12702 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 12703 return -EINVAL; 12704 } 12705 12706 if (struct_meta) { 12707 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 12708 return -EINVAL; 12709 } 12710 } 12711 12712 mark_reg_known_zero(env, regs, BPF_REG_0); 12713 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12714 regs[BPF_REG_0].btf = ret_btf; 12715 regs[BPF_REG_0].btf_id = ret_btf_id; 12716 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) 12717 regs[BPF_REG_0].type |= MEM_PERCPU; 12718 12719 insn_aux->obj_new_size = ret_t->size; 12720 insn_aux->kptr_struct_meta = struct_meta; 12721 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 12722 mark_reg_known_zero(env, regs, BPF_REG_0); 12723 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12724 regs[BPF_REG_0].btf = meta.arg_btf; 12725 regs[BPF_REG_0].btf_id = meta.arg_btf_id; 12726 12727 insn_aux->kptr_struct_meta = 12728 btf_find_struct_meta(meta.arg_btf, 12729 meta.arg_btf_id); 12730 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 12731 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 12732 struct btf_field *field = meta.arg_list_head.field; 12733 12734 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12735 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12736 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12737 struct btf_field *field = meta.arg_rbtree_root.field; 12738 12739 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12740 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12741 mark_reg_known_zero(env, regs, BPF_REG_0); 12742 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 12743 regs[BPF_REG_0].btf = desc_btf; 12744 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 12745 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 12746 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 12747 if (!ret_t || !btf_type_is_struct(ret_t)) { 12748 verbose(env, 12749 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 12750 return -EINVAL; 12751 } 12752 12753 mark_reg_known_zero(env, regs, BPF_REG_0); 12754 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 12755 regs[BPF_REG_0].btf = desc_btf; 12756 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 12757 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 12758 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 12759 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 12760 12761 mark_reg_known_zero(env, regs, BPF_REG_0); 12762 12763 if (!meta.arg_constant.found) { 12764 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 12765 return -EFAULT; 12766 } 12767 12768 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 12769 12770 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 12771 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 12772 12773 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 12774 regs[BPF_REG_0].type |= MEM_RDONLY; 12775 } else { 12776 /* this will set env->seen_direct_write to true */ 12777 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 12778 verbose(env, "the prog does not allow writes to packet data\n"); 12779 return -EINVAL; 12780 } 12781 } 12782 12783 if (!meta.initialized_dynptr.id) { 12784 verbose(env, "verifier internal error: no dynptr id\n"); 12785 return -EFAULT; 12786 } 12787 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 12788 12789 /* we don't need to set BPF_REG_0's ref obj id 12790 * because packet slices are not refcounted (see 12791 * dynptr_type_refcounted) 12792 */ 12793 } else { 12794 verbose(env, "kernel function %s unhandled dynamic return type\n", 12795 meta.func_name); 12796 return -EFAULT; 12797 } 12798 } else if (btf_type_is_void(ptr_type)) { 12799 /* kfunc returning 'void *' is equivalent to returning scalar */ 12800 mark_reg_unknown(env, regs, BPF_REG_0); 12801 } else if (!__btf_type_is_struct(ptr_type)) { 12802 if (!meta.r0_size) { 12803 __u32 sz; 12804 12805 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 12806 meta.r0_size = sz; 12807 meta.r0_rdonly = true; 12808 } 12809 } 12810 if (!meta.r0_size) { 12811 ptr_type_name = btf_name_by_offset(desc_btf, 12812 ptr_type->name_off); 12813 verbose(env, 12814 "kernel function %s returns pointer type %s %s is not supported\n", 12815 func_name, 12816 btf_type_str(ptr_type), 12817 ptr_type_name); 12818 return -EINVAL; 12819 } 12820 12821 mark_reg_known_zero(env, regs, BPF_REG_0); 12822 regs[BPF_REG_0].type = PTR_TO_MEM; 12823 regs[BPF_REG_0].mem_size = meta.r0_size; 12824 12825 if (meta.r0_rdonly) 12826 regs[BPF_REG_0].type |= MEM_RDONLY; 12827 12828 /* Ensures we don't access the memory after a release_reference() */ 12829 if (meta.ref_obj_id) 12830 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 12831 } else { 12832 mark_reg_known_zero(env, regs, BPF_REG_0); 12833 regs[BPF_REG_0].btf = desc_btf; 12834 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 12835 regs[BPF_REG_0].btf_id = ptr_type_id; 12836 12837 if (is_iter_next_kfunc(&meta)) { 12838 struct bpf_reg_state *cur_iter; 12839 12840 cur_iter = get_iter_from_state(env->cur_state, &meta); 12841 12842 if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */ 12843 regs[BPF_REG_0].type |= MEM_RCU; 12844 else 12845 regs[BPF_REG_0].type |= PTR_TRUSTED; 12846 } 12847 } 12848 12849 if (is_kfunc_ret_null(&meta)) { 12850 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 12851 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 12852 regs[BPF_REG_0].id = ++env->id_gen; 12853 } 12854 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 12855 if (is_kfunc_acquire(&meta)) { 12856 int id = acquire_reference_state(env, insn_idx); 12857 12858 if (id < 0) 12859 return id; 12860 if (is_kfunc_ret_null(&meta)) 12861 regs[BPF_REG_0].id = id; 12862 regs[BPF_REG_0].ref_obj_id = id; 12863 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12864 ref_set_non_owning(env, ®s[BPF_REG_0]); 12865 } 12866 12867 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 12868 regs[BPF_REG_0].id = ++env->id_gen; 12869 } else if (btf_type_is_void(t)) { 12870 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12871 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 12872 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 12873 insn_aux->kptr_struct_meta = 12874 btf_find_struct_meta(meta.arg_btf, 12875 meta.arg_btf_id); 12876 } 12877 } 12878 } 12879 12880 nargs = btf_type_vlen(meta.func_proto); 12881 args = (const struct btf_param *)(meta.func_proto + 1); 12882 for (i = 0; i < nargs; i++) { 12883 u32 regno = i + 1; 12884 12885 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 12886 if (btf_type_is_ptr(t)) 12887 mark_btf_func_reg_size(env, regno, sizeof(void *)); 12888 else 12889 /* scalar. ensured by btf_check_kfunc_arg_match() */ 12890 mark_btf_func_reg_size(env, regno, t->size); 12891 } 12892 12893 if (is_iter_next_kfunc(&meta)) { 12894 err = process_iter_next_call(env, insn_idx, &meta); 12895 if (err) 12896 return err; 12897 } 12898 12899 return 0; 12900 } 12901 12902 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 12903 const struct bpf_reg_state *reg, 12904 enum bpf_reg_type type) 12905 { 12906 bool known = tnum_is_const(reg->var_off); 12907 s64 val = reg->var_off.value; 12908 s64 smin = reg->smin_value; 12909 12910 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 12911 verbose(env, "math between %s pointer and %lld is not allowed\n", 12912 reg_type_str(env, type), val); 12913 return false; 12914 } 12915 12916 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 12917 verbose(env, "%s pointer offset %d is not allowed\n", 12918 reg_type_str(env, type), reg->off); 12919 return false; 12920 } 12921 12922 if (smin == S64_MIN) { 12923 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 12924 reg_type_str(env, type)); 12925 return false; 12926 } 12927 12928 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 12929 verbose(env, "value %lld makes %s pointer be out of bounds\n", 12930 smin, reg_type_str(env, type)); 12931 return false; 12932 } 12933 12934 return true; 12935 } 12936 12937 enum { 12938 REASON_BOUNDS = -1, 12939 REASON_TYPE = -2, 12940 REASON_PATHS = -3, 12941 REASON_LIMIT = -4, 12942 REASON_STACK = -5, 12943 }; 12944 12945 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 12946 u32 *alu_limit, bool mask_to_left) 12947 { 12948 u32 max = 0, ptr_limit = 0; 12949 12950 switch (ptr_reg->type) { 12951 case PTR_TO_STACK: 12952 /* Offset 0 is out-of-bounds, but acceptable start for the 12953 * left direction, see BPF_REG_FP. Also, unknown scalar 12954 * offset where we would need to deal with min/max bounds is 12955 * currently prohibited for unprivileged. 12956 */ 12957 max = MAX_BPF_STACK + mask_to_left; 12958 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 12959 break; 12960 case PTR_TO_MAP_VALUE: 12961 max = ptr_reg->map_ptr->value_size; 12962 ptr_limit = (mask_to_left ? 12963 ptr_reg->smin_value : 12964 ptr_reg->umax_value) + ptr_reg->off; 12965 break; 12966 default: 12967 return REASON_TYPE; 12968 } 12969 12970 if (ptr_limit >= max) 12971 return REASON_LIMIT; 12972 *alu_limit = ptr_limit; 12973 return 0; 12974 } 12975 12976 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 12977 const struct bpf_insn *insn) 12978 { 12979 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 12980 } 12981 12982 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 12983 u32 alu_state, u32 alu_limit) 12984 { 12985 /* If we arrived here from different branches with different 12986 * state or limits to sanitize, then this won't work. 12987 */ 12988 if (aux->alu_state && 12989 (aux->alu_state != alu_state || 12990 aux->alu_limit != alu_limit)) 12991 return REASON_PATHS; 12992 12993 /* Corresponding fixup done in do_misc_fixups(). */ 12994 aux->alu_state = alu_state; 12995 aux->alu_limit = alu_limit; 12996 return 0; 12997 } 12998 12999 static int sanitize_val_alu(struct bpf_verifier_env *env, 13000 struct bpf_insn *insn) 13001 { 13002 struct bpf_insn_aux_data *aux = cur_aux(env); 13003 13004 if (can_skip_alu_sanitation(env, insn)) 13005 return 0; 13006 13007 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 13008 } 13009 13010 static bool sanitize_needed(u8 opcode) 13011 { 13012 return opcode == BPF_ADD || opcode == BPF_SUB; 13013 } 13014 13015 struct bpf_sanitize_info { 13016 struct bpf_insn_aux_data aux; 13017 bool mask_to_left; 13018 }; 13019 13020 static struct bpf_verifier_state * 13021 sanitize_speculative_path(struct bpf_verifier_env *env, 13022 const struct bpf_insn *insn, 13023 u32 next_idx, u32 curr_idx) 13024 { 13025 struct bpf_verifier_state *branch; 13026 struct bpf_reg_state *regs; 13027 13028 branch = push_stack(env, next_idx, curr_idx, true); 13029 if (branch && insn) { 13030 regs = branch->frame[branch->curframe]->regs; 13031 if (BPF_SRC(insn->code) == BPF_K) { 13032 mark_reg_unknown(env, regs, insn->dst_reg); 13033 } else if (BPF_SRC(insn->code) == BPF_X) { 13034 mark_reg_unknown(env, regs, insn->dst_reg); 13035 mark_reg_unknown(env, regs, insn->src_reg); 13036 } 13037 } 13038 return branch; 13039 } 13040 13041 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 13042 struct bpf_insn *insn, 13043 const struct bpf_reg_state *ptr_reg, 13044 const struct bpf_reg_state *off_reg, 13045 struct bpf_reg_state *dst_reg, 13046 struct bpf_sanitize_info *info, 13047 const bool commit_window) 13048 { 13049 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 13050 struct bpf_verifier_state *vstate = env->cur_state; 13051 bool off_is_imm = tnum_is_const(off_reg->var_off); 13052 bool off_is_neg = off_reg->smin_value < 0; 13053 bool ptr_is_dst_reg = ptr_reg == dst_reg; 13054 u8 opcode = BPF_OP(insn->code); 13055 u32 alu_state, alu_limit; 13056 struct bpf_reg_state tmp; 13057 bool ret; 13058 int err; 13059 13060 if (can_skip_alu_sanitation(env, insn)) 13061 return 0; 13062 13063 /* We already marked aux for masking from non-speculative 13064 * paths, thus we got here in the first place. We only care 13065 * to explore bad access from here. 13066 */ 13067 if (vstate->speculative) 13068 goto do_sim; 13069 13070 if (!commit_window) { 13071 if (!tnum_is_const(off_reg->var_off) && 13072 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 13073 return REASON_BOUNDS; 13074 13075 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 13076 (opcode == BPF_SUB && !off_is_neg); 13077 } 13078 13079 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 13080 if (err < 0) 13081 return err; 13082 13083 if (commit_window) { 13084 /* In commit phase we narrow the masking window based on 13085 * the observed pointer move after the simulated operation. 13086 */ 13087 alu_state = info->aux.alu_state; 13088 alu_limit = abs(info->aux.alu_limit - alu_limit); 13089 } else { 13090 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 13091 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 13092 alu_state |= ptr_is_dst_reg ? 13093 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 13094 13095 /* Limit pruning on unknown scalars to enable deep search for 13096 * potential masking differences from other program paths. 13097 */ 13098 if (!off_is_imm) 13099 env->explore_alu_limits = true; 13100 } 13101 13102 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 13103 if (err < 0) 13104 return err; 13105 do_sim: 13106 /* If we're in commit phase, we're done here given we already 13107 * pushed the truncated dst_reg into the speculative verification 13108 * stack. 13109 * 13110 * Also, when register is a known constant, we rewrite register-based 13111 * operation to immediate-based, and thus do not need masking (and as 13112 * a consequence, do not need to simulate the zero-truncation either). 13113 */ 13114 if (commit_window || off_is_imm) 13115 return 0; 13116 13117 /* Simulate and find potential out-of-bounds access under 13118 * speculative execution from truncation as a result of 13119 * masking when off was not within expected range. If off 13120 * sits in dst, then we temporarily need to move ptr there 13121 * to simulate dst (== 0) +/-= ptr. Needed, for example, 13122 * for cases where we use K-based arithmetic in one direction 13123 * and truncated reg-based in the other in order to explore 13124 * bad access. 13125 */ 13126 if (!ptr_is_dst_reg) { 13127 tmp = *dst_reg; 13128 copy_register_state(dst_reg, ptr_reg); 13129 } 13130 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 13131 env->insn_idx); 13132 if (!ptr_is_dst_reg && ret) 13133 *dst_reg = tmp; 13134 return !ret ? REASON_STACK : 0; 13135 } 13136 13137 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 13138 { 13139 struct bpf_verifier_state *vstate = env->cur_state; 13140 13141 /* If we simulate paths under speculation, we don't update the 13142 * insn as 'seen' such that when we verify unreachable paths in 13143 * the non-speculative domain, sanitize_dead_code() can still 13144 * rewrite/sanitize them. 13145 */ 13146 if (!vstate->speculative) 13147 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 13148 } 13149 13150 static int sanitize_err(struct bpf_verifier_env *env, 13151 const struct bpf_insn *insn, int reason, 13152 const struct bpf_reg_state *off_reg, 13153 const struct bpf_reg_state *dst_reg) 13154 { 13155 static const char *err = "pointer arithmetic with it prohibited for !root"; 13156 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 13157 u32 dst = insn->dst_reg, src = insn->src_reg; 13158 13159 switch (reason) { 13160 case REASON_BOUNDS: 13161 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 13162 off_reg == dst_reg ? dst : src, err); 13163 break; 13164 case REASON_TYPE: 13165 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 13166 off_reg == dst_reg ? src : dst, err); 13167 break; 13168 case REASON_PATHS: 13169 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 13170 dst, op, err); 13171 break; 13172 case REASON_LIMIT: 13173 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 13174 dst, op, err); 13175 break; 13176 case REASON_STACK: 13177 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 13178 dst, err); 13179 break; 13180 default: 13181 verbose(env, "verifier internal error: unknown reason (%d)\n", 13182 reason); 13183 break; 13184 } 13185 13186 return -EACCES; 13187 } 13188 13189 /* check that stack access falls within stack limits and that 'reg' doesn't 13190 * have a variable offset. 13191 * 13192 * Variable offset is prohibited for unprivileged mode for simplicity since it 13193 * requires corresponding support in Spectre masking for stack ALU. See also 13194 * retrieve_ptr_limit(). 13195 * 13196 * 13197 * 'off' includes 'reg->off'. 13198 */ 13199 static int check_stack_access_for_ptr_arithmetic( 13200 struct bpf_verifier_env *env, 13201 int regno, 13202 const struct bpf_reg_state *reg, 13203 int off) 13204 { 13205 if (!tnum_is_const(reg->var_off)) { 13206 char tn_buf[48]; 13207 13208 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 13209 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 13210 regno, tn_buf, off); 13211 return -EACCES; 13212 } 13213 13214 if (off >= 0 || off < -MAX_BPF_STACK) { 13215 verbose(env, "R%d stack pointer arithmetic goes out of range, " 13216 "prohibited for !root; off=%d\n", regno, off); 13217 return -EACCES; 13218 } 13219 13220 return 0; 13221 } 13222 13223 static int sanitize_check_bounds(struct bpf_verifier_env *env, 13224 const struct bpf_insn *insn, 13225 const struct bpf_reg_state *dst_reg) 13226 { 13227 u32 dst = insn->dst_reg; 13228 13229 /* For unprivileged we require that resulting offset must be in bounds 13230 * in order to be able to sanitize access later on. 13231 */ 13232 if (env->bypass_spec_v1) 13233 return 0; 13234 13235 switch (dst_reg->type) { 13236 case PTR_TO_STACK: 13237 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 13238 dst_reg->off + dst_reg->var_off.value)) 13239 return -EACCES; 13240 break; 13241 case PTR_TO_MAP_VALUE: 13242 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 13243 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 13244 "prohibited for !root\n", dst); 13245 return -EACCES; 13246 } 13247 break; 13248 default: 13249 break; 13250 } 13251 13252 return 0; 13253 } 13254 13255 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 13256 * Caller should also handle BPF_MOV case separately. 13257 * If we return -EACCES, caller may want to try again treating pointer as a 13258 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 13259 */ 13260 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 13261 struct bpf_insn *insn, 13262 const struct bpf_reg_state *ptr_reg, 13263 const struct bpf_reg_state *off_reg) 13264 { 13265 struct bpf_verifier_state *vstate = env->cur_state; 13266 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13267 struct bpf_reg_state *regs = state->regs, *dst_reg; 13268 bool known = tnum_is_const(off_reg->var_off); 13269 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 13270 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 13271 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 13272 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 13273 struct bpf_sanitize_info info = {}; 13274 u8 opcode = BPF_OP(insn->code); 13275 u32 dst = insn->dst_reg; 13276 int ret; 13277 13278 dst_reg = ®s[dst]; 13279 13280 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 13281 smin_val > smax_val || umin_val > umax_val) { 13282 /* Taint dst register if offset had invalid bounds derived from 13283 * e.g. dead branches. 13284 */ 13285 __mark_reg_unknown(env, dst_reg); 13286 return 0; 13287 } 13288 13289 if (BPF_CLASS(insn->code) != BPF_ALU64) { 13290 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 13291 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13292 __mark_reg_unknown(env, dst_reg); 13293 return 0; 13294 } 13295 13296 verbose(env, 13297 "R%d 32-bit pointer arithmetic prohibited\n", 13298 dst); 13299 return -EACCES; 13300 } 13301 13302 if (ptr_reg->type & PTR_MAYBE_NULL) { 13303 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 13304 dst, reg_type_str(env, ptr_reg->type)); 13305 return -EACCES; 13306 } 13307 13308 switch (base_type(ptr_reg->type)) { 13309 case PTR_TO_CTX: 13310 case PTR_TO_MAP_VALUE: 13311 case PTR_TO_MAP_KEY: 13312 case PTR_TO_STACK: 13313 case PTR_TO_PACKET_META: 13314 case PTR_TO_PACKET: 13315 case PTR_TO_TP_BUFFER: 13316 case PTR_TO_BTF_ID: 13317 case PTR_TO_MEM: 13318 case PTR_TO_BUF: 13319 case PTR_TO_FUNC: 13320 case CONST_PTR_TO_DYNPTR: 13321 break; 13322 case PTR_TO_FLOW_KEYS: 13323 if (known) 13324 break; 13325 fallthrough; 13326 case CONST_PTR_TO_MAP: 13327 /* smin_val represents the known value */ 13328 if (known && smin_val == 0 && opcode == BPF_ADD) 13329 break; 13330 fallthrough; 13331 default: 13332 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 13333 dst, reg_type_str(env, ptr_reg->type)); 13334 return -EACCES; 13335 } 13336 13337 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 13338 * The id may be overwritten later if we create a new variable offset. 13339 */ 13340 dst_reg->type = ptr_reg->type; 13341 dst_reg->id = ptr_reg->id; 13342 13343 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 13344 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 13345 return -EINVAL; 13346 13347 /* pointer types do not carry 32-bit bounds at the moment. */ 13348 __mark_reg32_unbounded(dst_reg); 13349 13350 if (sanitize_needed(opcode)) { 13351 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 13352 &info, false); 13353 if (ret < 0) 13354 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13355 } 13356 13357 switch (opcode) { 13358 case BPF_ADD: 13359 /* We can take a fixed offset as long as it doesn't overflow 13360 * the s32 'off' field 13361 */ 13362 if (known && (ptr_reg->off + smin_val == 13363 (s64)(s32)(ptr_reg->off + smin_val))) { 13364 /* pointer += K. Accumulate it into fixed offset */ 13365 dst_reg->smin_value = smin_ptr; 13366 dst_reg->smax_value = smax_ptr; 13367 dst_reg->umin_value = umin_ptr; 13368 dst_reg->umax_value = umax_ptr; 13369 dst_reg->var_off = ptr_reg->var_off; 13370 dst_reg->off = ptr_reg->off + smin_val; 13371 dst_reg->raw = ptr_reg->raw; 13372 break; 13373 } 13374 /* A new variable offset is created. Note that off_reg->off 13375 * == 0, since it's a scalar. 13376 * dst_reg gets the pointer type and since some positive 13377 * integer value was added to the pointer, give it a new 'id' 13378 * if it's a PTR_TO_PACKET. 13379 * this creates a new 'base' pointer, off_reg (variable) gets 13380 * added into the variable offset, and we copy the fixed offset 13381 * from ptr_reg. 13382 */ 13383 if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) || 13384 check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) { 13385 dst_reg->smin_value = S64_MIN; 13386 dst_reg->smax_value = S64_MAX; 13387 } 13388 if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) || 13389 check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) { 13390 dst_reg->umin_value = 0; 13391 dst_reg->umax_value = U64_MAX; 13392 } 13393 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 13394 dst_reg->off = ptr_reg->off; 13395 dst_reg->raw = ptr_reg->raw; 13396 if (reg_is_pkt_pointer(ptr_reg)) { 13397 dst_reg->id = ++env->id_gen; 13398 /* something was added to pkt_ptr, set range to zero */ 13399 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13400 } 13401 break; 13402 case BPF_SUB: 13403 if (dst_reg == off_reg) { 13404 /* scalar -= pointer. Creates an unknown scalar */ 13405 verbose(env, "R%d tried to subtract pointer from scalar\n", 13406 dst); 13407 return -EACCES; 13408 } 13409 /* We don't allow subtraction from FP, because (according to 13410 * test_verifier.c test "invalid fp arithmetic", JITs might not 13411 * be able to deal with it. 13412 */ 13413 if (ptr_reg->type == PTR_TO_STACK) { 13414 verbose(env, "R%d subtraction from stack pointer prohibited\n", 13415 dst); 13416 return -EACCES; 13417 } 13418 if (known && (ptr_reg->off - smin_val == 13419 (s64)(s32)(ptr_reg->off - smin_val))) { 13420 /* pointer -= K. Subtract it from fixed offset */ 13421 dst_reg->smin_value = smin_ptr; 13422 dst_reg->smax_value = smax_ptr; 13423 dst_reg->umin_value = umin_ptr; 13424 dst_reg->umax_value = umax_ptr; 13425 dst_reg->var_off = ptr_reg->var_off; 13426 dst_reg->id = ptr_reg->id; 13427 dst_reg->off = ptr_reg->off - smin_val; 13428 dst_reg->raw = ptr_reg->raw; 13429 break; 13430 } 13431 /* A new variable offset is created. If the subtrahend is known 13432 * nonnegative, then any reg->range we had before is still good. 13433 */ 13434 if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) || 13435 check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) { 13436 /* Overflow possible, we know nothing */ 13437 dst_reg->smin_value = S64_MIN; 13438 dst_reg->smax_value = S64_MAX; 13439 } 13440 if (umin_ptr < umax_val) { 13441 /* Overflow possible, we know nothing */ 13442 dst_reg->umin_value = 0; 13443 dst_reg->umax_value = U64_MAX; 13444 } else { 13445 /* Cannot overflow (as long as bounds are consistent) */ 13446 dst_reg->umin_value = umin_ptr - umax_val; 13447 dst_reg->umax_value = umax_ptr - umin_val; 13448 } 13449 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 13450 dst_reg->off = ptr_reg->off; 13451 dst_reg->raw = ptr_reg->raw; 13452 if (reg_is_pkt_pointer(ptr_reg)) { 13453 dst_reg->id = ++env->id_gen; 13454 /* something was added to pkt_ptr, set range to zero */ 13455 if (smin_val < 0) 13456 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13457 } 13458 break; 13459 case BPF_AND: 13460 case BPF_OR: 13461 case BPF_XOR: 13462 /* bitwise ops on pointers are troublesome, prohibit. */ 13463 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 13464 dst, bpf_alu_string[opcode >> 4]); 13465 return -EACCES; 13466 default: 13467 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 13468 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 13469 dst, bpf_alu_string[opcode >> 4]); 13470 return -EACCES; 13471 } 13472 13473 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 13474 return -EINVAL; 13475 reg_bounds_sync(dst_reg); 13476 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 13477 return -EACCES; 13478 if (sanitize_needed(opcode)) { 13479 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 13480 &info, true); 13481 if (ret < 0) 13482 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13483 } 13484 13485 return 0; 13486 } 13487 13488 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 13489 struct bpf_reg_state *src_reg) 13490 { 13491 s32 *dst_smin = &dst_reg->s32_min_value; 13492 s32 *dst_smax = &dst_reg->s32_max_value; 13493 u32 *dst_umin = &dst_reg->u32_min_value; 13494 u32 *dst_umax = &dst_reg->u32_max_value; 13495 13496 if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) || 13497 check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) { 13498 *dst_smin = S32_MIN; 13499 *dst_smax = S32_MAX; 13500 } 13501 if (check_add_overflow(*dst_umin, src_reg->u32_min_value, dst_umin) || 13502 check_add_overflow(*dst_umax, src_reg->u32_max_value, dst_umax)) { 13503 *dst_umin = 0; 13504 *dst_umax = U32_MAX; 13505 } 13506 } 13507 13508 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 13509 struct bpf_reg_state *src_reg) 13510 { 13511 s64 *dst_smin = &dst_reg->smin_value; 13512 s64 *dst_smax = &dst_reg->smax_value; 13513 u64 *dst_umin = &dst_reg->umin_value; 13514 u64 *dst_umax = &dst_reg->umax_value; 13515 13516 if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) || 13517 check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) { 13518 *dst_smin = S64_MIN; 13519 *dst_smax = S64_MAX; 13520 } 13521 if (check_add_overflow(*dst_umin, src_reg->umin_value, dst_umin) || 13522 check_add_overflow(*dst_umax, src_reg->umax_value, dst_umax)) { 13523 *dst_umin = 0; 13524 *dst_umax = U64_MAX; 13525 } 13526 } 13527 13528 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 13529 struct bpf_reg_state *src_reg) 13530 { 13531 s32 *dst_smin = &dst_reg->s32_min_value; 13532 s32 *dst_smax = &dst_reg->s32_max_value; 13533 u32 umin_val = src_reg->u32_min_value; 13534 u32 umax_val = src_reg->u32_max_value; 13535 13536 if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) || 13537 check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) { 13538 /* Overflow possible, we know nothing */ 13539 *dst_smin = S32_MIN; 13540 *dst_smax = S32_MAX; 13541 } 13542 if (dst_reg->u32_min_value < umax_val) { 13543 /* Overflow possible, we know nothing */ 13544 dst_reg->u32_min_value = 0; 13545 dst_reg->u32_max_value = U32_MAX; 13546 } else { 13547 /* Cannot overflow (as long as bounds are consistent) */ 13548 dst_reg->u32_min_value -= umax_val; 13549 dst_reg->u32_max_value -= umin_val; 13550 } 13551 } 13552 13553 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 13554 struct bpf_reg_state *src_reg) 13555 { 13556 s64 *dst_smin = &dst_reg->smin_value; 13557 s64 *dst_smax = &dst_reg->smax_value; 13558 u64 umin_val = src_reg->umin_value; 13559 u64 umax_val = src_reg->umax_value; 13560 13561 if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) || 13562 check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) { 13563 /* Overflow possible, we know nothing */ 13564 *dst_smin = S64_MIN; 13565 *dst_smax = S64_MAX; 13566 } 13567 if (dst_reg->umin_value < umax_val) { 13568 /* Overflow possible, we know nothing */ 13569 dst_reg->umin_value = 0; 13570 dst_reg->umax_value = U64_MAX; 13571 } else { 13572 /* Cannot overflow (as long as bounds are consistent) */ 13573 dst_reg->umin_value -= umax_val; 13574 dst_reg->umax_value -= umin_val; 13575 } 13576 } 13577 13578 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 13579 struct bpf_reg_state *src_reg) 13580 { 13581 s32 smin_val = src_reg->s32_min_value; 13582 u32 umin_val = src_reg->u32_min_value; 13583 u32 umax_val = src_reg->u32_max_value; 13584 13585 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 13586 /* Ain't nobody got time to multiply that sign */ 13587 __mark_reg32_unbounded(dst_reg); 13588 return; 13589 } 13590 /* Both values are positive, so we can work with unsigned and 13591 * copy the result to signed (unless it exceeds S32_MAX). 13592 */ 13593 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 13594 /* Potential overflow, we know nothing */ 13595 __mark_reg32_unbounded(dst_reg); 13596 return; 13597 } 13598 dst_reg->u32_min_value *= umin_val; 13599 dst_reg->u32_max_value *= umax_val; 13600 if (dst_reg->u32_max_value > S32_MAX) { 13601 /* Overflow possible, we know nothing */ 13602 dst_reg->s32_min_value = S32_MIN; 13603 dst_reg->s32_max_value = S32_MAX; 13604 } else { 13605 dst_reg->s32_min_value = dst_reg->u32_min_value; 13606 dst_reg->s32_max_value = dst_reg->u32_max_value; 13607 } 13608 } 13609 13610 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 13611 struct bpf_reg_state *src_reg) 13612 { 13613 s64 smin_val = src_reg->smin_value; 13614 u64 umin_val = src_reg->umin_value; 13615 u64 umax_val = src_reg->umax_value; 13616 13617 if (smin_val < 0 || dst_reg->smin_value < 0) { 13618 /* Ain't nobody got time to multiply that sign */ 13619 __mark_reg64_unbounded(dst_reg); 13620 return; 13621 } 13622 /* Both values are positive, so we can work with unsigned and 13623 * copy the result to signed (unless it exceeds S64_MAX). 13624 */ 13625 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 13626 /* Potential overflow, we know nothing */ 13627 __mark_reg64_unbounded(dst_reg); 13628 return; 13629 } 13630 dst_reg->umin_value *= umin_val; 13631 dst_reg->umax_value *= umax_val; 13632 if (dst_reg->umax_value > S64_MAX) { 13633 /* Overflow possible, we know nothing */ 13634 dst_reg->smin_value = S64_MIN; 13635 dst_reg->smax_value = S64_MAX; 13636 } else { 13637 dst_reg->smin_value = dst_reg->umin_value; 13638 dst_reg->smax_value = dst_reg->umax_value; 13639 } 13640 } 13641 13642 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 13643 struct bpf_reg_state *src_reg) 13644 { 13645 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13646 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13647 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13648 u32 umax_val = src_reg->u32_max_value; 13649 13650 if (src_known && dst_known) { 13651 __mark_reg32_known(dst_reg, var32_off.value); 13652 return; 13653 } 13654 13655 /* We get our minimum from the var_off, since that's inherently 13656 * bitwise. Our maximum is the minimum of the operands' maxima. 13657 */ 13658 dst_reg->u32_min_value = var32_off.value; 13659 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 13660 13661 /* Safe to set s32 bounds by casting u32 result into s32 when u32 13662 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 13663 */ 13664 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 13665 dst_reg->s32_min_value = dst_reg->u32_min_value; 13666 dst_reg->s32_max_value = dst_reg->u32_max_value; 13667 } else { 13668 dst_reg->s32_min_value = S32_MIN; 13669 dst_reg->s32_max_value = S32_MAX; 13670 } 13671 } 13672 13673 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 13674 struct bpf_reg_state *src_reg) 13675 { 13676 bool src_known = tnum_is_const(src_reg->var_off); 13677 bool dst_known = tnum_is_const(dst_reg->var_off); 13678 u64 umax_val = src_reg->umax_value; 13679 13680 if (src_known && dst_known) { 13681 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13682 return; 13683 } 13684 13685 /* We get our minimum from the var_off, since that's inherently 13686 * bitwise. Our maximum is the minimum of the operands' maxima. 13687 */ 13688 dst_reg->umin_value = dst_reg->var_off.value; 13689 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 13690 13691 /* Safe to set s64 bounds by casting u64 result into s64 when u64 13692 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 13693 */ 13694 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 13695 dst_reg->smin_value = dst_reg->umin_value; 13696 dst_reg->smax_value = dst_reg->umax_value; 13697 } else { 13698 dst_reg->smin_value = S64_MIN; 13699 dst_reg->smax_value = S64_MAX; 13700 } 13701 /* We may learn something more from the var_off */ 13702 __update_reg_bounds(dst_reg); 13703 } 13704 13705 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 13706 struct bpf_reg_state *src_reg) 13707 { 13708 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13709 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13710 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13711 u32 umin_val = src_reg->u32_min_value; 13712 13713 if (src_known && dst_known) { 13714 __mark_reg32_known(dst_reg, var32_off.value); 13715 return; 13716 } 13717 13718 /* We get our maximum from the var_off, and our minimum is the 13719 * maximum of the operands' minima 13720 */ 13721 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 13722 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13723 13724 /* Safe to set s32 bounds by casting u32 result into s32 when u32 13725 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 13726 */ 13727 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 13728 dst_reg->s32_min_value = dst_reg->u32_min_value; 13729 dst_reg->s32_max_value = dst_reg->u32_max_value; 13730 } else { 13731 dst_reg->s32_min_value = S32_MIN; 13732 dst_reg->s32_max_value = S32_MAX; 13733 } 13734 } 13735 13736 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 13737 struct bpf_reg_state *src_reg) 13738 { 13739 bool src_known = tnum_is_const(src_reg->var_off); 13740 bool dst_known = tnum_is_const(dst_reg->var_off); 13741 u64 umin_val = src_reg->umin_value; 13742 13743 if (src_known && dst_known) { 13744 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13745 return; 13746 } 13747 13748 /* We get our maximum from the var_off, and our minimum is the 13749 * maximum of the operands' minima 13750 */ 13751 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 13752 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13753 13754 /* Safe to set s64 bounds by casting u64 result into s64 when u64 13755 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 13756 */ 13757 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 13758 dst_reg->smin_value = dst_reg->umin_value; 13759 dst_reg->smax_value = dst_reg->umax_value; 13760 } else { 13761 dst_reg->smin_value = S64_MIN; 13762 dst_reg->smax_value = S64_MAX; 13763 } 13764 /* We may learn something more from the var_off */ 13765 __update_reg_bounds(dst_reg); 13766 } 13767 13768 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 13769 struct bpf_reg_state *src_reg) 13770 { 13771 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13772 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13773 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13774 13775 if (src_known && dst_known) { 13776 __mark_reg32_known(dst_reg, var32_off.value); 13777 return; 13778 } 13779 13780 /* We get both minimum and maximum from the var32_off. */ 13781 dst_reg->u32_min_value = var32_off.value; 13782 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13783 13784 /* Safe to set s32 bounds by casting u32 result into s32 when u32 13785 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 13786 */ 13787 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 13788 dst_reg->s32_min_value = dst_reg->u32_min_value; 13789 dst_reg->s32_max_value = dst_reg->u32_max_value; 13790 } else { 13791 dst_reg->s32_min_value = S32_MIN; 13792 dst_reg->s32_max_value = S32_MAX; 13793 } 13794 } 13795 13796 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 13797 struct bpf_reg_state *src_reg) 13798 { 13799 bool src_known = tnum_is_const(src_reg->var_off); 13800 bool dst_known = tnum_is_const(dst_reg->var_off); 13801 13802 if (src_known && dst_known) { 13803 /* dst_reg->var_off.value has been updated earlier */ 13804 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13805 return; 13806 } 13807 13808 /* We get both minimum and maximum from the var_off. */ 13809 dst_reg->umin_value = dst_reg->var_off.value; 13810 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13811 13812 /* Safe to set s64 bounds by casting u64 result into s64 when u64 13813 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 13814 */ 13815 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 13816 dst_reg->smin_value = dst_reg->umin_value; 13817 dst_reg->smax_value = dst_reg->umax_value; 13818 } else { 13819 dst_reg->smin_value = S64_MIN; 13820 dst_reg->smax_value = S64_MAX; 13821 } 13822 13823 __update_reg_bounds(dst_reg); 13824 } 13825 13826 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13827 u64 umin_val, u64 umax_val) 13828 { 13829 /* We lose all sign bit information (except what we can pick 13830 * up from var_off) 13831 */ 13832 dst_reg->s32_min_value = S32_MIN; 13833 dst_reg->s32_max_value = S32_MAX; 13834 /* If we might shift our top bit out, then we know nothing */ 13835 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 13836 dst_reg->u32_min_value = 0; 13837 dst_reg->u32_max_value = U32_MAX; 13838 } else { 13839 dst_reg->u32_min_value <<= umin_val; 13840 dst_reg->u32_max_value <<= umax_val; 13841 } 13842 } 13843 13844 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13845 struct bpf_reg_state *src_reg) 13846 { 13847 u32 umax_val = src_reg->u32_max_value; 13848 u32 umin_val = src_reg->u32_min_value; 13849 /* u32 alu operation will zext upper bits */ 13850 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13851 13852 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13853 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 13854 /* Not required but being careful mark reg64 bounds as unknown so 13855 * that we are forced to pick them up from tnum and zext later and 13856 * if some path skips this step we are still safe. 13857 */ 13858 __mark_reg64_unbounded(dst_reg); 13859 __update_reg32_bounds(dst_reg); 13860 } 13861 13862 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 13863 u64 umin_val, u64 umax_val) 13864 { 13865 /* Special case <<32 because it is a common compiler pattern to sign 13866 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 13867 * positive we know this shift will also be positive so we can track 13868 * bounds correctly. Otherwise we lose all sign bit information except 13869 * what we can pick up from var_off. Perhaps we can generalize this 13870 * later to shifts of any length. 13871 */ 13872 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 13873 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 13874 else 13875 dst_reg->smax_value = S64_MAX; 13876 13877 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 13878 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 13879 else 13880 dst_reg->smin_value = S64_MIN; 13881 13882 /* If we might shift our top bit out, then we know nothing */ 13883 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 13884 dst_reg->umin_value = 0; 13885 dst_reg->umax_value = U64_MAX; 13886 } else { 13887 dst_reg->umin_value <<= umin_val; 13888 dst_reg->umax_value <<= umax_val; 13889 } 13890 } 13891 13892 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 13893 struct bpf_reg_state *src_reg) 13894 { 13895 u64 umax_val = src_reg->umax_value; 13896 u64 umin_val = src_reg->umin_value; 13897 13898 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 13899 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 13900 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13901 13902 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 13903 /* We may learn something more from the var_off */ 13904 __update_reg_bounds(dst_reg); 13905 } 13906 13907 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 13908 struct bpf_reg_state *src_reg) 13909 { 13910 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13911 u32 umax_val = src_reg->u32_max_value; 13912 u32 umin_val = src_reg->u32_min_value; 13913 13914 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13915 * be negative, then either: 13916 * 1) src_reg might be zero, so the sign bit of the result is 13917 * unknown, so we lose our signed bounds 13918 * 2) it's known negative, thus the unsigned bounds capture the 13919 * signed bounds 13920 * 3) the signed bounds cross zero, so they tell us nothing 13921 * about the result 13922 * If the value in dst_reg is known nonnegative, then again the 13923 * unsigned bounds capture the signed bounds. 13924 * Thus, in all cases it suffices to blow away our signed bounds 13925 * and rely on inferring new ones from the unsigned bounds and 13926 * var_off of the result. 13927 */ 13928 dst_reg->s32_min_value = S32_MIN; 13929 dst_reg->s32_max_value = S32_MAX; 13930 13931 dst_reg->var_off = tnum_rshift(subreg, umin_val); 13932 dst_reg->u32_min_value >>= umax_val; 13933 dst_reg->u32_max_value >>= umin_val; 13934 13935 __mark_reg64_unbounded(dst_reg); 13936 __update_reg32_bounds(dst_reg); 13937 } 13938 13939 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 13940 struct bpf_reg_state *src_reg) 13941 { 13942 u64 umax_val = src_reg->umax_value; 13943 u64 umin_val = src_reg->umin_value; 13944 13945 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13946 * be negative, then either: 13947 * 1) src_reg might be zero, so the sign bit of the result is 13948 * unknown, so we lose our signed bounds 13949 * 2) it's known negative, thus the unsigned bounds capture the 13950 * signed bounds 13951 * 3) the signed bounds cross zero, so they tell us nothing 13952 * about the result 13953 * If the value in dst_reg is known nonnegative, then again the 13954 * unsigned bounds capture the signed bounds. 13955 * Thus, in all cases it suffices to blow away our signed bounds 13956 * and rely on inferring new ones from the unsigned bounds and 13957 * var_off of the result. 13958 */ 13959 dst_reg->smin_value = S64_MIN; 13960 dst_reg->smax_value = S64_MAX; 13961 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 13962 dst_reg->umin_value >>= umax_val; 13963 dst_reg->umax_value >>= umin_val; 13964 13965 /* Its not easy to operate on alu32 bounds here because it depends 13966 * on bits being shifted in. Take easy way out and mark unbounded 13967 * so we can recalculate later from tnum. 13968 */ 13969 __mark_reg32_unbounded(dst_reg); 13970 __update_reg_bounds(dst_reg); 13971 } 13972 13973 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 13974 struct bpf_reg_state *src_reg) 13975 { 13976 u64 umin_val = src_reg->u32_min_value; 13977 13978 /* Upon reaching here, src_known is true and 13979 * umax_val is equal to umin_val. 13980 */ 13981 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 13982 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 13983 13984 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 13985 13986 /* blow away the dst_reg umin_value/umax_value and rely on 13987 * dst_reg var_off to refine the result. 13988 */ 13989 dst_reg->u32_min_value = 0; 13990 dst_reg->u32_max_value = U32_MAX; 13991 13992 __mark_reg64_unbounded(dst_reg); 13993 __update_reg32_bounds(dst_reg); 13994 } 13995 13996 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 13997 struct bpf_reg_state *src_reg) 13998 { 13999 u64 umin_val = src_reg->umin_value; 14000 14001 /* Upon reaching here, src_known is true and umax_val is equal 14002 * to umin_val. 14003 */ 14004 dst_reg->smin_value >>= umin_val; 14005 dst_reg->smax_value >>= umin_val; 14006 14007 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 14008 14009 /* blow away the dst_reg umin_value/umax_value and rely on 14010 * dst_reg var_off to refine the result. 14011 */ 14012 dst_reg->umin_value = 0; 14013 dst_reg->umax_value = U64_MAX; 14014 14015 /* Its not easy to operate on alu32 bounds here because it depends 14016 * on bits being shifted in from upper 32-bits. Take easy way out 14017 * and mark unbounded so we can recalculate later from tnum. 14018 */ 14019 __mark_reg32_unbounded(dst_reg); 14020 __update_reg_bounds(dst_reg); 14021 } 14022 14023 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn, 14024 const struct bpf_reg_state *src_reg) 14025 { 14026 bool src_is_const = false; 14027 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 14028 14029 if (insn_bitness == 32) { 14030 if (tnum_subreg_is_const(src_reg->var_off) 14031 && src_reg->s32_min_value == src_reg->s32_max_value 14032 && src_reg->u32_min_value == src_reg->u32_max_value) 14033 src_is_const = true; 14034 } else { 14035 if (tnum_is_const(src_reg->var_off) 14036 && src_reg->smin_value == src_reg->smax_value 14037 && src_reg->umin_value == src_reg->umax_value) 14038 src_is_const = true; 14039 } 14040 14041 switch (BPF_OP(insn->code)) { 14042 case BPF_ADD: 14043 case BPF_SUB: 14044 case BPF_AND: 14045 case BPF_XOR: 14046 case BPF_OR: 14047 case BPF_MUL: 14048 return true; 14049 14050 /* Shift operators range is only computable if shift dimension operand 14051 * is a constant. Shifts greater than 31 or 63 are undefined. This 14052 * includes shifts by a negative number. 14053 */ 14054 case BPF_LSH: 14055 case BPF_RSH: 14056 case BPF_ARSH: 14057 return (src_is_const && src_reg->umax_value < insn_bitness); 14058 default: 14059 return false; 14060 } 14061 } 14062 14063 /* WARNING: This function does calculations on 64-bit values, but the actual 14064 * execution may occur on 32-bit values. Therefore, things like bitshifts 14065 * need extra checks in the 32-bit case. 14066 */ 14067 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 14068 struct bpf_insn *insn, 14069 struct bpf_reg_state *dst_reg, 14070 struct bpf_reg_state src_reg) 14071 { 14072 u8 opcode = BPF_OP(insn->code); 14073 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14074 int ret; 14075 14076 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) { 14077 __mark_reg_unknown(env, dst_reg); 14078 return 0; 14079 } 14080 14081 if (sanitize_needed(opcode)) { 14082 ret = sanitize_val_alu(env, insn); 14083 if (ret < 0) 14084 return sanitize_err(env, insn, ret, NULL, NULL); 14085 } 14086 14087 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 14088 * There are two classes of instructions: The first class we track both 14089 * alu32 and alu64 sign/unsigned bounds independently this provides the 14090 * greatest amount of precision when alu operations are mixed with jmp32 14091 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 14092 * and BPF_OR. This is possible because these ops have fairly easy to 14093 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 14094 * See alu32 verifier tests for examples. The second class of 14095 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 14096 * with regards to tracking sign/unsigned bounds because the bits may 14097 * cross subreg boundaries in the alu64 case. When this happens we mark 14098 * the reg unbounded in the subreg bound space and use the resulting 14099 * tnum to calculate an approximation of the sign/unsigned bounds. 14100 */ 14101 switch (opcode) { 14102 case BPF_ADD: 14103 scalar32_min_max_add(dst_reg, &src_reg); 14104 scalar_min_max_add(dst_reg, &src_reg); 14105 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 14106 break; 14107 case BPF_SUB: 14108 scalar32_min_max_sub(dst_reg, &src_reg); 14109 scalar_min_max_sub(dst_reg, &src_reg); 14110 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 14111 break; 14112 case BPF_MUL: 14113 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 14114 scalar32_min_max_mul(dst_reg, &src_reg); 14115 scalar_min_max_mul(dst_reg, &src_reg); 14116 break; 14117 case BPF_AND: 14118 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 14119 scalar32_min_max_and(dst_reg, &src_reg); 14120 scalar_min_max_and(dst_reg, &src_reg); 14121 break; 14122 case BPF_OR: 14123 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 14124 scalar32_min_max_or(dst_reg, &src_reg); 14125 scalar_min_max_or(dst_reg, &src_reg); 14126 break; 14127 case BPF_XOR: 14128 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 14129 scalar32_min_max_xor(dst_reg, &src_reg); 14130 scalar_min_max_xor(dst_reg, &src_reg); 14131 break; 14132 case BPF_LSH: 14133 if (alu32) 14134 scalar32_min_max_lsh(dst_reg, &src_reg); 14135 else 14136 scalar_min_max_lsh(dst_reg, &src_reg); 14137 break; 14138 case BPF_RSH: 14139 if (alu32) 14140 scalar32_min_max_rsh(dst_reg, &src_reg); 14141 else 14142 scalar_min_max_rsh(dst_reg, &src_reg); 14143 break; 14144 case BPF_ARSH: 14145 if (alu32) 14146 scalar32_min_max_arsh(dst_reg, &src_reg); 14147 else 14148 scalar_min_max_arsh(dst_reg, &src_reg); 14149 break; 14150 default: 14151 break; 14152 } 14153 14154 /* ALU32 ops are zero extended into 64bit register */ 14155 if (alu32) 14156 zext_32_to_64(dst_reg); 14157 reg_bounds_sync(dst_reg); 14158 return 0; 14159 } 14160 14161 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 14162 * and var_off. 14163 */ 14164 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 14165 struct bpf_insn *insn) 14166 { 14167 struct bpf_verifier_state *vstate = env->cur_state; 14168 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14169 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 14170 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 14171 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14172 u8 opcode = BPF_OP(insn->code); 14173 int err; 14174 14175 dst_reg = ®s[insn->dst_reg]; 14176 src_reg = NULL; 14177 14178 if (dst_reg->type == PTR_TO_ARENA) { 14179 struct bpf_insn_aux_data *aux = cur_aux(env); 14180 14181 if (BPF_CLASS(insn->code) == BPF_ALU64) 14182 /* 14183 * 32-bit operations zero upper bits automatically. 14184 * 64-bit operations need to be converted to 32. 14185 */ 14186 aux->needs_zext = true; 14187 14188 /* Any arithmetic operations are allowed on arena pointers */ 14189 return 0; 14190 } 14191 14192 if (dst_reg->type != SCALAR_VALUE) 14193 ptr_reg = dst_reg; 14194 14195 if (BPF_SRC(insn->code) == BPF_X) { 14196 src_reg = ®s[insn->src_reg]; 14197 if (src_reg->type != SCALAR_VALUE) { 14198 if (dst_reg->type != SCALAR_VALUE) { 14199 /* Combining two pointers by any ALU op yields 14200 * an arbitrary scalar. Disallow all math except 14201 * pointer subtraction 14202 */ 14203 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 14204 mark_reg_unknown(env, regs, insn->dst_reg); 14205 return 0; 14206 } 14207 verbose(env, "R%d pointer %s pointer prohibited\n", 14208 insn->dst_reg, 14209 bpf_alu_string[opcode >> 4]); 14210 return -EACCES; 14211 } else { 14212 /* scalar += pointer 14213 * This is legal, but we have to reverse our 14214 * src/dest handling in computing the range 14215 */ 14216 err = mark_chain_precision(env, insn->dst_reg); 14217 if (err) 14218 return err; 14219 return adjust_ptr_min_max_vals(env, insn, 14220 src_reg, dst_reg); 14221 } 14222 } else if (ptr_reg) { 14223 /* pointer += scalar */ 14224 err = mark_chain_precision(env, insn->src_reg); 14225 if (err) 14226 return err; 14227 return adjust_ptr_min_max_vals(env, insn, 14228 dst_reg, src_reg); 14229 } else if (dst_reg->precise) { 14230 /* if dst_reg is precise, src_reg should be precise as well */ 14231 err = mark_chain_precision(env, insn->src_reg); 14232 if (err) 14233 return err; 14234 } 14235 } else { 14236 /* Pretend the src is a reg with a known value, since we only 14237 * need to be able to read from this state. 14238 */ 14239 off_reg.type = SCALAR_VALUE; 14240 __mark_reg_known(&off_reg, insn->imm); 14241 src_reg = &off_reg; 14242 if (ptr_reg) /* pointer += K */ 14243 return adjust_ptr_min_max_vals(env, insn, 14244 ptr_reg, src_reg); 14245 } 14246 14247 /* Got here implies adding two SCALAR_VALUEs */ 14248 if (WARN_ON_ONCE(ptr_reg)) { 14249 print_verifier_state(env, state, true); 14250 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 14251 return -EINVAL; 14252 } 14253 if (WARN_ON(!src_reg)) { 14254 print_verifier_state(env, state, true); 14255 verbose(env, "verifier internal error: no src_reg\n"); 14256 return -EINVAL; 14257 } 14258 err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 14259 if (err) 14260 return err; 14261 /* 14262 * Compilers can generate the code 14263 * r1 = r2 14264 * r1 += 0x1 14265 * if r2 < 1000 goto ... 14266 * use r1 in memory access 14267 * So remember constant delta between r2 and r1 and update r1 after 14268 * 'if' condition. 14269 */ 14270 if (env->bpf_capable && BPF_OP(insn->code) == BPF_ADD && 14271 dst_reg->id && is_reg_const(src_reg, alu32)) { 14272 u64 val = reg_const_value(src_reg, alu32); 14273 14274 if ((dst_reg->id & BPF_ADD_CONST) || 14275 /* prevent overflow in sync_linked_regs() later */ 14276 val > (u32)S32_MAX) { 14277 /* 14278 * If the register already went through rX += val 14279 * we cannot accumulate another val into rx->off. 14280 */ 14281 dst_reg->off = 0; 14282 dst_reg->id = 0; 14283 } else { 14284 dst_reg->id |= BPF_ADD_CONST; 14285 dst_reg->off = val; 14286 } 14287 } else { 14288 /* 14289 * Make sure ID is cleared otherwise dst_reg min/max could be 14290 * incorrectly propagated into other registers by sync_linked_regs() 14291 */ 14292 dst_reg->id = 0; 14293 } 14294 return 0; 14295 } 14296 14297 /* check validity of 32-bit and 64-bit arithmetic operations */ 14298 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 14299 { 14300 struct bpf_reg_state *regs = cur_regs(env); 14301 u8 opcode = BPF_OP(insn->code); 14302 int err; 14303 14304 if (opcode == BPF_END || opcode == BPF_NEG) { 14305 if (opcode == BPF_NEG) { 14306 if (BPF_SRC(insn->code) != BPF_K || 14307 insn->src_reg != BPF_REG_0 || 14308 insn->off != 0 || insn->imm != 0) { 14309 verbose(env, "BPF_NEG uses reserved fields\n"); 14310 return -EINVAL; 14311 } 14312 } else { 14313 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 14314 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 14315 (BPF_CLASS(insn->code) == BPF_ALU64 && 14316 BPF_SRC(insn->code) != BPF_TO_LE)) { 14317 verbose(env, "BPF_END uses reserved fields\n"); 14318 return -EINVAL; 14319 } 14320 } 14321 14322 /* check src operand */ 14323 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14324 if (err) 14325 return err; 14326 14327 if (is_pointer_value(env, insn->dst_reg)) { 14328 verbose(env, "R%d pointer arithmetic prohibited\n", 14329 insn->dst_reg); 14330 return -EACCES; 14331 } 14332 14333 /* check dest operand */ 14334 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14335 if (err) 14336 return err; 14337 14338 } else if (opcode == BPF_MOV) { 14339 14340 if (BPF_SRC(insn->code) == BPF_X) { 14341 if (BPF_CLASS(insn->code) == BPF_ALU) { 14342 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) || 14343 insn->imm) { 14344 verbose(env, "BPF_MOV uses reserved fields\n"); 14345 return -EINVAL; 14346 } 14347 } else if (insn->off == BPF_ADDR_SPACE_CAST) { 14348 if (insn->imm != 1 && insn->imm != 1u << 16) { 14349 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n"); 14350 return -EINVAL; 14351 } 14352 if (!env->prog->aux->arena) { 14353 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n"); 14354 return -EINVAL; 14355 } 14356 } else { 14357 if ((insn->off != 0 && insn->off != 8 && insn->off != 16 && 14358 insn->off != 32) || insn->imm) { 14359 verbose(env, "BPF_MOV uses reserved fields\n"); 14360 return -EINVAL; 14361 } 14362 } 14363 14364 /* check src operand */ 14365 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14366 if (err) 14367 return err; 14368 } else { 14369 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 14370 verbose(env, "BPF_MOV uses reserved fields\n"); 14371 return -EINVAL; 14372 } 14373 } 14374 14375 /* check dest operand, mark as required later */ 14376 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14377 if (err) 14378 return err; 14379 14380 if (BPF_SRC(insn->code) == BPF_X) { 14381 struct bpf_reg_state *src_reg = regs + insn->src_reg; 14382 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 14383 14384 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14385 if (insn->imm) { 14386 /* off == BPF_ADDR_SPACE_CAST */ 14387 mark_reg_unknown(env, regs, insn->dst_reg); 14388 if (insn->imm == 1) { /* cast from as(1) to as(0) */ 14389 dst_reg->type = PTR_TO_ARENA; 14390 /* PTR_TO_ARENA is 32-bit */ 14391 dst_reg->subreg_def = env->insn_idx + 1; 14392 } 14393 } else if (insn->off == 0) { 14394 /* case: R1 = R2 14395 * copy register state to dest reg 14396 */ 14397 assign_scalar_id_before_mov(env, src_reg); 14398 copy_register_state(dst_reg, src_reg); 14399 dst_reg->live |= REG_LIVE_WRITTEN; 14400 dst_reg->subreg_def = DEF_NOT_SUBREG; 14401 } else { 14402 /* case: R1 = (s8, s16 s32)R2 */ 14403 if (is_pointer_value(env, insn->src_reg)) { 14404 verbose(env, 14405 "R%d sign-extension part of pointer\n", 14406 insn->src_reg); 14407 return -EACCES; 14408 } else if (src_reg->type == SCALAR_VALUE) { 14409 bool no_sext; 14410 14411 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 14412 if (no_sext) 14413 assign_scalar_id_before_mov(env, src_reg); 14414 copy_register_state(dst_reg, src_reg); 14415 if (!no_sext) 14416 dst_reg->id = 0; 14417 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 14418 dst_reg->live |= REG_LIVE_WRITTEN; 14419 dst_reg->subreg_def = DEF_NOT_SUBREG; 14420 } else { 14421 mark_reg_unknown(env, regs, insn->dst_reg); 14422 } 14423 } 14424 } else { 14425 /* R1 = (u32) R2 */ 14426 if (is_pointer_value(env, insn->src_reg)) { 14427 verbose(env, 14428 "R%d partial copy of pointer\n", 14429 insn->src_reg); 14430 return -EACCES; 14431 } else if (src_reg->type == SCALAR_VALUE) { 14432 if (insn->off == 0) { 14433 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 14434 14435 if (is_src_reg_u32) 14436 assign_scalar_id_before_mov(env, src_reg); 14437 copy_register_state(dst_reg, src_reg); 14438 /* Make sure ID is cleared if src_reg is not in u32 14439 * range otherwise dst_reg min/max could be incorrectly 14440 * propagated into src_reg by sync_linked_regs() 14441 */ 14442 if (!is_src_reg_u32) 14443 dst_reg->id = 0; 14444 dst_reg->live |= REG_LIVE_WRITTEN; 14445 dst_reg->subreg_def = env->insn_idx + 1; 14446 } else { 14447 /* case: W1 = (s8, s16)W2 */ 14448 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 14449 14450 if (no_sext) 14451 assign_scalar_id_before_mov(env, src_reg); 14452 copy_register_state(dst_reg, src_reg); 14453 if (!no_sext) 14454 dst_reg->id = 0; 14455 dst_reg->live |= REG_LIVE_WRITTEN; 14456 dst_reg->subreg_def = env->insn_idx + 1; 14457 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 14458 } 14459 } else { 14460 mark_reg_unknown(env, regs, 14461 insn->dst_reg); 14462 } 14463 zext_32_to_64(dst_reg); 14464 reg_bounds_sync(dst_reg); 14465 } 14466 } else { 14467 /* case: R = imm 14468 * remember the value we stored into this reg 14469 */ 14470 /* clear any state __mark_reg_known doesn't set */ 14471 mark_reg_unknown(env, regs, insn->dst_reg); 14472 regs[insn->dst_reg].type = SCALAR_VALUE; 14473 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14474 __mark_reg_known(regs + insn->dst_reg, 14475 insn->imm); 14476 } else { 14477 __mark_reg_known(regs + insn->dst_reg, 14478 (u32)insn->imm); 14479 } 14480 } 14481 14482 } else if (opcode > BPF_END) { 14483 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 14484 return -EINVAL; 14485 14486 } else { /* all other ALU ops: and, sub, xor, add, ... */ 14487 14488 if (BPF_SRC(insn->code) == BPF_X) { 14489 if (insn->imm != 0 || insn->off > 1 || 14490 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14491 verbose(env, "BPF_ALU uses reserved fields\n"); 14492 return -EINVAL; 14493 } 14494 /* check src1 operand */ 14495 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14496 if (err) 14497 return err; 14498 } else { 14499 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 14500 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14501 verbose(env, "BPF_ALU uses reserved fields\n"); 14502 return -EINVAL; 14503 } 14504 } 14505 14506 /* check src2 operand */ 14507 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14508 if (err) 14509 return err; 14510 14511 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 14512 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 14513 verbose(env, "div by zero\n"); 14514 return -EINVAL; 14515 } 14516 14517 if ((opcode == BPF_LSH || opcode == BPF_RSH || 14518 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 14519 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 14520 14521 if (insn->imm < 0 || insn->imm >= size) { 14522 verbose(env, "invalid shift %d\n", insn->imm); 14523 return -EINVAL; 14524 } 14525 } 14526 14527 /* check dest operand */ 14528 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14529 err = err ?: adjust_reg_min_max_vals(env, insn); 14530 if (err) 14531 return err; 14532 } 14533 14534 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 14535 } 14536 14537 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 14538 struct bpf_reg_state *dst_reg, 14539 enum bpf_reg_type type, 14540 bool range_right_open) 14541 { 14542 struct bpf_func_state *state; 14543 struct bpf_reg_state *reg; 14544 int new_range; 14545 14546 if (dst_reg->off < 0 || 14547 (dst_reg->off == 0 && range_right_open)) 14548 /* This doesn't give us any range */ 14549 return; 14550 14551 if (dst_reg->umax_value > MAX_PACKET_OFF || 14552 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 14553 /* Risk of overflow. For instance, ptr + (1<<63) may be less 14554 * than pkt_end, but that's because it's also less than pkt. 14555 */ 14556 return; 14557 14558 new_range = dst_reg->off; 14559 if (range_right_open) 14560 new_range++; 14561 14562 /* Examples for register markings: 14563 * 14564 * pkt_data in dst register: 14565 * 14566 * r2 = r3; 14567 * r2 += 8; 14568 * if (r2 > pkt_end) goto <handle exception> 14569 * <access okay> 14570 * 14571 * r2 = r3; 14572 * r2 += 8; 14573 * if (r2 < pkt_end) goto <access okay> 14574 * <handle exception> 14575 * 14576 * Where: 14577 * r2 == dst_reg, pkt_end == src_reg 14578 * r2=pkt(id=n,off=8,r=0) 14579 * r3=pkt(id=n,off=0,r=0) 14580 * 14581 * pkt_data in src register: 14582 * 14583 * r2 = r3; 14584 * r2 += 8; 14585 * if (pkt_end >= r2) goto <access okay> 14586 * <handle exception> 14587 * 14588 * r2 = r3; 14589 * r2 += 8; 14590 * if (pkt_end <= r2) goto <handle exception> 14591 * <access okay> 14592 * 14593 * Where: 14594 * pkt_end == dst_reg, r2 == src_reg 14595 * r2=pkt(id=n,off=8,r=0) 14596 * r3=pkt(id=n,off=0,r=0) 14597 * 14598 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 14599 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 14600 * and [r3, r3 + 8-1) respectively is safe to access depending on 14601 * the check. 14602 */ 14603 14604 /* If our ids match, then we must have the same max_value. And we 14605 * don't care about the other reg's fixed offset, since if it's too big 14606 * the range won't allow anything. 14607 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 14608 */ 14609 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14610 if (reg->type == type && reg->id == dst_reg->id) 14611 /* keep the maximum range already checked */ 14612 reg->range = max(reg->range, new_range); 14613 })); 14614 } 14615 14616 /* 14617 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 14618 */ 14619 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14620 u8 opcode, bool is_jmp32) 14621 { 14622 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 14623 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 14624 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value; 14625 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value; 14626 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value; 14627 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value; 14628 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value; 14629 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value; 14630 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value; 14631 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value; 14632 14633 switch (opcode) { 14634 case BPF_JEQ: 14635 /* constants, umin/umax and smin/smax checks would be 14636 * redundant in this case because they all should match 14637 */ 14638 if (tnum_is_const(t1) && tnum_is_const(t2)) 14639 return t1.value == t2.value; 14640 /* non-overlapping ranges */ 14641 if (umin1 > umax2 || umax1 < umin2) 14642 return 0; 14643 if (smin1 > smax2 || smax1 < smin2) 14644 return 0; 14645 if (!is_jmp32) { 14646 /* if 64-bit ranges are inconclusive, see if we can 14647 * utilize 32-bit subrange knowledge to eliminate 14648 * branches that can't be taken a priori 14649 */ 14650 if (reg1->u32_min_value > reg2->u32_max_value || 14651 reg1->u32_max_value < reg2->u32_min_value) 14652 return 0; 14653 if (reg1->s32_min_value > reg2->s32_max_value || 14654 reg1->s32_max_value < reg2->s32_min_value) 14655 return 0; 14656 } 14657 break; 14658 case BPF_JNE: 14659 /* constants, umin/umax and smin/smax checks would be 14660 * redundant in this case because they all should match 14661 */ 14662 if (tnum_is_const(t1) && tnum_is_const(t2)) 14663 return t1.value != t2.value; 14664 /* non-overlapping ranges */ 14665 if (umin1 > umax2 || umax1 < umin2) 14666 return 1; 14667 if (smin1 > smax2 || smax1 < smin2) 14668 return 1; 14669 if (!is_jmp32) { 14670 /* if 64-bit ranges are inconclusive, see if we can 14671 * utilize 32-bit subrange knowledge to eliminate 14672 * branches that can't be taken a priori 14673 */ 14674 if (reg1->u32_min_value > reg2->u32_max_value || 14675 reg1->u32_max_value < reg2->u32_min_value) 14676 return 1; 14677 if (reg1->s32_min_value > reg2->s32_max_value || 14678 reg1->s32_max_value < reg2->s32_min_value) 14679 return 1; 14680 } 14681 break; 14682 case BPF_JSET: 14683 if (!is_reg_const(reg2, is_jmp32)) { 14684 swap(reg1, reg2); 14685 swap(t1, t2); 14686 } 14687 if (!is_reg_const(reg2, is_jmp32)) 14688 return -1; 14689 if ((~t1.mask & t1.value) & t2.value) 14690 return 1; 14691 if (!((t1.mask | t1.value) & t2.value)) 14692 return 0; 14693 break; 14694 case BPF_JGT: 14695 if (umin1 > umax2) 14696 return 1; 14697 else if (umax1 <= umin2) 14698 return 0; 14699 break; 14700 case BPF_JSGT: 14701 if (smin1 > smax2) 14702 return 1; 14703 else if (smax1 <= smin2) 14704 return 0; 14705 break; 14706 case BPF_JLT: 14707 if (umax1 < umin2) 14708 return 1; 14709 else if (umin1 >= umax2) 14710 return 0; 14711 break; 14712 case BPF_JSLT: 14713 if (smax1 < smin2) 14714 return 1; 14715 else if (smin1 >= smax2) 14716 return 0; 14717 break; 14718 case BPF_JGE: 14719 if (umin1 >= umax2) 14720 return 1; 14721 else if (umax1 < umin2) 14722 return 0; 14723 break; 14724 case BPF_JSGE: 14725 if (smin1 >= smax2) 14726 return 1; 14727 else if (smax1 < smin2) 14728 return 0; 14729 break; 14730 case BPF_JLE: 14731 if (umax1 <= umin2) 14732 return 1; 14733 else if (umin1 > umax2) 14734 return 0; 14735 break; 14736 case BPF_JSLE: 14737 if (smax1 <= smin2) 14738 return 1; 14739 else if (smin1 > smax2) 14740 return 0; 14741 break; 14742 } 14743 14744 return -1; 14745 } 14746 14747 static int flip_opcode(u32 opcode) 14748 { 14749 /* How can we transform "a <op> b" into "b <op> a"? */ 14750 static const u8 opcode_flip[16] = { 14751 /* these stay the same */ 14752 [BPF_JEQ >> 4] = BPF_JEQ, 14753 [BPF_JNE >> 4] = BPF_JNE, 14754 [BPF_JSET >> 4] = BPF_JSET, 14755 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 14756 [BPF_JGE >> 4] = BPF_JLE, 14757 [BPF_JGT >> 4] = BPF_JLT, 14758 [BPF_JLE >> 4] = BPF_JGE, 14759 [BPF_JLT >> 4] = BPF_JGT, 14760 [BPF_JSGE >> 4] = BPF_JSLE, 14761 [BPF_JSGT >> 4] = BPF_JSLT, 14762 [BPF_JSLE >> 4] = BPF_JSGE, 14763 [BPF_JSLT >> 4] = BPF_JSGT 14764 }; 14765 return opcode_flip[opcode >> 4]; 14766 } 14767 14768 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 14769 struct bpf_reg_state *src_reg, 14770 u8 opcode) 14771 { 14772 struct bpf_reg_state *pkt; 14773 14774 if (src_reg->type == PTR_TO_PACKET_END) { 14775 pkt = dst_reg; 14776 } else if (dst_reg->type == PTR_TO_PACKET_END) { 14777 pkt = src_reg; 14778 opcode = flip_opcode(opcode); 14779 } else { 14780 return -1; 14781 } 14782 14783 if (pkt->range >= 0) 14784 return -1; 14785 14786 switch (opcode) { 14787 case BPF_JLE: 14788 /* pkt <= pkt_end */ 14789 fallthrough; 14790 case BPF_JGT: 14791 /* pkt > pkt_end */ 14792 if (pkt->range == BEYOND_PKT_END) 14793 /* pkt has at last one extra byte beyond pkt_end */ 14794 return opcode == BPF_JGT; 14795 break; 14796 case BPF_JLT: 14797 /* pkt < pkt_end */ 14798 fallthrough; 14799 case BPF_JGE: 14800 /* pkt >= pkt_end */ 14801 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 14802 return opcode == BPF_JGE; 14803 break; 14804 } 14805 return -1; 14806 } 14807 14808 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 14809 * and return: 14810 * 1 - branch will be taken and "goto target" will be executed 14811 * 0 - branch will not be taken and fall-through to next insn 14812 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 14813 * range [0,10] 14814 */ 14815 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14816 u8 opcode, bool is_jmp32) 14817 { 14818 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 14819 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 14820 14821 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 14822 u64 val; 14823 14824 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 14825 if (!is_reg_const(reg2, is_jmp32)) { 14826 opcode = flip_opcode(opcode); 14827 swap(reg1, reg2); 14828 } 14829 /* and ensure that reg2 is a constant */ 14830 if (!is_reg_const(reg2, is_jmp32)) 14831 return -1; 14832 14833 if (!reg_not_null(reg1)) 14834 return -1; 14835 14836 /* If pointer is valid tests against zero will fail so we can 14837 * use this to direct branch taken. 14838 */ 14839 val = reg_const_value(reg2, is_jmp32); 14840 if (val != 0) 14841 return -1; 14842 14843 switch (opcode) { 14844 case BPF_JEQ: 14845 return 0; 14846 case BPF_JNE: 14847 return 1; 14848 default: 14849 return -1; 14850 } 14851 } 14852 14853 /* now deal with two scalars, but not necessarily constants */ 14854 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32); 14855 } 14856 14857 /* Opcode that corresponds to a *false* branch condition. 14858 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 14859 */ 14860 static u8 rev_opcode(u8 opcode) 14861 { 14862 switch (opcode) { 14863 case BPF_JEQ: return BPF_JNE; 14864 case BPF_JNE: return BPF_JEQ; 14865 /* JSET doesn't have it's reverse opcode in BPF, so add 14866 * BPF_X flag to denote the reverse of that operation 14867 */ 14868 case BPF_JSET: return BPF_JSET | BPF_X; 14869 case BPF_JSET | BPF_X: return BPF_JSET; 14870 case BPF_JGE: return BPF_JLT; 14871 case BPF_JGT: return BPF_JLE; 14872 case BPF_JLE: return BPF_JGT; 14873 case BPF_JLT: return BPF_JGE; 14874 case BPF_JSGE: return BPF_JSLT; 14875 case BPF_JSGT: return BPF_JSLE; 14876 case BPF_JSLE: return BPF_JSGT; 14877 case BPF_JSLT: return BPF_JSGE; 14878 default: return 0; 14879 } 14880 } 14881 14882 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 14883 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14884 u8 opcode, bool is_jmp32) 14885 { 14886 struct tnum t; 14887 u64 val; 14888 14889 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */ 14890 switch (opcode) { 14891 case BPF_JGE: 14892 case BPF_JGT: 14893 case BPF_JSGE: 14894 case BPF_JSGT: 14895 opcode = flip_opcode(opcode); 14896 swap(reg1, reg2); 14897 break; 14898 default: 14899 break; 14900 } 14901 14902 switch (opcode) { 14903 case BPF_JEQ: 14904 if (is_jmp32) { 14905 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14906 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14907 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14908 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14909 reg2->u32_min_value = reg1->u32_min_value; 14910 reg2->u32_max_value = reg1->u32_max_value; 14911 reg2->s32_min_value = reg1->s32_min_value; 14912 reg2->s32_max_value = reg1->s32_max_value; 14913 14914 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 14915 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14916 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 14917 } else { 14918 reg1->umin_value = max(reg1->umin_value, reg2->umin_value); 14919 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14920 reg1->smin_value = max(reg1->smin_value, reg2->smin_value); 14921 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14922 reg2->umin_value = reg1->umin_value; 14923 reg2->umax_value = reg1->umax_value; 14924 reg2->smin_value = reg1->smin_value; 14925 reg2->smax_value = reg1->smax_value; 14926 14927 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 14928 reg2->var_off = reg1->var_off; 14929 } 14930 break; 14931 case BPF_JNE: 14932 if (!is_reg_const(reg2, is_jmp32)) 14933 swap(reg1, reg2); 14934 if (!is_reg_const(reg2, is_jmp32)) 14935 break; 14936 14937 /* try to recompute the bound of reg1 if reg2 is a const and 14938 * is exactly the edge of reg1. 14939 */ 14940 val = reg_const_value(reg2, is_jmp32); 14941 if (is_jmp32) { 14942 /* u32_min_value is not equal to 0xffffffff at this point, 14943 * because otherwise u32_max_value is 0xffffffff as well, 14944 * in such a case both reg1 and reg2 would be constants, 14945 * jump would be predicted and reg_set_min_max() won't 14946 * be called. 14947 * 14948 * Same reasoning works for all {u,s}{min,max}{32,64} cases 14949 * below. 14950 */ 14951 if (reg1->u32_min_value == (u32)val) 14952 reg1->u32_min_value++; 14953 if (reg1->u32_max_value == (u32)val) 14954 reg1->u32_max_value--; 14955 if (reg1->s32_min_value == (s32)val) 14956 reg1->s32_min_value++; 14957 if (reg1->s32_max_value == (s32)val) 14958 reg1->s32_max_value--; 14959 } else { 14960 if (reg1->umin_value == (u64)val) 14961 reg1->umin_value++; 14962 if (reg1->umax_value == (u64)val) 14963 reg1->umax_value--; 14964 if (reg1->smin_value == (s64)val) 14965 reg1->smin_value++; 14966 if (reg1->smax_value == (s64)val) 14967 reg1->smax_value--; 14968 } 14969 break; 14970 case BPF_JSET: 14971 if (!is_reg_const(reg2, is_jmp32)) 14972 swap(reg1, reg2); 14973 if (!is_reg_const(reg2, is_jmp32)) 14974 break; 14975 val = reg_const_value(reg2, is_jmp32); 14976 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 14977 * requires single bit to learn something useful. E.g., if we 14978 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 14979 * are actually set? We can learn something definite only if 14980 * it's a single-bit value to begin with. 14981 * 14982 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 14983 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 14984 * bit 1 is set, which we can readily use in adjustments. 14985 */ 14986 if (!is_power_of_2(val)) 14987 break; 14988 if (is_jmp32) { 14989 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 14990 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14991 } else { 14992 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 14993 } 14994 break; 14995 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 14996 if (!is_reg_const(reg2, is_jmp32)) 14997 swap(reg1, reg2); 14998 if (!is_reg_const(reg2, is_jmp32)) 14999 break; 15000 val = reg_const_value(reg2, is_jmp32); 15001 if (is_jmp32) { 15002 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 15003 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15004 } else { 15005 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 15006 } 15007 break; 15008 case BPF_JLE: 15009 if (is_jmp32) { 15010 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 15011 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 15012 } else { 15013 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 15014 reg2->umin_value = max(reg1->umin_value, reg2->umin_value); 15015 } 15016 break; 15017 case BPF_JLT: 15018 if (is_jmp32) { 15019 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1); 15020 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value); 15021 } else { 15022 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1); 15023 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value); 15024 } 15025 break; 15026 case BPF_JSLE: 15027 if (is_jmp32) { 15028 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 15029 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 15030 } else { 15031 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 15032 reg2->smin_value = max(reg1->smin_value, reg2->smin_value); 15033 } 15034 break; 15035 case BPF_JSLT: 15036 if (is_jmp32) { 15037 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1); 15038 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value); 15039 } else { 15040 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1); 15041 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value); 15042 } 15043 break; 15044 default: 15045 return; 15046 } 15047 } 15048 15049 /* Adjusts the register min/max values in the case that the dst_reg and 15050 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K 15051 * check, in which case we have a fake SCALAR_VALUE representing insn->imm). 15052 * Technically we can do similar adjustments for pointers to the same object, 15053 * but we don't support that right now. 15054 */ 15055 static int reg_set_min_max(struct bpf_verifier_env *env, 15056 struct bpf_reg_state *true_reg1, 15057 struct bpf_reg_state *true_reg2, 15058 struct bpf_reg_state *false_reg1, 15059 struct bpf_reg_state *false_reg2, 15060 u8 opcode, bool is_jmp32) 15061 { 15062 int err; 15063 15064 /* If either register is a pointer, we can't learn anything about its 15065 * variable offset from the compare (unless they were a pointer into 15066 * the same object, but we don't bother with that). 15067 */ 15068 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE) 15069 return 0; 15070 15071 /* fallthrough (FALSE) branch */ 15072 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32); 15073 reg_bounds_sync(false_reg1); 15074 reg_bounds_sync(false_reg2); 15075 15076 /* jump (TRUE) branch */ 15077 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32); 15078 reg_bounds_sync(true_reg1); 15079 reg_bounds_sync(true_reg2); 15080 15081 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1"); 15082 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2"); 15083 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1"); 15084 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2"); 15085 return err; 15086 } 15087 15088 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 15089 struct bpf_reg_state *reg, u32 id, 15090 bool is_null) 15091 { 15092 if (type_may_be_null(reg->type) && reg->id == id && 15093 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 15094 /* Old offset (both fixed and variable parts) should have been 15095 * known-zero, because we don't allow pointer arithmetic on 15096 * pointers that might be NULL. If we see this happening, don't 15097 * convert the register. 15098 * 15099 * But in some cases, some helpers that return local kptrs 15100 * advance offset for the returned pointer. In those cases, it 15101 * is fine to expect to see reg->off. 15102 */ 15103 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 15104 return; 15105 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 15106 WARN_ON_ONCE(reg->off)) 15107 return; 15108 15109 if (is_null) { 15110 reg->type = SCALAR_VALUE; 15111 /* We don't need id and ref_obj_id from this point 15112 * onwards anymore, thus we should better reset it, 15113 * so that state pruning has chances to take effect. 15114 */ 15115 reg->id = 0; 15116 reg->ref_obj_id = 0; 15117 15118 return; 15119 } 15120 15121 mark_ptr_not_null_reg(reg); 15122 15123 if (!reg_may_point_to_spin_lock(reg)) { 15124 /* For not-NULL ptr, reg->ref_obj_id will be reset 15125 * in release_reference(). 15126 * 15127 * reg->id is still used by spin_lock ptr. Other 15128 * than spin_lock ptr type, reg->id can be reset. 15129 */ 15130 reg->id = 0; 15131 } 15132 } 15133 } 15134 15135 /* The logic is similar to find_good_pkt_pointers(), both could eventually 15136 * be folded together at some point. 15137 */ 15138 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 15139 bool is_null) 15140 { 15141 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 15142 struct bpf_reg_state *regs = state->regs, *reg; 15143 u32 ref_obj_id = regs[regno].ref_obj_id; 15144 u32 id = regs[regno].id; 15145 15146 if (ref_obj_id && ref_obj_id == id && is_null) 15147 /* regs[regno] is in the " == NULL" branch. 15148 * No one could have freed the reference state before 15149 * doing the NULL check. 15150 */ 15151 WARN_ON_ONCE(release_reference_state(state, id)); 15152 15153 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15154 mark_ptr_or_null_reg(state, reg, id, is_null); 15155 })); 15156 } 15157 15158 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 15159 struct bpf_reg_state *dst_reg, 15160 struct bpf_reg_state *src_reg, 15161 struct bpf_verifier_state *this_branch, 15162 struct bpf_verifier_state *other_branch) 15163 { 15164 if (BPF_SRC(insn->code) != BPF_X) 15165 return false; 15166 15167 /* Pointers are always 64-bit. */ 15168 if (BPF_CLASS(insn->code) == BPF_JMP32) 15169 return false; 15170 15171 switch (BPF_OP(insn->code)) { 15172 case BPF_JGT: 15173 if ((dst_reg->type == PTR_TO_PACKET && 15174 src_reg->type == PTR_TO_PACKET_END) || 15175 (dst_reg->type == PTR_TO_PACKET_META && 15176 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15177 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 15178 find_good_pkt_pointers(this_branch, dst_reg, 15179 dst_reg->type, false); 15180 mark_pkt_end(other_branch, insn->dst_reg, true); 15181 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15182 src_reg->type == PTR_TO_PACKET) || 15183 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15184 src_reg->type == PTR_TO_PACKET_META)) { 15185 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 15186 find_good_pkt_pointers(other_branch, src_reg, 15187 src_reg->type, true); 15188 mark_pkt_end(this_branch, insn->src_reg, false); 15189 } else { 15190 return false; 15191 } 15192 break; 15193 case BPF_JLT: 15194 if ((dst_reg->type == PTR_TO_PACKET && 15195 src_reg->type == PTR_TO_PACKET_END) || 15196 (dst_reg->type == PTR_TO_PACKET_META && 15197 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15198 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 15199 find_good_pkt_pointers(other_branch, dst_reg, 15200 dst_reg->type, true); 15201 mark_pkt_end(this_branch, insn->dst_reg, false); 15202 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15203 src_reg->type == PTR_TO_PACKET) || 15204 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15205 src_reg->type == PTR_TO_PACKET_META)) { 15206 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 15207 find_good_pkt_pointers(this_branch, src_reg, 15208 src_reg->type, false); 15209 mark_pkt_end(other_branch, insn->src_reg, true); 15210 } else { 15211 return false; 15212 } 15213 break; 15214 case BPF_JGE: 15215 if ((dst_reg->type == PTR_TO_PACKET && 15216 src_reg->type == PTR_TO_PACKET_END) || 15217 (dst_reg->type == PTR_TO_PACKET_META && 15218 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15219 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 15220 find_good_pkt_pointers(this_branch, dst_reg, 15221 dst_reg->type, true); 15222 mark_pkt_end(other_branch, insn->dst_reg, false); 15223 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15224 src_reg->type == PTR_TO_PACKET) || 15225 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15226 src_reg->type == PTR_TO_PACKET_META)) { 15227 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 15228 find_good_pkt_pointers(other_branch, src_reg, 15229 src_reg->type, false); 15230 mark_pkt_end(this_branch, insn->src_reg, true); 15231 } else { 15232 return false; 15233 } 15234 break; 15235 case BPF_JLE: 15236 if ((dst_reg->type == PTR_TO_PACKET && 15237 src_reg->type == PTR_TO_PACKET_END) || 15238 (dst_reg->type == PTR_TO_PACKET_META && 15239 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15240 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 15241 find_good_pkt_pointers(other_branch, dst_reg, 15242 dst_reg->type, false); 15243 mark_pkt_end(this_branch, insn->dst_reg, true); 15244 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15245 src_reg->type == PTR_TO_PACKET) || 15246 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15247 src_reg->type == PTR_TO_PACKET_META)) { 15248 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 15249 find_good_pkt_pointers(this_branch, src_reg, 15250 src_reg->type, true); 15251 mark_pkt_end(other_branch, insn->src_reg, false); 15252 } else { 15253 return false; 15254 } 15255 break; 15256 default: 15257 return false; 15258 } 15259 15260 return true; 15261 } 15262 15263 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg, 15264 u32 id, u32 frameno, u32 spi_or_reg, bool is_reg) 15265 { 15266 struct linked_reg *e; 15267 15268 if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id) 15269 return; 15270 15271 e = linked_regs_push(reg_set); 15272 if (e) { 15273 e->frameno = frameno; 15274 e->is_reg = is_reg; 15275 e->regno = spi_or_reg; 15276 } else { 15277 reg->id = 0; 15278 } 15279 } 15280 15281 /* For all R being scalar registers or spilled scalar registers 15282 * in verifier state, save R in linked_regs if R->id == id. 15283 * If there are too many Rs sharing same id, reset id for leftover Rs. 15284 */ 15285 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id, 15286 struct linked_regs *linked_regs) 15287 { 15288 struct bpf_func_state *func; 15289 struct bpf_reg_state *reg; 15290 int i, j; 15291 15292 id = id & ~BPF_ADD_CONST; 15293 for (i = vstate->curframe; i >= 0; i--) { 15294 func = vstate->frame[i]; 15295 for (j = 0; j < BPF_REG_FP; j++) { 15296 reg = &func->regs[j]; 15297 __collect_linked_regs(linked_regs, reg, id, i, j, true); 15298 } 15299 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 15300 if (!is_spilled_reg(&func->stack[j])) 15301 continue; 15302 reg = &func->stack[j].spilled_ptr; 15303 __collect_linked_regs(linked_regs, reg, id, i, j, false); 15304 } 15305 } 15306 } 15307 15308 /* For all R in linked_regs, copy known_reg range into R 15309 * if R->id == known_reg->id. 15310 */ 15311 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg, 15312 struct linked_regs *linked_regs) 15313 { 15314 struct bpf_reg_state fake_reg; 15315 struct bpf_reg_state *reg; 15316 struct linked_reg *e; 15317 int i; 15318 15319 for (i = 0; i < linked_regs->cnt; ++i) { 15320 e = &linked_regs->entries[i]; 15321 reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno] 15322 : &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr; 15323 if (reg->type != SCALAR_VALUE || reg == known_reg) 15324 continue; 15325 if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST)) 15326 continue; 15327 if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) || 15328 reg->off == known_reg->off) { 15329 copy_register_state(reg, known_reg); 15330 } else { 15331 s32 saved_off = reg->off; 15332 15333 fake_reg.type = SCALAR_VALUE; 15334 __mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off); 15335 15336 /* reg = known_reg; reg += delta */ 15337 copy_register_state(reg, known_reg); 15338 /* 15339 * Must preserve off, id and add_const flag, 15340 * otherwise another sync_linked_regs() will be incorrect. 15341 */ 15342 reg->off = saved_off; 15343 15344 scalar32_min_max_add(reg, &fake_reg); 15345 scalar_min_max_add(reg, &fake_reg); 15346 reg->var_off = tnum_add(reg->var_off, fake_reg.var_off); 15347 } 15348 } 15349 } 15350 15351 static int check_cond_jmp_op(struct bpf_verifier_env *env, 15352 struct bpf_insn *insn, int *insn_idx) 15353 { 15354 struct bpf_verifier_state *this_branch = env->cur_state; 15355 struct bpf_verifier_state *other_branch; 15356 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 15357 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 15358 struct bpf_reg_state *eq_branch_regs; 15359 struct linked_regs linked_regs = {}; 15360 u8 opcode = BPF_OP(insn->code); 15361 bool is_jmp32; 15362 int pred = -1; 15363 int err; 15364 15365 /* Only conditional jumps are expected to reach here. */ 15366 if (opcode == BPF_JA || opcode > BPF_JCOND) { 15367 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 15368 return -EINVAL; 15369 } 15370 15371 if (opcode == BPF_JCOND) { 15372 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 15373 int idx = *insn_idx; 15374 15375 if (insn->code != (BPF_JMP | BPF_JCOND) || 15376 insn->src_reg != BPF_MAY_GOTO || 15377 insn->dst_reg || insn->imm || insn->off == 0) { 15378 verbose(env, "invalid may_goto off %d imm %d\n", 15379 insn->off, insn->imm); 15380 return -EINVAL; 15381 } 15382 prev_st = find_prev_entry(env, cur_st->parent, idx); 15383 15384 /* branch out 'fallthrough' insn as a new state to explore */ 15385 queued_st = push_stack(env, idx + 1, idx, false); 15386 if (!queued_st) 15387 return -ENOMEM; 15388 15389 queued_st->may_goto_depth++; 15390 if (prev_st) 15391 widen_imprecise_scalars(env, prev_st, queued_st); 15392 *insn_idx += insn->off; 15393 return 0; 15394 } 15395 15396 /* check src2 operand */ 15397 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15398 if (err) 15399 return err; 15400 15401 dst_reg = ®s[insn->dst_reg]; 15402 if (BPF_SRC(insn->code) == BPF_X) { 15403 if (insn->imm != 0) { 15404 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 15405 return -EINVAL; 15406 } 15407 15408 /* check src1 operand */ 15409 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15410 if (err) 15411 return err; 15412 15413 src_reg = ®s[insn->src_reg]; 15414 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 15415 is_pointer_value(env, insn->src_reg)) { 15416 verbose(env, "R%d pointer comparison prohibited\n", 15417 insn->src_reg); 15418 return -EACCES; 15419 } 15420 } else { 15421 if (insn->src_reg != BPF_REG_0) { 15422 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 15423 return -EINVAL; 15424 } 15425 src_reg = &env->fake_reg[0]; 15426 memset(src_reg, 0, sizeof(*src_reg)); 15427 src_reg->type = SCALAR_VALUE; 15428 __mark_reg_known(src_reg, insn->imm); 15429 } 15430 15431 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 15432 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32); 15433 if (pred >= 0) { 15434 /* If we get here with a dst_reg pointer type it is because 15435 * above is_branch_taken() special cased the 0 comparison. 15436 */ 15437 if (!__is_pointer_value(false, dst_reg)) 15438 err = mark_chain_precision(env, insn->dst_reg); 15439 if (BPF_SRC(insn->code) == BPF_X && !err && 15440 !__is_pointer_value(false, src_reg)) 15441 err = mark_chain_precision(env, insn->src_reg); 15442 if (err) 15443 return err; 15444 } 15445 15446 if (pred == 1) { 15447 /* Only follow the goto, ignore fall-through. If needed, push 15448 * the fall-through branch for simulation under speculative 15449 * execution. 15450 */ 15451 if (!env->bypass_spec_v1 && 15452 !sanitize_speculative_path(env, insn, *insn_idx + 1, 15453 *insn_idx)) 15454 return -EFAULT; 15455 if (env->log.level & BPF_LOG_LEVEL) 15456 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15457 *insn_idx += insn->off; 15458 return 0; 15459 } else if (pred == 0) { 15460 /* Only follow the fall-through branch, since that's where the 15461 * program will go. If needed, push the goto branch for 15462 * simulation under speculative execution. 15463 */ 15464 if (!env->bypass_spec_v1 && 15465 !sanitize_speculative_path(env, insn, 15466 *insn_idx + insn->off + 1, 15467 *insn_idx)) 15468 return -EFAULT; 15469 if (env->log.level & BPF_LOG_LEVEL) 15470 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15471 return 0; 15472 } 15473 15474 /* Push scalar registers sharing same ID to jump history, 15475 * do this before creating 'other_branch', so that both 15476 * 'this_branch' and 'other_branch' share this history 15477 * if parent state is created. 15478 */ 15479 if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id) 15480 collect_linked_regs(this_branch, src_reg->id, &linked_regs); 15481 if (dst_reg->type == SCALAR_VALUE && dst_reg->id) 15482 collect_linked_regs(this_branch, dst_reg->id, &linked_regs); 15483 if (linked_regs.cnt > 1) { 15484 err = push_jmp_history(env, this_branch, 0, linked_regs_pack(&linked_regs)); 15485 if (err) 15486 return err; 15487 } 15488 15489 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 15490 false); 15491 if (!other_branch) 15492 return -EFAULT; 15493 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 15494 15495 if (BPF_SRC(insn->code) == BPF_X) { 15496 err = reg_set_min_max(env, 15497 &other_branch_regs[insn->dst_reg], 15498 &other_branch_regs[insn->src_reg], 15499 dst_reg, src_reg, opcode, is_jmp32); 15500 } else /* BPF_SRC(insn->code) == BPF_K */ { 15501 /* reg_set_min_max() can mangle the fake_reg. Make a copy 15502 * so that these are two different memory locations. The 15503 * src_reg is not used beyond here in context of K. 15504 */ 15505 memcpy(&env->fake_reg[1], &env->fake_reg[0], 15506 sizeof(env->fake_reg[0])); 15507 err = reg_set_min_max(env, 15508 &other_branch_regs[insn->dst_reg], 15509 &env->fake_reg[0], 15510 dst_reg, &env->fake_reg[1], 15511 opcode, is_jmp32); 15512 } 15513 if (err) 15514 return err; 15515 15516 if (BPF_SRC(insn->code) == BPF_X && 15517 src_reg->type == SCALAR_VALUE && src_reg->id && 15518 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 15519 sync_linked_regs(this_branch, src_reg, &linked_regs); 15520 sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs); 15521 } 15522 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 15523 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 15524 sync_linked_regs(this_branch, dst_reg, &linked_regs); 15525 sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs); 15526 } 15527 15528 /* if one pointer register is compared to another pointer 15529 * register check if PTR_MAYBE_NULL could be lifted. 15530 * E.g. register A - maybe null 15531 * register B - not null 15532 * for JNE A, B, ... - A is not null in the false branch; 15533 * for JEQ A, B, ... - A is not null in the true branch. 15534 * 15535 * Since PTR_TO_BTF_ID points to a kernel struct that does 15536 * not need to be null checked by the BPF program, i.e., 15537 * could be null even without PTR_MAYBE_NULL marking, so 15538 * only propagate nullness when neither reg is that type. 15539 */ 15540 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 15541 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 15542 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 15543 base_type(src_reg->type) != PTR_TO_BTF_ID && 15544 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 15545 eq_branch_regs = NULL; 15546 switch (opcode) { 15547 case BPF_JEQ: 15548 eq_branch_regs = other_branch_regs; 15549 break; 15550 case BPF_JNE: 15551 eq_branch_regs = regs; 15552 break; 15553 default: 15554 /* do nothing */ 15555 break; 15556 } 15557 if (eq_branch_regs) { 15558 if (type_may_be_null(src_reg->type)) 15559 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 15560 else 15561 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 15562 } 15563 } 15564 15565 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 15566 * NOTE: these optimizations below are related with pointer comparison 15567 * which will never be JMP32. 15568 */ 15569 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 15570 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 15571 type_may_be_null(dst_reg->type)) { 15572 /* Mark all identical registers in each branch as either 15573 * safe or unknown depending R == 0 or R != 0 conditional. 15574 */ 15575 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 15576 opcode == BPF_JNE); 15577 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 15578 opcode == BPF_JEQ); 15579 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 15580 this_branch, other_branch) && 15581 is_pointer_value(env, insn->dst_reg)) { 15582 verbose(env, "R%d pointer comparison prohibited\n", 15583 insn->dst_reg); 15584 return -EACCES; 15585 } 15586 if (env->log.level & BPF_LOG_LEVEL) 15587 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15588 return 0; 15589 } 15590 15591 /* verify BPF_LD_IMM64 instruction */ 15592 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 15593 { 15594 struct bpf_insn_aux_data *aux = cur_aux(env); 15595 struct bpf_reg_state *regs = cur_regs(env); 15596 struct bpf_reg_state *dst_reg; 15597 struct bpf_map *map; 15598 int err; 15599 15600 if (BPF_SIZE(insn->code) != BPF_DW) { 15601 verbose(env, "invalid BPF_LD_IMM insn\n"); 15602 return -EINVAL; 15603 } 15604 if (insn->off != 0) { 15605 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 15606 return -EINVAL; 15607 } 15608 15609 err = check_reg_arg(env, insn->dst_reg, DST_OP); 15610 if (err) 15611 return err; 15612 15613 dst_reg = ®s[insn->dst_reg]; 15614 if (insn->src_reg == 0) { 15615 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 15616 15617 dst_reg->type = SCALAR_VALUE; 15618 __mark_reg_known(®s[insn->dst_reg], imm); 15619 return 0; 15620 } 15621 15622 /* All special src_reg cases are listed below. From this point onwards 15623 * we either succeed and assign a corresponding dst_reg->type after 15624 * zeroing the offset, or fail and reject the program. 15625 */ 15626 mark_reg_known_zero(env, regs, insn->dst_reg); 15627 15628 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 15629 dst_reg->type = aux->btf_var.reg_type; 15630 switch (base_type(dst_reg->type)) { 15631 case PTR_TO_MEM: 15632 dst_reg->mem_size = aux->btf_var.mem_size; 15633 break; 15634 case PTR_TO_BTF_ID: 15635 dst_reg->btf = aux->btf_var.btf; 15636 dst_reg->btf_id = aux->btf_var.btf_id; 15637 break; 15638 default: 15639 verbose(env, "bpf verifier is misconfigured\n"); 15640 return -EFAULT; 15641 } 15642 return 0; 15643 } 15644 15645 if (insn->src_reg == BPF_PSEUDO_FUNC) { 15646 struct bpf_prog_aux *aux = env->prog->aux; 15647 u32 subprogno = find_subprog(env, 15648 env->insn_idx + insn->imm + 1); 15649 15650 if (!aux->func_info) { 15651 verbose(env, "missing btf func_info\n"); 15652 return -EINVAL; 15653 } 15654 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 15655 verbose(env, "callback function not static\n"); 15656 return -EINVAL; 15657 } 15658 15659 dst_reg->type = PTR_TO_FUNC; 15660 dst_reg->subprogno = subprogno; 15661 return 0; 15662 } 15663 15664 map = env->used_maps[aux->map_index]; 15665 dst_reg->map_ptr = map; 15666 15667 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 15668 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 15669 if (map->map_type == BPF_MAP_TYPE_ARENA) { 15670 __mark_reg_unknown(env, dst_reg); 15671 return 0; 15672 } 15673 dst_reg->type = PTR_TO_MAP_VALUE; 15674 dst_reg->off = aux->map_off; 15675 WARN_ON_ONCE(map->max_entries != 1); 15676 /* We want reg->id to be same (0) as map_value is not distinct */ 15677 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 15678 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 15679 dst_reg->type = CONST_PTR_TO_MAP; 15680 } else { 15681 verbose(env, "bpf verifier is misconfigured\n"); 15682 return -EINVAL; 15683 } 15684 15685 return 0; 15686 } 15687 15688 static bool may_access_skb(enum bpf_prog_type type) 15689 { 15690 switch (type) { 15691 case BPF_PROG_TYPE_SOCKET_FILTER: 15692 case BPF_PROG_TYPE_SCHED_CLS: 15693 case BPF_PROG_TYPE_SCHED_ACT: 15694 return true; 15695 default: 15696 return false; 15697 } 15698 } 15699 15700 /* verify safety of LD_ABS|LD_IND instructions: 15701 * - they can only appear in the programs where ctx == skb 15702 * - since they are wrappers of function calls, they scratch R1-R5 registers, 15703 * preserve R6-R9, and store return value into R0 15704 * 15705 * Implicit input: 15706 * ctx == skb == R6 == CTX 15707 * 15708 * Explicit input: 15709 * SRC == any register 15710 * IMM == 32-bit immediate 15711 * 15712 * Output: 15713 * R0 - 8/16/32-bit skb data converted to cpu endianness 15714 */ 15715 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 15716 { 15717 struct bpf_reg_state *regs = cur_regs(env); 15718 static const int ctx_reg = BPF_REG_6; 15719 u8 mode = BPF_MODE(insn->code); 15720 int i, err; 15721 15722 if (!may_access_skb(resolve_prog_type(env->prog))) { 15723 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 15724 return -EINVAL; 15725 } 15726 15727 if (!env->ops->gen_ld_abs) { 15728 verbose(env, "bpf verifier is misconfigured\n"); 15729 return -EINVAL; 15730 } 15731 15732 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 15733 BPF_SIZE(insn->code) == BPF_DW || 15734 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 15735 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 15736 return -EINVAL; 15737 } 15738 15739 /* check whether implicit source operand (register R6) is readable */ 15740 err = check_reg_arg(env, ctx_reg, SRC_OP); 15741 if (err) 15742 return err; 15743 15744 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 15745 * gen_ld_abs() may terminate the program at runtime, leading to 15746 * reference leak. 15747 */ 15748 err = check_reference_leak(env, false); 15749 if (err) { 15750 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 15751 return err; 15752 } 15753 15754 if (env->cur_state->active_lock.ptr) { 15755 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 15756 return -EINVAL; 15757 } 15758 15759 if (env->cur_state->active_rcu_lock) { 15760 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 15761 return -EINVAL; 15762 } 15763 15764 if (env->cur_state->active_preempt_lock) { 15765 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_preempt_disable-ed region\n"); 15766 return -EINVAL; 15767 } 15768 15769 if (regs[ctx_reg].type != PTR_TO_CTX) { 15770 verbose(env, 15771 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 15772 return -EINVAL; 15773 } 15774 15775 if (mode == BPF_IND) { 15776 /* check explicit source operand */ 15777 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15778 if (err) 15779 return err; 15780 } 15781 15782 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 15783 if (err < 0) 15784 return err; 15785 15786 /* reset caller saved regs to unreadable */ 15787 for (i = 0; i < CALLER_SAVED_REGS; i++) { 15788 mark_reg_not_init(env, regs, caller_saved[i]); 15789 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 15790 } 15791 15792 /* mark destination R0 register as readable, since it contains 15793 * the value fetched from the packet. 15794 * Already marked as written above. 15795 */ 15796 mark_reg_unknown(env, regs, BPF_REG_0); 15797 /* ld_abs load up to 32-bit skb data. */ 15798 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 15799 return 0; 15800 } 15801 15802 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 15803 { 15804 const char *exit_ctx = "At program exit"; 15805 struct tnum enforce_attach_type_range = tnum_unknown; 15806 const struct bpf_prog *prog = env->prog; 15807 struct bpf_reg_state *reg; 15808 struct bpf_retval_range range = retval_range(0, 1); 15809 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 15810 int err; 15811 struct bpf_func_state *frame = env->cur_state->frame[0]; 15812 const bool is_subprog = frame->subprogno; 15813 bool return_32bit = false; 15814 15815 /* LSM and struct_ops func-ptr's return type could be "void" */ 15816 if (!is_subprog || frame->in_exception_callback_fn) { 15817 switch (prog_type) { 15818 case BPF_PROG_TYPE_LSM: 15819 if (prog->expected_attach_type == BPF_LSM_CGROUP) 15820 /* See below, can be 0 or 0-1 depending on hook. */ 15821 break; 15822 fallthrough; 15823 case BPF_PROG_TYPE_STRUCT_OPS: 15824 if (!prog->aux->attach_func_proto->type) 15825 return 0; 15826 break; 15827 default: 15828 break; 15829 } 15830 } 15831 15832 /* eBPF calling convention is such that R0 is used 15833 * to return the value from eBPF program. 15834 * Make sure that it's readable at this time 15835 * of bpf_exit, which means that program wrote 15836 * something into it earlier 15837 */ 15838 err = check_reg_arg(env, regno, SRC_OP); 15839 if (err) 15840 return err; 15841 15842 if (is_pointer_value(env, regno)) { 15843 verbose(env, "R%d leaks addr as return value\n", regno); 15844 return -EACCES; 15845 } 15846 15847 reg = cur_regs(env) + regno; 15848 15849 if (frame->in_async_callback_fn) { 15850 /* enforce return zero from async callbacks like timer */ 15851 exit_ctx = "At async callback return"; 15852 range = retval_range(0, 0); 15853 goto enforce_retval; 15854 } 15855 15856 if (is_subprog && !frame->in_exception_callback_fn) { 15857 if (reg->type != SCALAR_VALUE) { 15858 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 15859 regno, reg_type_str(env, reg->type)); 15860 return -EINVAL; 15861 } 15862 return 0; 15863 } 15864 15865 switch (prog_type) { 15866 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 15867 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 15868 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 15869 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG || 15870 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 15871 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 15872 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME || 15873 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 15874 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME || 15875 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME) 15876 range = retval_range(1, 1); 15877 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 15878 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 15879 range = retval_range(0, 3); 15880 break; 15881 case BPF_PROG_TYPE_CGROUP_SKB: 15882 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 15883 range = retval_range(0, 3); 15884 enforce_attach_type_range = tnum_range(2, 3); 15885 } 15886 break; 15887 case BPF_PROG_TYPE_CGROUP_SOCK: 15888 case BPF_PROG_TYPE_SOCK_OPS: 15889 case BPF_PROG_TYPE_CGROUP_DEVICE: 15890 case BPF_PROG_TYPE_CGROUP_SYSCTL: 15891 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 15892 break; 15893 case BPF_PROG_TYPE_RAW_TRACEPOINT: 15894 if (!env->prog->aux->attach_btf_id) 15895 return 0; 15896 range = retval_range(0, 0); 15897 break; 15898 case BPF_PROG_TYPE_TRACING: 15899 switch (env->prog->expected_attach_type) { 15900 case BPF_TRACE_FENTRY: 15901 case BPF_TRACE_FEXIT: 15902 range = retval_range(0, 0); 15903 break; 15904 case BPF_TRACE_RAW_TP: 15905 case BPF_MODIFY_RETURN: 15906 return 0; 15907 case BPF_TRACE_ITER: 15908 break; 15909 default: 15910 return -ENOTSUPP; 15911 } 15912 break; 15913 case BPF_PROG_TYPE_SK_LOOKUP: 15914 range = retval_range(SK_DROP, SK_PASS); 15915 break; 15916 15917 case BPF_PROG_TYPE_LSM: 15918 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 15919 /* no range found, any return value is allowed */ 15920 if (!get_func_retval_range(env->prog, &range)) 15921 return 0; 15922 /* no restricted range, any return value is allowed */ 15923 if (range.minval == S32_MIN && range.maxval == S32_MAX) 15924 return 0; 15925 return_32bit = true; 15926 } else if (!env->prog->aux->attach_func_proto->type) { 15927 /* Make sure programs that attach to void 15928 * hooks don't try to modify return value. 15929 */ 15930 range = retval_range(1, 1); 15931 } 15932 break; 15933 15934 case BPF_PROG_TYPE_NETFILTER: 15935 range = retval_range(NF_DROP, NF_ACCEPT); 15936 break; 15937 case BPF_PROG_TYPE_EXT: 15938 /* freplace program can return anything as its return value 15939 * depends on the to-be-replaced kernel func or bpf program. 15940 */ 15941 default: 15942 return 0; 15943 } 15944 15945 enforce_retval: 15946 if (reg->type != SCALAR_VALUE) { 15947 verbose(env, "%s the register R%d is not a known value (%s)\n", 15948 exit_ctx, regno, reg_type_str(env, reg->type)); 15949 return -EINVAL; 15950 } 15951 15952 err = mark_chain_precision(env, regno); 15953 if (err) 15954 return err; 15955 15956 if (!retval_range_within(range, reg, return_32bit)) { 15957 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 15958 if (!is_subprog && 15959 prog->expected_attach_type == BPF_LSM_CGROUP && 15960 prog_type == BPF_PROG_TYPE_LSM && 15961 !prog->aux->attach_func_proto->type) 15962 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 15963 return -EINVAL; 15964 } 15965 15966 if (!tnum_is_unknown(enforce_attach_type_range) && 15967 tnum_in(enforce_attach_type_range, reg->var_off)) 15968 env->prog->enforce_expected_attach_type = 1; 15969 return 0; 15970 } 15971 15972 /* non-recursive DFS pseudo code 15973 * 1 procedure DFS-iterative(G,v): 15974 * 2 label v as discovered 15975 * 3 let S be a stack 15976 * 4 S.push(v) 15977 * 5 while S is not empty 15978 * 6 t <- S.peek() 15979 * 7 if t is what we're looking for: 15980 * 8 return t 15981 * 9 for all edges e in G.adjacentEdges(t) do 15982 * 10 if edge e is already labelled 15983 * 11 continue with the next edge 15984 * 12 w <- G.adjacentVertex(t,e) 15985 * 13 if vertex w is not discovered and not explored 15986 * 14 label e as tree-edge 15987 * 15 label w as discovered 15988 * 16 S.push(w) 15989 * 17 continue at 5 15990 * 18 else if vertex w is discovered 15991 * 19 label e as back-edge 15992 * 20 else 15993 * 21 // vertex w is explored 15994 * 22 label e as forward- or cross-edge 15995 * 23 label t as explored 15996 * 24 S.pop() 15997 * 15998 * convention: 15999 * 0x10 - discovered 16000 * 0x11 - discovered and fall-through edge labelled 16001 * 0x12 - discovered and fall-through and branch edges labelled 16002 * 0x20 - explored 16003 */ 16004 16005 enum { 16006 DISCOVERED = 0x10, 16007 EXPLORED = 0x20, 16008 FALLTHROUGH = 1, 16009 BRANCH = 2, 16010 }; 16011 16012 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 16013 { 16014 env->insn_aux_data[idx].prune_point = true; 16015 } 16016 16017 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 16018 { 16019 return env->insn_aux_data[insn_idx].prune_point; 16020 } 16021 16022 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 16023 { 16024 env->insn_aux_data[idx].force_checkpoint = true; 16025 } 16026 16027 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 16028 { 16029 return env->insn_aux_data[insn_idx].force_checkpoint; 16030 } 16031 16032 static void mark_calls_callback(struct bpf_verifier_env *env, int idx) 16033 { 16034 env->insn_aux_data[idx].calls_callback = true; 16035 } 16036 16037 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx) 16038 { 16039 return env->insn_aux_data[insn_idx].calls_callback; 16040 } 16041 16042 enum { 16043 DONE_EXPLORING = 0, 16044 KEEP_EXPLORING = 1, 16045 }; 16046 16047 /* t, w, e - match pseudo-code above: 16048 * t - index of current instruction 16049 * w - next instruction 16050 * e - edge 16051 */ 16052 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 16053 { 16054 int *insn_stack = env->cfg.insn_stack; 16055 int *insn_state = env->cfg.insn_state; 16056 16057 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 16058 return DONE_EXPLORING; 16059 16060 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 16061 return DONE_EXPLORING; 16062 16063 if (w < 0 || w >= env->prog->len) { 16064 verbose_linfo(env, t, "%d: ", t); 16065 verbose(env, "jump out of range from insn %d to %d\n", t, w); 16066 return -EINVAL; 16067 } 16068 16069 if (e == BRANCH) { 16070 /* mark branch target for state pruning */ 16071 mark_prune_point(env, w); 16072 mark_jmp_point(env, w); 16073 } 16074 16075 if (insn_state[w] == 0) { 16076 /* tree-edge */ 16077 insn_state[t] = DISCOVERED | e; 16078 insn_state[w] = DISCOVERED; 16079 if (env->cfg.cur_stack >= env->prog->len) 16080 return -E2BIG; 16081 insn_stack[env->cfg.cur_stack++] = w; 16082 return KEEP_EXPLORING; 16083 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 16084 if (env->bpf_capable) 16085 return DONE_EXPLORING; 16086 verbose_linfo(env, t, "%d: ", t); 16087 verbose_linfo(env, w, "%d: ", w); 16088 verbose(env, "back-edge from insn %d to %d\n", t, w); 16089 return -EINVAL; 16090 } else if (insn_state[w] == EXPLORED) { 16091 /* forward- or cross-edge */ 16092 insn_state[t] = DISCOVERED | e; 16093 } else { 16094 verbose(env, "insn state internal bug\n"); 16095 return -EFAULT; 16096 } 16097 return DONE_EXPLORING; 16098 } 16099 16100 static int visit_func_call_insn(int t, struct bpf_insn *insns, 16101 struct bpf_verifier_env *env, 16102 bool visit_callee) 16103 { 16104 int ret, insn_sz; 16105 16106 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 16107 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 16108 if (ret) 16109 return ret; 16110 16111 mark_prune_point(env, t + insn_sz); 16112 /* when we exit from subprog, we need to record non-linear history */ 16113 mark_jmp_point(env, t + insn_sz); 16114 16115 if (visit_callee) { 16116 mark_prune_point(env, t); 16117 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env); 16118 } 16119 return ret; 16120 } 16121 16122 /* Bitmask with 1s for all caller saved registers */ 16123 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 16124 16125 /* Return a bitmask specifying which caller saved registers are 16126 * clobbered by a call to a helper *as if* this helper follows 16127 * bpf_fastcall contract: 16128 * - includes R0 if function is non-void; 16129 * - includes R1-R5 if corresponding parameter has is described 16130 * in the function prototype. 16131 */ 16132 static u32 helper_fastcall_clobber_mask(const struct bpf_func_proto *fn) 16133 { 16134 u32 mask; 16135 int i; 16136 16137 mask = 0; 16138 if (fn->ret_type != RET_VOID) 16139 mask |= BIT(BPF_REG_0); 16140 for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) 16141 if (fn->arg_type[i] != ARG_DONTCARE) 16142 mask |= BIT(BPF_REG_1 + i); 16143 return mask; 16144 } 16145 16146 /* True if do_misc_fixups() replaces calls to helper number 'imm', 16147 * replacement patch is presumed to follow bpf_fastcall contract 16148 * (see mark_fastcall_pattern_for_call() below). 16149 */ 16150 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm) 16151 { 16152 switch (imm) { 16153 #ifdef CONFIG_X86_64 16154 case BPF_FUNC_get_smp_processor_id: 16155 return env->prog->jit_requested && bpf_jit_supports_percpu_insn(); 16156 #endif 16157 default: 16158 return false; 16159 } 16160 } 16161 16162 /* Same as helper_fastcall_clobber_mask() but for kfuncs, see comment above */ 16163 static u32 kfunc_fastcall_clobber_mask(struct bpf_kfunc_call_arg_meta *meta) 16164 { 16165 u32 vlen, i, mask; 16166 16167 vlen = btf_type_vlen(meta->func_proto); 16168 mask = 0; 16169 if (!btf_type_is_void(btf_type_by_id(meta->btf, meta->func_proto->type))) 16170 mask |= BIT(BPF_REG_0); 16171 for (i = 0; i < vlen; ++i) 16172 mask |= BIT(BPF_REG_1 + i); 16173 return mask; 16174 } 16175 16176 /* Same as verifier_inlines_helper_call() but for kfuncs, see comment above */ 16177 static bool is_fastcall_kfunc_call(struct bpf_kfunc_call_arg_meta *meta) 16178 { 16179 if (meta->btf == btf_vmlinux) 16180 return meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 16181 meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]; 16182 return false; 16183 } 16184 16185 /* LLVM define a bpf_fastcall function attribute. 16186 * This attribute means that function scratches only some of 16187 * the caller saved registers defined by ABI. 16188 * For BPF the set of such registers could be defined as follows: 16189 * - R0 is scratched only if function is non-void; 16190 * - R1-R5 are scratched only if corresponding parameter type is defined 16191 * in the function prototype. 16192 * 16193 * The contract between kernel and clang allows to simultaneously use 16194 * such functions and maintain backwards compatibility with old 16195 * kernels that don't understand bpf_fastcall calls: 16196 * 16197 * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5 16198 * registers are not scratched by the call; 16199 * 16200 * - as a post-processing step, clang visits each bpf_fastcall call and adds 16201 * spill/fill for every live r0-r5; 16202 * 16203 * - stack offsets used for the spill/fill are allocated as lowest 16204 * stack offsets in whole function and are not used for any other 16205 * purposes; 16206 * 16207 * - when kernel loads a program, it looks for such patterns 16208 * (bpf_fastcall function surrounded by spills/fills) and checks if 16209 * spill/fill stack offsets are used exclusively in fastcall patterns; 16210 * 16211 * - if so, and if verifier or current JIT inlines the call to the 16212 * bpf_fastcall function (e.g. a helper call), kernel removes unnecessary 16213 * spill/fill pairs; 16214 * 16215 * - when old kernel loads a program, presence of spill/fill pairs 16216 * keeps BPF program valid, albeit slightly less efficient. 16217 * 16218 * For example: 16219 * 16220 * r1 = 1; 16221 * r2 = 2; 16222 * *(u64 *)(r10 - 8) = r1; r1 = 1; 16223 * *(u64 *)(r10 - 16) = r2; r2 = 2; 16224 * call %[to_be_inlined] --> call %[to_be_inlined] 16225 * r2 = *(u64 *)(r10 - 16); r0 = r1; 16226 * r1 = *(u64 *)(r10 - 8); r0 += r2; 16227 * r0 = r1; exit; 16228 * r0 += r2; 16229 * exit; 16230 * 16231 * The purpose of mark_fastcall_pattern_for_call is to: 16232 * - look for such patterns; 16233 * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern; 16234 * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction; 16235 * - update env->subprog_info[*]->fastcall_stack_off to find an offset 16236 * at which bpf_fastcall spill/fill stack slots start; 16237 * - update env->subprog_info[*]->keep_fastcall_stack. 16238 * 16239 * The .fastcall_pattern and .fastcall_stack_off are used by 16240 * check_fastcall_stack_contract() to check if every stack access to 16241 * fastcall spill/fill stack slot originates from spill/fill 16242 * instructions, members of fastcall patterns. 16243 * 16244 * If such condition holds true for a subprogram, fastcall patterns could 16245 * be rewritten by remove_fastcall_spills_fills(). 16246 * Otherwise bpf_fastcall patterns are not changed in the subprogram 16247 * (code, presumably, generated by an older clang version). 16248 * 16249 * For example, it is *not* safe to remove spill/fill below: 16250 * 16251 * r1 = 1; 16252 * *(u64 *)(r10 - 8) = r1; r1 = 1; 16253 * call %[to_be_inlined] --> call %[to_be_inlined] 16254 * r1 = *(u64 *)(r10 - 8); r0 = *(u64 *)(r10 - 8); <---- wrong !!! 16255 * r0 = *(u64 *)(r10 - 8); r0 += r1; 16256 * r0 += r1; exit; 16257 * exit; 16258 */ 16259 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env, 16260 struct bpf_subprog_info *subprog, 16261 int insn_idx, s16 lowest_off) 16262 { 16263 struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx; 16264 struct bpf_insn *call = &env->prog->insnsi[insn_idx]; 16265 const struct bpf_func_proto *fn; 16266 u32 clobbered_regs_mask = ALL_CALLER_SAVED_REGS; 16267 u32 expected_regs_mask; 16268 bool can_be_inlined = false; 16269 s16 off; 16270 int i; 16271 16272 if (bpf_helper_call(call)) { 16273 if (get_helper_proto(env, call->imm, &fn) < 0) 16274 /* error would be reported later */ 16275 return; 16276 clobbered_regs_mask = helper_fastcall_clobber_mask(fn); 16277 can_be_inlined = fn->allow_fastcall && 16278 (verifier_inlines_helper_call(env, call->imm) || 16279 bpf_jit_inlines_helper_call(call->imm)); 16280 } 16281 16282 if (bpf_pseudo_kfunc_call(call)) { 16283 struct bpf_kfunc_call_arg_meta meta; 16284 int err; 16285 16286 err = fetch_kfunc_meta(env, call, &meta, NULL); 16287 if (err < 0) 16288 /* error would be reported later */ 16289 return; 16290 16291 clobbered_regs_mask = kfunc_fastcall_clobber_mask(&meta); 16292 can_be_inlined = is_fastcall_kfunc_call(&meta); 16293 } 16294 16295 if (clobbered_regs_mask == ALL_CALLER_SAVED_REGS) 16296 return; 16297 16298 /* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */ 16299 expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS; 16300 16301 /* match pairs of form: 16302 * 16303 * *(u64 *)(r10 - Y) = rX (where Y % 8 == 0) 16304 * ... 16305 * call %[to_be_inlined] 16306 * ... 16307 * rX = *(u64 *)(r10 - Y) 16308 */ 16309 for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) { 16310 if (insn_idx - i < 0 || insn_idx + i >= env->prog->len) 16311 break; 16312 stx = &insns[insn_idx - i]; 16313 ldx = &insns[insn_idx + i]; 16314 /* must be a stack spill/fill pair */ 16315 if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) || 16316 ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) || 16317 stx->dst_reg != BPF_REG_10 || 16318 ldx->src_reg != BPF_REG_10) 16319 break; 16320 /* must be a spill/fill for the same reg */ 16321 if (stx->src_reg != ldx->dst_reg) 16322 break; 16323 /* must be one of the previously unseen registers */ 16324 if ((BIT(stx->src_reg) & expected_regs_mask) == 0) 16325 break; 16326 /* must be a spill/fill for the same expected offset, 16327 * no need to check offset alignment, BPF_DW stack access 16328 * is always 8-byte aligned. 16329 */ 16330 if (stx->off != off || ldx->off != off) 16331 break; 16332 expected_regs_mask &= ~BIT(stx->src_reg); 16333 env->insn_aux_data[insn_idx - i].fastcall_pattern = 1; 16334 env->insn_aux_data[insn_idx + i].fastcall_pattern = 1; 16335 } 16336 if (i == 1) 16337 return; 16338 16339 /* Conditionally set 'fastcall_spills_num' to allow forward 16340 * compatibility when more helper functions are marked as 16341 * bpf_fastcall at compile time than current kernel supports, e.g: 16342 * 16343 * 1: *(u64 *)(r10 - 8) = r1 16344 * 2: call A ;; assume A is bpf_fastcall for current kernel 16345 * 3: r1 = *(u64 *)(r10 - 8) 16346 * 4: *(u64 *)(r10 - 8) = r1 16347 * 5: call B ;; assume B is not bpf_fastcall for current kernel 16348 * 6: r1 = *(u64 *)(r10 - 8) 16349 * 16350 * There is no need to block bpf_fastcall rewrite for such program. 16351 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy, 16352 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills() 16353 * does not remove spill/fill pair {4,6}. 16354 */ 16355 if (can_be_inlined) 16356 env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1; 16357 else 16358 subprog->keep_fastcall_stack = 1; 16359 subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off); 16360 } 16361 16362 static int mark_fastcall_patterns(struct bpf_verifier_env *env) 16363 { 16364 struct bpf_subprog_info *subprog = env->subprog_info; 16365 struct bpf_insn *insn; 16366 s16 lowest_off; 16367 int s, i; 16368 16369 for (s = 0; s < env->subprog_cnt; ++s, ++subprog) { 16370 /* find lowest stack spill offset used in this subprog */ 16371 lowest_off = 0; 16372 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 16373 insn = env->prog->insnsi + i; 16374 if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) || 16375 insn->dst_reg != BPF_REG_10) 16376 continue; 16377 lowest_off = min(lowest_off, insn->off); 16378 } 16379 /* use this offset to find fastcall patterns */ 16380 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 16381 insn = env->prog->insnsi + i; 16382 if (insn->code != (BPF_JMP | BPF_CALL)) 16383 continue; 16384 mark_fastcall_pattern_for_call(env, subprog, i, lowest_off); 16385 } 16386 } 16387 return 0; 16388 } 16389 16390 /* Visits the instruction at index t and returns one of the following: 16391 * < 0 - an error occurred 16392 * DONE_EXPLORING - the instruction was fully explored 16393 * KEEP_EXPLORING - there is still work to be done before it is fully explored 16394 */ 16395 static int visit_insn(int t, struct bpf_verifier_env *env) 16396 { 16397 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 16398 int ret, off, insn_sz; 16399 16400 if (bpf_pseudo_func(insn)) 16401 return visit_func_call_insn(t, insns, env, true); 16402 16403 /* All non-branch instructions have a single fall-through edge. */ 16404 if (BPF_CLASS(insn->code) != BPF_JMP && 16405 BPF_CLASS(insn->code) != BPF_JMP32) { 16406 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 16407 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 16408 } 16409 16410 switch (BPF_OP(insn->code)) { 16411 case BPF_EXIT: 16412 return DONE_EXPLORING; 16413 16414 case BPF_CALL: 16415 if (is_async_callback_calling_insn(insn)) 16416 /* Mark this call insn as a prune point to trigger 16417 * is_state_visited() check before call itself is 16418 * processed by __check_func_call(). Otherwise new 16419 * async state will be pushed for further exploration. 16420 */ 16421 mark_prune_point(env, t); 16422 /* For functions that invoke callbacks it is not known how many times 16423 * callback would be called. Verifier models callback calling functions 16424 * by repeatedly visiting callback bodies and returning to origin call 16425 * instruction. 16426 * In order to stop such iteration verifier needs to identify when a 16427 * state identical some state from a previous iteration is reached. 16428 * Check below forces creation of checkpoint before callback calling 16429 * instruction to allow search for such identical states. 16430 */ 16431 if (is_sync_callback_calling_insn(insn)) { 16432 mark_calls_callback(env, t); 16433 mark_force_checkpoint(env, t); 16434 mark_prune_point(env, t); 16435 mark_jmp_point(env, t); 16436 } 16437 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 16438 struct bpf_kfunc_call_arg_meta meta; 16439 16440 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 16441 if (ret == 0 && is_iter_next_kfunc(&meta)) { 16442 mark_prune_point(env, t); 16443 /* Checking and saving state checkpoints at iter_next() call 16444 * is crucial for fast convergence of open-coded iterator loop 16445 * logic, so we need to force it. If we don't do that, 16446 * is_state_visited() might skip saving a checkpoint, causing 16447 * unnecessarily long sequence of not checkpointed 16448 * instructions and jumps, leading to exhaustion of jump 16449 * history buffer, and potentially other undesired outcomes. 16450 * It is expected that with correct open-coded iterators 16451 * convergence will happen quickly, so we don't run a risk of 16452 * exhausting memory. 16453 */ 16454 mark_force_checkpoint(env, t); 16455 } 16456 } 16457 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 16458 16459 case BPF_JA: 16460 if (BPF_SRC(insn->code) != BPF_K) 16461 return -EINVAL; 16462 16463 if (BPF_CLASS(insn->code) == BPF_JMP) 16464 off = insn->off; 16465 else 16466 off = insn->imm; 16467 16468 /* unconditional jump with single edge */ 16469 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 16470 if (ret) 16471 return ret; 16472 16473 mark_prune_point(env, t + off + 1); 16474 mark_jmp_point(env, t + off + 1); 16475 16476 return ret; 16477 16478 default: 16479 /* conditional jump with two edges */ 16480 mark_prune_point(env, t); 16481 if (is_may_goto_insn(insn)) 16482 mark_force_checkpoint(env, t); 16483 16484 ret = push_insn(t, t + 1, FALLTHROUGH, env); 16485 if (ret) 16486 return ret; 16487 16488 return push_insn(t, t + insn->off + 1, BRANCH, env); 16489 } 16490 } 16491 16492 /* non-recursive depth-first-search to detect loops in BPF program 16493 * loop == back-edge in directed graph 16494 */ 16495 static int check_cfg(struct bpf_verifier_env *env) 16496 { 16497 int insn_cnt = env->prog->len; 16498 int *insn_stack, *insn_state; 16499 int ex_insn_beg, i, ret = 0; 16500 bool ex_done = false; 16501 16502 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 16503 if (!insn_state) 16504 return -ENOMEM; 16505 16506 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 16507 if (!insn_stack) { 16508 kvfree(insn_state); 16509 return -ENOMEM; 16510 } 16511 16512 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 16513 insn_stack[0] = 0; /* 0 is the first instruction */ 16514 env->cfg.cur_stack = 1; 16515 16516 walk_cfg: 16517 while (env->cfg.cur_stack > 0) { 16518 int t = insn_stack[env->cfg.cur_stack - 1]; 16519 16520 ret = visit_insn(t, env); 16521 switch (ret) { 16522 case DONE_EXPLORING: 16523 insn_state[t] = EXPLORED; 16524 env->cfg.cur_stack--; 16525 break; 16526 case KEEP_EXPLORING: 16527 break; 16528 default: 16529 if (ret > 0) { 16530 verbose(env, "visit_insn internal bug\n"); 16531 ret = -EFAULT; 16532 } 16533 goto err_free; 16534 } 16535 } 16536 16537 if (env->cfg.cur_stack < 0) { 16538 verbose(env, "pop stack internal bug\n"); 16539 ret = -EFAULT; 16540 goto err_free; 16541 } 16542 16543 if (env->exception_callback_subprog && !ex_done) { 16544 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start; 16545 16546 insn_state[ex_insn_beg] = DISCOVERED; 16547 insn_stack[0] = ex_insn_beg; 16548 env->cfg.cur_stack = 1; 16549 ex_done = true; 16550 goto walk_cfg; 16551 } 16552 16553 for (i = 0; i < insn_cnt; i++) { 16554 struct bpf_insn *insn = &env->prog->insnsi[i]; 16555 16556 if (insn_state[i] != EXPLORED) { 16557 verbose(env, "unreachable insn %d\n", i); 16558 ret = -EINVAL; 16559 goto err_free; 16560 } 16561 if (bpf_is_ldimm64(insn)) { 16562 if (insn_state[i + 1] != 0) { 16563 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 16564 ret = -EINVAL; 16565 goto err_free; 16566 } 16567 i++; /* skip second half of ldimm64 */ 16568 } 16569 } 16570 ret = 0; /* cfg looks good */ 16571 16572 err_free: 16573 kvfree(insn_state); 16574 kvfree(insn_stack); 16575 env->cfg.insn_state = env->cfg.insn_stack = NULL; 16576 return ret; 16577 } 16578 16579 static int check_abnormal_return(struct bpf_verifier_env *env) 16580 { 16581 int i; 16582 16583 for (i = 1; i < env->subprog_cnt; i++) { 16584 if (env->subprog_info[i].has_ld_abs) { 16585 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 16586 return -EINVAL; 16587 } 16588 if (env->subprog_info[i].has_tail_call) { 16589 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 16590 return -EINVAL; 16591 } 16592 } 16593 return 0; 16594 } 16595 16596 /* The minimum supported BTF func info size */ 16597 #define MIN_BPF_FUNCINFO_SIZE 8 16598 #define MAX_FUNCINFO_REC_SIZE 252 16599 16600 static int check_btf_func_early(struct bpf_verifier_env *env, 16601 const union bpf_attr *attr, 16602 bpfptr_t uattr) 16603 { 16604 u32 krec_size = sizeof(struct bpf_func_info); 16605 const struct btf_type *type, *func_proto; 16606 u32 i, nfuncs, urec_size, min_size; 16607 struct bpf_func_info *krecord; 16608 struct bpf_prog *prog; 16609 const struct btf *btf; 16610 u32 prev_offset = 0; 16611 bpfptr_t urecord; 16612 int ret = -ENOMEM; 16613 16614 nfuncs = attr->func_info_cnt; 16615 if (!nfuncs) { 16616 if (check_abnormal_return(env)) 16617 return -EINVAL; 16618 return 0; 16619 } 16620 16621 urec_size = attr->func_info_rec_size; 16622 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 16623 urec_size > MAX_FUNCINFO_REC_SIZE || 16624 urec_size % sizeof(u32)) { 16625 verbose(env, "invalid func info rec size %u\n", urec_size); 16626 return -EINVAL; 16627 } 16628 16629 prog = env->prog; 16630 btf = prog->aux->btf; 16631 16632 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 16633 min_size = min_t(u32, krec_size, urec_size); 16634 16635 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 16636 if (!krecord) 16637 return -ENOMEM; 16638 16639 for (i = 0; i < nfuncs; i++) { 16640 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 16641 if (ret) { 16642 if (ret == -E2BIG) { 16643 verbose(env, "nonzero tailing record in func info"); 16644 /* set the size kernel expects so loader can zero 16645 * out the rest of the record. 16646 */ 16647 if (copy_to_bpfptr_offset(uattr, 16648 offsetof(union bpf_attr, func_info_rec_size), 16649 &min_size, sizeof(min_size))) 16650 ret = -EFAULT; 16651 } 16652 goto err_free; 16653 } 16654 16655 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 16656 ret = -EFAULT; 16657 goto err_free; 16658 } 16659 16660 /* check insn_off */ 16661 ret = -EINVAL; 16662 if (i == 0) { 16663 if (krecord[i].insn_off) { 16664 verbose(env, 16665 "nonzero insn_off %u for the first func info record", 16666 krecord[i].insn_off); 16667 goto err_free; 16668 } 16669 } else if (krecord[i].insn_off <= prev_offset) { 16670 verbose(env, 16671 "same or smaller insn offset (%u) than previous func info record (%u)", 16672 krecord[i].insn_off, prev_offset); 16673 goto err_free; 16674 } 16675 16676 /* check type_id */ 16677 type = btf_type_by_id(btf, krecord[i].type_id); 16678 if (!type || !btf_type_is_func(type)) { 16679 verbose(env, "invalid type id %d in func info", 16680 krecord[i].type_id); 16681 goto err_free; 16682 } 16683 16684 func_proto = btf_type_by_id(btf, type->type); 16685 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 16686 /* btf_func_check() already verified it during BTF load */ 16687 goto err_free; 16688 16689 prev_offset = krecord[i].insn_off; 16690 bpfptr_add(&urecord, urec_size); 16691 } 16692 16693 prog->aux->func_info = krecord; 16694 prog->aux->func_info_cnt = nfuncs; 16695 return 0; 16696 16697 err_free: 16698 kvfree(krecord); 16699 return ret; 16700 } 16701 16702 static int check_btf_func(struct bpf_verifier_env *env, 16703 const union bpf_attr *attr, 16704 bpfptr_t uattr) 16705 { 16706 const struct btf_type *type, *func_proto, *ret_type; 16707 u32 i, nfuncs, urec_size; 16708 struct bpf_func_info *krecord; 16709 struct bpf_func_info_aux *info_aux = NULL; 16710 struct bpf_prog *prog; 16711 const struct btf *btf; 16712 bpfptr_t urecord; 16713 bool scalar_return; 16714 int ret = -ENOMEM; 16715 16716 nfuncs = attr->func_info_cnt; 16717 if (!nfuncs) { 16718 if (check_abnormal_return(env)) 16719 return -EINVAL; 16720 return 0; 16721 } 16722 if (nfuncs != env->subprog_cnt) { 16723 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 16724 return -EINVAL; 16725 } 16726 16727 urec_size = attr->func_info_rec_size; 16728 16729 prog = env->prog; 16730 btf = prog->aux->btf; 16731 16732 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 16733 16734 krecord = prog->aux->func_info; 16735 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 16736 if (!info_aux) 16737 return -ENOMEM; 16738 16739 for (i = 0; i < nfuncs; i++) { 16740 /* check insn_off */ 16741 ret = -EINVAL; 16742 16743 if (env->subprog_info[i].start != krecord[i].insn_off) { 16744 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 16745 goto err_free; 16746 } 16747 16748 /* Already checked type_id */ 16749 type = btf_type_by_id(btf, krecord[i].type_id); 16750 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 16751 /* Already checked func_proto */ 16752 func_proto = btf_type_by_id(btf, type->type); 16753 16754 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 16755 scalar_return = 16756 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 16757 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 16758 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 16759 goto err_free; 16760 } 16761 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 16762 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 16763 goto err_free; 16764 } 16765 16766 bpfptr_add(&urecord, urec_size); 16767 } 16768 16769 prog->aux->func_info_aux = info_aux; 16770 return 0; 16771 16772 err_free: 16773 kfree(info_aux); 16774 return ret; 16775 } 16776 16777 static void adjust_btf_func(struct bpf_verifier_env *env) 16778 { 16779 struct bpf_prog_aux *aux = env->prog->aux; 16780 int i; 16781 16782 if (!aux->func_info) 16783 return; 16784 16785 /* func_info is not available for hidden subprogs */ 16786 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 16787 aux->func_info[i].insn_off = env->subprog_info[i].start; 16788 } 16789 16790 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 16791 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 16792 16793 static int check_btf_line(struct bpf_verifier_env *env, 16794 const union bpf_attr *attr, 16795 bpfptr_t uattr) 16796 { 16797 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 16798 struct bpf_subprog_info *sub; 16799 struct bpf_line_info *linfo; 16800 struct bpf_prog *prog; 16801 const struct btf *btf; 16802 bpfptr_t ulinfo; 16803 int err; 16804 16805 nr_linfo = attr->line_info_cnt; 16806 if (!nr_linfo) 16807 return 0; 16808 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 16809 return -EINVAL; 16810 16811 rec_size = attr->line_info_rec_size; 16812 if (rec_size < MIN_BPF_LINEINFO_SIZE || 16813 rec_size > MAX_LINEINFO_REC_SIZE || 16814 rec_size & (sizeof(u32) - 1)) 16815 return -EINVAL; 16816 16817 /* Need to zero it in case the userspace may 16818 * pass in a smaller bpf_line_info object. 16819 */ 16820 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 16821 GFP_KERNEL | __GFP_NOWARN); 16822 if (!linfo) 16823 return -ENOMEM; 16824 16825 prog = env->prog; 16826 btf = prog->aux->btf; 16827 16828 s = 0; 16829 sub = env->subprog_info; 16830 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 16831 expected_size = sizeof(struct bpf_line_info); 16832 ncopy = min_t(u32, expected_size, rec_size); 16833 for (i = 0; i < nr_linfo; i++) { 16834 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 16835 if (err) { 16836 if (err == -E2BIG) { 16837 verbose(env, "nonzero tailing record in line_info"); 16838 if (copy_to_bpfptr_offset(uattr, 16839 offsetof(union bpf_attr, line_info_rec_size), 16840 &expected_size, sizeof(expected_size))) 16841 err = -EFAULT; 16842 } 16843 goto err_free; 16844 } 16845 16846 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 16847 err = -EFAULT; 16848 goto err_free; 16849 } 16850 16851 /* 16852 * Check insn_off to ensure 16853 * 1) strictly increasing AND 16854 * 2) bounded by prog->len 16855 * 16856 * The linfo[0].insn_off == 0 check logically falls into 16857 * the later "missing bpf_line_info for func..." case 16858 * because the first linfo[0].insn_off must be the 16859 * first sub also and the first sub must have 16860 * subprog_info[0].start == 0. 16861 */ 16862 if ((i && linfo[i].insn_off <= prev_offset) || 16863 linfo[i].insn_off >= prog->len) { 16864 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 16865 i, linfo[i].insn_off, prev_offset, 16866 prog->len); 16867 err = -EINVAL; 16868 goto err_free; 16869 } 16870 16871 if (!prog->insnsi[linfo[i].insn_off].code) { 16872 verbose(env, 16873 "Invalid insn code at line_info[%u].insn_off\n", 16874 i); 16875 err = -EINVAL; 16876 goto err_free; 16877 } 16878 16879 if (!btf_name_by_offset(btf, linfo[i].line_off) || 16880 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 16881 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 16882 err = -EINVAL; 16883 goto err_free; 16884 } 16885 16886 if (s != env->subprog_cnt) { 16887 if (linfo[i].insn_off == sub[s].start) { 16888 sub[s].linfo_idx = i; 16889 s++; 16890 } else if (sub[s].start < linfo[i].insn_off) { 16891 verbose(env, "missing bpf_line_info for func#%u\n", s); 16892 err = -EINVAL; 16893 goto err_free; 16894 } 16895 } 16896 16897 prev_offset = linfo[i].insn_off; 16898 bpfptr_add(&ulinfo, rec_size); 16899 } 16900 16901 if (s != env->subprog_cnt) { 16902 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 16903 env->subprog_cnt - s, s); 16904 err = -EINVAL; 16905 goto err_free; 16906 } 16907 16908 prog->aux->linfo = linfo; 16909 prog->aux->nr_linfo = nr_linfo; 16910 16911 return 0; 16912 16913 err_free: 16914 kvfree(linfo); 16915 return err; 16916 } 16917 16918 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 16919 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 16920 16921 static int check_core_relo(struct bpf_verifier_env *env, 16922 const union bpf_attr *attr, 16923 bpfptr_t uattr) 16924 { 16925 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 16926 struct bpf_core_relo core_relo = {}; 16927 struct bpf_prog *prog = env->prog; 16928 const struct btf *btf = prog->aux->btf; 16929 struct bpf_core_ctx ctx = { 16930 .log = &env->log, 16931 .btf = btf, 16932 }; 16933 bpfptr_t u_core_relo; 16934 int err; 16935 16936 nr_core_relo = attr->core_relo_cnt; 16937 if (!nr_core_relo) 16938 return 0; 16939 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 16940 return -EINVAL; 16941 16942 rec_size = attr->core_relo_rec_size; 16943 if (rec_size < MIN_CORE_RELO_SIZE || 16944 rec_size > MAX_CORE_RELO_SIZE || 16945 rec_size % sizeof(u32)) 16946 return -EINVAL; 16947 16948 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 16949 expected_size = sizeof(struct bpf_core_relo); 16950 ncopy = min_t(u32, expected_size, rec_size); 16951 16952 /* Unlike func_info and line_info, copy and apply each CO-RE 16953 * relocation record one at a time. 16954 */ 16955 for (i = 0; i < nr_core_relo; i++) { 16956 /* future proofing when sizeof(bpf_core_relo) changes */ 16957 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 16958 if (err) { 16959 if (err == -E2BIG) { 16960 verbose(env, "nonzero tailing record in core_relo"); 16961 if (copy_to_bpfptr_offset(uattr, 16962 offsetof(union bpf_attr, core_relo_rec_size), 16963 &expected_size, sizeof(expected_size))) 16964 err = -EFAULT; 16965 } 16966 break; 16967 } 16968 16969 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 16970 err = -EFAULT; 16971 break; 16972 } 16973 16974 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 16975 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 16976 i, core_relo.insn_off, prog->len); 16977 err = -EINVAL; 16978 break; 16979 } 16980 16981 err = bpf_core_apply(&ctx, &core_relo, i, 16982 &prog->insnsi[core_relo.insn_off / 8]); 16983 if (err) 16984 break; 16985 bpfptr_add(&u_core_relo, rec_size); 16986 } 16987 return err; 16988 } 16989 16990 static int check_btf_info_early(struct bpf_verifier_env *env, 16991 const union bpf_attr *attr, 16992 bpfptr_t uattr) 16993 { 16994 struct btf *btf; 16995 int err; 16996 16997 if (!attr->func_info_cnt && !attr->line_info_cnt) { 16998 if (check_abnormal_return(env)) 16999 return -EINVAL; 17000 return 0; 17001 } 17002 17003 btf = btf_get_by_fd(attr->prog_btf_fd); 17004 if (IS_ERR(btf)) 17005 return PTR_ERR(btf); 17006 if (btf_is_kernel(btf)) { 17007 btf_put(btf); 17008 return -EACCES; 17009 } 17010 env->prog->aux->btf = btf; 17011 17012 err = check_btf_func_early(env, attr, uattr); 17013 if (err) 17014 return err; 17015 return 0; 17016 } 17017 17018 static int check_btf_info(struct bpf_verifier_env *env, 17019 const union bpf_attr *attr, 17020 bpfptr_t uattr) 17021 { 17022 int err; 17023 17024 if (!attr->func_info_cnt && !attr->line_info_cnt) { 17025 if (check_abnormal_return(env)) 17026 return -EINVAL; 17027 return 0; 17028 } 17029 17030 err = check_btf_func(env, attr, uattr); 17031 if (err) 17032 return err; 17033 17034 err = check_btf_line(env, attr, uattr); 17035 if (err) 17036 return err; 17037 17038 err = check_core_relo(env, attr, uattr); 17039 if (err) 17040 return err; 17041 17042 return 0; 17043 } 17044 17045 /* check %cur's range satisfies %old's */ 17046 static bool range_within(const struct bpf_reg_state *old, 17047 const struct bpf_reg_state *cur) 17048 { 17049 return old->umin_value <= cur->umin_value && 17050 old->umax_value >= cur->umax_value && 17051 old->smin_value <= cur->smin_value && 17052 old->smax_value >= cur->smax_value && 17053 old->u32_min_value <= cur->u32_min_value && 17054 old->u32_max_value >= cur->u32_max_value && 17055 old->s32_min_value <= cur->s32_min_value && 17056 old->s32_max_value >= cur->s32_max_value; 17057 } 17058 17059 /* If in the old state two registers had the same id, then they need to have 17060 * the same id in the new state as well. But that id could be different from 17061 * the old state, so we need to track the mapping from old to new ids. 17062 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 17063 * regs with old id 5 must also have new id 9 for the new state to be safe. But 17064 * regs with a different old id could still have new id 9, we don't care about 17065 * that. 17066 * So we look through our idmap to see if this old id has been seen before. If 17067 * so, we require the new id to match; otherwise, we add the id pair to the map. 17068 */ 17069 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 17070 { 17071 struct bpf_id_pair *map = idmap->map; 17072 unsigned int i; 17073 17074 /* either both IDs should be set or both should be zero */ 17075 if (!!old_id != !!cur_id) 17076 return false; 17077 17078 if (old_id == 0) /* cur_id == 0 as well */ 17079 return true; 17080 17081 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 17082 if (!map[i].old) { 17083 /* Reached an empty slot; haven't seen this id before */ 17084 map[i].old = old_id; 17085 map[i].cur = cur_id; 17086 return true; 17087 } 17088 if (map[i].old == old_id) 17089 return map[i].cur == cur_id; 17090 if (map[i].cur == cur_id) 17091 return false; 17092 } 17093 /* We ran out of idmap slots, which should be impossible */ 17094 WARN_ON_ONCE(1); 17095 return false; 17096 } 17097 17098 /* Similar to check_ids(), but allocate a unique temporary ID 17099 * for 'old_id' or 'cur_id' of zero. 17100 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 17101 */ 17102 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 17103 { 17104 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 17105 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 17106 17107 return check_ids(old_id, cur_id, idmap); 17108 } 17109 17110 static void clean_func_state(struct bpf_verifier_env *env, 17111 struct bpf_func_state *st) 17112 { 17113 enum bpf_reg_liveness live; 17114 int i, j; 17115 17116 for (i = 0; i < BPF_REG_FP; i++) { 17117 live = st->regs[i].live; 17118 /* liveness must not touch this register anymore */ 17119 st->regs[i].live |= REG_LIVE_DONE; 17120 if (!(live & REG_LIVE_READ)) 17121 /* since the register is unused, clear its state 17122 * to make further comparison simpler 17123 */ 17124 __mark_reg_not_init(env, &st->regs[i]); 17125 } 17126 17127 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 17128 live = st->stack[i].spilled_ptr.live; 17129 /* liveness must not touch this stack slot anymore */ 17130 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 17131 if (!(live & REG_LIVE_READ)) { 17132 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 17133 for (j = 0; j < BPF_REG_SIZE; j++) 17134 st->stack[i].slot_type[j] = STACK_INVALID; 17135 } 17136 } 17137 } 17138 17139 static void clean_verifier_state(struct bpf_verifier_env *env, 17140 struct bpf_verifier_state *st) 17141 { 17142 int i; 17143 17144 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 17145 /* all regs in this state in all frames were already marked */ 17146 return; 17147 17148 for (i = 0; i <= st->curframe; i++) 17149 clean_func_state(env, st->frame[i]); 17150 } 17151 17152 /* the parentage chains form a tree. 17153 * the verifier states are added to state lists at given insn and 17154 * pushed into state stack for future exploration. 17155 * when the verifier reaches bpf_exit insn some of the verifer states 17156 * stored in the state lists have their final liveness state already, 17157 * but a lot of states will get revised from liveness point of view when 17158 * the verifier explores other branches. 17159 * Example: 17160 * 1: r0 = 1 17161 * 2: if r1 == 100 goto pc+1 17162 * 3: r0 = 2 17163 * 4: exit 17164 * when the verifier reaches exit insn the register r0 in the state list of 17165 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 17166 * of insn 2 and goes exploring further. At the insn 4 it will walk the 17167 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 17168 * 17169 * Since the verifier pushes the branch states as it sees them while exploring 17170 * the program the condition of walking the branch instruction for the second 17171 * time means that all states below this branch were already explored and 17172 * their final liveness marks are already propagated. 17173 * Hence when the verifier completes the search of state list in is_state_visited() 17174 * we can call this clean_live_states() function to mark all liveness states 17175 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 17176 * will not be used. 17177 * This function also clears the registers and stack for states that !READ 17178 * to simplify state merging. 17179 * 17180 * Important note here that walking the same branch instruction in the callee 17181 * doesn't meant that the states are DONE. The verifier has to compare 17182 * the callsites 17183 */ 17184 static void clean_live_states(struct bpf_verifier_env *env, int insn, 17185 struct bpf_verifier_state *cur) 17186 { 17187 struct bpf_verifier_state_list *sl; 17188 17189 sl = *explored_state(env, insn); 17190 while (sl) { 17191 if (sl->state.branches) 17192 goto next; 17193 if (sl->state.insn_idx != insn || 17194 !same_callsites(&sl->state, cur)) 17195 goto next; 17196 clean_verifier_state(env, &sl->state); 17197 next: 17198 sl = sl->next; 17199 } 17200 } 17201 17202 static bool regs_exact(const struct bpf_reg_state *rold, 17203 const struct bpf_reg_state *rcur, 17204 struct bpf_idmap *idmap) 17205 { 17206 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 17207 check_ids(rold->id, rcur->id, idmap) && 17208 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 17209 } 17210 17211 enum exact_level { 17212 NOT_EXACT, 17213 EXACT, 17214 RANGE_WITHIN 17215 }; 17216 17217 /* Returns true if (rold safe implies rcur safe) */ 17218 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 17219 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, 17220 enum exact_level exact) 17221 { 17222 if (exact == EXACT) 17223 return regs_exact(rold, rcur, idmap); 17224 17225 if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT) 17226 /* explored state didn't use this */ 17227 return true; 17228 if (rold->type == NOT_INIT) { 17229 if (exact == NOT_EXACT || rcur->type == NOT_INIT) 17230 /* explored state can't have used this */ 17231 return true; 17232 } 17233 17234 /* Enforce that register types have to match exactly, including their 17235 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 17236 * rule. 17237 * 17238 * One can make a point that using a pointer register as unbounded 17239 * SCALAR would be technically acceptable, but this could lead to 17240 * pointer leaks because scalars are allowed to leak while pointers 17241 * are not. We could make this safe in special cases if root is 17242 * calling us, but it's probably not worth the hassle. 17243 * 17244 * Also, register types that are *not* MAYBE_NULL could technically be 17245 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 17246 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 17247 * to the same map). 17248 * However, if the old MAYBE_NULL register then got NULL checked, 17249 * doing so could have affected others with the same id, and we can't 17250 * check for that because we lost the id when we converted to 17251 * a non-MAYBE_NULL variant. 17252 * So, as a general rule we don't allow mixing MAYBE_NULL and 17253 * non-MAYBE_NULL registers as well. 17254 */ 17255 if (rold->type != rcur->type) 17256 return false; 17257 17258 switch (base_type(rold->type)) { 17259 case SCALAR_VALUE: 17260 if (env->explore_alu_limits) { 17261 /* explore_alu_limits disables tnum_in() and range_within() 17262 * logic and requires everything to be strict 17263 */ 17264 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 17265 check_scalar_ids(rold->id, rcur->id, idmap); 17266 } 17267 if (!rold->precise && exact == NOT_EXACT) 17268 return true; 17269 if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST)) 17270 return false; 17271 if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off)) 17272 return false; 17273 /* Why check_ids() for scalar registers? 17274 * 17275 * Consider the following BPF code: 17276 * 1: r6 = ... unbound scalar, ID=a ... 17277 * 2: r7 = ... unbound scalar, ID=b ... 17278 * 3: if (r6 > r7) goto +1 17279 * 4: r6 = r7 17280 * 5: if (r6 > X) goto ... 17281 * 6: ... memory operation using r7 ... 17282 * 17283 * First verification path is [1-6]: 17284 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 17285 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark 17286 * r7 <= X, because r6 and r7 share same id. 17287 * Next verification path is [1-4, 6]. 17288 * 17289 * Instruction (6) would be reached in two states: 17290 * I. r6{.id=b}, r7{.id=b} via path 1-6; 17291 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 17292 * 17293 * Use check_ids() to distinguish these states. 17294 * --- 17295 * Also verify that new value satisfies old value range knowledge. 17296 */ 17297 return range_within(rold, rcur) && 17298 tnum_in(rold->var_off, rcur->var_off) && 17299 check_scalar_ids(rold->id, rcur->id, idmap); 17300 case PTR_TO_MAP_KEY: 17301 case PTR_TO_MAP_VALUE: 17302 case PTR_TO_MEM: 17303 case PTR_TO_BUF: 17304 case PTR_TO_TP_BUFFER: 17305 /* If the new min/max/var_off satisfy the old ones and 17306 * everything else matches, we are OK. 17307 */ 17308 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 17309 range_within(rold, rcur) && 17310 tnum_in(rold->var_off, rcur->var_off) && 17311 check_ids(rold->id, rcur->id, idmap) && 17312 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 17313 case PTR_TO_PACKET_META: 17314 case PTR_TO_PACKET: 17315 /* We must have at least as much range as the old ptr 17316 * did, so that any accesses which were safe before are 17317 * still safe. This is true even if old range < old off, 17318 * since someone could have accessed through (ptr - k), or 17319 * even done ptr -= k in a register, to get a safe access. 17320 */ 17321 if (rold->range > rcur->range) 17322 return false; 17323 /* If the offsets don't match, we can't trust our alignment; 17324 * nor can we be sure that we won't fall out of range. 17325 */ 17326 if (rold->off != rcur->off) 17327 return false; 17328 /* id relations must be preserved */ 17329 if (!check_ids(rold->id, rcur->id, idmap)) 17330 return false; 17331 /* new val must satisfy old val knowledge */ 17332 return range_within(rold, rcur) && 17333 tnum_in(rold->var_off, rcur->var_off); 17334 case PTR_TO_STACK: 17335 /* two stack pointers are equal only if they're pointing to 17336 * the same stack frame, since fp-8 in foo != fp-8 in bar 17337 */ 17338 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 17339 case PTR_TO_ARENA: 17340 return true; 17341 default: 17342 return regs_exact(rold, rcur, idmap); 17343 } 17344 } 17345 17346 static struct bpf_reg_state unbound_reg; 17347 17348 static __init int unbound_reg_init(void) 17349 { 17350 __mark_reg_unknown_imprecise(&unbound_reg); 17351 unbound_reg.live |= REG_LIVE_READ; 17352 return 0; 17353 } 17354 late_initcall(unbound_reg_init); 17355 17356 static bool is_stack_all_misc(struct bpf_verifier_env *env, 17357 struct bpf_stack_state *stack) 17358 { 17359 u32 i; 17360 17361 for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) { 17362 if ((stack->slot_type[i] == STACK_MISC) || 17363 (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack)) 17364 continue; 17365 return false; 17366 } 17367 17368 return true; 17369 } 17370 17371 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env, 17372 struct bpf_stack_state *stack) 17373 { 17374 if (is_spilled_scalar_reg64(stack)) 17375 return &stack->spilled_ptr; 17376 17377 if (is_stack_all_misc(env, stack)) 17378 return &unbound_reg; 17379 17380 return NULL; 17381 } 17382 17383 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 17384 struct bpf_func_state *cur, struct bpf_idmap *idmap, 17385 enum exact_level exact) 17386 { 17387 int i, spi; 17388 17389 /* walk slots of the explored stack and ignore any additional 17390 * slots in the current stack, since explored(safe) state 17391 * didn't use them 17392 */ 17393 for (i = 0; i < old->allocated_stack; i++) { 17394 struct bpf_reg_state *old_reg, *cur_reg; 17395 17396 spi = i / BPF_REG_SIZE; 17397 17398 if (exact != NOT_EXACT && 17399 (i >= cur->allocated_stack || 17400 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 17401 cur->stack[spi].slot_type[i % BPF_REG_SIZE])) 17402 return false; 17403 17404 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) 17405 && exact == NOT_EXACT) { 17406 i += BPF_REG_SIZE - 1; 17407 /* explored state didn't use this */ 17408 continue; 17409 } 17410 17411 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 17412 continue; 17413 17414 if (env->allow_uninit_stack && 17415 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 17416 continue; 17417 17418 /* explored stack has more populated slots than current stack 17419 * and these slots were used 17420 */ 17421 if (i >= cur->allocated_stack) 17422 return false; 17423 17424 /* 64-bit scalar spill vs all slots MISC and vice versa. 17425 * Load from all slots MISC produces unbound scalar. 17426 * Construct a fake register for such stack and call 17427 * regsafe() to ensure scalar ids are compared. 17428 */ 17429 old_reg = scalar_reg_for_stack(env, &old->stack[spi]); 17430 cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]); 17431 if (old_reg && cur_reg) { 17432 if (!regsafe(env, old_reg, cur_reg, idmap, exact)) 17433 return false; 17434 i += BPF_REG_SIZE - 1; 17435 continue; 17436 } 17437 17438 /* if old state was safe with misc data in the stack 17439 * it will be safe with zero-initialized stack. 17440 * The opposite is not true 17441 */ 17442 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 17443 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 17444 continue; 17445 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 17446 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 17447 /* Ex: old explored (safe) state has STACK_SPILL in 17448 * this stack slot, but current has STACK_MISC -> 17449 * this verifier states are not equivalent, 17450 * return false to continue verification of this path 17451 */ 17452 return false; 17453 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 17454 continue; 17455 /* Both old and cur are having same slot_type */ 17456 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 17457 case STACK_SPILL: 17458 /* when explored and current stack slot are both storing 17459 * spilled registers, check that stored pointers types 17460 * are the same as well. 17461 * Ex: explored safe path could have stored 17462 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 17463 * but current path has stored: 17464 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 17465 * such verifier states are not equivalent. 17466 * return false to continue verification of this path 17467 */ 17468 if (!regsafe(env, &old->stack[spi].spilled_ptr, 17469 &cur->stack[spi].spilled_ptr, idmap, exact)) 17470 return false; 17471 break; 17472 case STACK_DYNPTR: 17473 old_reg = &old->stack[spi].spilled_ptr; 17474 cur_reg = &cur->stack[spi].spilled_ptr; 17475 if (old_reg->dynptr.type != cur_reg->dynptr.type || 17476 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 17477 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 17478 return false; 17479 break; 17480 case STACK_ITER: 17481 old_reg = &old->stack[spi].spilled_ptr; 17482 cur_reg = &cur->stack[spi].spilled_ptr; 17483 /* iter.depth is not compared between states as it 17484 * doesn't matter for correctness and would otherwise 17485 * prevent convergence; we maintain it only to prevent 17486 * infinite loop check triggering, see 17487 * iter_active_depths_differ() 17488 */ 17489 if (old_reg->iter.btf != cur_reg->iter.btf || 17490 old_reg->iter.btf_id != cur_reg->iter.btf_id || 17491 old_reg->iter.state != cur_reg->iter.state || 17492 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 17493 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 17494 return false; 17495 break; 17496 case STACK_MISC: 17497 case STACK_ZERO: 17498 case STACK_INVALID: 17499 continue; 17500 /* Ensure that new unhandled slot types return false by default */ 17501 default: 17502 return false; 17503 } 17504 } 17505 return true; 17506 } 17507 17508 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 17509 struct bpf_idmap *idmap) 17510 { 17511 int i; 17512 17513 if (old->acquired_refs != cur->acquired_refs) 17514 return false; 17515 17516 for (i = 0; i < old->acquired_refs; i++) { 17517 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 17518 return false; 17519 } 17520 17521 return true; 17522 } 17523 17524 /* compare two verifier states 17525 * 17526 * all states stored in state_list are known to be valid, since 17527 * verifier reached 'bpf_exit' instruction through them 17528 * 17529 * this function is called when verifier exploring different branches of 17530 * execution popped from the state stack. If it sees an old state that has 17531 * more strict register state and more strict stack state then this execution 17532 * branch doesn't need to be explored further, since verifier already 17533 * concluded that more strict state leads to valid finish. 17534 * 17535 * Therefore two states are equivalent if register state is more conservative 17536 * and explored stack state is more conservative than the current one. 17537 * Example: 17538 * explored current 17539 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 17540 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 17541 * 17542 * In other words if current stack state (one being explored) has more 17543 * valid slots than old one that already passed validation, it means 17544 * the verifier can stop exploring and conclude that current state is valid too 17545 * 17546 * Similarly with registers. If explored state has register type as invalid 17547 * whereas register type in current state is meaningful, it means that 17548 * the current state will reach 'bpf_exit' instruction safely 17549 */ 17550 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 17551 struct bpf_func_state *cur, enum exact_level exact) 17552 { 17553 int i; 17554 17555 if (old->callback_depth > cur->callback_depth) 17556 return false; 17557 17558 for (i = 0; i < MAX_BPF_REG; i++) 17559 if (!regsafe(env, &old->regs[i], &cur->regs[i], 17560 &env->idmap_scratch, exact)) 17561 return false; 17562 17563 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 17564 return false; 17565 17566 if (!refsafe(old, cur, &env->idmap_scratch)) 17567 return false; 17568 17569 return true; 17570 } 17571 17572 static void reset_idmap_scratch(struct bpf_verifier_env *env) 17573 { 17574 env->idmap_scratch.tmp_id_gen = env->id_gen; 17575 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 17576 } 17577 17578 static bool states_equal(struct bpf_verifier_env *env, 17579 struct bpf_verifier_state *old, 17580 struct bpf_verifier_state *cur, 17581 enum exact_level exact) 17582 { 17583 int i; 17584 17585 if (old->curframe != cur->curframe) 17586 return false; 17587 17588 reset_idmap_scratch(env); 17589 17590 /* Verification state from speculative execution simulation 17591 * must never prune a non-speculative execution one. 17592 */ 17593 if (old->speculative && !cur->speculative) 17594 return false; 17595 17596 if (old->active_lock.ptr != cur->active_lock.ptr) 17597 return false; 17598 17599 /* Old and cur active_lock's have to be either both present 17600 * or both absent. 17601 */ 17602 if (!!old->active_lock.id != !!cur->active_lock.id) 17603 return false; 17604 17605 if (old->active_lock.id && 17606 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch)) 17607 return false; 17608 17609 if (old->active_rcu_lock != cur->active_rcu_lock) 17610 return false; 17611 17612 if (old->active_preempt_lock != cur->active_preempt_lock) 17613 return false; 17614 17615 if (old->in_sleepable != cur->in_sleepable) 17616 return false; 17617 17618 /* for states to be equal callsites have to be the same 17619 * and all frame states need to be equivalent 17620 */ 17621 for (i = 0; i <= old->curframe; i++) { 17622 if (old->frame[i]->callsite != cur->frame[i]->callsite) 17623 return false; 17624 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact)) 17625 return false; 17626 } 17627 return true; 17628 } 17629 17630 /* Return 0 if no propagation happened. Return negative error code if error 17631 * happened. Otherwise, return the propagated bit. 17632 */ 17633 static int propagate_liveness_reg(struct bpf_verifier_env *env, 17634 struct bpf_reg_state *reg, 17635 struct bpf_reg_state *parent_reg) 17636 { 17637 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 17638 u8 flag = reg->live & REG_LIVE_READ; 17639 int err; 17640 17641 /* When comes here, read flags of PARENT_REG or REG could be any of 17642 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 17643 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 17644 */ 17645 if (parent_flag == REG_LIVE_READ64 || 17646 /* Or if there is no read flag from REG. */ 17647 !flag || 17648 /* Or if the read flag from REG is the same as PARENT_REG. */ 17649 parent_flag == flag) 17650 return 0; 17651 17652 err = mark_reg_read(env, reg, parent_reg, flag); 17653 if (err) 17654 return err; 17655 17656 return flag; 17657 } 17658 17659 /* A write screens off any subsequent reads; but write marks come from the 17660 * straight-line code between a state and its parent. When we arrive at an 17661 * equivalent state (jump target or such) we didn't arrive by the straight-line 17662 * code, so read marks in the state must propagate to the parent regardless 17663 * of the state's write marks. That's what 'parent == state->parent' comparison 17664 * in mark_reg_read() is for. 17665 */ 17666 static int propagate_liveness(struct bpf_verifier_env *env, 17667 const struct bpf_verifier_state *vstate, 17668 struct bpf_verifier_state *vparent) 17669 { 17670 struct bpf_reg_state *state_reg, *parent_reg; 17671 struct bpf_func_state *state, *parent; 17672 int i, frame, err = 0; 17673 17674 if (vparent->curframe != vstate->curframe) { 17675 WARN(1, "propagate_live: parent frame %d current frame %d\n", 17676 vparent->curframe, vstate->curframe); 17677 return -EFAULT; 17678 } 17679 /* Propagate read liveness of registers... */ 17680 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 17681 for (frame = 0; frame <= vstate->curframe; frame++) { 17682 parent = vparent->frame[frame]; 17683 state = vstate->frame[frame]; 17684 parent_reg = parent->regs; 17685 state_reg = state->regs; 17686 /* We don't need to worry about FP liveness, it's read-only */ 17687 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 17688 err = propagate_liveness_reg(env, &state_reg[i], 17689 &parent_reg[i]); 17690 if (err < 0) 17691 return err; 17692 if (err == REG_LIVE_READ64) 17693 mark_insn_zext(env, &parent_reg[i]); 17694 } 17695 17696 /* Propagate stack slots. */ 17697 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 17698 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 17699 parent_reg = &parent->stack[i].spilled_ptr; 17700 state_reg = &state->stack[i].spilled_ptr; 17701 err = propagate_liveness_reg(env, state_reg, 17702 parent_reg); 17703 if (err < 0) 17704 return err; 17705 } 17706 } 17707 return 0; 17708 } 17709 17710 /* find precise scalars in the previous equivalent state and 17711 * propagate them into the current state 17712 */ 17713 static int propagate_precision(struct bpf_verifier_env *env, 17714 const struct bpf_verifier_state *old) 17715 { 17716 struct bpf_reg_state *state_reg; 17717 struct bpf_func_state *state; 17718 int i, err = 0, fr; 17719 bool first; 17720 17721 for (fr = old->curframe; fr >= 0; fr--) { 17722 state = old->frame[fr]; 17723 state_reg = state->regs; 17724 first = true; 17725 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 17726 if (state_reg->type != SCALAR_VALUE || 17727 !state_reg->precise || 17728 !(state_reg->live & REG_LIVE_READ)) 17729 continue; 17730 if (env->log.level & BPF_LOG_LEVEL2) { 17731 if (first) 17732 verbose(env, "frame %d: propagating r%d", fr, i); 17733 else 17734 verbose(env, ",r%d", i); 17735 } 17736 bt_set_frame_reg(&env->bt, fr, i); 17737 first = false; 17738 } 17739 17740 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 17741 if (!is_spilled_reg(&state->stack[i])) 17742 continue; 17743 state_reg = &state->stack[i].spilled_ptr; 17744 if (state_reg->type != SCALAR_VALUE || 17745 !state_reg->precise || 17746 !(state_reg->live & REG_LIVE_READ)) 17747 continue; 17748 if (env->log.level & BPF_LOG_LEVEL2) { 17749 if (first) 17750 verbose(env, "frame %d: propagating fp%d", 17751 fr, (-i - 1) * BPF_REG_SIZE); 17752 else 17753 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 17754 } 17755 bt_set_frame_slot(&env->bt, fr, i); 17756 first = false; 17757 } 17758 if (!first) 17759 verbose(env, "\n"); 17760 } 17761 17762 err = mark_chain_precision_batch(env); 17763 if (err < 0) 17764 return err; 17765 17766 return 0; 17767 } 17768 17769 static bool states_maybe_looping(struct bpf_verifier_state *old, 17770 struct bpf_verifier_state *cur) 17771 { 17772 struct bpf_func_state *fold, *fcur; 17773 int i, fr = cur->curframe; 17774 17775 if (old->curframe != fr) 17776 return false; 17777 17778 fold = old->frame[fr]; 17779 fcur = cur->frame[fr]; 17780 for (i = 0; i < MAX_BPF_REG; i++) 17781 if (memcmp(&fold->regs[i], &fcur->regs[i], 17782 offsetof(struct bpf_reg_state, parent))) 17783 return false; 17784 return true; 17785 } 17786 17787 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 17788 { 17789 return env->insn_aux_data[insn_idx].is_iter_next; 17790 } 17791 17792 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 17793 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 17794 * states to match, which otherwise would look like an infinite loop. So while 17795 * iter_next() calls are taken care of, we still need to be careful and 17796 * prevent erroneous and too eager declaration of "ininite loop", when 17797 * iterators are involved. 17798 * 17799 * Here's a situation in pseudo-BPF assembly form: 17800 * 17801 * 0: again: ; set up iter_next() call args 17802 * 1: r1 = &it ; <CHECKPOINT HERE> 17803 * 2: call bpf_iter_num_next ; this is iter_next() call 17804 * 3: if r0 == 0 goto done 17805 * 4: ... something useful here ... 17806 * 5: goto again ; another iteration 17807 * 6: done: 17808 * 7: r1 = &it 17809 * 8: call bpf_iter_num_destroy ; clean up iter state 17810 * 9: exit 17811 * 17812 * This is a typical loop. Let's assume that we have a prune point at 1:, 17813 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 17814 * again`, assuming other heuristics don't get in a way). 17815 * 17816 * When we first time come to 1:, let's say we have some state X. We proceed 17817 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 17818 * Now we come back to validate that forked ACTIVE state. We proceed through 17819 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 17820 * are converging. But the problem is that we don't know that yet, as this 17821 * convergence has to happen at iter_next() call site only. So if nothing is 17822 * done, at 1: verifier will use bounded loop logic and declare infinite 17823 * looping (and would be *technically* correct, if not for iterator's 17824 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 17825 * don't want that. So what we do in process_iter_next_call() when we go on 17826 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 17827 * a different iteration. So when we suspect an infinite loop, we additionally 17828 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 17829 * pretend we are not looping and wait for next iter_next() call. 17830 * 17831 * This only applies to ACTIVE state. In DRAINED state we don't expect to 17832 * loop, because that would actually mean infinite loop, as DRAINED state is 17833 * "sticky", and so we'll keep returning into the same instruction with the 17834 * same state (at least in one of possible code paths). 17835 * 17836 * This approach allows to keep infinite loop heuristic even in the face of 17837 * active iterator. E.g., C snippet below is and will be detected as 17838 * inifintely looping: 17839 * 17840 * struct bpf_iter_num it; 17841 * int *p, x; 17842 * 17843 * bpf_iter_num_new(&it, 0, 10); 17844 * while ((p = bpf_iter_num_next(&t))) { 17845 * x = p; 17846 * while (x--) {} // <<-- infinite loop here 17847 * } 17848 * 17849 */ 17850 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 17851 { 17852 struct bpf_reg_state *slot, *cur_slot; 17853 struct bpf_func_state *state; 17854 int i, fr; 17855 17856 for (fr = old->curframe; fr >= 0; fr--) { 17857 state = old->frame[fr]; 17858 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 17859 if (state->stack[i].slot_type[0] != STACK_ITER) 17860 continue; 17861 17862 slot = &state->stack[i].spilled_ptr; 17863 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 17864 continue; 17865 17866 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 17867 if (cur_slot->iter.depth != slot->iter.depth) 17868 return true; 17869 } 17870 } 17871 return false; 17872 } 17873 17874 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 17875 { 17876 struct bpf_verifier_state_list *new_sl; 17877 struct bpf_verifier_state_list *sl, **pprev; 17878 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry; 17879 int i, j, n, err, states_cnt = 0; 17880 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx); 17881 bool add_new_state = force_new_state; 17882 bool force_exact; 17883 17884 /* bpf progs typically have pruning point every 4 instructions 17885 * http://vger.kernel.org/bpfconf2019.html#session-1 17886 * Do not add new state for future pruning if the verifier hasn't seen 17887 * at least 2 jumps and at least 8 instructions. 17888 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 17889 * In tests that amounts to up to 50% reduction into total verifier 17890 * memory consumption and 20% verifier time speedup. 17891 */ 17892 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 17893 env->insn_processed - env->prev_insn_processed >= 8) 17894 add_new_state = true; 17895 17896 pprev = explored_state(env, insn_idx); 17897 sl = *pprev; 17898 17899 clean_live_states(env, insn_idx, cur); 17900 17901 while (sl) { 17902 states_cnt++; 17903 if (sl->state.insn_idx != insn_idx) 17904 goto next; 17905 17906 if (sl->state.branches) { 17907 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 17908 17909 if (frame->in_async_callback_fn && 17910 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 17911 /* Different async_entry_cnt means that the verifier is 17912 * processing another entry into async callback. 17913 * Seeing the same state is not an indication of infinite 17914 * loop or infinite recursion. 17915 * But finding the same state doesn't mean that it's safe 17916 * to stop processing the current state. The previous state 17917 * hasn't yet reached bpf_exit, since state.branches > 0. 17918 * Checking in_async_callback_fn alone is not enough either. 17919 * Since the verifier still needs to catch infinite loops 17920 * inside async callbacks. 17921 */ 17922 goto skip_inf_loop_check; 17923 } 17924 /* BPF open-coded iterators loop detection is special. 17925 * states_maybe_looping() logic is too simplistic in detecting 17926 * states that *might* be equivalent, because it doesn't know 17927 * about ID remapping, so don't even perform it. 17928 * See process_iter_next_call() and iter_active_depths_differ() 17929 * for overview of the logic. When current and one of parent 17930 * states are detected as equivalent, it's a good thing: we prove 17931 * convergence and can stop simulating further iterations. 17932 * It's safe to assume that iterator loop will finish, taking into 17933 * account iter_next() contract of eventually returning 17934 * sticky NULL result. 17935 * 17936 * Note, that states have to be compared exactly in this case because 17937 * read and precision marks might not be finalized inside the loop. 17938 * E.g. as in the program below: 17939 * 17940 * 1. r7 = -16 17941 * 2. r6 = bpf_get_prandom_u32() 17942 * 3. while (bpf_iter_num_next(&fp[-8])) { 17943 * 4. if (r6 != 42) { 17944 * 5. r7 = -32 17945 * 6. r6 = bpf_get_prandom_u32() 17946 * 7. continue 17947 * 8. } 17948 * 9. r0 = r10 17949 * 10. r0 += r7 17950 * 11. r8 = *(u64 *)(r0 + 0) 17951 * 12. r6 = bpf_get_prandom_u32() 17952 * 13. } 17953 * 17954 * Here verifier would first visit path 1-3, create a checkpoint at 3 17955 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 17956 * not have read or precision mark for r7 yet, thus inexact states 17957 * comparison would discard current state with r7=-32 17958 * => unsafe memory access at 11 would not be caught. 17959 */ 17960 if (is_iter_next_insn(env, insn_idx)) { 17961 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 17962 struct bpf_func_state *cur_frame; 17963 struct bpf_reg_state *iter_state, *iter_reg; 17964 int spi; 17965 17966 cur_frame = cur->frame[cur->curframe]; 17967 /* btf_check_iter_kfuncs() enforces that 17968 * iter state pointer is always the first arg 17969 */ 17970 iter_reg = &cur_frame->regs[BPF_REG_1]; 17971 /* current state is valid due to states_equal(), 17972 * so we can assume valid iter and reg state, 17973 * no need for extra (re-)validations 17974 */ 17975 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 17976 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 17977 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 17978 update_loop_entry(cur, &sl->state); 17979 goto hit; 17980 } 17981 } 17982 goto skip_inf_loop_check; 17983 } 17984 if (is_may_goto_insn_at(env, insn_idx)) { 17985 if (sl->state.may_goto_depth != cur->may_goto_depth && 17986 states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 17987 update_loop_entry(cur, &sl->state); 17988 goto hit; 17989 } 17990 } 17991 if (calls_callback(env, insn_idx)) { 17992 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) 17993 goto hit; 17994 goto skip_inf_loop_check; 17995 } 17996 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 17997 if (states_maybe_looping(&sl->state, cur) && 17998 states_equal(env, &sl->state, cur, EXACT) && 17999 !iter_active_depths_differ(&sl->state, cur) && 18000 sl->state.may_goto_depth == cur->may_goto_depth && 18001 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 18002 verbose_linfo(env, insn_idx, "; "); 18003 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 18004 verbose(env, "cur state:"); 18005 print_verifier_state(env, cur->frame[cur->curframe], true); 18006 verbose(env, "old state:"); 18007 print_verifier_state(env, sl->state.frame[cur->curframe], true); 18008 return -EINVAL; 18009 } 18010 /* if the verifier is processing a loop, avoid adding new state 18011 * too often, since different loop iterations have distinct 18012 * states and may not help future pruning. 18013 * This threshold shouldn't be too low to make sure that 18014 * a loop with large bound will be rejected quickly. 18015 * The most abusive loop will be: 18016 * r1 += 1 18017 * if r1 < 1000000 goto pc-2 18018 * 1M insn_procssed limit / 100 == 10k peak states. 18019 * This threshold shouldn't be too high either, since states 18020 * at the end of the loop are likely to be useful in pruning. 18021 */ 18022 skip_inf_loop_check: 18023 if (!force_new_state && 18024 env->jmps_processed - env->prev_jmps_processed < 20 && 18025 env->insn_processed - env->prev_insn_processed < 100) 18026 add_new_state = false; 18027 goto miss; 18028 } 18029 /* If sl->state is a part of a loop and this loop's entry is a part of 18030 * current verification path then states have to be compared exactly. 18031 * 'force_exact' is needed to catch the following case: 18032 * 18033 * initial Here state 'succ' was processed first, 18034 * | it was eventually tracked to produce a 18035 * V state identical to 'hdr'. 18036 * .---------> hdr All branches from 'succ' had been explored 18037 * | | and thus 'succ' has its .branches == 0. 18038 * | V 18039 * | .------... Suppose states 'cur' and 'succ' correspond 18040 * | | | to the same instruction + callsites. 18041 * | V V In such case it is necessary to check 18042 * | ... ... if 'succ' and 'cur' are states_equal(). 18043 * | | | If 'succ' and 'cur' are a part of the 18044 * | V V same loop exact flag has to be set. 18045 * | succ <- cur To check if that is the case, verify 18046 * | | if loop entry of 'succ' is in current 18047 * | V DFS path. 18048 * | ... 18049 * | | 18050 * '----' 18051 * 18052 * Additional details are in the comment before get_loop_entry(). 18053 */ 18054 loop_entry = get_loop_entry(&sl->state); 18055 force_exact = loop_entry && loop_entry->branches > 0; 18056 if (states_equal(env, &sl->state, cur, force_exact ? RANGE_WITHIN : NOT_EXACT)) { 18057 if (force_exact) 18058 update_loop_entry(cur, loop_entry); 18059 hit: 18060 sl->hit_cnt++; 18061 /* reached equivalent register/stack state, 18062 * prune the search. 18063 * Registers read by the continuation are read by us. 18064 * If we have any write marks in env->cur_state, they 18065 * will prevent corresponding reads in the continuation 18066 * from reaching our parent (an explored_state). Our 18067 * own state will get the read marks recorded, but 18068 * they'll be immediately forgotten as we're pruning 18069 * this state and will pop a new one. 18070 */ 18071 err = propagate_liveness(env, &sl->state, cur); 18072 18073 /* if previous state reached the exit with precision and 18074 * current state is equivalent to it (except precision marks) 18075 * the precision needs to be propagated back in 18076 * the current state. 18077 */ 18078 if (is_jmp_point(env, env->insn_idx)) 18079 err = err ? : push_jmp_history(env, cur, 0, 0); 18080 err = err ? : propagate_precision(env, &sl->state); 18081 if (err) 18082 return err; 18083 return 1; 18084 } 18085 miss: 18086 /* when new state is not going to be added do not increase miss count. 18087 * Otherwise several loop iterations will remove the state 18088 * recorded earlier. The goal of these heuristics is to have 18089 * states from some iterations of the loop (some in the beginning 18090 * and some at the end) to help pruning. 18091 */ 18092 if (add_new_state) 18093 sl->miss_cnt++; 18094 /* heuristic to determine whether this state is beneficial 18095 * to keep checking from state equivalence point of view. 18096 * Higher numbers increase max_states_per_insn and verification time, 18097 * but do not meaningfully decrease insn_processed. 18098 * 'n' controls how many times state could miss before eviction. 18099 * Use bigger 'n' for checkpoints because evicting checkpoint states 18100 * too early would hinder iterator convergence. 18101 */ 18102 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 18103 if (sl->miss_cnt > sl->hit_cnt * n + n) { 18104 /* the state is unlikely to be useful. Remove it to 18105 * speed up verification 18106 */ 18107 *pprev = sl->next; 18108 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE && 18109 !sl->state.used_as_loop_entry) { 18110 u32 br = sl->state.branches; 18111 18112 WARN_ONCE(br, 18113 "BUG live_done but branches_to_explore %d\n", 18114 br); 18115 free_verifier_state(&sl->state, false); 18116 kfree(sl); 18117 env->peak_states--; 18118 } else { 18119 /* cannot free this state, since parentage chain may 18120 * walk it later. Add it for free_list instead to 18121 * be freed at the end of verification 18122 */ 18123 sl->next = env->free_list; 18124 env->free_list = sl; 18125 } 18126 sl = *pprev; 18127 continue; 18128 } 18129 next: 18130 pprev = &sl->next; 18131 sl = *pprev; 18132 } 18133 18134 if (env->max_states_per_insn < states_cnt) 18135 env->max_states_per_insn = states_cnt; 18136 18137 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 18138 return 0; 18139 18140 if (!add_new_state) 18141 return 0; 18142 18143 /* There were no equivalent states, remember the current one. 18144 * Technically the current state is not proven to be safe yet, 18145 * but it will either reach outer most bpf_exit (which means it's safe) 18146 * or it will be rejected. When there are no loops the verifier won't be 18147 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 18148 * again on the way to bpf_exit. 18149 * When looping the sl->state.branches will be > 0 and this state 18150 * will not be considered for equivalence until branches == 0. 18151 */ 18152 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 18153 if (!new_sl) 18154 return -ENOMEM; 18155 env->total_states++; 18156 env->peak_states++; 18157 env->prev_jmps_processed = env->jmps_processed; 18158 env->prev_insn_processed = env->insn_processed; 18159 18160 /* forget precise markings we inherited, see __mark_chain_precision */ 18161 if (env->bpf_capable) 18162 mark_all_scalars_imprecise(env, cur); 18163 18164 /* add new state to the head of linked list */ 18165 new = &new_sl->state; 18166 err = copy_verifier_state(new, cur); 18167 if (err) { 18168 free_verifier_state(new, false); 18169 kfree(new_sl); 18170 return err; 18171 } 18172 new->insn_idx = insn_idx; 18173 WARN_ONCE(new->branches != 1, 18174 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 18175 18176 cur->parent = new; 18177 cur->first_insn_idx = insn_idx; 18178 cur->dfs_depth = new->dfs_depth + 1; 18179 clear_jmp_history(cur); 18180 new_sl->next = *explored_state(env, insn_idx); 18181 *explored_state(env, insn_idx) = new_sl; 18182 /* connect new state to parentage chain. Current frame needs all 18183 * registers connected. Only r6 - r9 of the callers are alive (pushed 18184 * to the stack implicitly by JITs) so in callers' frames connect just 18185 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 18186 * the state of the call instruction (with WRITTEN set), and r0 comes 18187 * from callee with its full parentage chain, anyway. 18188 */ 18189 /* clear write marks in current state: the writes we did are not writes 18190 * our child did, so they don't screen off its reads from us. 18191 * (There are no read marks in current state, because reads always mark 18192 * their parent and current state never has children yet. Only 18193 * explored_states can get read marks.) 18194 */ 18195 for (j = 0; j <= cur->curframe; j++) { 18196 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 18197 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 18198 for (i = 0; i < BPF_REG_FP; i++) 18199 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 18200 } 18201 18202 /* all stack frames are accessible from callee, clear them all */ 18203 for (j = 0; j <= cur->curframe; j++) { 18204 struct bpf_func_state *frame = cur->frame[j]; 18205 struct bpf_func_state *newframe = new->frame[j]; 18206 18207 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 18208 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 18209 frame->stack[i].spilled_ptr.parent = 18210 &newframe->stack[i].spilled_ptr; 18211 } 18212 } 18213 return 0; 18214 } 18215 18216 /* Return true if it's OK to have the same insn return a different type. */ 18217 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 18218 { 18219 switch (base_type(type)) { 18220 case PTR_TO_CTX: 18221 case PTR_TO_SOCKET: 18222 case PTR_TO_SOCK_COMMON: 18223 case PTR_TO_TCP_SOCK: 18224 case PTR_TO_XDP_SOCK: 18225 case PTR_TO_BTF_ID: 18226 case PTR_TO_ARENA: 18227 return false; 18228 default: 18229 return true; 18230 } 18231 } 18232 18233 /* If an instruction was previously used with particular pointer types, then we 18234 * need to be careful to avoid cases such as the below, where it may be ok 18235 * for one branch accessing the pointer, but not ok for the other branch: 18236 * 18237 * R1 = sock_ptr 18238 * goto X; 18239 * ... 18240 * R1 = some_other_valid_ptr; 18241 * goto X; 18242 * ... 18243 * R2 = *(u32 *)(R1 + 0); 18244 */ 18245 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 18246 { 18247 return src != prev && (!reg_type_mismatch_ok(src) || 18248 !reg_type_mismatch_ok(prev)); 18249 } 18250 18251 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 18252 bool allow_trust_mismatch) 18253 { 18254 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 18255 18256 if (*prev_type == NOT_INIT) { 18257 /* Saw a valid insn 18258 * dst_reg = *(u32 *)(src_reg + off) 18259 * save type to validate intersecting paths 18260 */ 18261 *prev_type = type; 18262 } else if (reg_type_mismatch(type, *prev_type)) { 18263 /* Abuser program is trying to use the same insn 18264 * dst_reg = *(u32*) (src_reg + off) 18265 * with different pointer types: 18266 * src_reg == ctx in one branch and 18267 * src_reg == stack|map in some other branch. 18268 * Reject it. 18269 */ 18270 if (allow_trust_mismatch && 18271 base_type(type) == PTR_TO_BTF_ID && 18272 base_type(*prev_type) == PTR_TO_BTF_ID) { 18273 /* 18274 * Have to support a use case when one path through 18275 * the program yields TRUSTED pointer while another 18276 * is UNTRUSTED. Fallback to UNTRUSTED to generate 18277 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 18278 */ 18279 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 18280 } else { 18281 verbose(env, "same insn cannot be used with different pointers\n"); 18282 return -EINVAL; 18283 } 18284 } 18285 18286 return 0; 18287 } 18288 18289 static int do_check(struct bpf_verifier_env *env) 18290 { 18291 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 18292 struct bpf_verifier_state *state = env->cur_state; 18293 struct bpf_insn *insns = env->prog->insnsi; 18294 struct bpf_reg_state *regs; 18295 int insn_cnt = env->prog->len; 18296 bool do_print_state = false; 18297 int prev_insn_idx = -1; 18298 18299 for (;;) { 18300 bool exception_exit = false; 18301 struct bpf_insn *insn; 18302 u8 class; 18303 int err; 18304 18305 /* reset current history entry on each new instruction */ 18306 env->cur_hist_ent = NULL; 18307 18308 env->prev_insn_idx = prev_insn_idx; 18309 if (env->insn_idx >= insn_cnt) { 18310 verbose(env, "invalid insn idx %d insn_cnt %d\n", 18311 env->insn_idx, insn_cnt); 18312 return -EFAULT; 18313 } 18314 18315 insn = &insns[env->insn_idx]; 18316 class = BPF_CLASS(insn->code); 18317 18318 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 18319 verbose(env, 18320 "BPF program is too large. Processed %d insn\n", 18321 env->insn_processed); 18322 return -E2BIG; 18323 } 18324 18325 state->last_insn_idx = env->prev_insn_idx; 18326 18327 if (is_prune_point(env, env->insn_idx)) { 18328 err = is_state_visited(env, env->insn_idx); 18329 if (err < 0) 18330 return err; 18331 if (err == 1) { 18332 /* found equivalent state, can prune the search */ 18333 if (env->log.level & BPF_LOG_LEVEL) { 18334 if (do_print_state) 18335 verbose(env, "\nfrom %d to %d%s: safe\n", 18336 env->prev_insn_idx, env->insn_idx, 18337 env->cur_state->speculative ? 18338 " (speculative execution)" : ""); 18339 else 18340 verbose(env, "%d: safe\n", env->insn_idx); 18341 } 18342 goto process_bpf_exit; 18343 } 18344 } 18345 18346 if (is_jmp_point(env, env->insn_idx)) { 18347 err = push_jmp_history(env, state, 0, 0); 18348 if (err) 18349 return err; 18350 } 18351 18352 if (signal_pending(current)) 18353 return -EAGAIN; 18354 18355 if (need_resched()) 18356 cond_resched(); 18357 18358 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 18359 verbose(env, "\nfrom %d to %d%s:", 18360 env->prev_insn_idx, env->insn_idx, 18361 env->cur_state->speculative ? 18362 " (speculative execution)" : ""); 18363 print_verifier_state(env, state->frame[state->curframe], true); 18364 do_print_state = false; 18365 } 18366 18367 if (env->log.level & BPF_LOG_LEVEL) { 18368 const struct bpf_insn_cbs cbs = { 18369 .cb_call = disasm_kfunc_name, 18370 .cb_print = verbose, 18371 .private_data = env, 18372 }; 18373 18374 if (verifier_state_scratched(env)) 18375 print_insn_state(env, state->frame[state->curframe]); 18376 18377 verbose_linfo(env, env->insn_idx, "; "); 18378 env->prev_log_pos = env->log.end_pos; 18379 verbose(env, "%d: ", env->insn_idx); 18380 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 18381 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 18382 env->prev_log_pos = env->log.end_pos; 18383 } 18384 18385 if (bpf_prog_is_offloaded(env->prog->aux)) { 18386 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 18387 env->prev_insn_idx); 18388 if (err) 18389 return err; 18390 } 18391 18392 regs = cur_regs(env); 18393 sanitize_mark_insn_seen(env); 18394 prev_insn_idx = env->insn_idx; 18395 18396 if (class == BPF_ALU || class == BPF_ALU64) { 18397 err = check_alu_op(env, insn); 18398 if (err) 18399 return err; 18400 18401 } else if (class == BPF_LDX) { 18402 enum bpf_reg_type src_reg_type; 18403 18404 /* check for reserved fields is already done */ 18405 18406 /* check src operand */ 18407 err = check_reg_arg(env, insn->src_reg, SRC_OP); 18408 if (err) 18409 return err; 18410 18411 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 18412 if (err) 18413 return err; 18414 18415 src_reg_type = regs[insn->src_reg].type; 18416 18417 /* check that memory (src_reg + off) is readable, 18418 * the state of dst_reg will be updated by this func 18419 */ 18420 err = check_mem_access(env, env->insn_idx, insn->src_reg, 18421 insn->off, BPF_SIZE(insn->code), 18422 BPF_READ, insn->dst_reg, false, 18423 BPF_MODE(insn->code) == BPF_MEMSX); 18424 err = err ?: save_aux_ptr_type(env, src_reg_type, true); 18425 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], "ldx"); 18426 if (err) 18427 return err; 18428 } else if (class == BPF_STX) { 18429 enum bpf_reg_type dst_reg_type; 18430 18431 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 18432 err = check_atomic(env, env->insn_idx, insn); 18433 if (err) 18434 return err; 18435 env->insn_idx++; 18436 continue; 18437 } 18438 18439 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 18440 verbose(env, "BPF_STX uses reserved fields\n"); 18441 return -EINVAL; 18442 } 18443 18444 /* check src1 operand */ 18445 err = check_reg_arg(env, insn->src_reg, SRC_OP); 18446 if (err) 18447 return err; 18448 /* check src2 operand */ 18449 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 18450 if (err) 18451 return err; 18452 18453 dst_reg_type = regs[insn->dst_reg].type; 18454 18455 /* check that memory (dst_reg + off) is writeable */ 18456 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 18457 insn->off, BPF_SIZE(insn->code), 18458 BPF_WRITE, insn->src_reg, false, false); 18459 if (err) 18460 return err; 18461 18462 err = save_aux_ptr_type(env, dst_reg_type, false); 18463 if (err) 18464 return err; 18465 } else if (class == BPF_ST) { 18466 enum bpf_reg_type dst_reg_type; 18467 18468 if (BPF_MODE(insn->code) != BPF_MEM || 18469 insn->src_reg != BPF_REG_0) { 18470 verbose(env, "BPF_ST uses reserved fields\n"); 18471 return -EINVAL; 18472 } 18473 /* check src operand */ 18474 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 18475 if (err) 18476 return err; 18477 18478 dst_reg_type = regs[insn->dst_reg].type; 18479 18480 /* check that memory (dst_reg + off) is writeable */ 18481 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 18482 insn->off, BPF_SIZE(insn->code), 18483 BPF_WRITE, -1, false, false); 18484 if (err) 18485 return err; 18486 18487 err = save_aux_ptr_type(env, dst_reg_type, false); 18488 if (err) 18489 return err; 18490 } else if (class == BPF_JMP || class == BPF_JMP32) { 18491 u8 opcode = BPF_OP(insn->code); 18492 18493 env->jmps_processed++; 18494 if (opcode == BPF_CALL) { 18495 if (BPF_SRC(insn->code) != BPF_K || 18496 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 18497 && insn->off != 0) || 18498 (insn->src_reg != BPF_REG_0 && 18499 insn->src_reg != BPF_PSEUDO_CALL && 18500 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 18501 insn->dst_reg != BPF_REG_0 || 18502 class == BPF_JMP32) { 18503 verbose(env, "BPF_CALL uses reserved fields\n"); 18504 return -EINVAL; 18505 } 18506 18507 if (env->cur_state->active_lock.ptr) { 18508 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 18509 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 18510 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 18511 verbose(env, "function calls are not allowed while holding a lock\n"); 18512 return -EINVAL; 18513 } 18514 } 18515 if (insn->src_reg == BPF_PSEUDO_CALL) { 18516 err = check_func_call(env, insn, &env->insn_idx); 18517 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 18518 err = check_kfunc_call(env, insn, &env->insn_idx); 18519 if (!err && is_bpf_throw_kfunc(insn)) { 18520 exception_exit = true; 18521 goto process_bpf_exit_full; 18522 } 18523 } else { 18524 err = check_helper_call(env, insn, &env->insn_idx); 18525 } 18526 if (err) 18527 return err; 18528 18529 mark_reg_scratched(env, BPF_REG_0); 18530 } else if (opcode == BPF_JA) { 18531 if (BPF_SRC(insn->code) != BPF_K || 18532 insn->src_reg != BPF_REG_0 || 18533 insn->dst_reg != BPF_REG_0 || 18534 (class == BPF_JMP && insn->imm != 0) || 18535 (class == BPF_JMP32 && insn->off != 0)) { 18536 verbose(env, "BPF_JA uses reserved fields\n"); 18537 return -EINVAL; 18538 } 18539 18540 if (class == BPF_JMP) 18541 env->insn_idx += insn->off + 1; 18542 else 18543 env->insn_idx += insn->imm + 1; 18544 continue; 18545 18546 } else if (opcode == BPF_EXIT) { 18547 if (BPF_SRC(insn->code) != BPF_K || 18548 insn->imm != 0 || 18549 insn->src_reg != BPF_REG_0 || 18550 insn->dst_reg != BPF_REG_0 || 18551 class == BPF_JMP32) { 18552 verbose(env, "BPF_EXIT uses reserved fields\n"); 18553 return -EINVAL; 18554 } 18555 process_bpf_exit_full: 18556 if (env->cur_state->active_lock.ptr && !env->cur_state->curframe) { 18557 verbose(env, "bpf_spin_unlock is missing\n"); 18558 return -EINVAL; 18559 } 18560 18561 if (env->cur_state->active_rcu_lock && !env->cur_state->curframe) { 18562 verbose(env, "bpf_rcu_read_unlock is missing\n"); 18563 return -EINVAL; 18564 } 18565 18566 if (env->cur_state->active_preempt_lock && !env->cur_state->curframe) { 18567 verbose(env, "%d bpf_preempt_enable%s missing\n", 18568 env->cur_state->active_preempt_lock, 18569 env->cur_state->active_preempt_lock == 1 ? " is" : "(s) are"); 18570 return -EINVAL; 18571 } 18572 18573 /* We must do check_reference_leak here before 18574 * prepare_func_exit to handle the case when 18575 * state->curframe > 0, it may be a callback 18576 * function, for which reference_state must 18577 * match caller reference state when it exits. 18578 */ 18579 err = check_reference_leak(env, exception_exit); 18580 if (err) 18581 return err; 18582 18583 /* The side effect of the prepare_func_exit 18584 * which is being skipped is that it frees 18585 * bpf_func_state. Typically, process_bpf_exit 18586 * will only be hit with outermost exit. 18587 * copy_verifier_state in pop_stack will handle 18588 * freeing of any extra bpf_func_state left over 18589 * from not processing all nested function 18590 * exits. We also skip return code checks as 18591 * they are not needed for exceptional exits. 18592 */ 18593 if (exception_exit) 18594 goto process_bpf_exit; 18595 18596 if (state->curframe) { 18597 /* exit from nested function */ 18598 err = prepare_func_exit(env, &env->insn_idx); 18599 if (err) 18600 return err; 18601 do_print_state = true; 18602 continue; 18603 } 18604 18605 err = check_return_code(env, BPF_REG_0, "R0"); 18606 if (err) 18607 return err; 18608 process_bpf_exit: 18609 mark_verifier_state_scratched(env); 18610 update_branch_counts(env, env->cur_state); 18611 err = pop_stack(env, &prev_insn_idx, 18612 &env->insn_idx, pop_log); 18613 if (err < 0) { 18614 if (err != -ENOENT) 18615 return err; 18616 break; 18617 } else { 18618 do_print_state = true; 18619 continue; 18620 } 18621 } else { 18622 err = check_cond_jmp_op(env, insn, &env->insn_idx); 18623 if (err) 18624 return err; 18625 } 18626 } else if (class == BPF_LD) { 18627 u8 mode = BPF_MODE(insn->code); 18628 18629 if (mode == BPF_ABS || mode == BPF_IND) { 18630 err = check_ld_abs(env, insn); 18631 if (err) 18632 return err; 18633 18634 } else if (mode == BPF_IMM) { 18635 err = check_ld_imm(env, insn); 18636 if (err) 18637 return err; 18638 18639 env->insn_idx++; 18640 sanitize_mark_insn_seen(env); 18641 } else { 18642 verbose(env, "invalid BPF_LD mode\n"); 18643 return -EINVAL; 18644 } 18645 } else { 18646 verbose(env, "unknown insn class %d\n", class); 18647 return -EINVAL; 18648 } 18649 18650 env->insn_idx++; 18651 } 18652 18653 return 0; 18654 } 18655 18656 static int find_btf_percpu_datasec(struct btf *btf) 18657 { 18658 const struct btf_type *t; 18659 const char *tname; 18660 int i, n; 18661 18662 /* 18663 * Both vmlinux and module each have their own ".data..percpu" 18664 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 18665 * types to look at only module's own BTF types. 18666 */ 18667 n = btf_nr_types(btf); 18668 if (btf_is_module(btf)) 18669 i = btf_nr_types(btf_vmlinux); 18670 else 18671 i = 1; 18672 18673 for(; i < n; i++) { 18674 t = btf_type_by_id(btf, i); 18675 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 18676 continue; 18677 18678 tname = btf_name_by_offset(btf, t->name_off); 18679 if (!strcmp(tname, ".data..percpu")) 18680 return i; 18681 } 18682 18683 return -ENOENT; 18684 } 18685 18686 /* replace pseudo btf_id with kernel symbol address */ 18687 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 18688 struct bpf_insn *insn, 18689 struct bpf_insn_aux_data *aux) 18690 { 18691 const struct btf_var_secinfo *vsi; 18692 const struct btf_type *datasec; 18693 struct btf_mod_pair *btf_mod; 18694 const struct btf_type *t; 18695 const char *sym_name; 18696 bool percpu = false; 18697 u32 type, id = insn->imm; 18698 struct btf *btf; 18699 s32 datasec_id; 18700 u64 addr; 18701 int i, btf_fd, err; 18702 18703 btf_fd = insn[1].imm; 18704 if (btf_fd) { 18705 btf = btf_get_by_fd(btf_fd); 18706 if (IS_ERR(btf)) { 18707 verbose(env, "invalid module BTF object FD specified.\n"); 18708 return -EINVAL; 18709 } 18710 } else { 18711 if (!btf_vmlinux) { 18712 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 18713 return -EINVAL; 18714 } 18715 btf = btf_vmlinux; 18716 btf_get(btf); 18717 } 18718 18719 t = btf_type_by_id(btf, id); 18720 if (!t) { 18721 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 18722 err = -ENOENT; 18723 goto err_put; 18724 } 18725 18726 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 18727 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 18728 err = -EINVAL; 18729 goto err_put; 18730 } 18731 18732 sym_name = btf_name_by_offset(btf, t->name_off); 18733 addr = kallsyms_lookup_name(sym_name); 18734 if (!addr) { 18735 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 18736 sym_name); 18737 err = -ENOENT; 18738 goto err_put; 18739 } 18740 insn[0].imm = (u32)addr; 18741 insn[1].imm = addr >> 32; 18742 18743 if (btf_type_is_func(t)) { 18744 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 18745 aux->btf_var.mem_size = 0; 18746 goto check_btf; 18747 } 18748 18749 datasec_id = find_btf_percpu_datasec(btf); 18750 if (datasec_id > 0) { 18751 datasec = btf_type_by_id(btf, datasec_id); 18752 for_each_vsi(i, datasec, vsi) { 18753 if (vsi->type == id) { 18754 percpu = true; 18755 break; 18756 } 18757 } 18758 } 18759 18760 type = t->type; 18761 t = btf_type_skip_modifiers(btf, type, NULL); 18762 if (percpu) { 18763 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 18764 aux->btf_var.btf = btf; 18765 aux->btf_var.btf_id = type; 18766 } else if (!btf_type_is_struct(t)) { 18767 const struct btf_type *ret; 18768 const char *tname; 18769 u32 tsize; 18770 18771 /* resolve the type size of ksym. */ 18772 ret = btf_resolve_size(btf, t, &tsize); 18773 if (IS_ERR(ret)) { 18774 tname = btf_name_by_offset(btf, t->name_off); 18775 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 18776 tname, PTR_ERR(ret)); 18777 err = -EINVAL; 18778 goto err_put; 18779 } 18780 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 18781 aux->btf_var.mem_size = tsize; 18782 } else { 18783 aux->btf_var.reg_type = PTR_TO_BTF_ID; 18784 aux->btf_var.btf = btf; 18785 aux->btf_var.btf_id = type; 18786 } 18787 check_btf: 18788 /* check whether we recorded this BTF (and maybe module) already */ 18789 for (i = 0; i < env->used_btf_cnt; i++) { 18790 if (env->used_btfs[i].btf == btf) { 18791 btf_put(btf); 18792 return 0; 18793 } 18794 } 18795 18796 if (env->used_btf_cnt >= MAX_USED_BTFS) { 18797 err = -E2BIG; 18798 goto err_put; 18799 } 18800 18801 btf_mod = &env->used_btfs[env->used_btf_cnt]; 18802 btf_mod->btf = btf; 18803 btf_mod->module = NULL; 18804 18805 /* if we reference variables from kernel module, bump its refcount */ 18806 if (btf_is_module(btf)) { 18807 btf_mod->module = btf_try_get_module(btf); 18808 if (!btf_mod->module) { 18809 err = -ENXIO; 18810 goto err_put; 18811 } 18812 } 18813 18814 env->used_btf_cnt++; 18815 18816 return 0; 18817 err_put: 18818 btf_put(btf); 18819 return err; 18820 } 18821 18822 static bool is_tracing_prog_type(enum bpf_prog_type type) 18823 { 18824 switch (type) { 18825 case BPF_PROG_TYPE_KPROBE: 18826 case BPF_PROG_TYPE_TRACEPOINT: 18827 case BPF_PROG_TYPE_PERF_EVENT: 18828 case BPF_PROG_TYPE_RAW_TRACEPOINT: 18829 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 18830 return true; 18831 default: 18832 return false; 18833 } 18834 } 18835 18836 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 18837 struct bpf_map *map, 18838 struct bpf_prog *prog) 18839 18840 { 18841 enum bpf_prog_type prog_type = resolve_prog_type(prog); 18842 18843 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 18844 btf_record_has_field(map->record, BPF_RB_ROOT)) { 18845 if (is_tracing_prog_type(prog_type)) { 18846 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 18847 return -EINVAL; 18848 } 18849 } 18850 18851 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 18852 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 18853 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 18854 return -EINVAL; 18855 } 18856 18857 if (is_tracing_prog_type(prog_type)) { 18858 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 18859 return -EINVAL; 18860 } 18861 } 18862 18863 if (btf_record_has_field(map->record, BPF_TIMER)) { 18864 if (is_tracing_prog_type(prog_type)) { 18865 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 18866 return -EINVAL; 18867 } 18868 } 18869 18870 if (btf_record_has_field(map->record, BPF_WORKQUEUE)) { 18871 if (is_tracing_prog_type(prog_type)) { 18872 verbose(env, "tracing progs cannot use bpf_wq yet\n"); 18873 return -EINVAL; 18874 } 18875 } 18876 18877 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 18878 !bpf_offload_prog_map_match(prog, map)) { 18879 verbose(env, "offload device mismatch between prog and map\n"); 18880 return -EINVAL; 18881 } 18882 18883 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 18884 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 18885 return -EINVAL; 18886 } 18887 18888 if (prog->sleepable) 18889 switch (map->map_type) { 18890 case BPF_MAP_TYPE_HASH: 18891 case BPF_MAP_TYPE_LRU_HASH: 18892 case BPF_MAP_TYPE_ARRAY: 18893 case BPF_MAP_TYPE_PERCPU_HASH: 18894 case BPF_MAP_TYPE_PERCPU_ARRAY: 18895 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 18896 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 18897 case BPF_MAP_TYPE_HASH_OF_MAPS: 18898 case BPF_MAP_TYPE_RINGBUF: 18899 case BPF_MAP_TYPE_USER_RINGBUF: 18900 case BPF_MAP_TYPE_INODE_STORAGE: 18901 case BPF_MAP_TYPE_SK_STORAGE: 18902 case BPF_MAP_TYPE_TASK_STORAGE: 18903 case BPF_MAP_TYPE_CGRP_STORAGE: 18904 case BPF_MAP_TYPE_QUEUE: 18905 case BPF_MAP_TYPE_STACK: 18906 case BPF_MAP_TYPE_ARENA: 18907 break; 18908 default: 18909 verbose(env, 18910 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 18911 return -EINVAL; 18912 } 18913 18914 return 0; 18915 } 18916 18917 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 18918 { 18919 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 18920 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 18921 } 18922 18923 /* Add map behind fd to used maps list, if it's not already there, and return 18924 * its index. Also set *reused to true if this map was already in the list of 18925 * used maps. 18926 * Returns <0 on error, or >= 0 index, on success. 18927 */ 18928 static int add_used_map_from_fd(struct bpf_verifier_env *env, int fd, bool *reused) 18929 { 18930 CLASS(fd, f)(fd); 18931 struct bpf_map *map; 18932 int i; 18933 18934 map = __bpf_map_get(f); 18935 if (IS_ERR(map)) { 18936 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 18937 return PTR_ERR(map); 18938 } 18939 18940 /* check whether we recorded this map already */ 18941 for (i = 0; i < env->used_map_cnt; i++) { 18942 if (env->used_maps[i] == map) { 18943 *reused = true; 18944 return i; 18945 } 18946 } 18947 18948 if (env->used_map_cnt >= MAX_USED_MAPS) { 18949 verbose(env, "The total number of maps per program has reached the limit of %u\n", 18950 MAX_USED_MAPS); 18951 return -E2BIG; 18952 } 18953 18954 if (env->prog->sleepable) 18955 atomic64_inc(&map->sleepable_refcnt); 18956 18957 /* hold the map. If the program is rejected by verifier, 18958 * the map will be released by release_maps() or it 18959 * will be used by the valid program until it's unloaded 18960 * and all maps are released in bpf_free_used_maps() 18961 */ 18962 bpf_map_inc(map); 18963 18964 *reused = false; 18965 env->used_maps[env->used_map_cnt++] = map; 18966 18967 return env->used_map_cnt - 1; 18968 } 18969 18970 /* find and rewrite pseudo imm in ld_imm64 instructions: 18971 * 18972 * 1. if it accesses map FD, replace it with actual map pointer. 18973 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 18974 * 18975 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 18976 */ 18977 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 18978 { 18979 struct bpf_insn *insn = env->prog->insnsi; 18980 int insn_cnt = env->prog->len; 18981 int i, err; 18982 18983 err = bpf_prog_calc_tag(env->prog); 18984 if (err) 18985 return err; 18986 18987 for (i = 0; i < insn_cnt; i++, insn++) { 18988 if (BPF_CLASS(insn->code) == BPF_LDX && 18989 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 18990 insn->imm != 0)) { 18991 verbose(env, "BPF_LDX uses reserved fields\n"); 18992 return -EINVAL; 18993 } 18994 18995 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 18996 struct bpf_insn_aux_data *aux; 18997 struct bpf_map *map; 18998 int map_idx; 18999 u64 addr; 19000 u32 fd; 19001 bool reused; 19002 19003 if (i == insn_cnt - 1 || insn[1].code != 0 || 19004 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 19005 insn[1].off != 0) { 19006 verbose(env, "invalid bpf_ld_imm64 insn\n"); 19007 return -EINVAL; 19008 } 19009 19010 if (insn[0].src_reg == 0) 19011 /* valid generic load 64-bit imm */ 19012 goto next_insn; 19013 19014 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 19015 aux = &env->insn_aux_data[i]; 19016 err = check_pseudo_btf_id(env, insn, aux); 19017 if (err) 19018 return err; 19019 goto next_insn; 19020 } 19021 19022 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 19023 aux = &env->insn_aux_data[i]; 19024 aux->ptr_type = PTR_TO_FUNC; 19025 goto next_insn; 19026 } 19027 19028 /* In final convert_pseudo_ld_imm64() step, this is 19029 * converted into regular 64-bit imm load insn. 19030 */ 19031 switch (insn[0].src_reg) { 19032 case BPF_PSEUDO_MAP_VALUE: 19033 case BPF_PSEUDO_MAP_IDX_VALUE: 19034 break; 19035 case BPF_PSEUDO_MAP_FD: 19036 case BPF_PSEUDO_MAP_IDX: 19037 if (insn[1].imm == 0) 19038 break; 19039 fallthrough; 19040 default: 19041 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 19042 return -EINVAL; 19043 } 19044 19045 switch (insn[0].src_reg) { 19046 case BPF_PSEUDO_MAP_IDX_VALUE: 19047 case BPF_PSEUDO_MAP_IDX: 19048 if (bpfptr_is_null(env->fd_array)) { 19049 verbose(env, "fd_idx without fd_array is invalid\n"); 19050 return -EPROTO; 19051 } 19052 if (copy_from_bpfptr_offset(&fd, env->fd_array, 19053 insn[0].imm * sizeof(fd), 19054 sizeof(fd))) 19055 return -EFAULT; 19056 break; 19057 default: 19058 fd = insn[0].imm; 19059 break; 19060 } 19061 19062 map_idx = add_used_map_from_fd(env, fd, &reused); 19063 if (map_idx < 0) 19064 return map_idx; 19065 map = env->used_maps[map_idx]; 19066 19067 aux = &env->insn_aux_data[i]; 19068 aux->map_index = map_idx; 19069 19070 err = check_map_prog_compatibility(env, map, env->prog); 19071 if (err) 19072 return err; 19073 19074 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 19075 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 19076 addr = (unsigned long)map; 19077 } else { 19078 u32 off = insn[1].imm; 19079 19080 if (off >= BPF_MAX_VAR_OFF) { 19081 verbose(env, "direct value offset of %u is not allowed\n", off); 19082 return -EINVAL; 19083 } 19084 19085 if (!map->ops->map_direct_value_addr) { 19086 verbose(env, "no direct value access support for this map type\n"); 19087 return -EINVAL; 19088 } 19089 19090 err = map->ops->map_direct_value_addr(map, &addr, off); 19091 if (err) { 19092 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 19093 map->value_size, off); 19094 return err; 19095 } 19096 19097 aux->map_off = off; 19098 addr += off; 19099 } 19100 19101 insn[0].imm = (u32)addr; 19102 insn[1].imm = addr >> 32; 19103 19104 /* proceed with extra checks only if its newly added used map */ 19105 if (reused) 19106 goto next_insn; 19107 19108 if (bpf_map_is_cgroup_storage(map) && 19109 bpf_cgroup_storage_assign(env->prog->aux, map)) { 19110 verbose(env, "only one cgroup storage of each type is allowed\n"); 19111 return -EBUSY; 19112 } 19113 if (map->map_type == BPF_MAP_TYPE_ARENA) { 19114 if (env->prog->aux->arena) { 19115 verbose(env, "Only one arena per program\n"); 19116 return -EBUSY; 19117 } 19118 if (!env->allow_ptr_leaks || !env->bpf_capable) { 19119 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n"); 19120 return -EPERM; 19121 } 19122 if (!env->prog->jit_requested) { 19123 verbose(env, "JIT is required to use arena\n"); 19124 return -EOPNOTSUPP; 19125 } 19126 if (!bpf_jit_supports_arena()) { 19127 verbose(env, "JIT doesn't support arena\n"); 19128 return -EOPNOTSUPP; 19129 } 19130 env->prog->aux->arena = (void *)map; 19131 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) { 19132 verbose(env, "arena's user address must be set via map_extra or mmap()\n"); 19133 return -EINVAL; 19134 } 19135 } 19136 19137 next_insn: 19138 insn++; 19139 i++; 19140 continue; 19141 } 19142 19143 /* Basic sanity check before we invest more work here. */ 19144 if (!bpf_opcode_in_insntable(insn->code)) { 19145 verbose(env, "unknown opcode %02x\n", insn->code); 19146 return -EINVAL; 19147 } 19148 } 19149 19150 /* now all pseudo BPF_LD_IMM64 instructions load valid 19151 * 'struct bpf_map *' into a register instead of user map_fd. 19152 * These pointers will be used later by verifier to validate map access. 19153 */ 19154 return 0; 19155 } 19156 19157 /* drop refcnt of maps used by the rejected program */ 19158 static void release_maps(struct bpf_verifier_env *env) 19159 { 19160 __bpf_free_used_maps(env->prog->aux, env->used_maps, 19161 env->used_map_cnt); 19162 } 19163 19164 /* drop refcnt of maps used by the rejected program */ 19165 static void release_btfs(struct bpf_verifier_env *env) 19166 { 19167 __bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt); 19168 } 19169 19170 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 19171 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 19172 { 19173 struct bpf_insn *insn = env->prog->insnsi; 19174 int insn_cnt = env->prog->len; 19175 int i; 19176 19177 for (i = 0; i < insn_cnt; i++, insn++) { 19178 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 19179 continue; 19180 if (insn->src_reg == BPF_PSEUDO_FUNC) 19181 continue; 19182 insn->src_reg = 0; 19183 } 19184 } 19185 19186 /* single env->prog->insni[off] instruction was replaced with the range 19187 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 19188 * [0, off) and [off, end) to new locations, so the patched range stays zero 19189 */ 19190 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 19191 struct bpf_insn_aux_data *new_data, 19192 struct bpf_prog *new_prog, u32 off, u32 cnt) 19193 { 19194 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 19195 struct bpf_insn *insn = new_prog->insnsi; 19196 u32 old_seen = old_data[off].seen; 19197 u32 prog_len; 19198 int i; 19199 19200 /* aux info at OFF always needs adjustment, no matter fast path 19201 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 19202 * original insn at old prog. 19203 */ 19204 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 19205 19206 if (cnt == 1) 19207 return; 19208 prog_len = new_prog->len; 19209 19210 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 19211 memcpy(new_data + off + cnt - 1, old_data + off, 19212 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 19213 for (i = off; i < off + cnt - 1; i++) { 19214 /* Expand insni[off]'s seen count to the patched range. */ 19215 new_data[i].seen = old_seen; 19216 new_data[i].zext_dst = insn_has_def32(env, insn + i); 19217 } 19218 env->insn_aux_data = new_data; 19219 vfree(old_data); 19220 } 19221 19222 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 19223 { 19224 int i; 19225 19226 if (len == 1) 19227 return; 19228 /* NOTE: fake 'exit' subprog should be updated as well. */ 19229 for (i = 0; i <= env->subprog_cnt; i++) { 19230 if (env->subprog_info[i].start <= off) 19231 continue; 19232 env->subprog_info[i].start += len - 1; 19233 } 19234 } 19235 19236 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 19237 { 19238 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 19239 int i, sz = prog->aux->size_poke_tab; 19240 struct bpf_jit_poke_descriptor *desc; 19241 19242 for (i = 0; i < sz; i++) { 19243 desc = &tab[i]; 19244 if (desc->insn_idx <= off) 19245 continue; 19246 desc->insn_idx += len - 1; 19247 } 19248 } 19249 19250 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 19251 const struct bpf_insn *patch, u32 len) 19252 { 19253 struct bpf_prog *new_prog; 19254 struct bpf_insn_aux_data *new_data = NULL; 19255 19256 if (len > 1) { 19257 new_data = vzalloc(array_size(env->prog->len + len - 1, 19258 sizeof(struct bpf_insn_aux_data))); 19259 if (!new_data) 19260 return NULL; 19261 } 19262 19263 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 19264 if (IS_ERR(new_prog)) { 19265 if (PTR_ERR(new_prog) == -ERANGE) 19266 verbose(env, 19267 "insn %d cannot be patched due to 16-bit range\n", 19268 env->insn_aux_data[off].orig_idx); 19269 vfree(new_data); 19270 return NULL; 19271 } 19272 adjust_insn_aux_data(env, new_data, new_prog, off, len); 19273 adjust_subprog_starts(env, off, len); 19274 adjust_poke_descs(new_prog, off, len); 19275 return new_prog; 19276 } 19277 19278 /* 19279 * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the 19280 * jump offset by 'delta'. 19281 */ 19282 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta) 19283 { 19284 struct bpf_insn *insn = prog->insnsi; 19285 u32 insn_cnt = prog->len, i; 19286 s32 imm; 19287 s16 off; 19288 19289 for (i = 0; i < insn_cnt; i++, insn++) { 19290 u8 code = insn->code; 19291 19292 if (tgt_idx <= i && i < tgt_idx + delta) 19293 continue; 19294 19295 if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) || 19296 BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT) 19297 continue; 19298 19299 if (insn->code == (BPF_JMP32 | BPF_JA)) { 19300 if (i + 1 + insn->imm != tgt_idx) 19301 continue; 19302 if (check_add_overflow(insn->imm, delta, &imm)) 19303 return -ERANGE; 19304 insn->imm = imm; 19305 } else { 19306 if (i + 1 + insn->off != tgt_idx) 19307 continue; 19308 if (check_add_overflow(insn->off, delta, &off)) 19309 return -ERANGE; 19310 insn->off = off; 19311 } 19312 } 19313 return 0; 19314 } 19315 19316 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 19317 u32 off, u32 cnt) 19318 { 19319 int i, j; 19320 19321 /* find first prog starting at or after off (first to remove) */ 19322 for (i = 0; i < env->subprog_cnt; i++) 19323 if (env->subprog_info[i].start >= off) 19324 break; 19325 /* find first prog starting at or after off + cnt (first to stay) */ 19326 for (j = i; j < env->subprog_cnt; j++) 19327 if (env->subprog_info[j].start >= off + cnt) 19328 break; 19329 /* if j doesn't start exactly at off + cnt, we are just removing 19330 * the front of previous prog 19331 */ 19332 if (env->subprog_info[j].start != off + cnt) 19333 j--; 19334 19335 if (j > i) { 19336 struct bpf_prog_aux *aux = env->prog->aux; 19337 int move; 19338 19339 /* move fake 'exit' subprog as well */ 19340 move = env->subprog_cnt + 1 - j; 19341 19342 memmove(env->subprog_info + i, 19343 env->subprog_info + j, 19344 sizeof(*env->subprog_info) * move); 19345 env->subprog_cnt -= j - i; 19346 19347 /* remove func_info */ 19348 if (aux->func_info) { 19349 move = aux->func_info_cnt - j; 19350 19351 memmove(aux->func_info + i, 19352 aux->func_info + j, 19353 sizeof(*aux->func_info) * move); 19354 aux->func_info_cnt -= j - i; 19355 /* func_info->insn_off is set after all code rewrites, 19356 * in adjust_btf_func() - no need to adjust 19357 */ 19358 } 19359 } else { 19360 /* convert i from "first prog to remove" to "first to adjust" */ 19361 if (env->subprog_info[i].start == off) 19362 i++; 19363 } 19364 19365 /* update fake 'exit' subprog as well */ 19366 for (; i <= env->subprog_cnt; i++) 19367 env->subprog_info[i].start -= cnt; 19368 19369 return 0; 19370 } 19371 19372 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 19373 u32 cnt) 19374 { 19375 struct bpf_prog *prog = env->prog; 19376 u32 i, l_off, l_cnt, nr_linfo; 19377 struct bpf_line_info *linfo; 19378 19379 nr_linfo = prog->aux->nr_linfo; 19380 if (!nr_linfo) 19381 return 0; 19382 19383 linfo = prog->aux->linfo; 19384 19385 /* find first line info to remove, count lines to be removed */ 19386 for (i = 0; i < nr_linfo; i++) 19387 if (linfo[i].insn_off >= off) 19388 break; 19389 19390 l_off = i; 19391 l_cnt = 0; 19392 for (; i < nr_linfo; i++) 19393 if (linfo[i].insn_off < off + cnt) 19394 l_cnt++; 19395 else 19396 break; 19397 19398 /* First live insn doesn't match first live linfo, it needs to "inherit" 19399 * last removed linfo. prog is already modified, so prog->len == off 19400 * means no live instructions after (tail of the program was removed). 19401 */ 19402 if (prog->len != off && l_cnt && 19403 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 19404 l_cnt--; 19405 linfo[--i].insn_off = off + cnt; 19406 } 19407 19408 /* remove the line info which refer to the removed instructions */ 19409 if (l_cnt) { 19410 memmove(linfo + l_off, linfo + i, 19411 sizeof(*linfo) * (nr_linfo - i)); 19412 19413 prog->aux->nr_linfo -= l_cnt; 19414 nr_linfo = prog->aux->nr_linfo; 19415 } 19416 19417 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 19418 for (i = l_off; i < nr_linfo; i++) 19419 linfo[i].insn_off -= cnt; 19420 19421 /* fix up all subprogs (incl. 'exit') which start >= off */ 19422 for (i = 0; i <= env->subprog_cnt; i++) 19423 if (env->subprog_info[i].linfo_idx > l_off) { 19424 /* program may have started in the removed region but 19425 * may not be fully removed 19426 */ 19427 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 19428 env->subprog_info[i].linfo_idx -= l_cnt; 19429 else 19430 env->subprog_info[i].linfo_idx = l_off; 19431 } 19432 19433 return 0; 19434 } 19435 19436 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 19437 { 19438 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 19439 unsigned int orig_prog_len = env->prog->len; 19440 int err; 19441 19442 if (bpf_prog_is_offloaded(env->prog->aux)) 19443 bpf_prog_offload_remove_insns(env, off, cnt); 19444 19445 err = bpf_remove_insns(env->prog, off, cnt); 19446 if (err) 19447 return err; 19448 19449 err = adjust_subprog_starts_after_remove(env, off, cnt); 19450 if (err) 19451 return err; 19452 19453 err = bpf_adj_linfo_after_remove(env, off, cnt); 19454 if (err) 19455 return err; 19456 19457 memmove(aux_data + off, aux_data + off + cnt, 19458 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 19459 19460 return 0; 19461 } 19462 19463 /* The verifier does more data flow analysis than llvm and will not 19464 * explore branches that are dead at run time. Malicious programs can 19465 * have dead code too. Therefore replace all dead at-run-time code 19466 * with 'ja -1'. 19467 * 19468 * Just nops are not optimal, e.g. if they would sit at the end of the 19469 * program and through another bug we would manage to jump there, then 19470 * we'd execute beyond program memory otherwise. Returning exception 19471 * code also wouldn't work since we can have subprogs where the dead 19472 * code could be located. 19473 */ 19474 static void sanitize_dead_code(struct bpf_verifier_env *env) 19475 { 19476 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 19477 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 19478 struct bpf_insn *insn = env->prog->insnsi; 19479 const int insn_cnt = env->prog->len; 19480 int i; 19481 19482 for (i = 0; i < insn_cnt; i++) { 19483 if (aux_data[i].seen) 19484 continue; 19485 memcpy(insn + i, &trap, sizeof(trap)); 19486 aux_data[i].zext_dst = false; 19487 } 19488 } 19489 19490 static bool insn_is_cond_jump(u8 code) 19491 { 19492 u8 op; 19493 19494 op = BPF_OP(code); 19495 if (BPF_CLASS(code) == BPF_JMP32) 19496 return op != BPF_JA; 19497 19498 if (BPF_CLASS(code) != BPF_JMP) 19499 return false; 19500 19501 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 19502 } 19503 19504 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 19505 { 19506 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 19507 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 19508 struct bpf_insn *insn = env->prog->insnsi; 19509 const int insn_cnt = env->prog->len; 19510 int i; 19511 19512 for (i = 0; i < insn_cnt; i++, insn++) { 19513 if (!insn_is_cond_jump(insn->code)) 19514 continue; 19515 19516 if (!aux_data[i + 1].seen) 19517 ja.off = insn->off; 19518 else if (!aux_data[i + 1 + insn->off].seen) 19519 ja.off = 0; 19520 else 19521 continue; 19522 19523 if (bpf_prog_is_offloaded(env->prog->aux)) 19524 bpf_prog_offload_replace_insn(env, i, &ja); 19525 19526 memcpy(insn, &ja, sizeof(ja)); 19527 } 19528 } 19529 19530 static int opt_remove_dead_code(struct bpf_verifier_env *env) 19531 { 19532 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 19533 int insn_cnt = env->prog->len; 19534 int i, err; 19535 19536 for (i = 0; i < insn_cnt; i++) { 19537 int j; 19538 19539 j = 0; 19540 while (i + j < insn_cnt && !aux_data[i + j].seen) 19541 j++; 19542 if (!j) 19543 continue; 19544 19545 err = verifier_remove_insns(env, i, j); 19546 if (err) 19547 return err; 19548 insn_cnt = env->prog->len; 19549 } 19550 19551 return 0; 19552 } 19553 19554 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 19555 19556 static int opt_remove_nops(struct bpf_verifier_env *env) 19557 { 19558 const struct bpf_insn ja = NOP; 19559 struct bpf_insn *insn = env->prog->insnsi; 19560 int insn_cnt = env->prog->len; 19561 int i, err; 19562 19563 for (i = 0; i < insn_cnt; i++) { 19564 if (memcmp(&insn[i], &ja, sizeof(ja))) 19565 continue; 19566 19567 err = verifier_remove_insns(env, i, 1); 19568 if (err) 19569 return err; 19570 insn_cnt--; 19571 i--; 19572 } 19573 19574 return 0; 19575 } 19576 19577 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 19578 const union bpf_attr *attr) 19579 { 19580 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 19581 struct bpf_insn_aux_data *aux = env->insn_aux_data; 19582 int i, patch_len, delta = 0, len = env->prog->len; 19583 struct bpf_insn *insns = env->prog->insnsi; 19584 struct bpf_prog *new_prog; 19585 bool rnd_hi32; 19586 19587 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 19588 zext_patch[1] = BPF_ZEXT_REG(0); 19589 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 19590 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 19591 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 19592 for (i = 0; i < len; i++) { 19593 int adj_idx = i + delta; 19594 struct bpf_insn insn; 19595 int load_reg; 19596 19597 insn = insns[adj_idx]; 19598 load_reg = insn_def_regno(&insn); 19599 if (!aux[adj_idx].zext_dst) { 19600 u8 code, class; 19601 u32 imm_rnd; 19602 19603 if (!rnd_hi32) 19604 continue; 19605 19606 code = insn.code; 19607 class = BPF_CLASS(code); 19608 if (load_reg == -1) 19609 continue; 19610 19611 /* NOTE: arg "reg" (the fourth one) is only used for 19612 * BPF_STX + SRC_OP, so it is safe to pass NULL 19613 * here. 19614 */ 19615 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 19616 if (class == BPF_LD && 19617 BPF_MODE(code) == BPF_IMM) 19618 i++; 19619 continue; 19620 } 19621 19622 /* ctx load could be transformed into wider load. */ 19623 if (class == BPF_LDX && 19624 aux[adj_idx].ptr_type == PTR_TO_CTX) 19625 continue; 19626 19627 imm_rnd = get_random_u32(); 19628 rnd_hi32_patch[0] = insn; 19629 rnd_hi32_patch[1].imm = imm_rnd; 19630 rnd_hi32_patch[3].dst_reg = load_reg; 19631 patch = rnd_hi32_patch; 19632 patch_len = 4; 19633 goto apply_patch_buffer; 19634 } 19635 19636 /* Add in an zero-extend instruction if a) the JIT has requested 19637 * it or b) it's a CMPXCHG. 19638 * 19639 * The latter is because: BPF_CMPXCHG always loads a value into 19640 * R0, therefore always zero-extends. However some archs' 19641 * equivalent instruction only does this load when the 19642 * comparison is successful. This detail of CMPXCHG is 19643 * orthogonal to the general zero-extension behaviour of the 19644 * CPU, so it's treated independently of bpf_jit_needs_zext. 19645 */ 19646 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 19647 continue; 19648 19649 /* Zero-extension is done by the caller. */ 19650 if (bpf_pseudo_kfunc_call(&insn)) 19651 continue; 19652 19653 if (WARN_ON(load_reg == -1)) { 19654 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 19655 return -EFAULT; 19656 } 19657 19658 zext_patch[0] = insn; 19659 zext_patch[1].dst_reg = load_reg; 19660 zext_patch[1].src_reg = load_reg; 19661 patch = zext_patch; 19662 patch_len = 2; 19663 apply_patch_buffer: 19664 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 19665 if (!new_prog) 19666 return -ENOMEM; 19667 env->prog = new_prog; 19668 insns = new_prog->insnsi; 19669 aux = env->insn_aux_data; 19670 delta += patch_len - 1; 19671 } 19672 19673 return 0; 19674 } 19675 19676 /* convert load instructions that access fields of a context type into a 19677 * sequence of instructions that access fields of the underlying structure: 19678 * struct __sk_buff -> struct sk_buff 19679 * struct bpf_sock_ops -> struct sock 19680 */ 19681 static int convert_ctx_accesses(struct bpf_verifier_env *env) 19682 { 19683 struct bpf_subprog_info *subprogs = env->subprog_info; 19684 const struct bpf_verifier_ops *ops = env->ops; 19685 int i, cnt, size, ctx_field_size, delta = 0, epilogue_cnt = 0; 19686 const int insn_cnt = env->prog->len; 19687 struct bpf_insn *epilogue_buf = env->epilogue_buf; 19688 struct bpf_insn *insn_buf = env->insn_buf; 19689 struct bpf_insn *insn; 19690 u32 target_size, size_default, off; 19691 struct bpf_prog *new_prog; 19692 enum bpf_access_type type; 19693 bool is_narrower_load; 19694 int epilogue_idx = 0; 19695 19696 if (ops->gen_epilogue) { 19697 epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog, 19698 -(subprogs[0].stack_depth + 8)); 19699 if (epilogue_cnt >= INSN_BUF_SIZE) { 19700 verbose(env, "bpf verifier is misconfigured\n"); 19701 return -EINVAL; 19702 } else if (epilogue_cnt) { 19703 /* Save the ARG_PTR_TO_CTX for the epilogue to use */ 19704 cnt = 0; 19705 subprogs[0].stack_depth += 8; 19706 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1, 19707 -subprogs[0].stack_depth); 19708 insn_buf[cnt++] = env->prog->insnsi[0]; 19709 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 19710 if (!new_prog) 19711 return -ENOMEM; 19712 env->prog = new_prog; 19713 delta += cnt - 1; 19714 } 19715 } 19716 19717 if (ops->gen_prologue || env->seen_direct_write) { 19718 if (!ops->gen_prologue) { 19719 verbose(env, "bpf verifier is misconfigured\n"); 19720 return -EINVAL; 19721 } 19722 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 19723 env->prog); 19724 if (cnt >= INSN_BUF_SIZE) { 19725 verbose(env, "bpf verifier is misconfigured\n"); 19726 return -EINVAL; 19727 } else if (cnt) { 19728 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 19729 if (!new_prog) 19730 return -ENOMEM; 19731 19732 env->prog = new_prog; 19733 delta += cnt - 1; 19734 } 19735 } 19736 19737 if (delta) 19738 WARN_ON(adjust_jmp_off(env->prog, 0, delta)); 19739 19740 if (bpf_prog_is_offloaded(env->prog->aux)) 19741 return 0; 19742 19743 insn = env->prog->insnsi + delta; 19744 19745 for (i = 0; i < insn_cnt; i++, insn++) { 19746 bpf_convert_ctx_access_t convert_ctx_access; 19747 u8 mode; 19748 19749 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 19750 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 19751 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 19752 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 19753 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 19754 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 19755 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 19756 type = BPF_READ; 19757 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 19758 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 19759 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 19760 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 19761 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 19762 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 19763 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 19764 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 19765 type = BPF_WRITE; 19766 } else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) || 19767 insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) && 19768 env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) { 19769 insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code); 19770 env->prog->aux->num_exentries++; 19771 continue; 19772 } else if (insn->code == (BPF_JMP | BPF_EXIT) && 19773 epilogue_cnt && 19774 i + delta < subprogs[1].start) { 19775 /* Generate epilogue for the main prog */ 19776 if (epilogue_idx) { 19777 /* jump back to the earlier generated epilogue */ 19778 insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1); 19779 cnt = 1; 19780 } else { 19781 memcpy(insn_buf, epilogue_buf, 19782 epilogue_cnt * sizeof(*epilogue_buf)); 19783 cnt = epilogue_cnt; 19784 /* epilogue_idx cannot be 0. It must have at 19785 * least one ctx ptr saving insn before the 19786 * epilogue. 19787 */ 19788 epilogue_idx = i + delta; 19789 } 19790 goto patch_insn_buf; 19791 } else { 19792 continue; 19793 } 19794 19795 if (type == BPF_WRITE && 19796 env->insn_aux_data[i + delta].sanitize_stack_spill) { 19797 struct bpf_insn patch[] = { 19798 *insn, 19799 BPF_ST_NOSPEC(), 19800 }; 19801 19802 cnt = ARRAY_SIZE(patch); 19803 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 19804 if (!new_prog) 19805 return -ENOMEM; 19806 19807 delta += cnt - 1; 19808 env->prog = new_prog; 19809 insn = new_prog->insnsi + i + delta; 19810 continue; 19811 } 19812 19813 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 19814 case PTR_TO_CTX: 19815 if (!ops->convert_ctx_access) 19816 continue; 19817 convert_ctx_access = ops->convert_ctx_access; 19818 break; 19819 case PTR_TO_SOCKET: 19820 case PTR_TO_SOCK_COMMON: 19821 convert_ctx_access = bpf_sock_convert_ctx_access; 19822 break; 19823 case PTR_TO_TCP_SOCK: 19824 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 19825 break; 19826 case PTR_TO_XDP_SOCK: 19827 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 19828 break; 19829 case PTR_TO_BTF_ID: 19830 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 19831 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 19832 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 19833 * be said once it is marked PTR_UNTRUSTED, hence we must handle 19834 * any faults for loads into such types. BPF_WRITE is disallowed 19835 * for this case. 19836 */ 19837 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 19838 if (type == BPF_READ) { 19839 if (BPF_MODE(insn->code) == BPF_MEM) 19840 insn->code = BPF_LDX | BPF_PROBE_MEM | 19841 BPF_SIZE((insn)->code); 19842 else 19843 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 19844 BPF_SIZE((insn)->code); 19845 env->prog->aux->num_exentries++; 19846 } 19847 continue; 19848 case PTR_TO_ARENA: 19849 if (BPF_MODE(insn->code) == BPF_MEMSX) { 19850 verbose(env, "sign extending loads from arena are not supported yet\n"); 19851 return -EOPNOTSUPP; 19852 } 19853 insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code); 19854 env->prog->aux->num_exentries++; 19855 continue; 19856 default: 19857 continue; 19858 } 19859 19860 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 19861 size = BPF_LDST_BYTES(insn); 19862 mode = BPF_MODE(insn->code); 19863 19864 /* If the read access is a narrower load of the field, 19865 * convert to a 4/8-byte load, to minimum program type specific 19866 * convert_ctx_access changes. If conversion is successful, 19867 * we will apply proper mask to the result. 19868 */ 19869 is_narrower_load = size < ctx_field_size; 19870 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 19871 off = insn->off; 19872 if (is_narrower_load) { 19873 u8 size_code; 19874 19875 if (type == BPF_WRITE) { 19876 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 19877 return -EINVAL; 19878 } 19879 19880 size_code = BPF_H; 19881 if (ctx_field_size == 4) 19882 size_code = BPF_W; 19883 else if (ctx_field_size == 8) 19884 size_code = BPF_DW; 19885 19886 insn->off = off & ~(size_default - 1); 19887 insn->code = BPF_LDX | BPF_MEM | size_code; 19888 } 19889 19890 target_size = 0; 19891 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 19892 &target_size); 19893 if (cnt == 0 || cnt >= INSN_BUF_SIZE || 19894 (ctx_field_size && !target_size)) { 19895 verbose(env, "bpf verifier is misconfigured\n"); 19896 return -EINVAL; 19897 } 19898 19899 if (is_narrower_load && size < target_size) { 19900 u8 shift = bpf_ctx_narrow_access_offset( 19901 off, size, size_default) * 8; 19902 if (shift && cnt + 1 >= INSN_BUF_SIZE) { 19903 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 19904 return -EINVAL; 19905 } 19906 if (ctx_field_size <= 4) { 19907 if (shift) 19908 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 19909 insn->dst_reg, 19910 shift); 19911 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 19912 (1 << size * 8) - 1); 19913 } else { 19914 if (shift) 19915 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 19916 insn->dst_reg, 19917 shift); 19918 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 19919 (1ULL << size * 8) - 1); 19920 } 19921 } 19922 if (mode == BPF_MEMSX) 19923 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 19924 insn->dst_reg, insn->dst_reg, 19925 size * 8, 0); 19926 19927 patch_insn_buf: 19928 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19929 if (!new_prog) 19930 return -ENOMEM; 19931 19932 delta += cnt - 1; 19933 19934 /* keep walking new program and skip insns we just inserted */ 19935 env->prog = new_prog; 19936 insn = new_prog->insnsi + i + delta; 19937 } 19938 19939 return 0; 19940 } 19941 19942 static int jit_subprogs(struct bpf_verifier_env *env) 19943 { 19944 struct bpf_prog *prog = env->prog, **func, *tmp; 19945 int i, j, subprog_start, subprog_end = 0, len, subprog; 19946 struct bpf_map *map_ptr; 19947 struct bpf_insn *insn; 19948 void *old_bpf_func; 19949 int err, num_exentries; 19950 19951 if (env->subprog_cnt <= 1) 19952 return 0; 19953 19954 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 19955 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 19956 continue; 19957 19958 /* Upon error here we cannot fall back to interpreter but 19959 * need a hard reject of the program. Thus -EFAULT is 19960 * propagated in any case. 19961 */ 19962 subprog = find_subprog(env, i + insn->imm + 1); 19963 if (subprog < 0) { 19964 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 19965 i + insn->imm + 1); 19966 return -EFAULT; 19967 } 19968 /* temporarily remember subprog id inside insn instead of 19969 * aux_data, since next loop will split up all insns into funcs 19970 */ 19971 insn->off = subprog; 19972 /* remember original imm in case JIT fails and fallback 19973 * to interpreter will be needed 19974 */ 19975 env->insn_aux_data[i].call_imm = insn->imm; 19976 /* point imm to __bpf_call_base+1 from JITs point of view */ 19977 insn->imm = 1; 19978 if (bpf_pseudo_func(insn)) { 19979 #if defined(MODULES_VADDR) 19980 u64 addr = MODULES_VADDR; 19981 #else 19982 u64 addr = VMALLOC_START; 19983 #endif 19984 /* jit (e.g. x86_64) may emit fewer instructions 19985 * if it learns a u32 imm is the same as a u64 imm. 19986 * Set close enough to possible prog address. 19987 */ 19988 insn[0].imm = (u32)addr; 19989 insn[1].imm = addr >> 32; 19990 } 19991 } 19992 19993 err = bpf_prog_alloc_jited_linfo(prog); 19994 if (err) 19995 goto out_undo_insn; 19996 19997 err = -ENOMEM; 19998 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 19999 if (!func) 20000 goto out_undo_insn; 20001 20002 for (i = 0; i < env->subprog_cnt; i++) { 20003 subprog_start = subprog_end; 20004 subprog_end = env->subprog_info[i + 1].start; 20005 20006 len = subprog_end - subprog_start; 20007 /* bpf_prog_run() doesn't call subprogs directly, 20008 * hence main prog stats include the runtime of subprogs. 20009 * subprogs don't have IDs and not reachable via prog_get_next_id 20010 * func[i]->stats will never be accessed and stays NULL 20011 */ 20012 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 20013 if (!func[i]) 20014 goto out_free; 20015 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 20016 len * sizeof(struct bpf_insn)); 20017 func[i]->type = prog->type; 20018 func[i]->len = len; 20019 if (bpf_prog_calc_tag(func[i])) 20020 goto out_free; 20021 func[i]->is_func = 1; 20022 func[i]->sleepable = prog->sleepable; 20023 func[i]->aux->func_idx = i; 20024 /* Below members will be freed only at prog->aux */ 20025 func[i]->aux->btf = prog->aux->btf; 20026 func[i]->aux->func_info = prog->aux->func_info; 20027 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 20028 func[i]->aux->poke_tab = prog->aux->poke_tab; 20029 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 20030 20031 for (j = 0; j < prog->aux->size_poke_tab; j++) { 20032 struct bpf_jit_poke_descriptor *poke; 20033 20034 poke = &prog->aux->poke_tab[j]; 20035 if (poke->insn_idx < subprog_end && 20036 poke->insn_idx >= subprog_start) 20037 poke->aux = func[i]->aux; 20038 } 20039 20040 func[i]->aux->name[0] = 'F'; 20041 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 20042 func[i]->jit_requested = 1; 20043 func[i]->blinding_requested = prog->blinding_requested; 20044 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 20045 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 20046 func[i]->aux->linfo = prog->aux->linfo; 20047 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 20048 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 20049 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 20050 func[i]->aux->arena = prog->aux->arena; 20051 num_exentries = 0; 20052 insn = func[i]->insnsi; 20053 for (j = 0; j < func[i]->len; j++, insn++) { 20054 if (BPF_CLASS(insn->code) == BPF_LDX && 20055 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 20056 BPF_MODE(insn->code) == BPF_PROBE_MEM32 || 20057 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 20058 num_exentries++; 20059 if ((BPF_CLASS(insn->code) == BPF_STX || 20060 BPF_CLASS(insn->code) == BPF_ST) && 20061 BPF_MODE(insn->code) == BPF_PROBE_MEM32) 20062 num_exentries++; 20063 if (BPF_CLASS(insn->code) == BPF_STX && 20064 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) 20065 num_exentries++; 20066 } 20067 func[i]->aux->num_exentries = num_exentries; 20068 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 20069 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb; 20070 if (!i) 20071 func[i]->aux->exception_boundary = env->seen_exception; 20072 func[i] = bpf_int_jit_compile(func[i]); 20073 if (!func[i]->jited) { 20074 err = -ENOTSUPP; 20075 goto out_free; 20076 } 20077 cond_resched(); 20078 } 20079 20080 /* at this point all bpf functions were successfully JITed 20081 * now populate all bpf_calls with correct addresses and 20082 * run last pass of JIT 20083 */ 20084 for (i = 0; i < env->subprog_cnt; i++) { 20085 insn = func[i]->insnsi; 20086 for (j = 0; j < func[i]->len; j++, insn++) { 20087 if (bpf_pseudo_func(insn)) { 20088 subprog = insn->off; 20089 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 20090 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 20091 continue; 20092 } 20093 if (!bpf_pseudo_call(insn)) 20094 continue; 20095 subprog = insn->off; 20096 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 20097 } 20098 20099 /* we use the aux data to keep a list of the start addresses 20100 * of the JITed images for each function in the program 20101 * 20102 * for some architectures, such as powerpc64, the imm field 20103 * might not be large enough to hold the offset of the start 20104 * address of the callee's JITed image from __bpf_call_base 20105 * 20106 * in such cases, we can lookup the start address of a callee 20107 * by using its subprog id, available from the off field of 20108 * the call instruction, as an index for this list 20109 */ 20110 func[i]->aux->func = func; 20111 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 20112 func[i]->aux->real_func_cnt = env->subprog_cnt; 20113 } 20114 for (i = 0; i < env->subprog_cnt; i++) { 20115 old_bpf_func = func[i]->bpf_func; 20116 tmp = bpf_int_jit_compile(func[i]); 20117 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 20118 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 20119 err = -ENOTSUPP; 20120 goto out_free; 20121 } 20122 cond_resched(); 20123 } 20124 20125 /* finally lock prog and jit images for all functions and 20126 * populate kallsysm. Begin at the first subprogram, since 20127 * bpf_prog_load will add the kallsyms for the main program. 20128 */ 20129 for (i = 1; i < env->subprog_cnt; i++) { 20130 err = bpf_prog_lock_ro(func[i]); 20131 if (err) 20132 goto out_free; 20133 } 20134 20135 for (i = 1; i < env->subprog_cnt; i++) 20136 bpf_prog_kallsyms_add(func[i]); 20137 20138 /* Last step: make now unused interpreter insns from main 20139 * prog consistent for later dump requests, so they can 20140 * later look the same as if they were interpreted only. 20141 */ 20142 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 20143 if (bpf_pseudo_func(insn)) { 20144 insn[0].imm = env->insn_aux_data[i].call_imm; 20145 insn[1].imm = insn->off; 20146 insn->off = 0; 20147 continue; 20148 } 20149 if (!bpf_pseudo_call(insn)) 20150 continue; 20151 insn->off = env->insn_aux_data[i].call_imm; 20152 subprog = find_subprog(env, i + insn->off + 1); 20153 insn->imm = subprog; 20154 } 20155 20156 prog->jited = 1; 20157 prog->bpf_func = func[0]->bpf_func; 20158 prog->jited_len = func[0]->jited_len; 20159 prog->aux->extable = func[0]->aux->extable; 20160 prog->aux->num_exentries = func[0]->aux->num_exentries; 20161 prog->aux->func = func; 20162 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 20163 prog->aux->real_func_cnt = env->subprog_cnt; 20164 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func; 20165 prog->aux->exception_boundary = func[0]->aux->exception_boundary; 20166 bpf_prog_jit_attempt_done(prog); 20167 return 0; 20168 out_free: 20169 /* We failed JIT'ing, so at this point we need to unregister poke 20170 * descriptors from subprogs, so that kernel is not attempting to 20171 * patch it anymore as we're freeing the subprog JIT memory. 20172 */ 20173 for (i = 0; i < prog->aux->size_poke_tab; i++) { 20174 map_ptr = prog->aux->poke_tab[i].tail_call.map; 20175 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 20176 } 20177 /* At this point we're guaranteed that poke descriptors are not 20178 * live anymore. We can just unlink its descriptor table as it's 20179 * released with the main prog. 20180 */ 20181 for (i = 0; i < env->subprog_cnt; i++) { 20182 if (!func[i]) 20183 continue; 20184 func[i]->aux->poke_tab = NULL; 20185 bpf_jit_free(func[i]); 20186 } 20187 kfree(func); 20188 out_undo_insn: 20189 /* cleanup main prog to be interpreted */ 20190 prog->jit_requested = 0; 20191 prog->blinding_requested = 0; 20192 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 20193 if (!bpf_pseudo_call(insn)) 20194 continue; 20195 insn->off = 0; 20196 insn->imm = env->insn_aux_data[i].call_imm; 20197 } 20198 bpf_prog_jit_attempt_done(prog); 20199 return err; 20200 } 20201 20202 static int fixup_call_args(struct bpf_verifier_env *env) 20203 { 20204 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 20205 struct bpf_prog *prog = env->prog; 20206 struct bpf_insn *insn = prog->insnsi; 20207 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 20208 int i, depth; 20209 #endif 20210 int err = 0; 20211 20212 if (env->prog->jit_requested && 20213 !bpf_prog_is_offloaded(env->prog->aux)) { 20214 err = jit_subprogs(env); 20215 if (err == 0) 20216 return 0; 20217 if (err == -EFAULT) 20218 return err; 20219 } 20220 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 20221 if (has_kfunc_call) { 20222 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 20223 return -EINVAL; 20224 } 20225 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 20226 /* When JIT fails the progs with bpf2bpf calls and tail_calls 20227 * have to be rejected, since interpreter doesn't support them yet. 20228 */ 20229 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 20230 return -EINVAL; 20231 } 20232 for (i = 0; i < prog->len; i++, insn++) { 20233 if (bpf_pseudo_func(insn)) { 20234 /* When JIT fails the progs with callback calls 20235 * have to be rejected, since interpreter doesn't support them yet. 20236 */ 20237 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 20238 return -EINVAL; 20239 } 20240 20241 if (!bpf_pseudo_call(insn)) 20242 continue; 20243 depth = get_callee_stack_depth(env, insn, i); 20244 if (depth < 0) 20245 return depth; 20246 bpf_patch_call_args(insn, depth); 20247 } 20248 err = 0; 20249 #endif 20250 return err; 20251 } 20252 20253 /* replace a generic kfunc with a specialized version if necessary */ 20254 static void specialize_kfunc(struct bpf_verifier_env *env, 20255 u32 func_id, u16 offset, unsigned long *addr) 20256 { 20257 struct bpf_prog *prog = env->prog; 20258 bool seen_direct_write; 20259 void *xdp_kfunc; 20260 bool is_rdonly; 20261 20262 if (bpf_dev_bound_kfunc_id(func_id)) { 20263 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 20264 if (xdp_kfunc) { 20265 *addr = (unsigned long)xdp_kfunc; 20266 return; 20267 } 20268 /* fallback to default kfunc when not supported by netdev */ 20269 } 20270 20271 if (offset) 20272 return; 20273 20274 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 20275 seen_direct_write = env->seen_direct_write; 20276 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 20277 20278 if (is_rdonly) 20279 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 20280 20281 /* restore env->seen_direct_write to its original value, since 20282 * may_access_direct_pkt_data mutates it 20283 */ 20284 env->seen_direct_write = seen_direct_write; 20285 } 20286 } 20287 20288 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 20289 u16 struct_meta_reg, 20290 u16 node_offset_reg, 20291 struct bpf_insn *insn, 20292 struct bpf_insn *insn_buf, 20293 int *cnt) 20294 { 20295 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 20296 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 20297 20298 insn_buf[0] = addr[0]; 20299 insn_buf[1] = addr[1]; 20300 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 20301 insn_buf[3] = *insn; 20302 *cnt = 4; 20303 } 20304 20305 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 20306 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 20307 { 20308 const struct bpf_kfunc_desc *desc; 20309 20310 if (!insn->imm) { 20311 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 20312 return -EINVAL; 20313 } 20314 20315 *cnt = 0; 20316 20317 /* insn->imm has the btf func_id. Replace it with an offset relative to 20318 * __bpf_call_base, unless the JIT needs to call functions that are 20319 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 20320 */ 20321 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 20322 if (!desc) { 20323 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 20324 insn->imm); 20325 return -EFAULT; 20326 } 20327 20328 if (!bpf_jit_supports_far_kfunc_call()) 20329 insn->imm = BPF_CALL_IMM(desc->addr); 20330 if (insn->off) 20331 return 0; 20332 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 20333 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 20334 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 20335 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 20336 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 20337 20338 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) { 20339 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 20340 insn_idx); 20341 return -EFAULT; 20342 } 20343 20344 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 20345 insn_buf[1] = addr[0]; 20346 insn_buf[2] = addr[1]; 20347 insn_buf[3] = *insn; 20348 *cnt = 4; 20349 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 20350 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] || 20351 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 20352 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 20353 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 20354 20355 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) { 20356 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 20357 insn_idx); 20358 return -EFAULT; 20359 } 20360 20361 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 20362 !kptr_struct_meta) { 20363 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 20364 insn_idx); 20365 return -EFAULT; 20366 } 20367 20368 insn_buf[0] = addr[0]; 20369 insn_buf[1] = addr[1]; 20370 insn_buf[2] = *insn; 20371 *cnt = 3; 20372 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 20373 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 20374 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 20375 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 20376 int struct_meta_reg = BPF_REG_3; 20377 int node_offset_reg = BPF_REG_4; 20378 20379 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 20380 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 20381 struct_meta_reg = BPF_REG_4; 20382 node_offset_reg = BPF_REG_5; 20383 } 20384 20385 if (!kptr_struct_meta) { 20386 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 20387 insn_idx); 20388 return -EFAULT; 20389 } 20390 20391 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 20392 node_offset_reg, insn, insn_buf, cnt); 20393 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 20394 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 20395 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 20396 *cnt = 1; 20397 } else if (is_bpf_wq_set_callback_impl_kfunc(desc->func_id)) { 20398 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(BPF_REG_4, (long)env->prog->aux) }; 20399 20400 insn_buf[0] = ld_addrs[0]; 20401 insn_buf[1] = ld_addrs[1]; 20402 insn_buf[2] = *insn; 20403 *cnt = 3; 20404 } 20405 return 0; 20406 } 20407 20408 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */ 20409 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len) 20410 { 20411 struct bpf_subprog_info *info = env->subprog_info; 20412 int cnt = env->subprog_cnt; 20413 struct bpf_prog *prog; 20414 20415 /* We only reserve one slot for hidden subprogs in subprog_info. */ 20416 if (env->hidden_subprog_cnt) { 20417 verbose(env, "verifier internal error: only one hidden subprog supported\n"); 20418 return -EFAULT; 20419 } 20420 /* We're not patching any existing instruction, just appending the new 20421 * ones for the hidden subprog. Hence all of the adjustment operations 20422 * in bpf_patch_insn_data are no-ops. 20423 */ 20424 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len); 20425 if (!prog) 20426 return -ENOMEM; 20427 env->prog = prog; 20428 info[cnt + 1].start = info[cnt].start; 20429 info[cnt].start = prog->len - len + 1; 20430 env->subprog_cnt++; 20431 env->hidden_subprog_cnt++; 20432 return 0; 20433 } 20434 20435 /* Do various post-verification rewrites in a single program pass. 20436 * These rewrites simplify JIT and interpreter implementations. 20437 */ 20438 static int do_misc_fixups(struct bpf_verifier_env *env) 20439 { 20440 struct bpf_prog *prog = env->prog; 20441 enum bpf_attach_type eatype = prog->expected_attach_type; 20442 enum bpf_prog_type prog_type = resolve_prog_type(prog); 20443 struct bpf_insn *insn = prog->insnsi; 20444 const struct bpf_func_proto *fn; 20445 const int insn_cnt = prog->len; 20446 const struct bpf_map_ops *ops; 20447 struct bpf_insn_aux_data *aux; 20448 struct bpf_insn *insn_buf = env->insn_buf; 20449 struct bpf_prog *new_prog; 20450 struct bpf_map *map_ptr; 20451 int i, ret, cnt, delta = 0, cur_subprog = 0; 20452 struct bpf_subprog_info *subprogs = env->subprog_info; 20453 u16 stack_depth = subprogs[cur_subprog].stack_depth; 20454 u16 stack_depth_extra = 0; 20455 20456 if (env->seen_exception && !env->exception_callback_subprog) { 20457 struct bpf_insn patch[] = { 20458 env->prog->insnsi[insn_cnt - 1], 20459 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1), 20460 BPF_EXIT_INSN(), 20461 }; 20462 20463 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch)); 20464 if (ret < 0) 20465 return ret; 20466 prog = env->prog; 20467 insn = prog->insnsi; 20468 20469 env->exception_callback_subprog = env->subprog_cnt - 1; 20470 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */ 20471 mark_subprog_exc_cb(env, env->exception_callback_subprog); 20472 } 20473 20474 for (i = 0; i < insn_cnt;) { 20475 if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) { 20476 if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) || 20477 (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) { 20478 /* convert to 32-bit mov that clears upper 32-bit */ 20479 insn->code = BPF_ALU | BPF_MOV | BPF_X; 20480 /* clear off and imm, so it's a normal 'wX = wY' from JIT pov */ 20481 insn->off = 0; 20482 insn->imm = 0; 20483 } /* cast from as(0) to as(1) should be handled by JIT */ 20484 goto next_insn; 20485 } 20486 20487 if (env->insn_aux_data[i + delta].needs_zext) 20488 /* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */ 20489 insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code); 20490 20491 /* Make sdiv/smod divide-by-minus-one exceptions impossible. */ 20492 if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) || 20493 insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) || 20494 insn->code == (BPF_ALU | BPF_MOD | BPF_K) || 20495 insn->code == (BPF_ALU | BPF_DIV | BPF_K)) && 20496 insn->off == 1 && insn->imm == -1) { 20497 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 20498 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 20499 struct bpf_insn *patchlet; 20500 struct bpf_insn chk_and_sdiv[] = { 20501 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 20502 BPF_NEG | BPF_K, insn->dst_reg, 20503 0, 0, 0), 20504 }; 20505 struct bpf_insn chk_and_smod[] = { 20506 BPF_MOV32_IMM(insn->dst_reg, 0), 20507 }; 20508 20509 patchlet = isdiv ? chk_and_sdiv : chk_and_smod; 20510 cnt = isdiv ? ARRAY_SIZE(chk_and_sdiv) : ARRAY_SIZE(chk_and_smod); 20511 20512 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 20513 if (!new_prog) 20514 return -ENOMEM; 20515 20516 delta += cnt - 1; 20517 env->prog = prog = new_prog; 20518 insn = new_prog->insnsi + i + delta; 20519 goto next_insn; 20520 } 20521 20522 /* Make divide-by-zero and divide-by-minus-one exceptions impossible. */ 20523 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 20524 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 20525 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 20526 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 20527 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 20528 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 20529 bool is_sdiv = isdiv && insn->off == 1; 20530 bool is_smod = !isdiv && insn->off == 1; 20531 struct bpf_insn *patchlet; 20532 struct bpf_insn chk_and_div[] = { 20533 /* [R,W]x div 0 -> 0 */ 20534 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 20535 BPF_JNE | BPF_K, insn->src_reg, 20536 0, 2, 0), 20537 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 20538 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 20539 *insn, 20540 }; 20541 struct bpf_insn chk_and_mod[] = { 20542 /* [R,W]x mod 0 -> [R,W]x */ 20543 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 20544 BPF_JEQ | BPF_K, insn->src_reg, 20545 0, 1 + (is64 ? 0 : 1), 0), 20546 *insn, 20547 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 20548 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 20549 }; 20550 struct bpf_insn chk_and_sdiv[] = { 20551 /* [R,W]x sdiv 0 -> 0 20552 * LLONG_MIN sdiv -1 -> LLONG_MIN 20553 * INT_MIN sdiv -1 -> INT_MIN 20554 */ 20555 BPF_MOV64_REG(BPF_REG_AX, insn->src_reg), 20556 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 20557 BPF_ADD | BPF_K, BPF_REG_AX, 20558 0, 0, 1), 20559 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 20560 BPF_JGT | BPF_K, BPF_REG_AX, 20561 0, 4, 1), 20562 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 20563 BPF_JEQ | BPF_K, BPF_REG_AX, 20564 0, 1, 0), 20565 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 20566 BPF_MOV | BPF_K, insn->dst_reg, 20567 0, 0, 0), 20568 /* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */ 20569 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 20570 BPF_NEG | BPF_K, insn->dst_reg, 20571 0, 0, 0), 20572 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 20573 *insn, 20574 }; 20575 struct bpf_insn chk_and_smod[] = { 20576 /* [R,W]x mod 0 -> [R,W]x */ 20577 /* [R,W]x mod -1 -> 0 */ 20578 BPF_MOV64_REG(BPF_REG_AX, insn->src_reg), 20579 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 20580 BPF_ADD | BPF_K, BPF_REG_AX, 20581 0, 0, 1), 20582 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 20583 BPF_JGT | BPF_K, BPF_REG_AX, 20584 0, 3, 1), 20585 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 20586 BPF_JEQ | BPF_K, BPF_REG_AX, 20587 0, 3 + (is64 ? 0 : 1), 1), 20588 BPF_MOV32_IMM(insn->dst_reg, 0), 20589 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 20590 *insn, 20591 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 20592 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 20593 }; 20594 20595 if (is_sdiv) { 20596 patchlet = chk_and_sdiv; 20597 cnt = ARRAY_SIZE(chk_and_sdiv); 20598 } else if (is_smod) { 20599 patchlet = chk_and_smod; 20600 cnt = ARRAY_SIZE(chk_and_smod) - (is64 ? 2 : 0); 20601 } else { 20602 patchlet = isdiv ? chk_and_div : chk_and_mod; 20603 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 20604 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 20605 } 20606 20607 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 20608 if (!new_prog) 20609 return -ENOMEM; 20610 20611 delta += cnt - 1; 20612 env->prog = prog = new_prog; 20613 insn = new_prog->insnsi + i + delta; 20614 goto next_insn; 20615 } 20616 20617 /* Make it impossible to de-reference a userspace address */ 20618 if (BPF_CLASS(insn->code) == BPF_LDX && 20619 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 20620 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) { 20621 struct bpf_insn *patch = &insn_buf[0]; 20622 u64 uaddress_limit = bpf_arch_uaddress_limit(); 20623 20624 if (!uaddress_limit) 20625 goto next_insn; 20626 20627 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg); 20628 if (insn->off) 20629 *patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off); 20630 *patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32); 20631 *patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2); 20632 *patch++ = *insn; 20633 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 20634 *patch++ = BPF_MOV64_IMM(insn->dst_reg, 0); 20635 20636 cnt = patch - insn_buf; 20637 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20638 if (!new_prog) 20639 return -ENOMEM; 20640 20641 delta += cnt - 1; 20642 env->prog = prog = new_prog; 20643 insn = new_prog->insnsi + i + delta; 20644 goto next_insn; 20645 } 20646 20647 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 20648 if (BPF_CLASS(insn->code) == BPF_LD && 20649 (BPF_MODE(insn->code) == BPF_ABS || 20650 BPF_MODE(insn->code) == BPF_IND)) { 20651 cnt = env->ops->gen_ld_abs(insn, insn_buf); 20652 if (cnt == 0 || cnt >= INSN_BUF_SIZE) { 20653 verbose(env, "bpf verifier is misconfigured\n"); 20654 return -EINVAL; 20655 } 20656 20657 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20658 if (!new_prog) 20659 return -ENOMEM; 20660 20661 delta += cnt - 1; 20662 env->prog = prog = new_prog; 20663 insn = new_prog->insnsi + i + delta; 20664 goto next_insn; 20665 } 20666 20667 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 20668 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 20669 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 20670 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 20671 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 20672 struct bpf_insn *patch = &insn_buf[0]; 20673 bool issrc, isneg, isimm; 20674 u32 off_reg; 20675 20676 aux = &env->insn_aux_data[i + delta]; 20677 if (!aux->alu_state || 20678 aux->alu_state == BPF_ALU_NON_POINTER) 20679 goto next_insn; 20680 20681 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 20682 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 20683 BPF_ALU_SANITIZE_SRC; 20684 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 20685 20686 off_reg = issrc ? insn->src_reg : insn->dst_reg; 20687 if (isimm) { 20688 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 20689 } else { 20690 if (isneg) 20691 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 20692 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 20693 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 20694 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 20695 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 20696 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 20697 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 20698 } 20699 if (!issrc) 20700 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 20701 insn->src_reg = BPF_REG_AX; 20702 if (isneg) 20703 insn->code = insn->code == code_add ? 20704 code_sub : code_add; 20705 *patch++ = *insn; 20706 if (issrc && isneg && !isimm) 20707 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 20708 cnt = patch - insn_buf; 20709 20710 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20711 if (!new_prog) 20712 return -ENOMEM; 20713 20714 delta += cnt - 1; 20715 env->prog = prog = new_prog; 20716 insn = new_prog->insnsi + i + delta; 20717 goto next_insn; 20718 } 20719 20720 if (is_may_goto_insn(insn)) { 20721 int stack_off = -stack_depth - 8; 20722 20723 stack_depth_extra = 8; 20724 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off); 20725 if (insn->off >= 0) 20726 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2); 20727 else 20728 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1); 20729 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1); 20730 insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off); 20731 cnt = 4; 20732 20733 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20734 if (!new_prog) 20735 return -ENOMEM; 20736 20737 delta += cnt - 1; 20738 env->prog = prog = new_prog; 20739 insn = new_prog->insnsi + i + delta; 20740 goto next_insn; 20741 } 20742 20743 if (insn->code != (BPF_JMP | BPF_CALL)) 20744 goto next_insn; 20745 if (insn->src_reg == BPF_PSEUDO_CALL) 20746 goto next_insn; 20747 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 20748 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 20749 if (ret) 20750 return ret; 20751 if (cnt == 0) 20752 goto next_insn; 20753 20754 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20755 if (!new_prog) 20756 return -ENOMEM; 20757 20758 delta += cnt - 1; 20759 env->prog = prog = new_prog; 20760 insn = new_prog->insnsi + i + delta; 20761 goto next_insn; 20762 } 20763 20764 /* Skip inlining the helper call if the JIT does it. */ 20765 if (bpf_jit_inlines_helper_call(insn->imm)) 20766 goto next_insn; 20767 20768 if (insn->imm == BPF_FUNC_get_route_realm) 20769 prog->dst_needed = 1; 20770 if (insn->imm == BPF_FUNC_get_prandom_u32) 20771 bpf_user_rnd_init_once(); 20772 if (insn->imm == BPF_FUNC_override_return) 20773 prog->kprobe_override = 1; 20774 if (insn->imm == BPF_FUNC_tail_call) { 20775 /* If we tail call into other programs, we 20776 * cannot make any assumptions since they can 20777 * be replaced dynamically during runtime in 20778 * the program array. 20779 */ 20780 prog->cb_access = 1; 20781 if (!allow_tail_call_in_subprogs(env)) 20782 prog->aux->stack_depth = MAX_BPF_STACK; 20783 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 20784 20785 /* mark bpf_tail_call as different opcode to avoid 20786 * conditional branch in the interpreter for every normal 20787 * call and to prevent accidental JITing by JIT compiler 20788 * that doesn't support bpf_tail_call yet 20789 */ 20790 insn->imm = 0; 20791 insn->code = BPF_JMP | BPF_TAIL_CALL; 20792 20793 aux = &env->insn_aux_data[i + delta]; 20794 if (env->bpf_capable && !prog->blinding_requested && 20795 prog->jit_requested && 20796 !bpf_map_key_poisoned(aux) && 20797 !bpf_map_ptr_poisoned(aux) && 20798 !bpf_map_ptr_unpriv(aux)) { 20799 struct bpf_jit_poke_descriptor desc = { 20800 .reason = BPF_POKE_REASON_TAIL_CALL, 20801 .tail_call.map = aux->map_ptr_state.map_ptr, 20802 .tail_call.key = bpf_map_key_immediate(aux), 20803 .insn_idx = i + delta, 20804 }; 20805 20806 ret = bpf_jit_add_poke_descriptor(prog, &desc); 20807 if (ret < 0) { 20808 verbose(env, "adding tail call poke descriptor failed\n"); 20809 return ret; 20810 } 20811 20812 insn->imm = ret + 1; 20813 goto next_insn; 20814 } 20815 20816 if (!bpf_map_ptr_unpriv(aux)) 20817 goto next_insn; 20818 20819 /* instead of changing every JIT dealing with tail_call 20820 * emit two extra insns: 20821 * if (index >= max_entries) goto out; 20822 * index &= array->index_mask; 20823 * to avoid out-of-bounds cpu speculation 20824 */ 20825 if (bpf_map_ptr_poisoned(aux)) { 20826 verbose(env, "tail_call abusing map_ptr\n"); 20827 return -EINVAL; 20828 } 20829 20830 map_ptr = aux->map_ptr_state.map_ptr; 20831 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 20832 map_ptr->max_entries, 2); 20833 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 20834 container_of(map_ptr, 20835 struct bpf_array, 20836 map)->index_mask); 20837 insn_buf[2] = *insn; 20838 cnt = 3; 20839 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20840 if (!new_prog) 20841 return -ENOMEM; 20842 20843 delta += cnt - 1; 20844 env->prog = prog = new_prog; 20845 insn = new_prog->insnsi + i + delta; 20846 goto next_insn; 20847 } 20848 20849 if (insn->imm == BPF_FUNC_timer_set_callback) { 20850 /* The verifier will process callback_fn as many times as necessary 20851 * with different maps and the register states prepared by 20852 * set_timer_callback_state will be accurate. 20853 * 20854 * The following use case is valid: 20855 * map1 is shared by prog1, prog2, prog3. 20856 * prog1 calls bpf_timer_init for some map1 elements 20857 * prog2 calls bpf_timer_set_callback for some map1 elements. 20858 * Those that were not bpf_timer_init-ed will return -EINVAL. 20859 * prog3 calls bpf_timer_start for some map1 elements. 20860 * Those that were not both bpf_timer_init-ed and 20861 * bpf_timer_set_callback-ed will return -EINVAL. 20862 */ 20863 struct bpf_insn ld_addrs[2] = { 20864 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 20865 }; 20866 20867 insn_buf[0] = ld_addrs[0]; 20868 insn_buf[1] = ld_addrs[1]; 20869 insn_buf[2] = *insn; 20870 cnt = 3; 20871 20872 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20873 if (!new_prog) 20874 return -ENOMEM; 20875 20876 delta += cnt - 1; 20877 env->prog = prog = new_prog; 20878 insn = new_prog->insnsi + i + delta; 20879 goto patch_call_imm; 20880 } 20881 20882 if (is_storage_get_function(insn->imm)) { 20883 if (!in_sleepable(env) || 20884 env->insn_aux_data[i + delta].storage_get_func_atomic) 20885 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 20886 else 20887 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 20888 insn_buf[1] = *insn; 20889 cnt = 2; 20890 20891 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20892 if (!new_prog) 20893 return -ENOMEM; 20894 20895 delta += cnt - 1; 20896 env->prog = prog = new_prog; 20897 insn = new_prog->insnsi + i + delta; 20898 goto patch_call_imm; 20899 } 20900 20901 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */ 20902 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) { 20903 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data, 20904 * bpf_mem_alloc() returns a ptr to the percpu data ptr. 20905 */ 20906 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0); 20907 insn_buf[1] = *insn; 20908 cnt = 2; 20909 20910 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20911 if (!new_prog) 20912 return -ENOMEM; 20913 20914 delta += cnt - 1; 20915 env->prog = prog = new_prog; 20916 insn = new_prog->insnsi + i + delta; 20917 goto patch_call_imm; 20918 } 20919 20920 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 20921 * and other inlining handlers are currently limited to 64 bit 20922 * only. 20923 */ 20924 if (prog->jit_requested && BITS_PER_LONG == 64 && 20925 (insn->imm == BPF_FUNC_map_lookup_elem || 20926 insn->imm == BPF_FUNC_map_update_elem || 20927 insn->imm == BPF_FUNC_map_delete_elem || 20928 insn->imm == BPF_FUNC_map_push_elem || 20929 insn->imm == BPF_FUNC_map_pop_elem || 20930 insn->imm == BPF_FUNC_map_peek_elem || 20931 insn->imm == BPF_FUNC_redirect_map || 20932 insn->imm == BPF_FUNC_for_each_map_elem || 20933 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 20934 aux = &env->insn_aux_data[i + delta]; 20935 if (bpf_map_ptr_poisoned(aux)) 20936 goto patch_call_imm; 20937 20938 map_ptr = aux->map_ptr_state.map_ptr; 20939 ops = map_ptr->ops; 20940 if (insn->imm == BPF_FUNC_map_lookup_elem && 20941 ops->map_gen_lookup) { 20942 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 20943 if (cnt == -EOPNOTSUPP) 20944 goto patch_map_ops_generic; 20945 if (cnt <= 0 || cnt >= INSN_BUF_SIZE) { 20946 verbose(env, "bpf verifier is misconfigured\n"); 20947 return -EINVAL; 20948 } 20949 20950 new_prog = bpf_patch_insn_data(env, i + delta, 20951 insn_buf, cnt); 20952 if (!new_prog) 20953 return -ENOMEM; 20954 20955 delta += cnt - 1; 20956 env->prog = prog = new_prog; 20957 insn = new_prog->insnsi + i + delta; 20958 goto next_insn; 20959 } 20960 20961 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 20962 (void *(*)(struct bpf_map *map, void *key))NULL)); 20963 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 20964 (long (*)(struct bpf_map *map, void *key))NULL)); 20965 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 20966 (long (*)(struct bpf_map *map, void *key, void *value, 20967 u64 flags))NULL)); 20968 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 20969 (long (*)(struct bpf_map *map, void *value, 20970 u64 flags))NULL)); 20971 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 20972 (long (*)(struct bpf_map *map, void *value))NULL)); 20973 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 20974 (long (*)(struct bpf_map *map, void *value))NULL)); 20975 BUILD_BUG_ON(!__same_type(ops->map_redirect, 20976 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 20977 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 20978 (long (*)(struct bpf_map *map, 20979 bpf_callback_t callback_fn, 20980 void *callback_ctx, 20981 u64 flags))NULL)); 20982 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 20983 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 20984 20985 patch_map_ops_generic: 20986 switch (insn->imm) { 20987 case BPF_FUNC_map_lookup_elem: 20988 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 20989 goto next_insn; 20990 case BPF_FUNC_map_update_elem: 20991 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 20992 goto next_insn; 20993 case BPF_FUNC_map_delete_elem: 20994 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 20995 goto next_insn; 20996 case BPF_FUNC_map_push_elem: 20997 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 20998 goto next_insn; 20999 case BPF_FUNC_map_pop_elem: 21000 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 21001 goto next_insn; 21002 case BPF_FUNC_map_peek_elem: 21003 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 21004 goto next_insn; 21005 case BPF_FUNC_redirect_map: 21006 insn->imm = BPF_CALL_IMM(ops->map_redirect); 21007 goto next_insn; 21008 case BPF_FUNC_for_each_map_elem: 21009 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 21010 goto next_insn; 21011 case BPF_FUNC_map_lookup_percpu_elem: 21012 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 21013 goto next_insn; 21014 } 21015 21016 goto patch_call_imm; 21017 } 21018 21019 /* Implement bpf_jiffies64 inline. */ 21020 if (prog->jit_requested && BITS_PER_LONG == 64 && 21021 insn->imm == BPF_FUNC_jiffies64) { 21022 struct bpf_insn ld_jiffies_addr[2] = { 21023 BPF_LD_IMM64(BPF_REG_0, 21024 (unsigned long)&jiffies), 21025 }; 21026 21027 insn_buf[0] = ld_jiffies_addr[0]; 21028 insn_buf[1] = ld_jiffies_addr[1]; 21029 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 21030 BPF_REG_0, 0); 21031 cnt = 3; 21032 21033 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 21034 cnt); 21035 if (!new_prog) 21036 return -ENOMEM; 21037 21038 delta += cnt - 1; 21039 env->prog = prog = new_prog; 21040 insn = new_prog->insnsi + i + delta; 21041 goto next_insn; 21042 } 21043 21044 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML) 21045 /* Implement bpf_get_smp_processor_id() inline. */ 21046 if (insn->imm == BPF_FUNC_get_smp_processor_id && 21047 verifier_inlines_helper_call(env, insn->imm)) { 21048 /* BPF_FUNC_get_smp_processor_id inlining is an 21049 * optimization, so if pcpu_hot.cpu_number is ever 21050 * changed in some incompatible and hard to support 21051 * way, it's fine to back out this inlining logic 21052 */ 21053 insn_buf[0] = BPF_MOV32_IMM(BPF_REG_0, (u32)(unsigned long)&pcpu_hot.cpu_number); 21054 insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0); 21055 insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0); 21056 cnt = 3; 21057 21058 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21059 if (!new_prog) 21060 return -ENOMEM; 21061 21062 delta += cnt - 1; 21063 env->prog = prog = new_prog; 21064 insn = new_prog->insnsi + i + delta; 21065 goto next_insn; 21066 } 21067 #endif 21068 /* Implement bpf_get_func_arg inline. */ 21069 if (prog_type == BPF_PROG_TYPE_TRACING && 21070 insn->imm == BPF_FUNC_get_func_arg) { 21071 /* Load nr_args from ctx - 8 */ 21072 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 21073 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 21074 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 21075 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 21076 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 21077 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 21078 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 21079 insn_buf[7] = BPF_JMP_A(1); 21080 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 21081 cnt = 9; 21082 21083 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21084 if (!new_prog) 21085 return -ENOMEM; 21086 21087 delta += cnt - 1; 21088 env->prog = prog = new_prog; 21089 insn = new_prog->insnsi + i + delta; 21090 goto next_insn; 21091 } 21092 21093 /* Implement bpf_get_func_ret inline. */ 21094 if (prog_type == BPF_PROG_TYPE_TRACING && 21095 insn->imm == BPF_FUNC_get_func_ret) { 21096 if (eatype == BPF_TRACE_FEXIT || 21097 eatype == BPF_MODIFY_RETURN) { 21098 /* Load nr_args from ctx - 8 */ 21099 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 21100 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 21101 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 21102 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 21103 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 21104 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 21105 cnt = 6; 21106 } else { 21107 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 21108 cnt = 1; 21109 } 21110 21111 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21112 if (!new_prog) 21113 return -ENOMEM; 21114 21115 delta += cnt - 1; 21116 env->prog = prog = new_prog; 21117 insn = new_prog->insnsi + i + delta; 21118 goto next_insn; 21119 } 21120 21121 /* Implement get_func_arg_cnt inline. */ 21122 if (prog_type == BPF_PROG_TYPE_TRACING && 21123 insn->imm == BPF_FUNC_get_func_arg_cnt) { 21124 /* Load nr_args from ctx - 8 */ 21125 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 21126 21127 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 21128 if (!new_prog) 21129 return -ENOMEM; 21130 21131 env->prog = prog = new_prog; 21132 insn = new_prog->insnsi + i + delta; 21133 goto next_insn; 21134 } 21135 21136 /* Implement bpf_get_func_ip inline. */ 21137 if (prog_type == BPF_PROG_TYPE_TRACING && 21138 insn->imm == BPF_FUNC_get_func_ip) { 21139 /* Load IP address from ctx - 16 */ 21140 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 21141 21142 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 21143 if (!new_prog) 21144 return -ENOMEM; 21145 21146 env->prog = prog = new_prog; 21147 insn = new_prog->insnsi + i + delta; 21148 goto next_insn; 21149 } 21150 21151 /* Implement bpf_get_branch_snapshot inline. */ 21152 if (IS_ENABLED(CONFIG_PERF_EVENTS) && 21153 prog->jit_requested && BITS_PER_LONG == 64 && 21154 insn->imm == BPF_FUNC_get_branch_snapshot) { 21155 /* We are dealing with the following func protos: 21156 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags); 21157 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt); 21158 */ 21159 const u32 br_entry_size = sizeof(struct perf_branch_entry); 21160 21161 /* struct perf_branch_entry is part of UAPI and is 21162 * used as an array element, so extremely unlikely to 21163 * ever grow or shrink 21164 */ 21165 BUILD_BUG_ON(br_entry_size != 24); 21166 21167 /* if (unlikely(flags)) return -EINVAL */ 21168 insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7); 21169 21170 /* Transform size (bytes) into number of entries (cnt = size / 24). 21171 * But to avoid expensive division instruction, we implement 21172 * divide-by-3 through multiplication, followed by further 21173 * division by 8 through 3-bit right shift. 21174 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr., 21175 * p. 227, chapter "Unsigned Division by 3" for details and proofs. 21176 * 21177 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab. 21178 */ 21179 insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab); 21180 insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0); 21181 insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36); 21182 21183 /* call perf_snapshot_branch_stack implementation */ 21184 insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack)); 21185 /* if (entry_cnt == 0) return -ENOENT */ 21186 insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4); 21187 /* return entry_cnt * sizeof(struct perf_branch_entry) */ 21188 insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size); 21189 insn_buf[7] = BPF_JMP_A(3); 21190 /* return -EINVAL; */ 21191 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 21192 insn_buf[9] = BPF_JMP_A(1); 21193 /* return -ENOENT; */ 21194 insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT); 21195 cnt = 11; 21196 21197 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21198 if (!new_prog) 21199 return -ENOMEM; 21200 21201 delta += cnt - 1; 21202 env->prog = prog = new_prog; 21203 insn = new_prog->insnsi + i + delta; 21204 continue; 21205 } 21206 21207 /* Implement bpf_kptr_xchg inline */ 21208 if (prog->jit_requested && BITS_PER_LONG == 64 && 21209 insn->imm == BPF_FUNC_kptr_xchg && 21210 bpf_jit_supports_ptr_xchg()) { 21211 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2); 21212 insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0); 21213 cnt = 2; 21214 21215 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21216 if (!new_prog) 21217 return -ENOMEM; 21218 21219 delta += cnt - 1; 21220 env->prog = prog = new_prog; 21221 insn = new_prog->insnsi + i + delta; 21222 goto next_insn; 21223 } 21224 patch_call_imm: 21225 fn = env->ops->get_func_proto(insn->imm, env->prog); 21226 /* all functions that have prototype and verifier allowed 21227 * programs to call them, must be real in-kernel functions 21228 */ 21229 if (!fn->func) { 21230 verbose(env, 21231 "kernel subsystem misconfigured func %s#%d\n", 21232 func_id_name(insn->imm), insn->imm); 21233 return -EFAULT; 21234 } 21235 insn->imm = fn->func - __bpf_call_base; 21236 next_insn: 21237 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 21238 subprogs[cur_subprog].stack_depth += stack_depth_extra; 21239 subprogs[cur_subprog].stack_extra = stack_depth_extra; 21240 cur_subprog++; 21241 stack_depth = subprogs[cur_subprog].stack_depth; 21242 stack_depth_extra = 0; 21243 } 21244 i++; 21245 insn++; 21246 } 21247 21248 env->prog->aux->stack_depth = subprogs[0].stack_depth; 21249 for (i = 0; i < env->subprog_cnt; i++) { 21250 int subprog_start = subprogs[i].start; 21251 int stack_slots = subprogs[i].stack_extra / 8; 21252 21253 if (!stack_slots) 21254 continue; 21255 if (stack_slots > 1) { 21256 verbose(env, "verifier bug: stack_slots supports may_goto only\n"); 21257 return -EFAULT; 21258 } 21259 21260 /* Add ST insn to subprog prologue to init extra stack */ 21261 insn_buf[0] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, 21262 -subprogs[i].stack_depth, BPF_MAX_LOOPS); 21263 /* Copy first actual insn to preserve it */ 21264 insn_buf[1] = env->prog->insnsi[subprog_start]; 21265 21266 new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, 2); 21267 if (!new_prog) 21268 return -ENOMEM; 21269 env->prog = prog = new_prog; 21270 /* 21271 * If may_goto is a first insn of a prog there could be a jmp 21272 * insn that points to it, hence adjust all such jmps to point 21273 * to insn after BPF_ST that inits may_goto count. 21274 * Adjustment will succeed because bpf_patch_insn_data() didn't fail. 21275 */ 21276 WARN_ON(adjust_jmp_off(env->prog, subprog_start, 1)); 21277 } 21278 21279 /* Since poke tab is now finalized, publish aux to tracker. */ 21280 for (i = 0; i < prog->aux->size_poke_tab; i++) { 21281 map_ptr = prog->aux->poke_tab[i].tail_call.map; 21282 if (!map_ptr->ops->map_poke_track || 21283 !map_ptr->ops->map_poke_untrack || 21284 !map_ptr->ops->map_poke_run) { 21285 verbose(env, "bpf verifier is misconfigured\n"); 21286 return -EINVAL; 21287 } 21288 21289 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 21290 if (ret < 0) { 21291 verbose(env, "tracking tail call prog failed\n"); 21292 return ret; 21293 } 21294 } 21295 21296 sort_kfunc_descs_by_imm_off(env->prog); 21297 21298 return 0; 21299 } 21300 21301 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 21302 int position, 21303 s32 stack_base, 21304 u32 callback_subprogno, 21305 u32 *total_cnt) 21306 { 21307 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 21308 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 21309 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 21310 int reg_loop_max = BPF_REG_6; 21311 int reg_loop_cnt = BPF_REG_7; 21312 int reg_loop_ctx = BPF_REG_8; 21313 21314 struct bpf_insn *insn_buf = env->insn_buf; 21315 struct bpf_prog *new_prog; 21316 u32 callback_start; 21317 u32 call_insn_offset; 21318 s32 callback_offset; 21319 u32 cnt = 0; 21320 21321 /* This represents an inlined version of bpf_iter.c:bpf_loop, 21322 * be careful to modify this code in sync. 21323 */ 21324 21325 /* Return error and jump to the end of the patch if 21326 * expected number of iterations is too big. 21327 */ 21328 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2); 21329 insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG); 21330 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16); 21331 /* spill R6, R7, R8 to use these as loop vars */ 21332 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset); 21333 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset); 21334 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset); 21335 /* initialize loop vars */ 21336 insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1); 21337 insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0); 21338 insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3); 21339 /* loop header, 21340 * if reg_loop_cnt >= reg_loop_max skip the loop body 21341 */ 21342 insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5); 21343 /* callback call, 21344 * correct callback offset would be set after patching 21345 */ 21346 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt); 21347 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx); 21348 insn_buf[cnt++] = BPF_CALL_REL(0); 21349 /* increment loop counter */ 21350 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1); 21351 /* jump to loop header if callback returned 0 */ 21352 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6); 21353 /* return value of bpf_loop, 21354 * set R0 to the number of iterations 21355 */ 21356 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt); 21357 /* restore original values of R6, R7, R8 */ 21358 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset); 21359 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset); 21360 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset); 21361 21362 *total_cnt = cnt; 21363 new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt); 21364 if (!new_prog) 21365 return new_prog; 21366 21367 /* callback start is known only after patching */ 21368 callback_start = env->subprog_info[callback_subprogno].start; 21369 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 21370 call_insn_offset = position + 12; 21371 callback_offset = callback_start - call_insn_offset - 1; 21372 new_prog->insnsi[call_insn_offset].imm = callback_offset; 21373 21374 return new_prog; 21375 } 21376 21377 static bool is_bpf_loop_call(struct bpf_insn *insn) 21378 { 21379 return insn->code == (BPF_JMP | BPF_CALL) && 21380 insn->src_reg == 0 && 21381 insn->imm == BPF_FUNC_loop; 21382 } 21383 21384 /* For all sub-programs in the program (including main) check 21385 * insn_aux_data to see if there are bpf_loop calls that require 21386 * inlining. If such calls are found the calls are replaced with a 21387 * sequence of instructions produced by `inline_bpf_loop` function and 21388 * subprog stack_depth is increased by the size of 3 registers. 21389 * This stack space is used to spill values of the R6, R7, R8. These 21390 * registers are used to store the loop bound, counter and context 21391 * variables. 21392 */ 21393 static int optimize_bpf_loop(struct bpf_verifier_env *env) 21394 { 21395 struct bpf_subprog_info *subprogs = env->subprog_info; 21396 int i, cur_subprog = 0, cnt, delta = 0; 21397 struct bpf_insn *insn = env->prog->insnsi; 21398 int insn_cnt = env->prog->len; 21399 u16 stack_depth = subprogs[cur_subprog].stack_depth; 21400 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 21401 u16 stack_depth_extra = 0; 21402 21403 for (i = 0; i < insn_cnt; i++, insn++) { 21404 struct bpf_loop_inline_state *inline_state = 21405 &env->insn_aux_data[i + delta].loop_inline_state; 21406 21407 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 21408 struct bpf_prog *new_prog; 21409 21410 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 21411 new_prog = inline_bpf_loop(env, 21412 i + delta, 21413 -(stack_depth + stack_depth_extra), 21414 inline_state->callback_subprogno, 21415 &cnt); 21416 if (!new_prog) 21417 return -ENOMEM; 21418 21419 delta += cnt - 1; 21420 env->prog = new_prog; 21421 insn = new_prog->insnsi + i + delta; 21422 } 21423 21424 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 21425 subprogs[cur_subprog].stack_depth += stack_depth_extra; 21426 cur_subprog++; 21427 stack_depth = subprogs[cur_subprog].stack_depth; 21428 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 21429 stack_depth_extra = 0; 21430 } 21431 } 21432 21433 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 21434 21435 return 0; 21436 } 21437 21438 /* Remove unnecessary spill/fill pairs, members of fastcall pattern, 21439 * adjust subprograms stack depth when possible. 21440 */ 21441 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env) 21442 { 21443 struct bpf_subprog_info *subprog = env->subprog_info; 21444 struct bpf_insn_aux_data *aux = env->insn_aux_data; 21445 struct bpf_insn *insn = env->prog->insnsi; 21446 int insn_cnt = env->prog->len; 21447 u32 spills_num; 21448 bool modified = false; 21449 int i, j; 21450 21451 for (i = 0; i < insn_cnt; i++, insn++) { 21452 if (aux[i].fastcall_spills_num > 0) { 21453 spills_num = aux[i].fastcall_spills_num; 21454 /* NOPs would be removed by opt_remove_nops() */ 21455 for (j = 1; j <= spills_num; ++j) { 21456 *(insn - j) = NOP; 21457 *(insn + j) = NOP; 21458 } 21459 modified = true; 21460 } 21461 if ((subprog + 1)->start == i + 1) { 21462 if (modified && !subprog->keep_fastcall_stack) 21463 subprog->stack_depth = -subprog->fastcall_stack_off; 21464 subprog++; 21465 modified = false; 21466 } 21467 } 21468 21469 return 0; 21470 } 21471 21472 static void free_states(struct bpf_verifier_env *env) 21473 { 21474 struct bpf_verifier_state_list *sl, *sln; 21475 int i; 21476 21477 sl = env->free_list; 21478 while (sl) { 21479 sln = sl->next; 21480 free_verifier_state(&sl->state, false); 21481 kfree(sl); 21482 sl = sln; 21483 } 21484 env->free_list = NULL; 21485 21486 if (!env->explored_states) 21487 return; 21488 21489 for (i = 0; i < state_htab_size(env); i++) { 21490 sl = env->explored_states[i]; 21491 21492 while (sl) { 21493 sln = sl->next; 21494 free_verifier_state(&sl->state, false); 21495 kfree(sl); 21496 sl = sln; 21497 } 21498 env->explored_states[i] = NULL; 21499 } 21500 } 21501 21502 static int do_check_common(struct bpf_verifier_env *env, int subprog) 21503 { 21504 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 21505 struct bpf_subprog_info *sub = subprog_info(env, subprog); 21506 struct bpf_verifier_state *state; 21507 struct bpf_reg_state *regs; 21508 int ret, i; 21509 21510 env->prev_linfo = NULL; 21511 env->pass_cnt++; 21512 21513 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 21514 if (!state) 21515 return -ENOMEM; 21516 state->curframe = 0; 21517 state->speculative = false; 21518 state->branches = 1; 21519 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 21520 if (!state->frame[0]) { 21521 kfree(state); 21522 return -ENOMEM; 21523 } 21524 env->cur_state = state; 21525 init_func_state(env, state->frame[0], 21526 BPF_MAIN_FUNC /* callsite */, 21527 0 /* frameno */, 21528 subprog); 21529 state->first_insn_idx = env->subprog_info[subprog].start; 21530 state->last_insn_idx = -1; 21531 21532 regs = state->frame[state->curframe]->regs; 21533 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 21534 const char *sub_name = subprog_name(env, subprog); 21535 struct bpf_subprog_arg_info *arg; 21536 struct bpf_reg_state *reg; 21537 21538 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 21539 ret = btf_prepare_func_args(env, subprog); 21540 if (ret) 21541 goto out; 21542 21543 if (subprog_is_exc_cb(env, subprog)) { 21544 state->frame[0]->in_exception_callback_fn = true; 21545 /* We have already ensured that the callback returns an integer, just 21546 * like all global subprogs. We need to determine it only has a single 21547 * scalar argument. 21548 */ 21549 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 21550 verbose(env, "exception cb only supports single integer argument\n"); 21551 ret = -EINVAL; 21552 goto out; 21553 } 21554 } 21555 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) { 21556 arg = &sub->args[i - BPF_REG_1]; 21557 reg = ®s[i]; 21558 21559 if (arg->arg_type == ARG_PTR_TO_CTX) { 21560 reg->type = PTR_TO_CTX; 21561 mark_reg_known_zero(env, regs, i); 21562 } else if (arg->arg_type == ARG_ANYTHING) { 21563 reg->type = SCALAR_VALUE; 21564 mark_reg_unknown(env, regs, i); 21565 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 21566 /* assume unspecial LOCAL dynptr type */ 21567 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen); 21568 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 21569 reg->type = PTR_TO_MEM; 21570 if (arg->arg_type & PTR_MAYBE_NULL) 21571 reg->type |= PTR_MAYBE_NULL; 21572 mark_reg_known_zero(env, regs, i); 21573 reg->mem_size = arg->mem_size; 21574 reg->id = ++env->id_gen; 21575 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 21576 reg->type = PTR_TO_BTF_ID; 21577 if (arg->arg_type & PTR_MAYBE_NULL) 21578 reg->type |= PTR_MAYBE_NULL; 21579 if (arg->arg_type & PTR_UNTRUSTED) 21580 reg->type |= PTR_UNTRUSTED; 21581 if (arg->arg_type & PTR_TRUSTED) 21582 reg->type |= PTR_TRUSTED; 21583 mark_reg_known_zero(env, regs, i); 21584 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */ 21585 reg->btf_id = arg->btf_id; 21586 reg->id = ++env->id_gen; 21587 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 21588 /* caller can pass either PTR_TO_ARENA or SCALAR */ 21589 mark_reg_unknown(env, regs, i); 21590 } else { 21591 WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n", 21592 i - BPF_REG_1, arg->arg_type); 21593 ret = -EFAULT; 21594 goto out; 21595 } 21596 } 21597 } else { 21598 /* if main BPF program has associated BTF info, validate that 21599 * it's matching expected signature, and otherwise mark BTF 21600 * info for main program as unreliable 21601 */ 21602 if (env->prog->aux->func_info_aux) { 21603 ret = btf_prepare_func_args(env, 0); 21604 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) 21605 env->prog->aux->func_info_aux[0].unreliable = true; 21606 } 21607 21608 /* 1st arg to a function */ 21609 regs[BPF_REG_1].type = PTR_TO_CTX; 21610 mark_reg_known_zero(env, regs, BPF_REG_1); 21611 } 21612 21613 ret = do_check(env); 21614 out: 21615 /* check for NULL is necessary, since cur_state can be freed inside 21616 * do_check() under memory pressure. 21617 */ 21618 if (env->cur_state) { 21619 free_verifier_state(env->cur_state, true); 21620 env->cur_state = NULL; 21621 } 21622 while (!pop_stack(env, NULL, NULL, false)); 21623 if (!ret && pop_log) 21624 bpf_vlog_reset(&env->log, 0); 21625 free_states(env); 21626 return ret; 21627 } 21628 21629 /* Lazily verify all global functions based on their BTF, if they are called 21630 * from main BPF program or any of subprograms transitively. 21631 * BPF global subprogs called from dead code are not validated. 21632 * All callable global functions must pass verification. 21633 * Otherwise the whole program is rejected. 21634 * Consider: 21635 * int bar(int); 21636 * int foo(int f) 21637 * { 21638 * return bar(f); 21639 * } 21640 * int bar(int b) 21641 * { 21642 * ... 21643 * } 21644 * foo() will be verified first for R1=any_scalar_value. During verification it 21645 * will be assumed that bar() already verified successfully and call to bar() 21646 * from foo() will be checked for type match only. Later bar() will be verified 21647 * independently to check that it's safe for R1=any_scalar_value. 21648 */ 21649 static int do_check_subprogs(struct bpf_verifier_env *env) 21650 { 21651 struct bpf_prog_aux *aux = env->prog->aux; 21652 struct bpf_func_info_aux *sub_aux; 21653 int i, ret, new_cnt; 21654 21655 if (!aux->func_info) 21656 return 0; 21657 21658 /* exception callback is presumed to be always called */ 21659 if (env->exception_callback_subprog) 21660 subprog_aux(env, env->exception_callback_subprog)->called = true; 21661 21662 again: 21663 new_cnt = 0; 21664 for (i = 1; i < env->subprog_cnt; i++) { 21665 if (!subprog_is_global(env, i)) 21666 continue; 21667 21668 sub_aux = subprog_aux(env, i); 21669 if (!sub_aux->called || sub_aux->verified) 21670 continue; 21671 21672 env->insn_idx = env->subprog_info[i].start; 21673 WARN_ON_ONCE(env->insn_idx == 0); 21674 ret = do_check_common(env, i); 21675 if (ret) { 21676 return ret; 21677 } else if (env->log.level & BPF_LOG_LEVEL) { 21678 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 21679 i, subprog_name(env, i)); 21680 } 21681 21682 /* We verified new global subprog, it might have called some 21683 * more global subprogs that we haven't verified yet, so we 21684 * need to do another pass over subprogs to verify those. 21685 */ 21686 sub_aux->verified = true; 21687 new_cnt++; 21688 } 21689 21690 /* We can't loop forever as we verify at least one global subprog on 21691 * each pass. 21692 */ 21693 if (new_cnt) 21694 goto again; 21695 21696 return 0; 21697 } 21698 21699 static int do_check_main(struct bpf_verifier_env *env) 21700 { 21701 int ret; 21702 21703 env->insn_idx = 0; 21704 ret = do_check_common(env, 0); 21705 if (!ret) 21706 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 21707 return ret; 21708 } 21709 21710 21711 static void print_verification_stats(struct bpf_verifier_env *env) 21712 { 21713 int i; 21714 21715 if (env->log.level & BPF_LOG_STATS) { 21716 verbose(env, "verification time %lld usec\n", 21717 div_u64(env->verification_time, 1000)); 21718 verbose(env, "stack depth "); 21719 for (i = 0; i < env->subprog_cnt; i++) { 21720 u32 depth = env->subprog_info[i].stack_depth; 21721 21722 verbose(env, "%d", depth); 21723 if (i + 1 < env->subprog_cnt) 21724 verbose(env, "+"); 21725 } 21726 verbose(env, "\n"); 21727 } 21728 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 21729 "total_states %d peak_states %d mark_read %d\n", 21730 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 21731 env->max_states_per_insn, env->total_states, 21732 env->peak_states, env->longest_mark_read_walk); 21733 } 21734 21735 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 21736 { 21737 const struct btf_type *t, *func_proto; 21738 const struct bpf_struct_ops_desc *st_ops_desc; 21739 const struct bpf_struct_ops *st_ops; 21740 const struct btf_member *member; 21741 struct bpf_prog *prog = env->prog; 21742 u32 btf_id, member_idx; 21743 struct btf *btf; 21744 const char *mname; 21745 int err; 21746 21747 if (!prog->gpl_compatible) { 21748 verbose(env, "struct ops programs must have a GPL compatible license\n"); 21749 return -EINVAL; 21750 } 21751 21752 if (!prog->aux->attach_btf_id) 21753 return -ENOTSUPP; 21754 21755 btf = prog->aux->attach_btf; 21756 if (btf_is_module(btf)) { 21757 /* Make sure st_ops is valid through the lifetime of env */ 21758 env->attach_btf_mod = btf_try_get_module(btf); 21759 if (!env->attach_btf_mod) { 21760 verbose(env, "struct_ops module %s is not found\n", 21761 btf_get_name(btf)); 21762 return -ENOTSUPP; 21763 } 21764 } 21765 21766 btf_id = prog->aux->attach_btf_id; 21767 st_ops_desc = bpf_struct_ops_find(btf, btf_id); 21768 if (!st_ops_desc) { 21769 verbose(env, "attach_btf_id %u is not a supported struct\n", 21770 btf_id); 21771 return -ENOTSUPP; 21772 } 21773 st_ops = st_ops_desc->st_ops; 21774 21775 t = st_ops_desc->type; 21776 member_idx = prog->expected_attach_type; 21777 if (member_idx >= btf_type_vlen(t)) { 21778 verbose(env, "attach to invalid member idx %u of struct %s\n", 21779 member_idx, st_ops->name); 21780 return -EINVAL; 21781 } 21782 21783 member = &btf_type_member(t)[member_idx]; 21784 mname = btf_name_by_offset(btf, member->name_off); 21785 func_proto = btf_type_resolve_func_ptr(btf, member->type, 21786 NULL); 21787 if (!func_proto) { 21788 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 21789 mname, member_idx, st_ops->name); 21790 return -EINVAL; 21791 } 21792 21793 err = bpf_struct_ops_supported(st_ops, __btf_member_bit_offset(t, member) / 8); 21794 if (err) { 21795 verbose(env, "attach to unsupported member %s of struct %s\n", 21796 mname, st_ops->name); 21797 return err; 21798 } 21799 21800 if (st_ops->check_member) { 21801 err = st_ops->check_member(t, member, prog); 21802 21803 if (err) { 21804 verbose(env, "attach to unsupported member %s of struct %s\n", 21805 mname, st_ops->name); 21806 return err; 21807 } 21808 } 21809 21810 /* btf_ctx_access() used this to provide argument type info */ 21811 prog->aux->ctx_arg_info = 21812 st_ops_desc->arg_info[member_idx].info; 21813 prog->aux->ctx_arg_info_size = 21814 st_ops_desc->arg_info[member_idx].cnt; 21815 21816 prog->aux->attach_func_proto = func_proto; 21817 prog->aux->attach_func_name = mname; 21818 env->ops = st_ops->verifier_ops; 21819 21820 return 0; 21821 } 21822 #define SECURITY_PREFIX "security_" 21823 21824 static int check_attach_modify_return(unsigned long addr, const char *func_name) 21825 { 21826 if (within_error_injection_list(addr) || 21827 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 21828 return 0; 21829 21830 return -EINVAL; 21831 } 21832 21833 /* list of non-sleepable functions that are otherwise on 21834 * ALLOW_ERROR_INJECTION list 21835 */ 21836 BTF_SET_START(btf_non_sleepable_error_inject) 21837 /* Three functions below can be called from sleepable and non-sleepable context. 21838 * Assume non-sleepable from bpf safety point of view. 21839 */ 21840 BTF_ID(func, __filemap_add_folio) 21841 #ifdef CONFIG_FAIL_PAGE_ALLOC 21842 BTF_ID(func, should_fail_alloc_page) 21843 #endif 21844 #ifdef CONFIG_FAILSLAB 21845 BTF_ID(func, should_failslab) 21846 #endif 21847 BTF_SET_END(btf_non_sleepable_error_inject) 21848 21849 static int check_non_sleepable_error_inject(u32 btf_id) 21850 { 21851 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 21852 } 21853 21854 int bpf_check_attach_target(struct bpf_verifier_log *log, 21855 const struct bpf_prog *prog, 21856 const struct bpf_prog *tgt_prog, 21857 u32 btf_id, 21858 struct bpf_attach_target_info *tgt_info) 21859 { 21860 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 21861 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 21862 char trace_symbol[KSYM_SYMBOL_LEN]; 21863 const char prefix[] = "btf_trace_"; 21864 struct bpf_raw_event_map *btp; 21865 int ret = 0, subprog = -1, i; 21866 const struct btf_type *t; 21867 bool conservative = true; 21868 const char *tname, *fname; 21869 struct btf *btf; 21870 long addr = 0; 21871 struct module *mod = NULL; 21872 21873 if (!btf_id) { 21874 bpf_log(log, "Tracing programs must provide btf_id\n"); 21875 return -EINVAL; 21876 } 21877 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 21878 if (!btf) { 21879 bpf_log(log, 21880 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 21881 return -EINVAL; 21882 } 21883 t = btf_type_by_id(btf, btf_id); 21884 if (!t) { 21885 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 21886 return -EINVAL; 21887 } 21888 tname = btf_name_by_offset(btf, t->name_off); 21889 if (!tname) { 21890 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 21891 return -EINVAL; 21892 } 21893 if (tgt_prog) { 21894 struct bpf_prog_aux *aux = tgt_prog->aux; 21895 21896 if (bpf_prog_is_dev_bound(prog->aux) && 21897 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 21898 bpf_log(log, "Target program bound device mismatch"); 21899 return -EINVAL; 21900 } 21901 21902 for (i = 0; i < aux->func_info_cnt; i++) 21903 if (aux->func_info[i].type_id == btf_id) { 21904 subprog = i; 21905 break; 21906 } 21907 if (subprog == -1) { 21908 bpf_log(log, "Subprog %s doesn't exist\n", tname); 21909 return -EINVAL; 21910 } 21911 if (aux->func && aux->func[subprog]->aux->exception_cb) { 21912 bpf_log(log, 21913 "%s programs cannot attach to exception callback\n", 21914 prog_extension ? "Extension" : "FENTRY/FEXIT"); 21915 return -EINVAL; 21916 } 21917 conservative = aux->func_info_aux[subprog].unreliable; 21918 if (prog_extension) { 21919 if (conservative) { 21920 bpf_log(log, 21921 "Cannot replace static functions\n"); 21922 return -EINVAL; 21923 } 21924 if (!prog->jit_requested) { 21925 bpf_log(log, 21926 "Extension programs should be JITed\n"); 21927 return -EINVAL; 21928 } 21929 } 21930 if (!tgt_prog->jited) { 21931 bpf_log(log, "Can attach to only JITed progs\n"); 21932 return -EINVAL; 21933 } 21934 if (prog_tracing) { 21935 if (aux->attach_tracing_prog) { 21936 /* 21937 * Target program is an fentry/fexit which is already attached 21938 * to another tracing program. More levels of nesting 21939 * attachment are not allowed. 21940 */ 21941 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 21942 return -EINVAL; 21943 } 21944 } else if (tgt_prog->type == prog->type) { 21945 /* 21946 * To avoid potential call chain cycles, prevent attaching of a 21947 * program extension to another extension. It's ok to attach 21948 * fentry/fexit to extension program. 21949 */ 21950 bpf_log(log, "Cannot recursively attach\n"); 21951 return -EINVAL; 21952 } 21953 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 21954 prog_extension && 21955 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 21956 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 21957 /* Program extensions can extend all program types 21958 * except fentry/fexit. The reason is the following. 21959 * The fentry/fexit programs are used for performance 21960 * analysis, stats and can be attached to any program 21961 * type. When extension program is replacing XDP function 21962 * it is necessary to allow performance analysis of all 21963 * functions. Both original XDP program and its program 21964 * extension. Hence attaching fentry/fexit to 21965 * BPF_PROG_TYPE_EXT is allowed. If extending of 21966 * fentry/fexit was allowed it would be possible to create 21967 * long call chain fentry->extension->fentry->extension 21968 * beyond reasonable stack size. Hence extending fentry 21969 * is not allowed. 21970 */ 21971 bpf_log(log, "Cannot extend fentry/fexit\n"); 21972 return -EINVAL; 21973 } 21974 } else { 21975 if (prog_extension) { 21976 bpf_log(log, "Cannot replace kernel functions\n"); 21977 return -EINVAL; 21978 } 21979 } 21980 21981 switch (prog->expected_attach_type) { 21982 case BPF_TRACE_RAW_TP: 21983 if (tgt_prog) { 21984 bpf_log(log, 21985 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 21986 return -EINVAL; 21987 } 21988 if (!btf_type_is_typedef(t)) { 21989 bpf_log(log, "attach_btf_id %u is not a typedef\n", 21990 btf_id); 21991 return -EINVAL; 21992 } 21993 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 21994 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 21995 btf_id, tname); 21996 return -EINVAL; 21997 } 21998 tname += sizeof(prefix) - 1; 21999 22000 /* The func_proto of "btf_trace_##tname" is generated from typedef without argument 22001 * names. Thus using bpf_raw_event_map to get argument names. 22002 */ 22003 btp = bpf_get_raw_tracepoint(tname); 22004 if (!btp) 22005 return -EINVAL; 22006 fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL, 22007 trace_symbol); 22008 bpf_put_raw_tracepoint(btp); 22009 22010 if (fname) 22011 ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC); 22012 22013 if (!fname || ret < 0) { 22014 bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n", 22015 prefix, tname); 22016 t = btf_type_by_id(btf, t->type); 22017 if (!btf_type_is_ptr(t)) 22018 /* should never happen in valid vmlinux build */ 22019 return -EINVAL; 22020 } else { 22021 t = btf_type_by_id(btf, ret); 22022 if (!btf_type_is_func(t)) 22023 /* should never happen in valid vmlinux build */ 22024 return -EINVAL; 22025 } 22026 22027 t = btf_type_by_id(btf, t->type); 22028 if (!btf_type_is_func_proto(t)) 22029 /* should never happen in valid vmlinux build */ 22030 return -EINVAL; 22031 22032 break; 22033 case BPF_TRACE_ITER: 22034 if (!btf_type_is_func(t)) { 22035 bpf_log(log, "attach_btf_id %u is not a function\n", 22036 btf_id); 22037 return -EINVAL; 22038 } 22039 t = btf_type_by_id(btf, t->type); 22040 if (!btf_type_is_func_proto(t)) 22041 return -EINVAL; 22042 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 22043 if (ret) 22044 return ret; 22045 break; 22046 default: 22047 if (!prog_extension) 22048 return -EINVAL; 22049 fallthrough; 22050 case BPF_MODIFY_RETURN: 22051 case BPF_LSM_MAC: 22052 case BPF_LSM_CGROUP: 22053 case BPF_TRACE_FENTRY: 22054 case BPF_TRACE_FEXIT: 22055 if (!btf_type_is_func(t)) { 22056 bpf_log(log, "attach_btf_id %u is not a function\n", 22057 btf_id); 22058 return -EINVAL; 22059 } 22060 if (prog_extension && 22061 btf_check_type_match(log, prog, btf, t)) 22062 return -EINVAL; 22063 t = btf_type_by_id(btf, t->type); 22064 if (!btf_type_is_func_proto(t)) 22065 return -EINVAL; 22066 22067 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 22068 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 22069 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 22070 return -EINVAL; 22071 22072 if (tgt_prog && conservative) 22073 t = NULL; 22074 22075 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 22076 if (ret < 0) 22077 return ret; 22078 22079 if (tgt_prog) { 22080 if (subprog == 0) 22081 addr = (long) tgt_prog->bpf_func; 22082 else 22083 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 22084 } else { 22085 if (btf_is_module(btf)) { 22086 mod = btf_try_get_module(btf); 22087 if (mod) 22088 addr = find_kallsyms_symbol_value(mod, tname); 22089 else 22090 addr = 0; 22091 } else { 22092 addr = kallsyms_lookup_name(tname); 22093 } 22094 if (!addr) { 22095 module_put(mod); 22096 bpf_log(log, 22097 "The address of function %s cannot be found\n", 22098 tname); 22099 return -ENOENT; 22100 } 22101 } 22102 22103 if (prog->sleepable) { 22104 ret = -EINVAL; 22105 switch (prog->type) { 22106 case BPF_PROG_TYPE_TRACING: 22107 22108 /* fentry/fexit/fmod_ret progs can be sleepable if they are 22109 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 22110 */ 22111 if (!check_non_sleepable_error_inject(btf_id) && 22112 within_error_injection_list(addr)) 22113 ret = 0; 22114 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 22115 * in the fmodret id set with the KF_SLEEPABLE flag. 22116 */ 22117 else { 22118 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 22119 prog); 22120 22121 if (flags && (*flags & KF_SLEEPABLE)) 22122 ret = 0; 22123 } 22124 break; 22125 case BPF_PROG_TYPE_LSM: 22126 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 22127 * Only some of them are sleepable. 22128 */ 22129 if (bpf_lsm_is_sleepable_hook(btf_id)) 22130 ret = 0; 22131 break; 22132 default: 22133 break; 22134 } 22135 if (ret) { 22136 module_put(mod); 22137 bpf_log(log, "%s is not sleepable\n", tname); 22138 return ret; 22139 } 22140 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 22141 if (tgt_prog) { 22142 module_put(mod); 22143 bpf_log(log, "can't modify return codes of BPF programs\n"); 22144 return -EINVAL; 22145 } 22146 ret = -EINVAL; 22147 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 22148 !check_attach_modify_return(addr, tname)) 22149 ret = 0; 22150 if (ret) { 22151 module_put(mod); 22152 bpf_log(log, "%s() is not modifiable\n", tname); 22153 return ret; 22154 } 22155 } 22156 22157 break; 22158 } 22159 tgt_info->tgt_addr = addr; 22160 tgt_info->tgt_name = tname; 22161 tgt_info->tgt_type = t; 22162 tgt_info->tgt_mod = mod; 22163 return 0; 22164 } 22165 22166 BTF_SET_START(btf_id_deny) 22167 BTF_ID_UNUSED 22168 #ifdef CONFIG_SMP 22169 BTF_ID(func, migrate_disable) 22170 BTF_ID(func, migrate_enable) 22171 #endif 22172 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 22173 BTF_ID(func, rcu_read_unlock_strict) 22174 #endif 22175 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 22176 BTF_ID(func, preempt_count_add) 22177 BTF_ID(func, preempt_count_sub) 22178 #endif 22179 #ifdef CONFIG_PREEMPT_RCU 22180 BTF_ID(func, __rcu_read_lock) 22181 BTF_ID(func, __rcu_read_unlock) 22182 #endif 22183 BTF_SET_END(btf_id_deny) 22184 22185 static bool can_be_sleepable(struct bpf_prog *prog) 22186 { 22187 if (prog->type == BPF_PROG_TYPE_TRACING) { 22188 switch (prog->expected_attach_type) { 22189 case BPF_TRACE_FENTRY: 22190 case BPF_TRACE_FEXIT: 22191 case BPF_MODIFY_RETURN: 22192 case BPF_TRACE_ITER: 22193 return true; 22194 default: 22195 return false; 22196 } 22197 } 22198 return prog->type == BPF_PROG_TYPE_LSM || 22199 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 22200 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 22201 } 22202 22203 static int check_attach_btf_id(struct bpf_verifier_env *env) 22204 { 22205 struct bpf_prog *prog = env->prog; 22206 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 22207 struct bpf_attach_target_info tgt_info = {}; 22208 u32 btf_id = prog->aux->attach_btf_id; 22209 struct bpf_trampoline *tr; 22210 int ret; 22211 u64 key; 22212 22213 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 22214 if (prog->sleepable) 22215 /* attach_btf_id checked to be zero already */ 22216 return 0; 22217 verbose(env, "Syscall programs can only be sleepable\n"); 22218 return -EINVAL; 22219 } 22220 22221 if (prog->sleepable && !can_be_sleepable(prog)) { 22222 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 22223 return -EINVAL; 22224 } 22225 22226 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 22227 return check_struct_ops_btf_id(env); 22228 22229 if (prog->type != BPF_PROG_TYPE_TRACING && 22230 prog->type != BPF_PROG_TYPE_LSM && 22231 prog->type != BPF_PROG_TYPE_EXT) 22232 return 0; 22233 22234 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 22235 if (ret) 22236 return ret; 22237 22238 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 22239 /* to make freplace equivalent to their targets, they need to 22240 * inherit env->ops and expected_attach_type for the rest of the 22241 * verification 22242 */ 22243 env->ops = bpf_verifier_ops[tgt_prog->type]; 22244 prog->expected_attach_type = tgt_prog->expected_attach_type; 22245 } 22246 22247 /* store info about the attachment target that will be used later */ 22248 prog->aux->attach_func_proto = tgt_info.tgt_type; 22249 prog->aux->attach_func_name = tgt_info.tgt_name; 22250 prog->aux->mod = tgt_info.tgt_mod; 22251 22252 if (tgt_prog) { 22253 prog->aux->saved_dst_prog_type = tgt_prog->type; 22254 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 22255 } 22256 22257 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 22258 prog->aux->attach_btf_trace = true; 22259 return 0; 22260 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 22261 if (!bpf_iter_prog_supported(prog)) 22262 return -EINVAL; 22263 return 0; 22264 } 22265 22266 if (prog->type == BPF_PROG_TYPE_LSM) { 22267 ret = bpf_lsm_verify_prog(&env->log, prog); 22268 if (ret < 0) 22269 return ret; 22270 } else if (prog->type == BPF_PROG_TYPE_TRACING && 22271 btf_id_set_contains(&btf_id_deny, btf_id)) { 22272 return -EINVAL; 22273 } 22274 22275 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 22276 tr = bpf_trampoline_get(key, &tgt_info); 22277 if (!tr) 22278 return -ENOMEM; 22279 22280 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 22281 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 22282 22283 prog->aux->dst_trampoline = tr; 22284 return 0; 22285 } 22286 22287 struct btf *bpf_get_btf_vmlinux(void) 22288 { 22289 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 22290 mutex_lock(&bpf_verifier_lock); 22291 if (!btf_vmlinux) 22292 btf_vmlinux = btf_parse_vmlinux(); 22293 mutex_unlock(&bpf_verifier_lock); 22294 } 22295 return btf_vmlinux; 22296 } 22297 22298 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 22299 { 22300 u64 start_time = ktime_get_ns(); 22301 struct bpf_verifier_env *env; 22302 int i, len, ret = -EINVAL, err; 22303 u32 log_true_size; 22304 bool is_priv; 22305 22306 /* no program is valid */ 22307 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 22308 return -EINVAL; 22309 22310 /* 'struct bpf_verifier_env' can be global, but since it's not small, 22311 * allocate/free it every time bpf_check() is called 22312 */ 22313 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 22314 if (!env) 22315 return -ENOMEM; 22316 22317 env->bt.env = env; 22318 22319 len = (*prog)->len; 22320 env->insn_aux_data = 22321 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 22322 ret = -ENOMEM; 22323 if (!env->insn_aux_data) 22324 goto err_free_env; 22325 for (i = 0; i < len; i++) 22326 env->insn_aux_data[i].orig_idx = i; 22327 env->prog = *prog; 22328 env->ops = bpf_verifier_ops[env->prog->type]; 22329 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 22330 22331 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 22332 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 22333 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 22334 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 22335 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 22336 22337 bpf_get_btf_vmlinux(); 22338 22339 /* grab the mutex to protect few globals used by verifier */ 22340 if (!is_priv) 22341 mutex_lock(&bpf_verifier_lock); 22342 22343 /* user could have requested verbose verifier output 22344 * and supplied buffer to store the verification trace 22345 */ 22346 ret = bpf_vlog_init(&env->log, attr->log_level, 22347 (char __user *) (unsigned long) attr->log_buf, 22348 attr->log_size); 22349 if (ret) 22350 goto err_unlock; 22351 22352 mark_verifier_state_clean(env); 22353 22354 if (IS_ERR(btf_vmlinux)) { 22355 /* Either gcc or pahole or kernel are broken. */ 22356 verbose(env, "in-kernel BTF is malformed\n"); 22357 ret = PTR_ERR(btf_vmlinux); 22358 goto skip_full_check; 22359 } 22360 22361 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 22362 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 22363 env->strict_alignment = true; 22364 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 22365 env->strict_alignment = false; 22366 22367 if (is_priv) 22368 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 22369 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 22370 22371 env->explored_states = kvcalloc(state_htab_size(env), 22372 sizeof(struct bpf_verifier_state_list *), 22373 GFP_USER); 22374 ret = -ENOMEM; 22375 if (!env->explored_states) 22376 goto skip_full_check; 22377 22378 ret = check_btf_info_early(env, attr, uattr); 22379 if (ret < 0) 22380 goto skip_full_check; 22381 22382 ret = add_subprog_and_kfunc(env); 22383 if (ret < 0) 22384 goto skip_full_check; 22385 22386 ret = check_subprogs(env); 22387 if (ret < 0) 22388 goto skip_full_check; 22389 22390 ret = check_btf_info(env, attr, uattr); 22391 if (ret < 0) 22392 goto skip_full_check; 22393 22394 ret = check_attach_btf_id(env); 22395 if (ret) 22396 goto skip_full_check; 22397 22398 ret = resolve_pseudo_ldimm64(env); 22399 if (ret < 0) 22400 goto skip_full_check; 22401 22402 if (bpf_prog_is_offloaded(env->prog->aux)) { 22403 ret = bpf_prog_offload_verifier_prep(env->prog); 22404 if (ret) 22405 goto skip_full_check; 22406 } 22407 22408 ret = check_cfg(env); 22409 if (ret < 0) 22410 goto skip_full_check; 22411 22412 ret = mark_fastcall_patterns(env); 22413 if (ret < 0) 22414 goto skip_full_check; 22415 22416 ret = do_check_main(env); 22417 ret = ret ?: do_check_subprogs(env); 22418 22419 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 22420 ret = bpf_prog_offload_finalize(env); 22421 22422 skip_full_check: 22423 kvfree(env->explored_states); 22424 22425 /* might decrease stack depth, keep it before passes that 22426 * allocate additional slots. 22427 */ 22428 if (ret == 0) 22429 ret = remove_fastcall_spills_fills(env); 22430 22431 if (ret == 0) 22432 ret = check_max_stack_depth(env); 22433 22434 /* instruction rewrites happen after this point */ 22435 if (ret == 0) 22436 ret = optimize_bpf_loop(env); 22437 22438 if (is_priv) { 22439 if (ret == 0) 22440 opt_hard_wire_dead_code_branches(env); 22441 if (ret == 0) 22442 ret = opt_remove_dead_code(env); 22443 if (ret == 0) 22444 ret = opt_remove_nops(env); 22445 } else { 22446 if (ret == 0) 22447 sanitize_dead_code(env); 22448 } 22449 22450 if (ret == 0) 22451 /* program is valid, convert *(u32*)(ctx + off) accesses */ 22452 ret = convert_ctx_accesses(env); 22453 22454 if (ret == 0) 22455 ret = do_misc_fixups(env); 22456 22457 /* do 32-bit optimization after insn patching has done so those patched 22458 * insns could be handled correctly. 22459 */ 22460 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 22461 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 22462 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 22463 : false; 22464 } 22465 22466 if (ret == 0) 22467 ret = fixup_call_args(env); 22468 22469 env->verification_time = ktime_get_ns() - start_time; 22470 print_verification_stats(env); 22471 env->prog->aux->verified_insns = env->insn_processed; 22472 22473 /* preserve original error even if log finalization is successful */ 22474 err = bpf_vlog_finalize(&env->log, &log_true_size); 22475 if (err) 22476 ret = err; 22477 22478 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 22479 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 22480 &log_true_size, sizeof(log_true_size))) { 22481 ret = -EFAULT; 22482 goto err_release_maps; 22483 } 22484 22485 if (ret) 22486 goto err_release_maps; 22487 22488 if (env->used_map_cnt) { 22489 /* if program passed verifier, update used_maps in bpf_prog_info */ 22490 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 22491 sizeof(env->used_maps[0]), 22492 GFP_KERNEL); 22493 22494 if (!env->prog->aux->used_maps) { 22495 ret = -ENOMEM; 22496 goto err_release_maps; 22497 } 22498 22499 memcpy(env->prog->aux->used_maps, env->used_maps, 22500 sizeof(env->used_maps[0]) * env->used_map_cnt); 22501 env->prog->aux->used_map_cnt = env->used_map_cnt; 22502 } 22503 if (env->used_btf_cnt) { 22504 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 22505 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 22506 sizeof(env->used_btfs[0]), 22507 GFP_KERNEL); 22508 if (!env->prog->aux->used_btfs) { 22509 ret = -ENOMEM; 22510 goto err_release_maps; 22511 } 22512 22513 memcpy(env->prog->aux->used_btfs, env->used_btfs, 22514 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 22515 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 22516 } 22517 if (env->used_map_cnt || env->used_btf_cnt) { 22518 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 22519 * bpf_ld_imm64 instructions 22520 */ 22521 convert_pseudo_ld_imm64(env); 22522 } 22523 22524 adjust_btf_func(env); 22525 22526 err_release_maps: 22527 if (!env->prog->aux->used_maps) 22528 /* if we didn't copy map pointers into bpf_prog_info, release 22529 * them now. Otherwise free_used_maps() will release them. 22530 */ 22531 release_maps(env); 22532 if (!env->prog->aux->used_btfs) 22533 release_btfs(env); 22534 22535 /* extension progs temporarily inherit the attach_type of their targets 22536 for verification purposes, so set it back to zero before returning 22537 */ 22538 if (env->prog->type == BPF_PROG_TYPE_EXT) 22539 env->prog->expected_attach_type = 0; 22540 22541 *prog = env->prog; 22542 22543 module_put(env->attach_btf_mod); 22544 err_unlock: 22545 if (!is_priv) 22546 mutex_unlock(&bpf_verifier_lock); 22547 vfree(env->insn_aux_data); 22548 err_free_env: 22549 kfree(env); 22550 return ret; 22551 } 22552